-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
1128 lines (975 loc) · 28.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* WordPress dependencies
*/
import {
forwardRef,
useEffect,
useRef,
useState,
useMemo,
useLayoutEffect,
} from '@wordpress/element';
import {
BACKSPACE,
DELETE,
ENTER,
LEFT,
RIGHT,
SPACE,
ESCAPE,
} from '@wordpress/keycodes';
import { getFilesFromDataTransfer } from '@wordpress/dom';
import { useMergeRefs } from '@wordpress/compose';
/**
* Internal dependencies
*/
import FormatEdit from './format-edit';
import { create } from '../create';
import { apply } from '../to-dom';
import { toHTMLString } from '../to-html-string';
import { remove } from '../remove';
import { removeFormat } from '../remove-format';
import { isCollapsed } from '../is-collapsed';
import { LINE_SEPARATOR } from '../special-characters';
import { indentListItems } from '../indent-list-items';
import { getActiveFormats } from '../get-active-formats';
import { updateFormats } from '../update-formats';
import { removeLineSeparator } from '../remove-line-separator';
import { isEmptyLine } from '../is-empty';
import { useFormatTypes } from './use-format-types';
import { useBoundaryStyle } from './use-boundary-style';
import { useInlineWarning } from './use-inline-warning';
import { insert } from '../insert';
import { useCopyHandler } from './use-copy-handler';
/** @typedef {import('@wordpress/element').WPSyntheticEvent} WPSyntheticEvent */
/**
* All inserting input types that would insert HTML into the DOM.
*
* @see https://www.w3.org/TR/input-events-2/#interface-InputEvent-Attributes
*
* @type {Set}
*/
const INSERTION_INPUT_TYPES_TO_IGNORE = new Set( [
'insertParagraph',
'insertOrderedList',
'insertUnorderedList',
'insertHorizontalRule',
'insertLink',
] );
/**
* In HTML, leading and trailing spaces are not visible, and multiple spaces
* elsewhere are visually reduced to one space. This rule prevents spaces from
* collapsing so all space is visible in the editor and can be removed. It also
* prevents some browsers from inserting non-breaking spaces at the end of a
* line to prevent the space from visually disappearing. Sometimes these non
* breaking spaces can linger in the editor causing unwanted non breaking spaces
* in between words. If also prevent Firefox from inserting a trailing `br` node
* to visualise any trailing space, causing the element to be saved.
*
* > Authors are encouraged to set the 'white-space' property on editing hosts
* > and on markup that was originally created through these editing mechanisms
* > to the value 'pre-wrap'. Default HTML whitespace handling is not well
* > suited to WYSIWYG editing, and line wrapping will not work correctly in
* > some corner cases if 'white-space' is left at its default value.
*
* https://html.spec.whatwg.org/multipage/interaction.html#best-practices-for-in-page-editors
*
* @type {string}
*/
const whiteSpace = 'pre-wrap';
/**
* A minimum width of 1px will prevent the rich text container from collapsing
* to 0 width and hiding the caret. This is useful for inline containers.
*/
const minWidth = '1px';
/**
* Default style object for the editable element.
*
* @type {Object<string,string>}
*/
const defaultStyle = { whiteSpace, minWidth };
const EMPTY_ACTIVE_FORMATS = [];
function createPrepareEditableTree( fns ) {
return ( value ) =>
fns.reduce(
( accumulator, fn ) => fn( accumulator, value.text ),
value.formats
);
}
/**
* If the selection is set on the placeholder element, collapse the selection to
* the start (before the placeholder).
*
* @param {Window} defaultView
*/
function fixPlaceholderSelection( defaultView ) {
const selection = defaultView.getSelection();
const { anchorNode, anchorOffset } = selection;
if ( anchorNode.nodeType !== anchorNode.ELEMENT_NODE ) {
return;
}
const targetNode = anchorNode.childNodes[ anchorOffset ];
if (
! targetNode ||
targetNode.nodeType !== targetNode.ELEMENT_NODE ||
! targetNode.getAttribute( 'data-rich-text-placeholder' )
) {
return;
}
selection.collapseToStart();
}
function RichText(
{
tagName: TagName = 'div',
value = '',
selectionStart,
selectionEnd,
children,
allowedFormats,
withoutInteractiveFormatting,
placeholder,
disabled,
preserveWhiteSpace,
onPaste,
format = 'string',
onBlur,
onDelete,
onEnter,
onSelectionChange,
onChange,
unstableOnFocus: onFocus,
clientId,
identifier,
__unstableMultilineTag: multilineTag,
__unstableMultilineRootTag: multilineRootTag,
__unstableDisableFormats: disableFormats,
__unstableDidAutomaticChange: didAutomaticChange,
__unstableInputRule: inputRule,
__unstableMarkAutomaticChange: markAutomaticChange,
__unstableAllowPrefixTransformations: allowPrefixTransformations,
__unstableUndo: undo,
__unstableIsCaretWithinFormattedText: isCaretWithinFormattedText,
__unstableOnEnterFormattedText: onEnterFormattedText,
__unstableOnExitFormattedText: onExitFormattedText,
__unstableOnCreateUndoLevel: onCreateUndoLevel,
__unstableIsSelected: isSelected,
},
forwardedRef
) {
const ref = useRef();
const [ activeFormats = [], setActiveFormats ] = useState();
const {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies,
} = useFormatTypes( {
clientId,
identifier,
withoutInteractiveFormatting,
allowedFormats,
} );
// For backward compatibility, fall back to tagName if it's a string.
// tagName can now be a component for light blocks.
if ( ! multilineRootTag && typeof TagName === 'string' ) {
multilineRootTag = TagName;
}
function getDoc() {
return ref.current.ownerDocument;
}
function getWin() {
return getDoc().defaultView;
}
/**
* Converts the outside data structure to our internal representation.
*
* @param {*} string The outside value, data type depends on props.
*
* @return {Object} An internal rich-text value.
*/
function formatToValue( string ) {
if ( disableFormats ) {
return {
text: string,
formats: Array( string.length ),
replacements: Array( string.length ),
};
}
if ( format !== 'string' ) {
return string;
}
const prepare = createPrepareEditableTree( valueHandlers );
const result = create( {
html: string,
multilineTag,
multilineWrapperTags:
multilineTag === 'li' ? [ 'ul', 'ol' ] : undefined,
preserveWhiteSpace,
} );
result.formats = prepare( result );
return result;
}
/**
* Removes editor only formats from the value.
*
* Editor only formats are applied using `prepareEditableTree`, so we need to
* remove them before converting the internal state
*
* @param {Object} val The internal rich-text value.
*
* @return {Object} A new rich-text value.
*/
function removeEditorOnlyFormats( val ) {
formatTypes.forEach( ( formatType ) => {
// Remove formats created by prepareEditableTree, because they are editor only.
if ( formatType.__experimentalCreatePrepareEditableTree ) {
val = removeFormat( val, formatType.name, 0, val.text.length );
}
} );
return val;
}
/**
* Converts the internal value to the external data format.
*
* @param {Object} val The internal rich-text value.
*
* @return {*} The external data format, data type depends on props.
*/
function valueToFormat( val ) {
if ( disableFormats ) {
return val.text;
}
val = removeEditorOnlyFormats( val );
if ( format !== 'string' ) {
return;
}
return toHTMLString( { value: val, multilineTag, preserveWhiteSpace } );
}
// Internal values are updated synchronously, unlike props and state.
const _value = useRef( value );
const record = useRef(
useMemo( () => {
const initialRecord = formatToValue( value );
initialRecord.start = selectionStart;
initialRecord.end = selectionEnd;
return initialRecord;
}, [] )
);
function createRecord() {
const selection = getWin().getSelection();
const range =
selection.rangeCount > 0 ? selection.getRangeAt( 0 ) : null;
return create( {
element: ref.current,
range,
multilineTag,
multilineWrapperTags:
multilineTag === 'li' ? [ 'ul', 'ol' ] : undefined,
__unstableIsEditableTree: true,
preserveWhiteSpace,
} );
}
function applyRecord( newRecord, { domOnly } = {} ) {
apply( {
value: newRecord,
current: ref.current,
multilineTag,
multilineWrapperTags:
multilineTag === 'li' ? [ 'ul', 'ol' ] : undefined,
prepareEditableTree: createPrepareEditableTree( prepareHandlers ),
__unstableDomOnly: domOnly,
placeholder,
} );
}
/**
* Handles a paste event.
*
* Saves the pasted data as plain text in `pastedPlainText`.
*
* @param {ClipboardEvent} event The paste event.
*/
function handlePaste( event ) {
if ( ! isSelected ) {
event.preventDefault();
return;
}
const { clipboardData } = event;
let plainText = '';
let html = '';
// IE11 only supports `Text` as an argument for `getData` and will
// otherwise throw an invalid argument error, so we try the standard
// arguments first, then fallback to `Text` if they fail.
try {
plainText = clipboardData.getData( 'text/plain' );
html = clipboardData.getData( 'text/html' );
} catch ( error1 ) {
try {
html = clipboardData.getData( 'Text' );
} catch ( error2 ) {
// Some browsers like UC Browser paste plain text by default and
// don't support clipboardData at all, so allow default
// behaviour.
return;
}
}
event.preventDefault();
// Allows us to ask for this information when we get a report.
window.console.log( 'Received HTML:\n\n', html );
window.console.log( 'Received plain text:\n\n', plainText );
if ( disableFormats ) {
handleChange( insert( record.current, plainText ) );
return;
}
const transformed = formatTypes.reduce(
( accumlator, { __unstablePasteRule } ) => {
// Only allow one transform.
if ( __unstablePasteRule && accumlator === record.current ) {
accumlator = __unstablePasteRule( record.current, {
html,
plainText,
} );
}
return accumlator;
},
record.current
);
if ( transformed !== record.current ) {
handleChange( transformed );
return;
}
if ( onPaste ) {
const files = getFilesFromDataTransfer( clipboardData );
const isInternal = clipboardData.getData( 'rich-text' ) === 'true';
onPaste( {
value: removeEditorOnlyFormats( record.current ),
onChange: handleChange,
html,
plainText,
isInternal,
files: [ ...files ],
activeFormats,
} );
}
}
/**
* Handles delete on keydown:
* - outdent list items,
* - delete content if everything is selected,
* - trigger the onDelete prop when selection is uncollapsed and at an edge.
*
* @param {WPSyntheticEvent} event A synthetic keyboard event.
*/
function handleDelete( event ) {
const { keyCode } = event;
if (
keyCode !== DELETE &&
keyCode !== BACKSPACE &&
keyCode !== ESCAPE
) {
return;
}
if ( didAutomaticChange ) {
event.preventDefault();
undo();
return;
}
if ( keyCode === ESCAPE ) {
return;
}
const currentValue = createRecord();
const { start, end, text } = currentValue;
const isReverse = keyCode === BACKSPACE;
// Always handle full content deletion ourselves.
if ( start === 0 && end !== 0 && end === text.length ) {
handleChange( remove( currentValue ) );
event.preventDefault();
return;
}
if ( multilineTag ) {
let newValue;
// Check to see if we should remove the first item if empty.
if (
isReverse &&
currentValue.start === 0 &&
currentValue.end === 0 &&
isEmptyLine( currentValue )
) {
newValue = removeLineSeparator( currentValue, ! isReverse );
} else {
newValue = removeLineSeparator( currentValue, isReverse );
}
if ( newValue ) {
handleChange( newValue );
event.preventDefault();
return;
}
}
// Only process delete if the key press occurs at an uncollapsed edge.
if (
! onDelete ||
! isCollapsed( currentValue ) ||
activeFormats.length ||
( isReverse && start !== 0 ) ||
( ! isReverse && end !== text.length )
) {
return;
}
onDelete( { isReverse, value: currentValue } );
event.preventDefault();
}
/**
* Triggers the `onEnter` prop on keydown.
*
* @param {WPSyntheticEvent} event A synthetic keyboard event.
*/
function handleEnter( event ) {
if ( event.keyCode !== ENTER ) {
return;
}
event.preventDefault();
if ( ! onEnter ) {
return;
}
onEnter( {
value: removeEditorOnlyFormats( createRecord() ),
onChange: handleChange,
shiftKey: event.shiftKey,
} );
}
/**
* Indents list items on space keydown.
*
* @param {WPSyntheticEvent} event A synthetic keyboard event.
*/
function handleSpace( event ) {
const { keyCode, shiftKey, altKey, metaKey, ctrlKey } = event;
if (
// Only override when no modifiers are pressed.
shiftKey ||
altKey ||
metaKey ||
ctrlKey ||
keyCode !== SPACE ||
multilineTag !== 'li'
) {
return;
}
const currentValue = createRecord();
if ( ! isCollapsed( currentValue ) ) {
return;
}
const { text, start } = currentValue;
const characterBefore = text[ start - 1 ];
// The caret must be at the start of a line.
if ( characterBefore && characterBefore !== LINE_SEPARATOR ) {
return;
}
handleChange(
indentListItems( currentValue, { type: multilineRootTag } )
);
event.preventDefault();
}
/**
* Handles horizontal keyboard navigation when no modifiers are pressed. The
* navigation is handled separately to move correctly around format
* boundaries.
*
* @param {WPSyntheticEvent} event A synthetic keyboard event.
*/
function handleHorizontalNavigation( event ) {
const { keyCode, shiftKey, altKey, metaKey, ctrlKey } = event;
if (
// Only override left and right keys without modifiers pressed.
shiftKey ||
altKey ||
metaKey ||
ctrlKey ||
( keyCode !== LEFT && keyCode !== RIGHT )
) {
return;
}
const {
text,
formats,
start,
end,
activeFormats: currentActiveFormats = [],
} = record.current;
const collapsed = isCollapsed( record.current );
// To do: ideally, we should look at visual position instead.
const { direction } = getWin().getComputedStyle( ref.current );
const reverseKey = direction === 'rtl' ? RIGHT : LEFT;
const isReverse = event.keyCode === reverseKey;
// If the selection is collapsed and at the very start, do nothing if
// navigating backward.
// If the selection is collapsed and at the very end, do nothing if
// navigating forward.
if ( collapsed && currentActiveFormats.length === 0 ) {
if ( start === 0 && isReverse ) {
return;
}
if ( end === text.length && ! isReverse ) {
return;
}
}
// If the selection is not collapsed, let the browser handle collapsing
// the selection for now. Later we could expand this logic to set
// boundary positions if needed.
if ( ! collapsed ) {
return;
}
const formatsBefore = formats[ start - 1 ] || EMPTY_ACTIVE_FORMATS;
const formatsAfter = formats[ start ] || EMPTY_ACTIVE_FORMATS;
let newActiveFormatsLength = currentActiveFormats.length;
let source = formatsAfter;
if ( formatsBefore.length > formatsAfter.length ) {
source = formatsBefore;
}
// If the amount of formats before the caret and after the caret is
// different, the caret is at a format boundary.
if ( formatsBefore.length < formatsAfter.length ) {
if (
! isReverse &&
currentActiveFormats.length < formatsAfter.length
) {
newActiveFormatsLength++;
}
if (
isReverse &&
currentActiveFormats.length > formatsBefore.length
) {
newActiveFormatsLength--;
}
} else if ( formatsBefore.length > formatsAfter.length ) {
if (
! isReverse &&
currentActiveFormats.length > formatsAfter.length
) {
newActiveFormatsLength--;
}
if (
isReverse &&
currentActiveFormats.length < formatsBefore.length
) {
newActiveFormatsLength++;
}
}
if ( newActiveFormatsLength === currentActiveFormats.length ) {
record.current._newActiveFormats = isReverse
? formatsBefore
: formatsAfter;
return;
}
event.preventDefault();
const newActiveFormats = source.slice( 0, newActiveFormatsLength );
const newValue = {
...record.current,
activeFormats: newActiveFormats,
};
record.current = newValue;
applyRecord( newValue );
setActiveFormats( newActiveFormats );
}
function handleKeyDown( event ) {
if ( event.defaultPrevented ) {
return;
}
handleDelete( event );
handleEnter( event );
handleSpace( event );
handleHorizontalNavigation( event );
}
const lastHistoryValue = useRef( value );
function createUndoLevel() {
// If the content is the same, no level needs to be created.
if ( lastHistoryValue.current === _value.current ) {
return;
}
onCreateUndoLevel();
lastHistoryValue.current = _value.current;
}
const isComposing = useRef( false );
const timeout = useRef();
/**
* Handle input on the next selection change event.
*
* @param {WPSyntheticEvent} event Synthetic input event.
*/
function handleInput( event ) {
// Do not trigger a change if characters are being composed. Browsers
// will usually emit a final `input` event when the characters are
// composed.
// As of December 2019, Safari doesn't support nativeEvent.isComposing.
if ( isComposing.current ) {
return;
}
let inputType;
if ( event ) {
inputType = event.inputType;
}
if ( ! inputType && event && event.nativeEvent ) {
inputType = event.nativeEvent.inputType;
}
// The browser formatted something or tried to insert HTML.
// Overwrite it. It will be handled later by the format library if
// needed.
if (
inputType &&
( inputType.indexOf( 'format' ) === 0 ||
INSERTION_INPUT_TYPES_TO_IGNORE.has( inputType ) )
) {
applyRecord( record.current );
return;
}
const currentValue = createRecord();
const { start, activeFormats: oldActiveFormats = [] } = record.current;
// Update the formats between the last and new caret position.
const change = updateFormats( {
value: currentValue,
start,
end: currentValue.start,
formats: oldActiveFormats,
} );
handleChange( change, { withoutHistory: true } );
// Create an undo level when input stops for over a second.
getWin().clearTimeout( timeout.current );
timeout.current = getWin().setTimeout( createUndoLevel, 1000 );
// Only run input rules when inserting text.
if ( inputType !== 'insertText' ) {
return;
}
if ( allowPrefixTransformations && inputRule ) {
inputRule( change, valueToFormat );
}
const transformed = formatTypes.reduce(
( accumlator, { __unstableInputRule } ) => {
if ( __unstableInputRule ) {
accumlator = __unstableInputRule( accumlator );
}
return accumlator;
},
change
);
if ( transformed !== change ) {
createUndoLevel();
handleChange( { ...transformed, activeFormats: oldActiveFormats } );
markAutomaticChange();
}
}
function handleCompositionStart() {
isComposing.current = true;
// Do not update the selection when characters are being composed as
// this rerenders the component and might distroy internal browser
// editing state.
getDoc().removeEventListener(
'selectionchange',
handleSelectionChange
);
}
function handleCompositionEnd() {
isComposing.current = false;
// Ensure the value is up-to-date for browsers that don't emit a final
// input event after composition.
handleInput( { inputType: 'insertText' } );
// Tracking selection changes can be resumed.
getDoc().addEventListener( 'selectionchange', handleSelectionChange );
}
const didMount = useRef( false );
/**
* Syncs the selection to local state. A callback for the `selectionchange`
* native events, `keyup`, `mouseup` and `touchend` synthetic events, and
* animation frames after the `focus` event.
*
* @param {Event|WPSyntheticEvent|DOMHighResTimeStamp} event
*/
function handleSelectionChange( event ) {
if ( ! ref.current ) {
return;
}
if ( ref.current.ownerDocument.activeElement !== ref.current ) {
return;
}
if ( event.type !== 'selectionchange' && ! isSelected ) {
return;
}
if ( disabled ) {
return;
}
// In case of a keyboard event, ignore selection changes during
// composition.
if ( isComposing.current ) {
return;
}
const { start, end, text } = createRecord();
const oldRecord = record.current;
// Fallback mechanism for IE11, which doesn't support the input event.
// Any input results in a selection change.
if ( text !== oldRecord.text ) {
handleInput();
return;
}
if ( start === oldRecord.start && end === oldRecord.end ) {
// Sometimes the browser may set the selection on the placeholder
// element, in which case the caret is not visible. We need to set
// the caret before the placeholder if that's the case.
if ( oldRecord.text.length === 0 && start === 0 ) {
fixPlaceholderSelection( getWin() );
}
return;
}
const newValue = {
...oldRecord,
start,
end,
// _newActiveFormats may be set on arrow key navigation to control
// the right boundary position. If undefined, getActiveFormats will
// give the active formats according to the browser.
activeFormats: oldRecord._newActiveFormats,
_newActiveFormats: undefined,
};
const newActiveFormats = getActiveFormats(
newValue,
EMPTY_ACTIVE_FORMATS
);
// Update the value with the new active formats.
newValue.activeFormats = newActiveFormats;
if ( ! isCaretWithinFormattedText && newActiveFormats.length ) {
onEnterFormattedText();
} else if ( isCaretWithinFormattedText && ! newActiveFormats.length ) {
onExitFormattedText();
}
// It is important that the internal value is updated first,
// otherwise the value will be wrong on render!
record.current = newValue;
applyRecord( newValue, { domOnly: true } );
onSelectionChange( start, end );
setActiveFormats( newActiveFormats );
}
/**
* Sync the value to global state. The node tree and selection will also be
* updated if differences are found.
*
* @param {Object} newRecord The record to sync and apply.
* @param {Object} $2 Named options.
* @param {boolean} $2.withoutHistory If true, no undo level will be
* created.
*/
function handleChange( newRecord, { withoutHistory } = {} ) {
if ( disableFormats ) {
newRecord.formats = Array( newRecord.text.length );
newRecord.replacements = Array( newRecord.text.length );
}
applyRecord( newRecord );
const { start, end, activeFormats: newActiveFormats = [] } = newRecord;
Object.values( changeHandlers ).forEach( ( changeHandler ) => {
changeHandler( newRecord.formats, newRecord.text );
} );
_value.current = valueToFormat( newRecord );
record.current = newRecord;
// Selection must be updated first, so it is recorded in history when
// the content change happens.
onSelectionChange( start, end );
onChange( _value.current );
setActiveFormats( newActiveFormats );
if ( ! withoutHistory ) {
createUndoLevel();
}
}
/**
* Select object when they are clicked. The browser will not set any
* selection when clicking e.g. an image.
*
* @param {WPSyntheticEvent} event Synthetic mousedown or touchstart event.
*/
function handlePointerDown( event ) {
const { target } = event;
// If the child element has no text content, it must be an object.
if ( target === ref.current || target.textContent ) {
return;
}
const { parentNode } = target;
const index = Array.from( parentNode.childNodes ).indexOf( target );
const range = getDoc().createRange();
const selection = getWin().getSelection();
range.setStart( target.parentNode, index );
range.setEnd( target.parentNode, index + 1 );
selection.removeAllRanges();
selection.addRange( range );
}
const rafId = useRef();
/**
* Handles a focus event on the contenteditable field, calling the
* `unstableOnFocus` prop callback if one is defined. The callback does not
* receive any arguments.
*
* This is marked as a private API and the `unstableOnFocus` prop is not
* documented, as the current requirements where it is used are subject to
* future refactoring following `isSelected` handling.
*
* @private
*/
function handleFocus() {
if ( onFocus ) {
onFocus();
}
if ( ! isSelected ) {
// We know for certain that on focus, the old selection is invalid.
// It will be recalculated on the next mouseup, keyup, or touchend
// event.
const index = undefined;
record.current = {
...record.current,
start: index,
end: index,
activeFormats: EMPTY_ACTIVE_FORMATS,
};
onSelectionChange( index, index );
setActiveFormats( EMPTY_ACTIVE_FORMATS );
} else {
onSelectionChange( record.current.start, record.current.end );
setActiveFormats(
getActiveFormats(
{
...record.current,
activeFormats: undefined,
},
EMPTY_ACTIVE_FORMATS
)
);
}
// Update selection as soon as possible, which is at the next animation
// frame. The event listener for selection changes may be added too late
// at this point, but this focus event is still too early to calculate
// the selection.
rafId.current = getWin().requestAnimationFrame( handleSelectionChange );
getDoc().addEventListener( 'selectionchange', handleSelectionChange );
}
function handleBlur() {
getDoc().removeEventListener(
'selectionchange',
handleSelectionChange
);
if ( onBlur ) {
onBlur();
}
}
function applyFromProps() {
_value.current = value;
record.current = formatToValue( value );
record.current.start = selectionStart;