-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
1018 lines (880 loc) · 28.7 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
/**
* External dependencies
*/
import classnames from 'classnames';
import {
defer,
find,
isNil,
isEqual,
omit,
} from 'lodash';
import memize from 'memize';
/**
* WordPress dependencies
*/
import { Component, Fragment, RawHTML } from '@wordpress/element';
import {
isHorizontalEdge,
getRectangleFromRange,
getScrollContainer,
} from '@wordpress/dom';
import { createBlobURL } from '@wordpress/blob';
import { BACKSPACE, DELETE, ENTER, rawShortcut } from '@wordpress/keycodes';
import { withDispatch, withSelect } from '@wordpress/data';
import { rawHandler, children, getBlockTransforms, findTransform } from '@wordpress/blocks';
import { withInstanceId, withSafeTimeout, compose } from '@wordpress/compose';
import { isURL } from '@wordpress/url';
import {
isEmpty,
create,
apply,
applyFormat,
split,
toHTMLString,
getTextContent,
insert,
insertLineSeparator,
isEmptyLine,
unstableToDom,
getSelectionStart,
getSelectionEnd,
remove,
isCollapsed,
} from '@wordpress/rich-text';
import { decodeEntities } from '@wordpress/html-entities';
/**
* Internal dependencies
*/
import Autocomplete from '../autocomplete';
import BlockFormatControls from '../block-format-controls';
import FormatEdit from './format-edit';
import FormatToolbar from './format-toolbar';
import TinyMCE, { TINYMCE_ZWSP } from './tinymce';
import { pickAriaProps } from './aria';
import { getPatterns } from './patterns';
import { withBlockEditContext } from '../block-edit/context';
/**
* Browser dependencies
*/
const { getSelection } = window;
export class RichText extends Component {
constructor( { value, onReplace, multiline } ) {
super( ...arguments );
if ( multiline === true || multiline === 'p' || multiline === 'li' ) {
this.multilineTag = multiline === true ? 'p' : multiline;
}
if ( this.multilineTag === 'li' ) {
this.multilineWrapperTags = [ 'ul', 'ol' ];
}
this.onInit = this.onInit.bind( this );
this.getSettings = this.getSettings.bind( this );
this.onSetup = this.onSetup.bind( this );
this.onFocus = this.onFocus.bind( this );
this.onChange = this.onChange.bind( this );
this.onNodeChange = this.onNodeChange.bind( this );
this.onDeleteKeyDown = this.onDeleteKeyDown.bind( this );
this.onKeyDown = this.onKeyDown.bind( this );
this.onKeyUp = this.onKeyUp.bind( this );
this.onPropagateUndo = this.onPropagateUndo.bind( this );
this.onPaste = this.onPaste.bind( this );
this.onCreateUndoLevel = this.onCreateUndoLevel.bind( this );
this.setFocusedElement = this.setFocusedElement.bind( this );
this.onInput = this.onInput.bind( this );
this.onSelectionChange = this.onSelectionChange.bind( this );
this.getRecord = this.getRecord.bind( this );
this.createRecord = this.createRecord.bind( this );
this.applyRecord = this.applyRecord.bind( this );
this.isEmpty = this.isEmpty.bind( this );
this.valueToFormat = this.valueToFormat.bind( this );
this.setRef = this.setRef.bind( this );
this.isActive = this.isActive.bind( this );
this.formatToValue = memize( this.formatToValue.bind( this ), { size: 1 } );
this.savedContent = value;
this.patterns = getPatterns( {
onReplace,
multilineTag: this.multilineTag,
valueToFormat: this.valueToFormat,
} );
this.enterPatterns = getBlockTransforms( 'from' ).filter( ( { type, trigger } ) =>
type === 'pattern' && trigger === 'enter'
);
this.state = {};
this.usedDeprecatedChildrenSource = Array.isArray( value );
}
componentDidMount() {
document.addEventListener( 'selectionchange', this.onSelectionChange );
}
componentWillUnmount() {
document.removeEventListener( 'selectionchange', this.onSelectionChange );
}
setRef( node ) {
this.editableRef = node;
}
isActive() {
return this.editableRef === document.activeElement;
}
/**
* Retrieves the settings for this block.
*
* Allows passing in settings which will be overwritten.
*
* @param {Object} settings The settings to overwrite.
* @return {Object} The settings for this block.
*/
getSettings( settings ) {
settings = {
...settings,
forced_root_block: this.multilineTag || false,
// Allow TinyMCE to keep one undo level for comparing changes.
// Prevent it otherwise from accumulating any history.
custom_undo_redo_levels: 1,
};
const { unstableGetSettings } = this.props;
if ( unstableGetSettings ) {
settings = unstableGetSettings( settings );
}
return settings;
}
/**
* Handles the onSetup event for the TinyMCE component.
*
* Will setup event handlers for the TinyMCE instance.
* An `onSetup` function in the props will be called if it is present.
*
* @param {tinymce} editor The editor instance as passed by TinyMCE.
*/
onSetup( editor ) {
this.editor = editor;
editor.on( 'init', this.onInit );
editor.on( 'nodechange', this.onNodeChange );
editor.on( 'BeforeExecCommand', this.onPropagateUndo );
// The change event in TinyMCE fires every time an undo level is added.
editor.on( 'change', this.onCreateUndoLevel );
const { unstableOnSetup } = this.props;
if ( unstableOnSetup ) {
unstableOnSetup( editor );
}
}
setFocusedElement() {
if ( this.props.setFocusedElement ) {
this.props.setFocusedElement( this.props.instanceId );
}
}
onInit() {
this.editor.shortcuts.add( rawShortcut.primary( 'z' ), '', 'Undo' );
this.editor.shortcuts.add( rawShortcut.primaryShift( 'z' ), '', 'Redo' );
// Remove TinyMCE Core shortcut for consistency with global editor
// shortcuts. Also clashes with Mac browsers.
this.editor.shortcuts.remove( 'meta+y', '', 'Redo' );
}
/**
* Handles an undo event from TinyMCE.
*
* @param {UndoEvent} event The undo event as triggered by TinyMCE.
*/
onPropagateUndo( event ) {
const { onUndo, onRedo } = this.props;
const { command } = event;
if ( command === 'Undo' && onUndo ) {
defer( onUndo );
event.preventDefault();
}
if ( command === 'Redo' && onRedo ) {
defer( onRedo );
event.preventDefault();
}
}
/**
* Get the current record (value and selection) from props and state.
*
* @return {Object} The current record (value and selection).
*/
getRecord() {
const { formats, text } = this.formatToValue( this.props.value );
const { start, end } = this.state;
return { formats, text, start, end };
}
createRecord() {
const range = getSelection().getRangeAt( 0 );
return create( {
element: this.editableRef,
range,
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
removeNode: ( node ) => node.getAttribute( 'data-mce-bogus' ) === 'all',
unwrapNode: ( node ) => !! node.getAttribute( 'data-mce-bogus' ),
removeAttribute: ( attribute ) => attribute.indexOf( 'data-mce-' ) === 0,
filterString: ( string ) => string.replace( TINYMCE_ZWSP, '' ),
} );
}
applyRecord( record ) {
apply( {
value: record,
current: this.editableRef,
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
createLinePadding( doc ) {
const element = doc.createElement( 'br' );
element.setAttribute( 'data-mce-bogus', '1' );
return element;
},
} );
}
isEmpty() {
return isEmpty( this.formatToValue( this.props.value ) );
}
/**
* Handles a paste event.
*
* Saves the pasted data as plain text in `pastedPlainText`.
*
* @param {PasteEvent} event The paste event.
*/
onPaste( event ) {
const clipboardData = event.clipboardData;
let { items, files } = clipboardData;
// In Edge these properties can be null instead of undefined, so a more
// rigorous test is required over using default values.
items = isNil( items ) ? [] : items;
files = isNil( files ) ? [] : files;
const item = find( [ ...items, ...files ], ( { type } ) => /^image\/(?:jpe?g|png|gif)$/.test( type ) );
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 );
// Only process file if no HTML is present.
// Note: a pasted file may have the URL as plain text.
if ( item && ! html ) {
const file = item.getAsFile ? item.getAsFile() : item;
const content = rawHandler( {
HTML: `<img src="${ createBlobURL( file ) }">`,
mode: 'BLOCKS',
tagName: this.props.tagName,
} );
const shouldReplace = this.props.onReplace && this.isEmpty();
// Allows us to ask for this information when we get a report.
window.console.log( 'Received item:\n\n', file );
if ( shouldReplace ) {
// Necessary to allow the paste bin to be removed without errors.
this.props.setTimeout( () => this.props.onReplace( content ) );
} else if ( this.props.onSplit ) {
// Necessary to get the right range.
// Also done in the TinyMCE paste plugin.
this.props.setTimeout( () => this.splitContent( content ) );
}
return;
}
// There is a selection, check if a URL is pasted.
if ( ! this.editor.selection.isCollapsed() ) {
const pastedText = ( html || plainText ).replace( /<[^>]+>/g, '' ).trim();
// A URL was pasted, turn the selection into a link
if ( isURL( pastedText ) ) {
this.onChange( applyFormat( this.getRecord(), {
type: 'a',
attributes: {
href: decodeEntities( pastedText ),
},
} ) );
// Allows us to ask for this information when we get a report.
window.console.log( 'Created link:\n\n', pastedText );
return;
}
}
const shouldReplace = this.props.onReplace && this.isEmpty();
let mode = 'INLINE';
if ( shouldReplace ) {
mode = 'BLOCKS';
} else if ( this.props.onSplit ) {
mode = 'AUTO';
}
const content = rawHandler( {
HTML: html,
plainText,
mode,
tagName: this.props.tagName,
canUserUseUnfilteredHTML: this.props.canUserUseUnfilteredHTML,
} );
if ( typeof content === 'string' ) {
const recordToInsert = create( { html: content } );
this.onChange( insert( this.getRecord(), recordToInsert ) );
} else if ( this.props.onSplit ) {
if ( ! content.length ) {
return;
}
if ( shouldReplace ) {
this.props.onReplace( content );
} else {
this.splitContent( content, { paste: true } );
}
}
}
/**
* 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.
*
* In contrast with `setFocusedElement`, this is only triggered in response
* to focus within the contenteditable field, whereas `setFocusedElement`
* is triggered on focus within any `RichText` descendent element.
*
* @see setFocusedElement
*
* @private
*/
onFocus() {
const { unstableOnFocus } = this.props;
if ( unstableOnFocus ) {
unstableOnFocus();
}
}
/**
* Handle input on the next selection change event.
*/
onInput() {
const record = this.createRecord();
const transformed = this.patterns.reduce( ( accumlator, transform ) => transform( accumlator ), record );
// Don't apply changes if there's no transform. Content will be up to
// date. In the future we could always let it flow back in the live DOM
// if there are no performance issues.
this.onChange( transformed, record === transformed );
}
/**
* Handles the `selectionchange` event: sync the selection to local state.
*/
onSelectionChange() {
// Ensure it's the active element. This is a global event.
if ( ! this.isActive() ) {
return;
}
const { start, end, formats } = this.createRecord();
if ( start !== this.state.start || end !== this.state.end ) {
const isCaretWithinFormattedText = this.props.isCaretWithinFormattedText;
if ( ! isCaretWithinFormattedText && formats[ start ] ) {
this.props.onEnterFormattedText();
} else if ( isCaretWithinFormattedText && ! formats[ start ] ) {
this.props.onExitFormattedText();
}
this.setState( { start, end } );
}
}
/**
* Sync the value to global state. The node tree and selection will also be
* updated if differences are found.
*
* @param {Object} record The record to sync and apply.
* @param {boolean} _withoutApply If true, the record won't be applied to
* the live DOM.
*/
onChange( record, _withoutApply ) {
if ( ! _withoutApply ) {
this.applyRecord( record );
}
const { start, end } = record;
this.savedContent = this.valueToFormat( record );
this.props.onChange( this.savedContent );
this.setState( { start, end } );
}
onCreateUndoLevel( event ) {
// TinyMCE fires a `change` event when the first letter in an instance
// is typed. This should not create a history record in Gutenberg.
// https://github.com/tinymce/tinymce/blob/4.7.11/src/core/main/ts/api/UndoManager.ts#L116-L125
// In other cases TinyMCE won't fire a `change` with at least a previous
// record present, so this is a reliable check.
// https://github.com/tinymce/tinymce/blob/4.7.11/src/core/main/ts/api/UndoManager.ts#L272-L275
if ( event && event.lastLevel === null ) {
return;
}
// Always ensure the content is up-to-date. This is needed because e.g.
// making something bold will trigger a TinyMCE change event but no
// input event. Avoid dispatching an action if the original event is
// blur because the content will already be up-to-date.
if ( ! event || ! event.originalEvent || event.originalEvent.type !== 'blur' ) {
this.onChange( this.createRecord(), true );
}
this.props.onCreateUndoLevel();
}
/**
* Handles a delete keyDown event to handle merge or removal for collapsed
* selection where caret is at directional edge: forward for a delete key,
* reverse for a backspace key.
*
* @link https://en.wikipedia.org/wiki/Caret_navigation
*
* @param {KeyboardEvent} event Keydown event.
*
* @return {?boolean} True if the event was handled.
*/
onDeleteKeyDown( event ) {
const { onMerge, onRemove } = this.props;
if ( ! onMerge && ! onRemove ) {
return;
}
const { keyCode } = event;
const isReverse = keyCode === BACKSPACE;
// Only process delete if the key press occurs at uncollapsed edge.
if ( ! isCollapsed( this.createRecord() ) ) {
return;
}
const empty = this.isEmpty();
// It is important to consider emptiness because an empty container
// will include a bogus TinyMCE BR node _after_ the caret, so in a
// forward deletion the isHorizontalEdge function will incorrectly
// interpret the presence of the bogus node as not being at the edge.
const isEdge = ( empty || isHorizontalEdge( this.editableRef, isReverse ) );
if ( ! isEdge ) {
return;
}
if ( onMerge ) {
onMerge( ! isReverse );
}
// Only handle remove on Backspace. This serves dual-purpose of being
// an intentional user interaction distinguishing between Backspace and
// Delete to remove the empty field, but also to avoid merge & remove
// causing destruction of two fields (merge, then removed merged).
if ( onRemove && empty && isReverse ) {
onRemove( ! isReverse );
}
return true;
}
/**
* Handles a keydown event.
*
* @param {KeyboardEvent} event The keydown event.
*/
onKeyDown( event ) {
const { keyCode } = event;
if ( keyCode === DELETE || keyCode === BACKSPACE ) {
event.preventDefault();
if ( this.onDeleteKeyDown( event ) ) {
return;
}
const value = this.createRecord();
const start = getSelectionStart( value );
const end = getSelectionEnd( value );
if ( keyCode === BACKSPACE ) {
this.onChange( remove(
value,
// Only remove the line if the selection is
// collapsed.
isCollapsed( value ) ? start - 1 : start,
end
) );
} else {
this.onChange( remove(
value,
start,
// Only remove the line if the selection is collapsed.
isCollapsed( value ) ? end + 1 : end,
) );
}
} else if ( keyCode === ENTER ) {
event.preventDefault();
const record = this.createRecord();
if ( this.props.onReplace ) {
const text = getTextContent( record );
const transformation = findTransform( this.enterPatterns, ( item ) => {
return item.regExp.test( text );
} );
if ( transformation ) {
this.props.onReplace( [
transformation.transform( { content: text } ),
] );
return;
}
}
if ( this.multilineTag ) {
if ( this.props.onSplit && isEmptyLine( record ) ) {
this.props.onSplit( ...split( record ).map( this.valueToFormat ) );
} else {
this.onChange( insertLineSeparator( record ) );
}
} else if ( event.shiftKey || ! this.props.onSplit ) {
const text = getTextContent( record );
const length = text.length;
let toInsert = '\n';
// If the caret is at the end of the text, and there is no
// trailing line break or no text at all, we have to insert two
// line breaks in order to create a new line visually and place
// the caret there.
if ( record.end === length && (
text.charAt( length - 1 ) !== '\n' || length === 0
) ) {
toInsert = '\n\n';
}
this.onChange( insert( record, toInsert ) );
} else {
this.splitContent();
}
}
}
/**
* Handles a keyup event.
*
* @param {number} $1.keyCode The key code that has been pressed on the
* keyboard.
*/
onKeyUp( { keyCode } ) {
// The input event does not fire when the whole field is selected and
// BACKSPACE is pressed.
if ( keyCode === BACKSPACE ) {
this.onChange( this.createRecord(), true );
}
// `scrollToRect` is called on `nodechange`, whereas calling it on
// `keyup` *when* moving to a new RichText element results in incorrect
// scrolling. Though the following allows false positives, it results
// in much smoother scrolling.
if ( this.props.isViewportSmall && keyCode !== BACKSPACE && keyCode !== ENTER ) {
this.scrollToRect( getRectangleFromRange( this.editor.selection.getRng() ) );
}
}
scrollToRect( rect ) {
const { top: caretTop } = rect;
const container = getScrollContainer( this.editableRef );
if ( ! container ) {
return;
}
// When scrolling, avoid positioning the caret at the very top of
// the viewport, providing some "air" and some textual context for
// the user, and avoiding toolbars.
const graceOffset = 100;
// Avoid pointless scrolling by establishing a threshold under
// which scrolling should be skipped;
const epsilon = 10;
const delta = caretTop - graceOffset;
if ( Math.abs( delta ) > epsilon ) {
container.scrollTo(
container.scrollLeft,
container.scrollTop + delta,
);
}
}
/**
* Splits the content at the location of the selection.
*
* Replaces the content of the editor inside this element with the contents
* before the selection. Sends the elements after the selection to the `onSplit`
* handler.
*
* @param {Array} blocks The blocks to add after the split point.
* @param {Object} context The context for splitting.
*/
splitContent( blocks = [], context = {} ) {
const { onSplit } = this.props;
const record = this.createRecord();
if ( ! onSplit ) {
return;
}
let [ before, after ] = split( record );
// In case split occurs at the trailing or leading edge of the field,
// assume that the before/after values respectively reflect the current
// value. This also provides an opportunity for the parent component to
// determine whether the before/after value has changed using a trivial
// strict equality operation.
if ( isEmpty( after ) ) {
before = record;
} else if ( isEmpty( before ) ) {
after = record;
}
// If pasting and the split would result in no content other than the
// pasted blocks, remove the before and after blocks.
if ( context.paste ) {
before = isEmpty( before ) ? null : before;
after = isEmpty( after ) ? null : after;
}
if ( before ) {
before = this.valueToFormat( before );
}
if ( after ) {
after = this.valueToFormat( after );
}
onSplit( before, after, ...blocks );
}
onNodeChange( { parents } ) {
if ( ! this.isActive() ) {
return;
}
if ( this.props.isViewportSmall ) {
let rect;
const selectedAnchor = find( parents, ( node ) => node.tagName === 'A' );
if ( selectedAnchor ) {
// If we selected a link, position the Link UI below the link
rect = selectedAnchor.getBoundingClientRect();
} else {
// Otherwise, position the Link UI below the cursor or text selection
rect = getRectangleFromRange( this.editor.selection.getRng() );
}
// Originally called on `focusin`, that hook turned out to be
// premature. On `nodechange` we can work with the finalized TinyMCE
// instance and scroll to proper position.
this.scrollToRect( rect );
}
}
componentDidUpdate( prevProps ) {
const { tagName, value, isSelected } = this.props;
if (
tagName === prevProps.tagName &&
value !== prevProps.value &&
value !== this.savedContent
) {
// Handle deprecated `children` and `node` sources.
// The old way of passing a value with the `node` matcher required
// the value to be mapped first, creating a new array each time, so
// a shallow check wouldn't work. We need to check deep equality.
// This is only executed for a deprecated API and will eventually be
// removed.
if ( Array.isArray( value ) && isEqual( value, this.savedContent ) ) {
return;
}
const record = this.formatToValue( value );
if ( isSelected ) {
const prevRecord = this.formatToValue( prevProps.value );
const length = getTextContent( prevRecord ).length;
record.start = length;
record.end = length;
}
this.applyRecord( record );
this.savedContent = value;
}
// If blocks are merged, but the content remains the same, e.g. merging
// an empty paragraph into another, then also set the selection to the
// end.
if ( isSelected && ! prevProps.isSelected && ! this.isActive() ) {
const record = this.formatToValue( value );
const prevRecord = this.formatToValue( prevProps.value );
const length = getTextContent( prevRecord ).length;
record.start = length;
record.end = length;
this.applyRecord( record );
}
}
formatToValue( value ) {
// Handle deprecated `children` and `node` sources.
if ( Array.isArray( value ) ) {
return create( {
html: children.toHTML( value ),
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
} );
}
if ( this.props.format === 'string' ) {
return create( {
html: value,
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
} );
}
// Guard for blocks passing `null` in onSplit callbacks. May be removed
// if onSplit is revised to not pass a `null` value.
if ( value === null ) {
return create();
}
return value;
}
valueToFormat( { formats, text } ) {
// Handle deprecated `children` and `node` sources.
if ( this.usedDeprecatedChildrenSource ) {
return children.fromDOM( unstableToDom( {
value: { formats, text },
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
} ).body.childNodes );
}
if ( this.props.format === 'string' ) {
return toHTMLString( {
value: { formats, text },
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
} );
}
return { formats, text };
}
render() {
const {
tagName: Tagname = 'div',
style,
value,
wrapperClassName,
className,
inlineToolbar = false,
formattingControls,
placeholder,
keepPlaceholderOnFocus = false,
isSelected,
autocompleters,
} = this.props;
const MultilineTag = this.multilineTag;
const ariaProps = pickAriaProps( this.props );
// Generating a key that includes `tagName` ensures that if the tag
// changes, we unmount and destroy the previous TinyMCE element, then
// mount and initialize a new child element in its place.
const key = [ 'editor', Tagname ].join();
const isPlaceholderVisible = placeholder && ( ! isSelected || keepPlaceholderOnFocus ) && this.isEmpty();
const classes = classnames( wrapperClassName, 'editor-rich-text' );
const record = this.getRecord();
return (
<div className={ classes }
onFocus={ this.setFocusedElement }
>
{ isSelected && ! inlineToolbar && (
<BlockFormatControls>
<FormatToolbar controls={ formattingControls } />
</BlockFormatControls>
) }
{ isSelected && inlineToolbar && (
<div className="editor-rich-text__inline-toolbar">
<FormatToolbar controls={ formattingControls } />
</div>
) }
<Autocomplete
onReplace={ this.props.onReplace }
completers={ autocompleters }
record={ record }
onChange={ this.onChange }
>
{ ( { isExpanded, listBoxId, activeId } ) => (
<Fragment>
<TinyMCE
tagName={ Tagname }
getSettings={ this.getSettings }
onSetup={ this.onSetup }
style={ style }
defaultValue={ value }
isPlaceholderVisible={ isPlaceholderVisible }
aria-label={ placeholder }
aria-autocomplete="list"
aria-expanded={ isExpanded }
aria-owns={ listBoxId }
aria-activedescendant={ activeId }
{ ...ariaProps }
className={ className }
key={ key }
onPaste={ this.onPaste }
onInput={ this.onInput }
onKeyDown={ this.onKeyDown }
onKeyUp={ this.onKeyUp }
onFocus={ this.onFocus }
multilineTag={ this.multilineTag }
multilineWrapperTags={ this.multilineWrapperTags }
setRef={ this.setRef }
/>
{ isPlaceholderVisible &&
<Tagname
className={ classnames( 'editor-rich-text__tinymce', className ) }
style={ style }
>
{ MultilineTag ? <MultilineTag>{ placeholder }</MultilineTag> : placeholder }
</Tagname>
}
{ isSelected && <FormatEdit value={ record } onChange={ this.onChange } /> }
</Fragment>
) }
</Autocomplete>
</div>
);
}
}
RichText.defaultProps = {
formattingControls: [ 'bold', 'italic', 'link', 'strikethrough' ],
format: 'string',
value: '',
};
const RichTextContainer = compose( [
withInstanceId,
withBlockEditContext( ( context, ownProps ) => {
// When explicitly set as not selected, do nothing.
if ( ownProps.isSelected === false ) {
return {};
}
// When explicitly set as selected, use the value stored in the context instead.
if ( ownProps.isSelected === true ) {
return {
isSelected: context.isSelected,
};
}
// Ensures that only one RichText component can be focused.
return {
isSelected: context.isSelected && context.focusedElement === ownProps.instanceId,
setFocusedElement: context.setFocusedElement,
};
} ),
withSelect( ( select ) => {
const { isViewportMatch } = select( 'core/viewport' );
const { canUserUseUnfilteredHTML, isCaretWithinFormattedText } = select( 'core/editor' );
return {
isViewportSmall: isViewportMatch( '< small' ),
canUserUseUnfilteredHTML: canUserUseUnfilteredHTML(),
isCaretWithinFormattedText: isCaretWithinFormattedText(),
};
} ),
withDispatch( ( dispatch ) => {
const {
createUndoLevel,
redo,
undo,
enterFormattedText,
exitFormattedText,
} = dispatch( 'core/editor' );
return {
onCreateUndoLevel: createUndoLevel,
onRedo: redo,
onUndo: undo,
onEnterFormattedText: enterFormattedText,
onExitFormattedText: exitFormattedText,
};
} ),
withSafeTimeout,
] )( RichText );
RichTextContainer.Content = ( { value, tagName: Tag, multiline, ...props } ) => {
let html = value;
let MultilineTag;
if ( multiline === true || multiline === 'p' || multiline === 'li' ) {
MultilineTag = multiline === true ? 'p' : multiline;
}
// Handle deprecated `children` and `node` sources.
if ( Array.isArray( value ) ) {
html = children.toHTML( value );
}
if ( ! html && MultilineTag ) {
html = `<${ MultilineTag }></${ MultilineTag }>`;
}
const content = <RawHTML>{ html }</RawHTML>;
if ( Tag ) {
return <Tag { ...omit( props, [ 'format' ] ) }>{ content }</Tag>;
}