-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
982 lines (847 loc) · 29.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
/**
* External dependencies
*/
import classnames from 'classnames';
import {
isEqual,
forEach,
merge,
identity,
find,
defer,
noop,
} from 'lodash';
import 'element-closest';
/**
* WordPress dependencies
*/
import { Component, Fragment, RawHTML, createRef } from '@wordpress/element';
import {
isHorizontalEdge,
getRectangleFromRange,
getScrollContainer,
} from '@wordpress/dom';
import { createBlobURL } from '@wordpress/blob';
import { BACKSPACE, DELETE, ENTER, LEFT, RIGHT, rawShortcut, isKeyboardEvent } from '@wordpress/keycodes';
import { Slot } from '@wordpress/components';
import { withSelect } from '@wordpress/data';
import { rawHandler, children } from '@wordpress/blocks';
import { withInstanceId, withSafeTimeout, compose } from '@wordpress/compose';
/**
* Internal dependencies
*/
import Autocomplete from '../autocomplete';
import BlockFormatControls from '../block-format-controls';
import FormatToolbar from './format-toolbar';
import TinyMCE from './tinymce';
import { pickAriaProps } from './aria';
import patterns from './patterns';
import { withBlockEditContext } from '../block-edit/context';
import { domToFormat, valueToString } from './format';
import TokenUI from './tokens/ui';
/**
* Browser dependencies
*/
const { Node, getSelection } = window;
/**
* Zero-width space character used by TinyMCE as a caret landing point for
* inline boundary nodes.
*
* @see tinymce/src/core/main/ts/text/Zwsp.ts
*
* @type {string}
*/
const TINYMCE_ZWSP = '\uFEFF';
export function getFormatProperties( formatName, parents ) {
switch ( formatName ) {
case 'link' : {
const anchor = find( parents, ( node ) => node.nodeName.toLowerCase() === 'a' );
return !! anchor ? { value: anchor.getAttribute( 'href' ) || '', target: anchor.getAttribute( 'target' ) || '', node: anchor } : {};
}
default:
return {};
}
}
const DEFAULT_FORMATS = [ 'bold', 'italic', 'strikethrough', 'link', 'code' ];
export class RichText extends Component {
constructor() {
super( ...arguments );
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.onHorizontalNavigationKeyDown = this.onHorizontalNavigationKeyDown.bind( this );
this.onKeyDown = this.onKeyDown.bind( this );
this.onKeyUp = this.onKeyUp.bind( this );
this.changeFormats = this.changeFormats.bind( this );
this.onPropagateUndo = this.onPropagateUndo.bind( this );
this.onPastePreProcess = this.onPastePreProcess.bind( this );
this.onPaste = this.onPaste.bind( this );
this.onCreateUndoLevel = this.onCreateUndoLevel.bind( this );
this.setFocusedElement = this.setFocusedElement.bind( this );
this.state = {
formats: {},
selectedNodeId: 0,
};
this.containerRef = createRef();
}
/**
* 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 ) {
return ( this.props.getSettings || identity )( {
...settings,
forced_root_block: this.props.multiline || false,
// Allow TinyMCE to keep one undo level for comparing changes.
// Prevent it otherwise from accumulating any history.
custom_undo_redo_levels: 1,
} );
}
/**
* 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( 'keydown', this.onKeyDown );
editor.on( 'keyup', this.onKeyUp );
editor.on( 'BeforeExecCommand', this.onPropagateUndo );
editor.on( 'PastePreProcess', this.onPastePreProcess, true /* Add before core handlers */ );
editor.on( 'paste', this.onPaste, true /* Add before core handlers */ );
editor.on( 'focus', this.onFocus );
editor.on( 'input', this.onChange );
// The change event in TinyMCE fires every time an undo level is added.
editor.on( 'change', this.onCreateUndoLevel );
patterns.apply( this, [ editor ] );
if ( this.props.onSetup ) {
this.props.onSetup( editor );
}
}
setFocusedElement() {
if ( this.props.setFocusedElement ) {
this.props.setFocusedElement( this.props.instanceId );
}
}
onInit() {
this.registerCustomFormatters();
this.editor.shortcuts.add( rawShortcut.primary( 'k' ), '', () => this.changeFormats( { link: { isAdding: true } } ) );
this.editor.shortcuts.add( rawShortcut.access( 'a' ), '', () => this.changeFormats( { link: { isAdding: true } } ) );
this.editor.shortcuts.add( rawShortcut.access( 's' ), '', () => this.changeFormats( { link: undefined } ) );
this.editor.shortcuts.add( rawShortcut.access( 'd' ), '', () => this.changeFormats( { strikethrough: ! this.state.formats.strikethrough } ) );
this.editor.shortcuts.add( rawShortcut.access( 'x' ), '', () => this.changeFormats( { code: ! this.state.formats.code } ) );
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' );
}
adaptFormatter( options ) {
switch ( options.type ) {
case 'inline-style': {
return {
inline: 'span',
styles: { ...options.style },
};
}
}
}
registerCustomFormatters() {
forEach( this.props.formatters, ( formatter ) => {
this.editor.formatter.register( formatter.format, this.adaptFormatter( formatter ) );
} );
}
/**
* Handles an undo event from TinyMCE.
*
* @param {UndoEvent} event The undo event as triggered by TinyMCE.
*/
onPropagateUndo( event ) {
const { onUndo, onRedo } = this.context;
const { command } = event;
if ( command === 'Undo' && onUndo ) {
defer( onUndo );
event.preventDefault();
}
if ( command === 'Redo' && onRedo ) {
defer( onRedo );
event.preventDefault();
}
}
/**
* Handles a paste event from TinyMCE.
*
* Saves the pasted data as plain text in `pastedPlainText`.
*
* @param {PasteEvent} event The paste event as triggered by TinyMCE.
*/
onPaste( event ) {
const dataTransfer =
event.clipboardData ||
event.dataTransfer ||
this.editor.getDoc().dataTransfer ||
// Removes the need for further `dataTransfer` checks.
{ getData: () => '' };
const { items = [], files = [], types = [] } = dataTransfer;
const item = find( [ ...items, ...files ], ( { type } ) => /^image\/(?:jpe?g|png|gif)$/.test( type ) );
const plainText = dataTransfer.getData( 'text/plain' );
const HTML = dataTransfer.getData( 'text/html' );
// 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 ) );
}
event.preventDefault();
}
this.pastedPlainText = plainText;
this.isPlainTextPaste = types.length === 1 && types[ 0 ] === 'text/plain';
}
/**
* Handles a PrePasteProcess event from TinyMCE.
*
* Will call the paste handler with the pasted data. If it is a string tries
* to put it in the containing TinyMCE editor. Otherwise call the `onSplit`
* handler.
*
* @param {PrePasteProcessEvent} event The PrePasteProcess event as triggered
* by TinyMCE.
*/
onPastePreProcess( event ) {
const HTML = this.isPlainTextPaste ? '' : event.content;
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', this.pastedPlainText );
// There is a selection, check if a URL is pasted.
if ( ! this.editor.selection.isCollapsed() ) {
const linkRegExp = /^(?:https?:)?\/\/\S+$/i;
const pastedText = event.content.replace( /<[^>]+>/g, '' ).trim();
// A URL was pasted, turn the selection into a link
if ( linkRegExp.test( pastedText ) ) {
this.editor.execCommand( 'mceInsertLink', false, {
href: this.editor.dom.decode( 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,
plainText: this.pastedPlainText,
mode,
tagName: this.props.tagName,
canUserUseUnfilteredHTML: this.props.canUserUseUnfilteredHTML,
} );
if ( typeof content === 'string' ) {
this.editor.insertContent( content );
} 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();
}
}
/**
* Handles any case where the content of the TinyMCE instance has changed.
*/
onChange() {
this.savedContent = this.getContent();
this.props.onChange( this.savedContent );
}
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.context.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 {tinymce.EditorEvent<KeyboardEvent>} event Keydown event.
*/
onDeleteKeyDown( event ) {
const { onMerge, onRemove } = this.props;
if ( ! onMerge && ! onRemove ) {
return;
}
const { keyCode } = event;
const isReverse = keyCode === BACKSPACE;
// User is using the Remove Block shortcut, so allow the event to bubble
// up to the BlockSettingsMenu component
if ( isKeyboardEvent.primaryAlt( event, 'Backspace' ) ) {
return;
}
const { isCollapsed } = getSelection();
// Only process delete if the key press occurs at uncollapsed edge.
if ( ! isCollapsed ) {
return;
}
// 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 isEmpty = this.isEmpty();
const isEdge = (
isEmpty ||
isHorizontalEdge( this.editor.getBody(), 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 && isEmpty && isReverse ) {
onRemove( ! isReverse );
}
event.preventDefault();
// Calling onMerge() or onRemove() will destroy the editor, so it's
// important that we stop other handlers (e.g. ones registered by
// TinyMCE) from also handling this event.
event.stopImmediatePropagation();
}
/**
* Handles a horizontal navigation key down event to handle the case where
* TinyMCE attempts to preventDefault when on the outside edge of an inline
* boundary when arrowing _away_ from the boundary, not within it. Replaces
* the TinyMCE event `preventDefault` behavior with a noop, such that those
* relying on `defaultPrevented` are not misinformed about the arrow event.
*
* If TinyMCE#4476 is resolved, this handling may be removed.
*
* @see https://github.com/tinymce/tinymce/issues/4476
*
* @param {tinymce.EditorEvent<KeyboardEvent>} event Keydown event.
*/
onHorizontalNavigationKeyDown( event ) {
const { focusNode } = getSelection();
const { nodeType, nodeValue } = focusNode;
if ( nodeType !== Node.TEXT_NODE ) {
return;
}
if ( nodeValue.length !== 1 || nodeValue[ 0 ] !== TINYMCE_ZWSP ) {
return;
}
const { keyCode } = event;
// Consider to be moving away from inline boundary based on:
//
// 1. Within a text fragment consisting only of ZWSP.
// 2. If in reverse, there is no previous sibling. If forward, there is
// no next sibling (i.e. end of node).
const isReverse = keyCode === LEFT;
const edgeSibling = isReverse ? 'previousSibling' : 'nextSibling';
if ( ! focusNode[ edgeSibling ] ) {
// Note: This is not reassigning on the native event, rather the
// "fixed" TinyMCE copy, which proxies its preventDefault to the
// native event. By reassigning here, we're effectively preventing
// the proxied call on the native event, but not otherwise mutating
// the original event object.
event.preventDefault = noop;
}
}
/**
* Handles a keydown event from TinyMCE.
*
* @param {KeydownEvent} event The keydown event as triggered by TinyMCE.
*/
onKeyDown( event ) {
const dom = this.editor.dom;
const rootNode = this.editor.getBody();
const { keyCode } = event;
const isDelete = keyCode === DELETE || keyCode === BACKSPACE;
if ( isDelete ) {
this.onDeleteKeyDown( event );
}
const isHorizontalNavigation = keyCode === LEFT || keyCode === RIGHT;
if ( isHorizontalNavigation ) {
this.onHorizontalNavigationKeyDown( event );
}
// If we click shift+Enter on inline RichTexts, we avoid creating two contenteditables
// We also split the content and call the onSplit prop if provided.
if ( keyCode === ENTER ) {
if ( this.props.multiline ) {
if ( ! this.props.onSplit ) {
return;
}
const selectedNode = this.editor.selection.getNode();
if ( selectedNode.parentNode !== rootNode ) {
return;
}
if ( ! dom.isEmpty( selectedNode ) ) {
return;
}
event.preventDefault();
const childNodes = Array.from( rootNode.childNodes );
const index = dom.nodeIndex( selectedNode );
const beforeNodes = childNodes.slice( 0, index );
const afterNodes = childNodes.slice( index + 1 );
const { format } = this.props;
const before = domToFormat( beforeNodes, format );
const after = domToFormat( afterNodes, format );
this.props.onSplit( before, after );
} else {
event.preventDefault();
if ( event.shiftKey || ! this.props.onSplit ) {
this.editor.execCommand( 'InsertLineBreak', false, event );
} else {
this.splitContent();
}
}
}
}
/**
* Handles TinyMCE key up event.
*
* @param {number} 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();
}
// `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.editor.getBody() );
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;
if ( ! onSplit ) {
return;
}
const rootNode = this.editor.getBody();
let before, after;
if ( rootNode.childNodes.length ) {
const { dom } = this.editor;
const beforeRange = dom.createRng();
const afterRange = dom.createRng();
const selectionRange = this.editor.selection.getRng();
beforeRange.setStart( rootNode, 0 );
beforeRange.setEnd( selectionRange.startContainer, selectionRange.startOffset );
afterRange.setStart( selectionRange.endContainer, selectionRange.endOffset );
afterRange.setEnd( rootNode, dom.nodeIndex( rootNode.lastChild ) + 1 );
const beforeFragment = beforeRange.cloneContents();
const afterFragment = afterRange.cloneContents();
const { format } = this.props;
before = domToFormat( beforeFragment.childNodes, format );
after = domToFormat( afterFragment.childNodes, format );
} else {
before = [];
after = [];
}
// 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 ( this.isEmpty( after ) ) {
before = this.props.value;
} else if ( this.isEmpty( before ) ) {
after = this.props.value;
}
// 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 = this.isEmpty( before ) ? null : before;
after = this.isEmpty( after ) ? null : after;
}
onSplit( before, after, ...blocks );
}
onNodeChange( { parents } ) {
if ( document.activeElement !== this.editor.getBody() ) {
return;
}
const formatNames = this.props.formattingControls;
const formats = this.editor.formatter.matchAll( formatNames ).reduce( ( accFormats, activeFormat ) => {
accFormats[ activeFormat ] = {
isActive: true,
...getFormatProperties( activeFormat, parents ),
};
return accFormats;
}, {} );
this.setState( { formats, selectedNodeId: this.state.selectedNodeId + 1 } );
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 );
}
}
setContent( content ) {
const { format } = this.props;
// If editor has focus while content is being set, save the selection
// and restore caret position after content is set.
let bookmark;
if ( this.editor.hasFocus() ) {
bookmark = this.editor.selection.getBookmark( 2, true );
}
this.savedContent = content;
this.editor.setContent( valueToString( content, format ) );
if ( bookmark ) {
this.editor.selection.moveToBookmark( bookmark );
}
}
getContent() {
const { format } = this.props;
return domToFormat( this.editor.getBody().childNodes, format );
}
componentDidUpdate( prevProps ) {
// The `savedContent` var allows us to avoid updating the content right after an `onChange` call
if (
!! this.editor &&
this.props.tagName === prevProps.tagName &&
this.props.value !== prevProps.value &&
this.props.value !== this.savedContent &&
// Comparing using isEqual is necessary especially to avoid unnecessary updateContent calls
// This fixes issues in multi richText blocks like quotes when moving the focus between
// the different editables.
! isEqual( this.props.value, prevProps.value ) &&
! isEqual( this.props.value, this.savedContent )
) {
this.setContent( this.props.value );
}
if ( 'development' === process.env.NODE_ENV ) {
if ( ! isEqual( this.props.formatters, prevProps.formatters ) ) {
// eslint-disable-next-line no-console
console.error( 'Formatters passed via `formatters` prop will only be registered once. Formatters can be enabled/disabled via the `formattingControls` prop.' );
}
}
}
/**
* Returns true if the field is currently empty, or false otherwise.
*
* @param {Array} value Content to check.
*
* @return {boolean} Whether field is empty.
*/
isEmpty( value = this.props.value ) {
return ! value || ! value.length;
}
isFormatActive( format ) {
return this.state.formats[ format ] && this.state.formats[ format ].isActive;
}
removeFormat( format ) {
this.editor.focus();
this.editor.formatter.remove( format );
// Formatter does not trigger a change event like `execCommand` does.
this.onCreateUndoLevel();
}
applyFormat( format, args, node ) {
this.editor.focus();
this.editor.formatter.apply( format, args, node );
// Formatter does not trigger a change event like `execCommand` does.
this.onCreateUndoLevel();
}
changeFormats( formats ) {
forEach( formats, ( formatValue, format ) => {
if ( format === 'link' ) {
if ( !! formatValue ) {
if ( formatValue.isAdding ) {
return;
}
const { value: href, target } = formatValue;
if ( ! this.isFormatActive( 'link' ) && this.editor.selection.isCollapsed() ) {
// When no link or text is selected, insert a link with the URL as its text
const anchorHTML = this.editor.dom.createHTML(
'a',
{ href, target },
this.editor.dom.encode( href )
);
this.editor.insertContent( anchorHTML );
} else {
// Use built-in TinyMCE command turn the selection into a link. This takes
// care of deleting any existing links within the selection
this.editor.execCommand( 'mceInsertLink', false, { href, target } );
}
} else {
this.editor.execCommand( 'Unlink' );
}
} else {
const isActive = this.isFormatActive( format );
if ( isActive && ! formatValue ) {
this.removeFormat( format );
} else if ( ! isActive && formatValue ) {
this.applyFormat( format );
}
}
} );
this.setState( ( state ) => ( {
formats: merge( {}, state.formats, formats ),
} ) );
}
render() {
const {
tagName: Tagname = 'div',
style,
value,
wrapperClassName,
className,
inlineToolbar = false,
formattingControls,
placeholder,
multiline: MultilineTag,
keepPlaceholderOnFocus = false,
isSelected,
formatters,
autocompleters,
format,
} = this.props;
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 formatToolbar = (
<FormatToolbar
selectedNodeId={ this.state.selectedNodeId }
formats={ this.state.formats }
onChange={ this.changeFormats }
enabledControls={ formattingControls }
customControls={ formatters }
/>
);
return (
<div className={ classes }
ref={ this.containerRef }
onFocus={ this.setFocusedElement }
>
{ isSelected && ! inlineToolbar && (
<BlockFormatControls>
{ formatToolbar }
</BlockFormatControls>
) }
{ isSelected && inlineToolbar && (
<div className="editor-rich-text__inline-toolbar">
{ formatToolbar }
</div>
) }
{ isSelected &&
<TokenUI
editor={ this.editor }
containerRef={ this.containerRef }
/>
}
<Autocomplete onReplace={ this.props.onReplace } completers={ autocompleters }>
{ ( { isExpanded, listBoxId, activeId } ) => (
<Fragment>
<TinyMCE
tagName={ Tagname }
getSettings={ this.getSettings }
onSetup={ this.onSetup }
style={ style }
defaultValue={ value }
format={ format }
isPlaceholderVisible={ isPlaceholderVisible }
aria-label={ placeholder }
aria-autocomplete="list"
aria-expanded={ isExpanded }
aria-owns={ listBoxId }
aria-activedescendant={ activeId }
{ ...ariaProps }
className={ className }
key={ key }
/>
{ isPlaceholderVisible &&
<Tagname
className={ classnames( 'editor-rich-text__tinymce', className ) }
style={ style }
>
{ MultilineTag ? <MultilineTag>{ placeholder }</MultilineTag> : placeholder }
</Tagname>
}
{ isSelected && <Slot name="RichText.Siblings" /> }
</Fragment>
) }
</Autocomplete>
</div>
);
}
}
RichText.contextTypes = {
onUndo: noop,
onRedo: noop,
onCreateUndoLevel: noop,
};
RichText.defaultProps = {
formattingControls: DEFAULT_FORMATS,
formatters: [],
format: 'children',
};
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 = identity } = select( 'core/viewport' ) || {};
const { canUserUseUnfilteredHTML } = select( 'core/editor' );
return {
isViewportSmall: isViewportMatch( '< small' ),
canUserUseUnfilteredHTML: canUserUseUnfilteredHTML(),
};
} ),
withSafeTimeout,
] )( RichText );
RichTextContainer.Content = ( { value, format, tagName: Tag, ...props } ) => {
let content;
switch ( format ) {
case 'string':
content = <RawHTML>{ value }</RawHTML>;
break;
case 'children':
content = <RawHTML>{ children.toHTML( value ) }</RawHTML>;
break;
}
if ( Tag ) {
return <Tag { ...props }>{ content }</Tag>;
}
return content;
};
RichTextContainer.Content.defaultProps = {
format: 'children',
};
export default RichTextContainer;