-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.native.js
1365 lines (1190 loc) · 39 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
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
/* eslint no-console: ["error", { allow: ["warn"] }] */
/**
* External dependencies
*/
import { View, Platform, Dimensions } from 'react-native';
import memize from 'memize';
import { colord } from 'colord';
/**
* WordPress dependencies
*/
import RCTAztecView from '@wordpress/react-native-aztec';
import {
showUserSuggestions,
showXpostSuggestions,
} from '@wordpress/react-native-bridge';
import { BlockFormatControls, getPxFromCssUnit } from '@wordpress/block-editor';
import { Component } from '@wordpress/element';
import {
compose,
debounce,
withPreferredColorScheme,
} from '@wordpress/compose';
import { withSelect } from '@wordpress/data';
import { childrenBlock } from '@wordpress/blocks';
import { decodeEntities } from '@wordpress/html-entities';
import { BACKSPACE, DELETE, ENTER } from '@wordpress/keycodes';
import { isURL } from '@wordpress/url';
import { atSymbol, plus } from '@wordpress/icons';
import { __ } from '@wordpress/i18n';
import {
applyFormat,
getActiveFormat,
getActiveFormats,
insert,
getTextContent,
isEmpty,
create,
toHTMLString,
isCollapsed,
remove,
} from '@wordpress/rich-text';
/**
* Internal dependencies
*/
import { useFormatTypes } from './use-format-types';
import FormatEdit from './format-edit';
import { getFormatColors } from './get-format-colors';
import styles from './style.scss';
import ToolbarButtonWithOptions from './toolbar-button-with-options';
const unescapeSpaces = ( text ) => {
return text.replace( / | /gi, ' ' );
};
// The flattened color palettes array is memoized to ensure that the same array instance is
// returned for the colors palettes. This value might be used as a prop, so having the same
// instance will prevent unnecessary re-renders of the RichText component.
const flatColorPalettes = memize( ( colorsPalettes ) => [
...( colorsPalettes?.theme || [] ),
...( colorsPalettes?.custom || [] ),
...( colorsPalettes?.default || [] ),
] );
const getSelectionColor = memize(
(
currentSelectionColor,
defaultSelectionColor,
baseGlobalStyles,
isBlockBasedTheme
) => {
let selectionColor = defaultSelectionColor;
if ( currentSelectionColor ) {
selectionColor = currentSelectionColor;
}
if ( isBlockBasedTheme ) {
const colordTextColor = colord( selectionColor );
const colordBackgroundColor = colord(
baseGlobalStyles?.color?.background
);
const isColordTextReadable = colordTextColor.isReadable(
colordBackgroundColor
);
if ( ! isColordTextReadable ) {
selectionColor = baseGlobalStyles?.color?.text;
}
}
return selectionColor;
}
);
const gutenbergFormatNamesToAztec = {
'core/bold': 'bold',
'core/italic': 'italic',
'core/strikethrough': 'strikethrough',
'core/text-color': 'mark',
};
const EMPTY_PARAGRAPH_TAGS = '<p></p>';
const DEFAULT_FONT_SIZE = 16;
const MIN_LINE_HEIGHT = 1;
export class RichText extends Component {
constructor( { value, selectionStart, selectionEnd } ) {
super( ...arguments );
this.isIOS = Platform.OS === 'ios';
this.createRecord = this.createRecord.bind( this );
this.onChangeFromAztec = this.onChangeFromAztec.bind( this );
this.onKeyDown = this.onKeyDown.bind( this );
this.handleEnter = this.handleEnter.bind( this );
this.handleDelete = this.handleDelete.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.onFormatChange = this.onFormatChange.bind( this );
this.formatToValue = memize( this.formatToValue.bind( this ), {
maxSize: 1,
} );
this.debounceCreateUndoLevel = debounce( this.onCreateUndoLevel, 1000 );
// 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.getHtmlToRender = this.getHtmlToRender.bind( this );
this.handleSuggestionFunc = this.handleSuggestionFunc.bind( this );
this.handleUserSuggestion = this.handleSuggestionFunc(
showUserSuggestions,
'@'
).bind( this );
this.handleXpostSuggestion = this.handleSuggestionFunc(
showXpostSuggestions,
'+'
).bind( this );
this.suggestionOptions = this.suggestionOptions.bind( this );
this.insertString = this.insertString.bind( this );
this.manipulateEventCounterToForceNativeToRefresh =
this.manipulateEventCounterToForceNativeToRefresh.bind( this );
this.shouldDropEventFromAztec =
this.shouldDropEventFromAztec.bind( this );
this.state = {
activeFormats: [],
selectedFormat: null,
height: 0,
currentFontSize: this.getFontSize( arguments[ 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,
colorPalette,
} = this.props;
const { value } = this.props;
const currentValue = this.formatToValue( value );
const { formats, replacements, text } = currentValue;
const { activeFormats } = this.state;
const newFormats = getFormatColors( formats, colorPalette );
return {
formats: newFormats,
replacements,
text,
start,
end,
activeFormats,
};
}
/**
* Creates a RichText value "record" from the current content and selection
* information
*
*
* @return {Object} A RichText value with formats and selection.
*/
createRecord() {
const { preserveWhiteSpace } = this.props;
const value = {
start: this.selectionStart,
end: this.selectionEnd,
...create( {
html: this.value,
range: null,
preserveWhiteSpace,
} ),
};
const start = Math.min( this.selectionStart, value.text.length );
const end = Math.min( this.selectionEnd, value.text.length );
return { ...value, start, end };
}
valueToFormat( value ) {
// Remove the outer root tags.
return this.removeRootTagsProducedByAztec( toHTMLString( { value } ) );
}
getActiveFormatNames( record ) {
const { formatTypes } = this.props;
return formatTypes
.map( ( { name } ) => name )
.filter( ( name ) => {
return getActiveFormat( record, name ) !== undefined;
} )
.map( ( name ) => gutenbergFormatNamesToAztec[ name ] )
.filter( Boolean );
}
onFormatChange( record ) {
const { start = 0, end = 0, activeFormats = [] } = record;
const changeHandlers = Object.fromEntries(
Object.entries( this.props ).filter( ( [ 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';
}
insertString( record, string ) {
if ( record && string ) {
this.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
const toInsert = insert( record, string );
this.onFormatChange( toInsert );
}
}
onCreateUndoLevel() {
const { __unstableOnCreateUndoLevel: onCreateUndoLevel } = this.props;
// If the content is the same, no level needs to be created.
if ( this.lastHistoryValue === this.value ) {
return;
}
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
*/
removeRootTagsProducedByAztec( html ) {
let result = this.removeRootTag( this.props.tagName, html );
if ( this.props.tagsToEliminate ) {
this.props.tagsToEliminate.forEach( ( element ) => {
result = this.removeTag( element, result );
} );
}
return result;
}
removeRootTag( tag, html ) {
const openingTagRegexp = RegExp( '^<' + tag + '[^>]*>', 'gim' );
const closingTagRegexp = RegExp( '</' + tag + '>$', 'gim' );
return html
.replace( openingTagRegexp, '' )
.replace( closingTagRegexp, '' );
}
removeTag( 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
*/
onChangeFromAztec( event ) {
if ( this.shouldDropEventFromAztec( event, 'onChange' ) ) {
return;
}
const contentWithoutRootTag = this.removeRootTagsProducedByAztec(
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.removeRootTagsProducedByAztec(
unescapeSpaces( event.nativeEvent.text )
);
this.debounceCreateUndoLevel();
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 ) {
this.setState( contentSize );
this.lastAztecEventType = 'content size change';
}
onKeyDown( event ) {
if ( event.defaultPrevented ) {
return;
}
// Add stubs for conformance in downstream autocompleters logic.
this.customEditableOnKeyDown?.( {
preventDefault: () => undefined,
...event,
key: RCTAztecView.KeyCodes[ event?.keyCode ],
} );
this.handleDelete( event );
this.handleEnter( event );
this.handleTriggerKeyCodes( event );
}
handleEnter( event ) {
if ( event.keyCode !== ENTER ) {
return;
}
const { onEnter } = this.props;
if ( ! onEnter ) {
return;
}
onEnter( {
value: this.createRecord(),
onChange: this.onFormatChange,
shiftKey: event.shiftKey,
} );
this.lastAztecEventType = 'input';
}
handleDelete( event ) {
if ( this.shouldDropEventFromAztec( event, 'handleDelete' ) ) {
return;
}
const { keyCode } = event;
if ( keyCode !== DELETE && keyCode !== BACKSPACE ) {
return;
}
const isReverse = keyCode === BACKSPACE;
const { onDelete } = this.props;
this.lastEventCount = event.nativeEvent.eventCount;
this.comesFromAztec = true;
this.firedAfterTextChanged = event.nativeEvent.firedAfterTextChanged;
const value = this.createRecord();
const { start, end, text } = value;
let newValue;
// Always handle full content deletion ourselves.
if ( start === 0 && end !== 0 && end >= text.length ) {
newValue = remove( value );
this.onFormatChange( newValue );
event.preventDefault();
return;
}
// Only process delete if the key press occurs at an uncollapsed edge.
if (
! onDelete ||
! isCollapsed( value ) ||
( isReverse && start !== 0 ) ||
( ! isReverse && end !== text.length )
) {
return;
}
onDelete( { isReverse, value } );
event.preventDefault();
this.lastAztecEventType = 'input';
}
handleTriggerKeyCodes( event ) {
const { keyCode } = event;
const triggeredOption = this.suggestionOptions().find( ( option ) => {
const triggeredKeyCode = option.triggerChar.charCodeAt( 0 );
return triggeredKeyCode === keyCode;
} );
if ( triggeredOption ) {
const record = this.getRecord();
const text = getTextContent( record );
// Only respond to the trigger if the selection is on the start of text or line
// or if the character before is a space.
const useTrigger =
text.length === 0 ||
record.start === 0 ||
text.charAt( record.start - 1 ) === '\n' ||
text.charAt( record.start - 1 ) === ' ';
if ( useTrigger && triggeredOption.onClick ) {
triggeredOption.onClick();
} else {
this.insertString( record, triggeredOption.triggerChar );
}
}
}
suggestionOptions() {
const { areMentionsSupported, areXPostsSupported } = this.props;
const allOptions = [
{
supported: areMentionsSupported,
title: __( 'Insert mention' ),
onClick: this.handleUserSuggestion,
triggerChar: '@',
value: 'mention',
label: __( 'Mention' ),
icon: atSymbol,
},
{
supported: areXPostsSupported,
title: __( 'Insert crosspost' ),
onClick: this.handleXpostSuggestion,
triggerChar: '+',
value: 'crosspost',
label: __( 'Crosspost' ),
icon: plus,
},
];
return allOptions.filter( ( op ) => op.supported );
}
handleSuggestionFunc( suggestionFunction, prefix ) {
return () => {
const record = this.getRecord();
suggestionFunction()
.then( ( suggestion ) => {
this.insertString( record, `${ prefix }${ suggestion } ` );
} )
.catch( () => {} );
};
}
/**
* Handles a paste event from the native Aztec Wrapper.
*
* @param {Object} event The paste event which wraps `nativeEvent`.
*/
onPaste( event ) {
const { onPaste, onChange } = this.props;
const { activeFormats = [] } = this.state;
const { pastedText, pastedHtml, files } = event.nativeEvent;
const currentRecord = this.createRecord();
event.preventDefault();
// 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 );
onChange( this.value );
// Allows us to ask for this information when we get a report.
window.console.log( 'Created link:\n\n', trimmedText );
return;
}
}
if ( onPaste ) {
onPaste( {
value: currentRecord,
onChange: this.onFormatChange,
html: pastedHtml,
plainText: pastedText,
files,
activeFormats,
} );
}
}
onFocus() {
this.isTouched = true;
const { unstableOnFocus, onSelectionChange } = this.props;
if ( unstableOnFocus ) {
unstableOnFocus();
}
// We know for certain that on focus, the old selection is invalid. It
// will be recalculated on `selectionchange`.
onSelectionChange( this.selectionStart, this.selectionEnd );
this.lastAztecEventType = 'focus';
}
onBlur( event ) {
this.isTouched = false;
// Check if value is up to date with latest state of native AztecView.
if (
event.nativeEvent.text &&
event.nativeEvent.text !== this.props.value
) {
this.onTextUpdate( event );
}
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 );
}
shouldDropEventFromAztec( event, logText ) {
const shouldDrop =
! this.isIOS && event.nativeEvent.eventCount <= this.lastEventCount;
if ( shouldDrop ) {
window.console.log(
`Dropping ${ logText } from Aztec as its event counter is older than latest sent to the native side. Got ${ event.nativeEvent.eventCount } but lastEventCount is ${ this.lastEventCount }.`
);
}
return shouldDrop;
}
/**
* Determines whether the text input should receive focus after an update.
* For cases where a RichText with a value is merged with an empty one.
*
* @param {Object} prevProps - The previous props of the component.
* @return {boolean} True if the text input should receive focus, false otherwise.
*/
shouldFocusTextInputAfterMerge( prevProps ) {
const {
__unstableIsSelected: isSelected,
blockIsSelected,
selectionStart,
selectionEnd,
__unstableMobileNoFocusOnMount,
} = this.props;
const {
__unstableIsSelected: prevIsSelected,
blockIsSelected: prevBlockIsSelected,
} = prevProps;
const noSelectionValues =
selectionStart === undefined && selectionEnd === undefined;
const textInputWasNotFocused = ! prevIsSelected && ! isSelected;
return (
! __unstableMobileNoFocusOnMount &&
noSelectionValues &&
textInputWasNotFocused &&
! prevBlockIsSelected &&
blockIsSelected
);
}
onSelectionChangeFromAztec( start, end, text, event ) {
if ( this.shouldDropEventFromAztec( event, 'onSelectionChange' ) ) {
return;
}
// `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.removeRootTagsProducedByAztec(
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 );
// Aztec can send us selection change events after it has lost focus.
// For instance the autocorrect feature will complete a partially written
// word when resigning focus, causing a selection change event.
// Forwarding this selection change could cause this RichText to regain
// focus and start a focus loop.
//
// See https://github.com/wordpress-mobile/gutenberg-mobile/issues/1696
if ( this.props.__unstableIsSelected ) {
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 ) {
const { preserveWhiteSpace } = this.props;
// Handle deprecated `children` and `node` sources.
if ( Array.isArray( value ) ) {
return create( {
html: childrenBlock.toHTML( value ),
preserveWhiteSpace,
} );
}
if ( this.props.format === 'string' ) {
return create( {
html: value,
preserveWhiteSpace,
} );
}
// 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;
}
manipulateEventCounterToForceNativeToRefresh() {
if ( this.isIOS ) {
this.lastEventCount = undefined;
return;
}
if ( typeof this.lastEventCount !== 'undefined' ) {
this.lastEventCount += 100; // bump by a hundred, hopefully native hasn't bombarded the JS side in the meantime.
} // no need to bump when 'undefined' as native side won't receive the key when the value is undefined, and that will cause force updating anyway,
// see https://github.com/WordPress/gutenberg/blob/82e578dcc75e67891c750a41a04c1e31994192fc/packages/react-native-aztec/android/src/main/java/org/wordpress/mobile/ReactNativeAztec/ReactAztecManager.java#L213-L215
}
shouldComponentUpdate( nextProps, nextState ) {
if (
nextProps.tagName !== this.props.tagName ||
nextProps.reversed !== this.props.reversed ||
nextProps.start !== this.props.start
) {
this.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
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.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
}
if ( ! this.comesFromAztec ) {
if (
typeof nextProps.selectionStart !== 'undefined' &&
typeof nextProps.selectionEnd !== 'undefined' &&
nextProps.selectionStart !== this.props.selectionStart &&
nextProps.selectionStart !== this.selectionStart &&
nextProps.__unstableIsSelected
) {
this.needsSelectionUpdate = true;
this.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
}
// For font size changes from a prop value a force refresh
// is needed without the selection update.
if ( nextProps?.fontSize !== this.props?.fontSize ) {
this.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
}
if (
( nextProps?.style?.fontSize !== this.props?.style?.fontSize &&
nextState.currentFontSize !==
this.state.currentFontSize ) ||
nextState.currentFontSize !== this.state.currentFontSize ||
nextProps?.style?.lineHeight !== this.props?.style?.lineHeight
) {
this.needsSelectionUpdate = true;
this.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
}
}
return true;
}
componentDidMount() {
// Request focus if wrapping block is selected and parent hasn't inhibited the focus request. This method of focusing
// is trying to implement the web-side counterpart of BlockList's `focusTabbable` where the BlockList is focusing an
// inputbox by searching the DOM. We don't have the DOM in RN so, using the combination of blockIsSelected and __unstableMobileNoFocusOnMount
// to determine if we should focus the RichText.
if (
this.props.blockIsSelected &&
! this.props.__unstableMobileNoFocusOnMount
) {
this._editor.focus();
this.onSelectionChange(
this.props.selectionStart || 0,
this.props.selectionEnd || 0
);
}
}
componentWillUnmount() {
if ( this._editor.isFocused() ) {
this._editor.blur();
}
}
componentDidUpdate( prevProps ) {
const { style, tagName } = this.props;
const { currentFontSize } = this.state;
if ( this.props.value !== this.value ) {
this.value = this.props.value;
}
const { __unstableIsSelected: prevIsSelected } = prevProps;
const { __unstableIsSelected: isSelected } = this.props;
if ( isSelected && ! prevIsSelected ) {
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.shouldFocusTextInputAfterMerge( prevProps ) ) {
// Since this is happening when merging blocks, the selection should be at the last character position.
// As a fallback the internal selectionEnd value is used.
const lastCharacterPosition =
this.value?.length ?? this.selectionEnd;
this._editor.focus();
this.props.onSelectionChange(
lastCharacterPosition,
lastCharacterPosition
);
} else if ( ! isSelected && prevIsSelected ) {
this._editor.blur();
}
// For font size values changes from the font size picker
// we compare previous values to refresh the selected font size,
// this is also used when the tag name changes
// e.g Heading block and a level change like h1->h2.
const currentFontSizeStyle = this.getParsedFontSize( style?.fontSize );
const prevFontSizeStyle = this.getParsedFontSize(
prevProps?.style?.fontSize
);
const isDifferentTag = prevProps.tagName !== tagName;
if (
( currentFontSize &&
( currentFontSizeStyle || prevFontSizeStyle ) &&
currentFontSizeStyle !== currentFontSize ) ||
isDifferentTag
) {
this.setState( {
currentFontSize: this.getFontSize( this.props ),
} );
}
}
getHtmlToRender( record, tagName ) {
// Save back to HTML from React tree.
let value = this.valueToFormat( record );
if ( value === undefined ) {
this.manipulateEventCounterToForceNativeToRefresh(); // force a refresh on the native side
value = '';
}
// On android if content is empty we need to send no content or else the placeholder will not show.
if (
! this.isIOS &&
( value === '' || value === EMPTY_PARAGRAPH_TAGS )
) {
return '';
}
if ( tagName ) {
let extraAttributes = ``;
if ( tagName === `ol` ) {
if ( this.props.reversed ) {
extraAttributes += ` reversed`;
}
if ( this.props.start ) {
extraAttributes += ` start=${ this.props.start }`;
}
}
value = `<${ tagName }${ extraAttributes }>${ value }</${ tagName }>`;
}
return value;
}
getEditableProps() {
return {
// Overridable props.
style: {},
className: 'rich-text',
onKeyDown: () => null,
};
}
getParsedFontSize( fontSize ) {
const { height, width } = Dimensions.get( 'window' );
const cssUnitOptions = { height, width, fontSize: DEFAULT_FONT_SIZE };
if ( ! fontSize ) {
return fontSize;
}
const selectedPxValue =
getPxFromCssUnit( fontSize, cssUnitOptions ) ?? DEFAULT_FONT_SIZE;
return parseFloat( selectedPxValue );
}
getFontSize( props ) {
const { baseGlobalStyles, tagName, fontSize, style } = props;
const tagNameFontSize =
baseGlobalStyles?.elements?.[ tagName ]?.typography?.fontSize;
let newFontSize = DEFAULT_FONT_SIZE;
// Disables line-height rendering for pre elements until we fix some issues with AztecAndroid.
if ( tagName === 'pre' && ! this.isIOS ) {
return undefined;
}
// For block-based themes, get the default editor font size.
if ( baseGlobalStyles?.typography?.fontSize && tagName === 'p' ) {
newFontSize = baseGlobalStyles?.typography?.fontSize;
}
// For block-based themes, get the default element font size
// e.g h1, h2.
if ( tagNameFontSize ) {
newFontSize = tagNameFontSize;
}
// For font size values provided from the styles,
// usually from values set from the font size picker.
if ( style?.fontSize ) {
newFontSize = style.fontSize;
}
// Fall-back to a font size provided from its props (if there's any)
// and there are no other default values to use.
if ( fontSize && ! tagNameFontSize && ! style?.fontSize ) {
newFontSize = fontSize;
}
// We need to always convert to px units because the selected value
// could be coming from the web where it could be stored as a different unit.
const selectedPxValue = this.getParsedFontSize( newFontSize );
return selectedPxValue;
}
getLineHeight() {
const { baseGlobalStyles, tagName, lineHeight, style } = this.props;
const tagNameLineHeight =
baseGlobalStyles?.elements?.[ tagName ]?.typography?.lineHeight;
let newLineHeight;
// Disables line-height rendering for pre elements until we fix some issues with AztecAndroid.
if ( tagName === 'pre' && ! this.isIOS ) {
return undefined;
}
if ( ! this.getIsBlockBasedTheme() ) {
return;
}
// For block-based themes, get the default editor line height.
if ( baseGlobalStyles?.typography?.lineHeight && tagName === 'p' ) {
newLineHeight = parseFloat(
baseGlobalStyles?.typography?.lineHeight
);