-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.native.js
907 lines (773 loc) · 27.4 KB
/
index.native.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
/*eslint no-console: ["error", { allow: ["warn"] }] */
/**
* External dependencies
*/
import RCTAztecView from 'react-native-aztec';
import { View, Platform } from 'react-native';
import {
pickBy,
} from 'lodash';
import memize from 'memize';
/**
* WordPress dependencies
*/
import { Component, RawHTML } from '@wordpress/element';
import { withInstanceId, compose } from '@wordpress/compose';
import { BlockFormatControls } from '@wordpress/block-editor';
import { withSelect, withDispatch } from '@wordpress/data';
import {
applyFormat,
getActiveFormat,
__unstableGetActiveFormats as getActiveFormats,
isEmpty,
create,
split,
toHTMLString,
insert,
__unstableInsertLineSeparator as insertLineSeparator,
__unstableIsEmptyLine as isEmptyLine,
isCollapsed,
} from '@wordpress/rich-text';
import { decodeEntities } from '@wordpress/html-entities';
import { BACKSPACE } from '@wordpress/keycodes';
import { pasteHandler, children } from '@wordpress/blocks';
import { isURL } from '@wordpress/url';
/**
* Internal dependencies
*/
import FormatEdit from './format-edit';
import FormatToolbar from './format-toolbar';
import { withBlockEditContext } from '../block-edit/context';
import { ListEdit } from './list-edit';
import styles from './style.scss';
const isRichTextValueEmpty = ( value ) => {
return ! value || ! value.length;
};
const unescapeSpaces = ( text ) => {
return text.replace( / | /gi, ' ' );
};
/**
* Calls {@link pasteHandler} with a fallback to plain text when HTML processing
* results in errors
*
* @param {Object} [options] The options to pass to {@link pasteHandler}
*
* @return {Array|string} A list of blocks or a string, depending on
* `handlerMode`.
*/
const saferPasteHandler = ( options ) => {
try {
return pasteHandler( options );
} catch ( error ) {
window.console.log( 'Pasting HTML failed:', error );
window.console.log( 'HTML:', options.HTML );
window.console.log( 'Falling back to plain text.' );
// fallback to plain text
return pasteHandler( { ...options, HTML: '' } );
}
};
const gutenbergFormatNamesToAztec = {
'core/bold': 'bold',
'core/italic': 'italic',
'core/strikethrough': 'strikethrough',
};
export class RichText extends Component {
constructor( { value, multiline, selectionStart, selectionEnd } ) {
super( ...arguments );
this.isMultiline = false;
if ( multiline === true || multiline === 'p' || multiline === 'li' ) {
this.multilineTag = multiline === true ? 'p' : multiline;
this.isMultiline = true;
}
if ( this.multilineTag === 'li' ) {
this.multilineWrapperTags = [ 'ul', 'ol' ];
}
if ( this.props.onSplit ) {
this.onSplit = this.props.onSplit;
} else if ( this.props.unstableOnSplit ) {
this.onSplit = this.props.unstableOnSplit;
}
this.isIOS = Platform.OS === 'ios';
this.createRecord = this.createRecord.bind( this );
this.onChange = this.onChange.bind( this );
this.onEnter = this.onEnter.bind( this );
this.onBackspace = this.onBackspace.bind( this );
this.onPaste = this.onPaste.bind( this );
this.onFocus = this.onFocus.bind( this );
this.onBlur = this.onBlur.bind( this );
this.onTextUpdate = this.onTextUpdate.bind( this );
this.onContentSizeChange = this.onContentSizeChange.bind( this );
this.onFormatChangeForceChild = this.onFormatChangeForceChild.bind( this );
this.onFormatChange = this.onFormatChange.bind( this );
this.formatToValue = memize(
this.formatToValue.bind( this ),
{ maxSize: 1 }
);
// This prevents a bug in Aztec which triggers onSelectionChange twice on format change
this.onSelectionChange = this.onSelectionChange.bind( this );
this.onSelectionChangeFromAztec = this.onSelectionChangeFromAztec.bind( this );
this.valueToFormat = this.valueToFormat.bind( this );
this.willTrimSpaces = this.willTrimSpaces.bind( this );
this.state = {
activeFormats: [],
selectedFormat: null,
height: 0,
};
this.needsSelectionUpdate = false;
this.savedContent = '';
this.isTouched = false;
this.lastAztecEventType = null;
this.lastHistoryValue = value;
// Internal values that are update synchronously, unlike props.
this.value = value;
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
}
/**
* Get the current record (value and selection) from props and state.
*
* @return {Object} The current record (value and selection).
*/
getRecord() {
const { selectionStart: start, selectionEnd: end } = this.props;
let { value } = this.props;
// Since we get the text selection from Aztec we need to be in sync with the HTML `value`
// Removing leading white spaces using `trim()` should make sure this is the case.
if ( typeof value === 'string' || value instanceof String ) {
value = value.trimLeft();
}
const { formats, replacements, text } = this.formatToValue( value );
const { activeFormats } = this.state;
return { formats, replacements, text, start, end, activeFormats };
}
/**
* Creates a RichText value "record" from native content and selection
* information
*
* @param {string} currentContent The content (usually an HTML string) from
* the native component.
* @param {number} selectionStart The start of the selection.
* @param {number} selectionEnd The end of the selection (same as start if
* cursor instead of selection).
*
* @return {Object} A RichText value with formats and selection.
*/
createRecord() {
return {
start: this.selectionStart,
end: this.selectionEnd,
...create( {
html: this.value,
range: null,
multilineTag: this.multilineTag,
multilineWrapperTags: this.multilineWrapperTags,
} ),
};
}
/*
* 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.
*
*/
splitContent( currentRecord, blocks = [], isPasted = false ) {
if ( ! this.onSplit ) {
return;
}
// TODO : Fix the index position in AztecNative for Android
let [ before, after ] = split( currentRecord );
// 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.text.length === currentRecord.text.length ) {
before = currentRecord;
} else if ( isEmpty( before ) && after.text.length === currentRecord.text.length ) {
after = currentRecord;
}
// If pasting and the split would result in no content other than the
// pasted blocks, remove the before and after blocks.
if ( isPasted ) {
before = isEmpty( before ) ? null : before;
after = isEmpty( after ) ? null : after;
}
if ( before ) {
before = this.valueToFormat( before );
}
if ( after ) {
after = this.valueToFormat( after );
}
// The onSplit event can cause a content update event for this block. Such event should
// definitely be processed by our native components, since they have no knowledge of
// how the split works. Setting lastEventCount to undefined forces the native component to
// always update when provided with new content.
this.lastEventCount = undefined;
this.onSplit( before, after, ...blocks );
}
valueToFormat( value ) {
// remove the outer root tags
return this.removeRootTagsProduceByAztec( toHTMLString( {
value,
multilineTag: this.multilineTag,
} ) );
}
getActiveFormatNames( record ) {
const {
formatTypes,
} = this.props;
return formatTypes.map( ( { name } ) => name ).filter( ( name ) => {
return getActiveFormat( record, name ) !== undefined;
} ).map( ( name ) => gutenbergFormatNamesToAztec[ name ] ).filter( Boolean );
}
onFormatChangeForceChild( record ) {
this.onFormatChange( record, true );
}
onFormatChange( record ) {
const { start, end, activeFormats = [] } = record;
const changeHandlers = pickBy( this.props, ( v, key ) =>
key.startsWith( 'format_on_change_functions_' )
);
Object.values( changeHandlers ).forEach( ( changeHandler ) => {
changeHandler( record.formats, record.text );
} );
this.value = this.valueToFormat( record );
this.props.onChange( this.value );
this.setState( { activeFormats } );
this.props.onSelectionChange( start, end );
this.selectionStart = start;
this.selectionEnd = end;
this.onCreateUndoLevel();
this.lastAztecEventType = 'format change';
}
onCreateUndoLevel() {
// If the content is the same, no level needs to be created.
if ( this.lastHistoryValue === this.value ) {
return;
}
this.props.onCreateUndoLevel();
this.lastHistoryValue = this.value;
}
/*
* Cleans up any root tags produced by aztec.
* TODO: This should be removed on a later version when aztec doesn't return the top tag of the text being edited
*/
removeRootTagsProduceByAztec( html ) {
let result = this.removeRootTag( this.props.tagName, html );
// Temporary workaround for https://github.com/WordPress/gutenberg/pull/13763
if ( this.props.rootTagsToEliminate ) {
this.props.rootTagsToEliminate.forEach( ( element ) => {
result = this.removeRootTag( element, result );
} );
}
return result;
}
removeRootTag( tag, html ) {
const openingTagRegexp = RegExp( '^<' + tag + '>', 'gim' );
const closingTagRegexp = RegExp( '</' + tag + '>$', 'gim' );
return html.replace( openingTagRegexp, '' ).replace( closingTagRegexp, '' );
}
/*
* Handles any case where the content of the AztecRN instance has changed
*/
onChange( event ) {
const contentWithoutRootTag = this.removeRootTagsProduceByAztec( unescapeSpaces( event.nativeEvent.text ) );
// On iOS, onChange can be triggered after selection changes, even though there are no content changes.
if ( contentWithoutRootTag === this.value ) {
return;
}
this.lastEventCount = event.nativeEvent.eventCount;
this.comesFromAztec = true;
this.firedAfterTextChanged = true; // the onChange event always fires after the fact
this.onTextUpdate( event );
this.lastAztecEventType = 'input';
}
onTextUpdate( event ) {
const contentWithoutRootTag = this.removeRootTagsProduceByAztec( unescapeSpaces( event.nativeEvent.text ) );
const refresh = this.value !== contentWithoutRootTag;
this.value = contentWithoutRootTag;
// we don't want to refresh if our goal is just to create a record
if ( refresh ) {
this.props.onChange( contentWithoutRootTag );
}
}
/*
* Handles any case where the content of the AztecRN instance has changed in size
*/
onContentSizeChange( contentSize ) {
const contentHeight = contentSize.height;
this.setState( { height: contentHeight } );
this.lastAztecEventType = 'content size change';
}
// eslint-disable-next-line no-unused-vars
onEnter( event ) {
this.lastEventCount = event.nativeEvent.eventCount;
this.comesFromAztec = true;
this.firedAfterTextChanged = event.nativeEvent.firedAfterTextChanged;
const currentRecord = this.createRecord();
if ( this.multilineTag ) {
if ( event.shiftKey ) {
this.needsSelectionUpdate = true;
const insertedLineBreak = { ...insert( currentRecord, '\n' ) };
this.onFormatChangeForceChild( insertedLineBreak );
} else if ( this.onSplit && isEmptyLine( currentRecord ) ) {
this.splitContent( currentRecord );
} else {
this.needsSelectionUpdate = true;
const insertedLineSeparator = { ...insertLineSeparator( currentRecord ) };
this.onFormatChange( insertedLineSeparator, ! this.firedAfterTextChanged );
}
} else if ( event.shiftKey || ! this.onSplit ) {
this.needsSelectionUpdate = true;
const insertedLineBreak = { ...insert( currentRecord, '\n' ) };
this.onFormatChangeForceChild( insertedLineBreak );
} else {
this.splitContent( currentRecord );
}
this.lastAztecEventType = 'input';
}
// eslint-disable-next-line no-unused-vars
onBackspace( event ) {
const { onMerge, onRemove } = this.props;
if ( ! onMerge && ! onRemove ) {
return;
}
const keyCode = BACKSPACE; // TODO : should we differentiate BACKSPACE and DELETE?
const isReverse = keyCode === BACKSPACE;
const empty = this.isEmpty();
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 );
}
event.preventDefault();
this.lastAztecEventType = 'input';
}
/**
* Handles a paste event from the native Aztec Wrapper.
*
* @param {PasteEvent} event The paste event which wraps `nativeEvent`.
*/
onPaste( event ) {
const isPasted = true;
const { onSplit } = this.props;
const { pastedText, pastedHtml, files } = event.nativeEvent;
const currentRecord = this.createRecord();
event.preventDefault();
// Only process file if no HTML is present.
// Note: a pasted file may have the URL as plain text.
if ( files && files.length > 0 ) {
const uploadId = Number.MAX_SAFE_INTEGER;
let html = '';
files.forEach( ( file ) => {
html += `<img src="${ file }" class="wp-image-${ uploadId }">`;
} );
const content = pasteHandler( {
HTML: html,
mode: 'BLOCKS',
tagName: this.props.tagName,
} );
const shouldReplace = this.props.onReplace && this.isEmpty();
if ( shouldReplace ) {
this.props.onReplace( content );
} else {
this.splitContent( currentRecord, content, isPasted );
}
return;
}
// There is a selection, check if a URL is pasted.
if ( ! isCollapsed( currentRecord ) ) {
const trimmedText = ( pastedHtml || pastedText ).replace( /<[^>]+>/g, '' )
.trim();
// A URL was pasted, turn the selection into a link
if ( isURL( trimmedText ) ) {
const linkedRecord = applyFormat( currentRecord, {
type: 'a',
attributes: {
href: decodeEntities( trimmedText ),
},
} );
this.value = this.valueToFormat( linkedRecord );
this.props.onChange( this.value );
// Allows us to ask for this information when we get a report.
window.console.log( 'Created link:\n\n', trimmedText );
return;
}
}
const shouldReplace = this.props.onReplace && this.isEmpty();
let mode = 'INLINE';
if ( shouldReplace ) {
mode = 'BLOCKS';
} else if ( onSplit ) {
mode = 'AUTO';
}
const pastedContent = saferPasteHandler( {
HTML: pastedHtml,
plainText: pastedText,
mode,
tagName: this.props.tagName,
canUserUseUnfilteredHTML: this.props.canUserUseUnfilteredHTML,
} );
if ( typeof pastedContent === 'string' ) {
const recordToInsert = create( { html: pastedContent } );
const insertedContent = insert( currentRecord, recordToInsert );
const newContent = this.valueToFormat( insertedContent );
this.lastEventCount = undefined;
this.value = newContent;
// explicitly set selection after inline paste
this.forceSelectionUpdate( insertedContent.start, insertedContent.end );
this.props.onChange( this.value );
} else if ( onSplit ) {
if ( ! pastedContent.length ) {
return;
}
if ( shouldReplace ) {
this.props.onReplace( pastedContent );
} else {
this.splitContent( currentRecord, pastedContent, isPasted );
}
}
}
onFocus() {
this.isTouched = true;
if ( this.props.onFocus ) {
this.props.onFocus();
}
this.lastAztecEventType = 'focus';
}
onBlur( event ) {
this.isTouched = false;
if ( this.props.onBlur ) {
this.props.onBlur( event );
}
this.lastAztecEventType = 'blur';
}
onSelectionChange( start, end ) {
const hasChanged = this.selectionStart !== start || this.selectionEnd !== end;
this.selectionStart = start;
this.selectionEnd = end;
// This is a manual selection change event if onChange was not triggered just before
// and we did not just trigger a text update
// `onChange` could be the last event and could have been triggered a long time ago so
// this approach is not perfectly reliable
const isManual = this.lastAztecEventType !== 'input' && this.props.value === this.value;
if ( hasChanged && isManual ) {
const value = this.createRecord();
const activeFormats = getActiveFormats( value );
this.setState( { activeFormats } );
}
this.props.onSelectionChange( start, end );
}
onSelectionChangeFromAztec( start, end, text, event ) {
// `end` can be less than `start` on iOS
// Let's fix that here so `rich-text/slice` can work properly
const realStart = Math.min( start, end );
const realEnd = Math.max( start, end );
// check and dicsard stray event, where the text and selection is equal to the ones already cached
const contentWithoutRootTag = this.removeRootTagsProduceByAztec( unescapeSpaces( event.nativeEvent.text ) );
if ( contentWithoutRootTag === this.value && realStart === this.selectionStart && realEnd === this.selectionEnd ) {
return;
}
this.comesFromAztec = true;
this.firedAfterTextChanged = true; // Selection change event always fires after the fact
// update text before updating selection
// Make sure there are changes made to the content before upgrading it upward
this.onTextUpdate( event );
this.onSelectionChange( realStart, realEnd );
// Update lastEventCount to prevent Aztec from re-rendering the content it just sent
this.lastEventCount = event.nativeEvent.eventCount;
this.lastAztecEventType = 'selection change';
}
isEmpty() {
return isEmpty( this.formatToValue( this.props.value ) );
}
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;
}
componentWillReceiveProps( nextProps ) {
if ( nextProps.value !== this.value ) {
this.value = this.props.value;
this.lastEventCount = undefined;
}
}
forceSelectionUpdate( start, end ) {
if ( ! this.needsSelectionUpdate ) {
this.needsSelectionUpdate = true;
this.selectionStart = start;
this.selectionEnd = end;
this.forceUpdate();
}
}
shouldComponentUpdate( nextProps ) {
if ( nextProps.tagName !== this.props.tagName ) {
this.lastEventCount = undefined;
this.value = undefined;
return true;
}
// TODO: Please re-introduce the check to avoid updating the content right after an `onChange` call.
// It was removed in https://github.com/WordPress/gutenberg/pull/12417 to fix undo/redo problem.
// If the component is changed React side (undo/redo/merging/splitting/custom text actions)
// we need to make sure the native is updated as well.
// Also, don't trust the "this.lastContent" as on Android, incomplete text events arrive
// with only some of the text, while the virtual keyboard's suggestion system does its magic.
// ** compare with this.lastContent for optimizing performance by not forcing Aztec with text it already has
// , but compare with props.value to not lose "half word" text because of Android virtual keyb autosuggestion behavior
if ( ( typeof nextProps.value !== 'undefined' ) &&
( typeof this.props.value !== 'undefined' ) &&
( ! this.comesFromAztec || ! this.firedAfterTextChanged ) &&
nextProps.value !== this.props.value ) {
// Gutenberg seems to try to mirror the caret state even on events that only change the content so,
// let's force caret update if state has selection set.
if ( typeof nextProps.selectionStart !== 'undefined' && typeof nextProps.selectionEnd !== 'undefined' ) {
this.needsSelectionUpdate = true;
}
this.lastEventCount = undefined; // force a refresh on the native side
}
if ( ! this.comesFromAztec ) {
if ( nextProps.selectionStart !== this.props.selectionStart &&
nextProps.selectionStart !== this.selectionStart &&
nextProps.isSelected ) {
this.needsSelectionUpdate = true;
this.lastEventCount = undefined; // force a refresh on the native side
}
}
return true;
}
componentDidMount() {
if ( this.props.isSelected ) {
this._editor.focus();
this.onSelectionChange( this.props.selectionStart || 0, this.props.selectionEnd || 0 );
}
}
componentWillUnmount() {
if ( this._editor.isFocused() ) {
this._editor.blur();
}
}
componentDidUpdate( prevProps ) {
if ( this.props.isSelected && ! prevProps.isSelected ) {
this._editor.focus();
// Update selection props explicitly when component is selected as Aztec won't call onSelectionChange
// if its internal value hasn't change. When created, default value is 0, 0
this.onSelectionChange( this.props.selectionStart || 0, this.props.selectionEnd || 0 );
} else if ( ! this.props.isSelected && prevProps.isSelected && this.isIOS ) {
this._editor.blur();
}
}
willTrimSpaces( html ) {
// regex for detecting spaces around block element html tags
const blockHtmlElements = '(div|br|blockquote|ul|ol|li|p|pre|h1|h2|h3|h4|h5|h6|iframe|hr)';
const leadingOrTrailingSpaces = new RegExp( `(\\s+)<\/?${ blockHtmlElements }>|<\/?${ blockHtmlElements }>(\\s+)`, 'g' );
const matches = html.match( leadingOrTrailingSpaces );
if ( matches && matches.length > 0 ) {
return true;
}
return false;
}
render() {
const {
tagName,
style,
formattingControls,
isSelected,
onTagNameChange,
} = this.props;
const record = this.getRecord();
// Save back to HTML from React tree
const value = this.valueToFormat( record );
let html = `<${ tagName }>${ value }</${ tagName }>`;
// We need to check if the value is undefined or empty, and then assign it properly otherwise the placeholder is not visible
if ( value === undefined || value === '' ) {
html = '';
this.lastEventCount = undefined; // force a refresh on the native side
}
let minHeight = styles[ 'block-editor-rich-text' ].minHeight;
if ( style && style.minHeight ) {
minHeight = style.minHeight;
}
let selection = null;
if ( this.needsSelectionUpdate ) {
this.needsSelectionUpdate = false;
// Aztec performs some html text cleanup while parsing it so, its internal representation gets out-of-sync with the
// representation of the format-lib on the RN side. We need to avoid trying to set the caret position because it may
// be outside the text bounds and crash Aztec, at least on Android.
if ( ! this.isIOS && this.willTrimSpaces( html ) ) {
// the html will get trimmed by the cleaning up functions in Aztec and caret position will get out-of-sync.
// So, skip forcing it, let Aztec just do its best and just log the fact.
console.warn( 'RichText value will be trimmed for spaces! Avoiding setting the caret position manually.' );
} else {
selection = { start: this.props.selectionStart, end: this.props.selectionEnd };
}
}
if ( this.comesFromAztec ) {
this.comesFromAztec = false;
this.firedAfterTextChanged = false;
}
return (
<View>
{ isSelected && this.multilineTag === 'li' && (
<ListEdit
onTagNameChange={ onTagNameChange }
tagName={ tagName }
value={ record }
onChange={ this.onFormatChangeForceChild }
/>
) }
{ isSelected && (
<BlockFormatControls>
<FormatToolbar controls={ formattingControls } />
</BlockFormatControls>
) }
<RCTAztecView
ref={ ( ref ) => {
this._editor = ref;
if ( this.props.setRef ) {
this.props.setRef( ref );
}
} }
style={ {
...style,
minHeight: Math.max( minHeight, this.state.height ),
} }
text={ { text: html, eventCount: this.lastEventCount, selection } }
placeholder={ this.props.placeholder }
placeholderTextColor={ this.props.placeholderTextColor || styles[ 'block-editor-rich-text' ].textDecorationColor }
deleteEnter={ this.props.deleteEnter }
onChange={ this.onChange }
onFocus={ this.onFocus }
onBlur={ this.onBlur }
onEnter={ this.onEnter }
onBackspace={ this.onBackspace }
onPaste={ this.onPaste }
activeFormats={ this.getActiveFormatNames( record ) }
onContentSizeChange={ this.onContentSizeChange }
onCaretVerticalPositionChange={ this.props.onCaretVerticalPositionChange }
onSelectionChange={ this.onSelectionChangeFromAztec }
isSelected={ isSelected }
blockType={ { tag: tagName } }
color={ 'black' }
maxImagesWidth={ 200 }
fontFamily={ this.props.fontFamily || styles[ 'block-editor-rich-text' ].fontFamily }
fontSize={ this.props.fontSize }
fontWeight={ this.props.fontWeight }
fontStyle={ this.props.fontStyle }
disableEditingMenu={ this.props.disableEditingMenu }
isMultiline={ this.isMultiline }
/>
{ isSelected && <FormatEdit value={ record } onChange={ this.onFormatChange } /> }
</View>
);
}
}
RichText.defaultProps = {
formattingControls: [ 'bold', 'italic', 'link', 'strikethrough' ],
format: 'string',
};
const RichTextContainer = compose( [
withInstanceId,
withBlockEditContext( ( { clientId, onFocus, isSelected, onCaretVerticalPositionChange }, ownProps ) => {
return {
clientId,
isSelected,
onFocus: onFocus || ownProps.onFocus,
onCaretVerticalPositionChange,
};
} ),
withSelect( ( select, {
clientId,
instanceId,
identifier = instanceId,
isSelected,
} ) => {
const { getFormatTypes } = select( 'core/rich-text' );
const {
getSelectionStart,
getSelectionEnd,
} = select( 'core/block-editor' );
const selectionStart = getSelectionStart();
const selectionEnd = getSelectionEnd();
if ( isSelected === undefined ) {
isSelected = (
selectionStart.clientId === clientId &&
selectionStart.attributeKey === identifier
);
}
return {
formatTypes: getFormatTypes(),
selectionStart: isSelected ? selectionStart.offset : undefined,
selectionEnd: isSelected ? selectionEnd.offset : undefined,
isSelected,
};
} ),
withDispatch( ( dispatch, {
clientId,
instanceId,
identifier = instanceId,
} ) => {
const {
__unstableMarkLastChangeAsPersistent,
selectionChange,
} = dispatch( 'core/block-editor' );
return {
onCreateUndoLevel: __unstableMarkLastChangeAsPersistent,
onSelectionChange( start, end ) {
selectionChange( clientId, identifier, start, end );
},
};
} ),
] )( RichText );
RichTextContainer.Content = ( { value, format, tagName: Tag, multiline, ...props } ) => {
let content;
let html = value;
let MultilineTag;
if ( multiline === true || multiline === 'p' || multiline === 'li' ) {
MultilineTag = multiline === true ? 'p' : multiline;
}
if ( ! html && MultilineTag ) {
html = `<${ MultilineTag }></${ MultilineTag }>`;
}
switch ( format ) {
case 'string':
content = <RawHTML>{ html }</RawHTML>;
break;
}
if ( Tag ) {
return <Tag { ...props }>{ content }</Tag>;
}
return content;
};
RichTextContainer.isEmpty = isRichTextValueEmpty;
RichTextContainer.Content.defaultProps = {
format: 'string',
};
export default RichTextContainer;
export { RichTextShortcut } from './shortcut';
export { RichTextToolbarButton } from './toolbar-button';
export { __unstableRichTextInputEvent } from './input-event';