-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.native.js
764 lines (698 loc) · 19.7 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
/**
* External dependencies
*/
import classnames from 'classnames';
import { omit } from 'lodash';
/**
* WordPress dependencies
*/
import {
RawHTML,
Platform,
useRef,
useCallback,
forwardRef,
} from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import {
pasteHandler,
children as childrenSource,
getBlockTransforms,
findTransform,
isUnmodifiedDefaultBlock,
} from '@wordpress/blocks';
import { useInstanceId, useMergeRefs } from '@wordpress/compose';
import {
__experimentalRichText as RichText,
__unstableCreateElement,
isEmpty,
__unstableIsEmptyLine as isEmptyLine,
insert,
__unstableInsertLineSeparator as insertLineSeparator,
create,
replace,
split,
__UNSTABLE_LINE_SEPARATOR as LINE_SEPARATOR,
toHTMLString,
slice,
} from '@wordpress/rich-text';
import deprecated from '@wordpress/deprecated';
import { isURL } from '@wordpress/url';
/**
* Internal dependencies
*/
import Autocomplete from '../autocomplete';
import { useBlockEditContext } from '../block-edit';
import { RemoveBrowserShortcuts } from './remove-browser-shortcuts';
import { filePasteHandler } from './file-paste-handler';
import FormatToolbarContainer from './format-toolbar-container';
import { useNativeProps } from './use-native-props';
import { store as blockEditorStore } from '../../store';
import {
addActiveFormats,
getMultilineTag,
getAllowedFormats,
isShortcode,
createLinkInParagraph,
} from './utils';
import EmbedHandlerPicker from './embed-handler-picker';
const wrapperClasses = 'block-editor-rich-text';
const classes = 'block-editor-rich-text__editable';
function RichTextWrapper(
{
children,
tagName,
start,
reversed,
value: originalValue,
onChange: originalOnChange,
isSelected: originalIsSelected,
multiline,
inlineToolbar,
wrapperClassName,
autocompleters,
onReplace,
placeholder,
allowedFormats,
formattingControls,
withoutInteractiveFormatting,
onRemove,
onMerge,
onSplit,
__unstableOnSplitAtEnd: onSplitAtEnd,
__unstableOnSplitMiddle: onSplitMiddle,
identifier,
preserveWhiteSpace,
__unstablePastePlainText: pastePlainText,
__unstableEmbedURLOnPaste,
__unstableDisableFormats: disableFormats,
disableLineBreaks,
unstableOnFocus,
__unstableAllowPrefixTransformations,
__unstableMultilineRootTag,
// Native props.
__unstableMobileNoFocusOnMount,
deleteEnter,
placeholderTextColor,
textAlign,
selectionColor,
tagsToEliminate,
rootTagsToEliminate,
disableEditingMenu,
fontSize,
fontFamily,
fontWeight,
fontStyle,
minWidth,
maxWidth,
onBlur,
setRef,
...props
},
forwardedRef
) {
const instanceId = useInstanceId( RichTextWrapper );
identifier = identifier || instanceId;
const fallbackRef = useRef();
const { clientId, isSelected: blockIsSelected } = useBlockEditContext();
const nativeProps = useNativeProps();
const embedHandlerPickerRef = useRef();
const selector = ( select ) => {
const {
getSelectionStart,
getSelectionEnd,
getSettings,
didAutomaticChange,
getBlock,
isMultiSelecting,
hasMultiSelection,
} = select( blockEditorStore );
const selectionStart = getSelectionStart();
const selectionEnd = getSelectionEnd();
const { __experimentalUndo: undo } = getSettings();
let isSelected;
if ( originalIsSelected === undefined ) {
isSelected =
selectionStart.clientId === clientId &&
selectionStart.attributeKey === identifier;
} else if ( originalIsSelected ) {
isSelected = selectionStart.clientId === clientId;
}
let extraProps = {};
if ( Platform.OS === 'native' ) {
// If the block of this RichText is unmodified then it's a candidate for replacing when adding a new block.
// In order to fix https://github.com/wordpress-mobile/gutenberg-mobile/issues/1126, let's blur on unmount in that case.
// This apparently assumes functionality the BlockHlder actually.
const block = clientId && getBlock( clientId );
const shouldBlurOnUnmount =
block && isSelected && isUnmodifiedDefaultBlock( block );
extraProps = {
shouldBlurOnUnmount,
};
}
return {
selectionStart: isSelected ? selectionStart.offset : undefined,
selectionEnd: isSelected ? selectionEnd.offset : undefined,
isSelected,
didAutomaticChange: didAutomaticChange(),
disabled: isMultiSelecting() || hasMultiSelection(),
undo,
...extraProps,
};
};
// This selector must run on every render so the right selection state is
// retrieved from the store on merge.
// To do: fix this somehow.
const {
selectionStart,
selectionEnd,
isSelected,
didAutomaticChange,
disabled,
undo,
shouldBlurOnUnmount,
} = useSelect( selector );
const {
__unstableMarkLastChangeAsPersistent,
enterFormattedText,
exitFormattedText,
selectionChange,
__unstableMarkAutomaticChange,
} = useDispatch( blockEditorStore );
const multilineTag = getMultilineTag( multiline );
const adjustedAllowedFormats = getAllowedFormats( {
allowedFormats,
formattingControls,
disableFormats,
} );
const hasFormats =
! adjustedAllowedFormats || adjustedAllowedFormats.length > 0;
let adjustedValue = originalValue;
let adjustedOnChange = originalOnChange;
// Handle deprecated format.
if ( Array.isArray( originalValue ) ) {
adjustedValue = childrenSource.toHTML( originalValue );
adjustedOnChange = ( newValue ) =>
originalOnChange(
childrenSource.fromDOM(
__unstableCreateElement( document, newValue ).childNodes
)
);
}
const onSelectionChange = useCallback(
( selectionChangeStart, selectionChangeEnd ) => {
selectionChange(
clientId,
identifier,
selectionChangeStart,
selectionChangeEnd
);
},
[ clientId, identifier ]
);
const onDelete = useCallback(
( { value, isReverse } ) => {
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( value ) && isReverse ) {
onRemove( ! isReverse );
}
},
[ onMerge, onRemove ]
);
/**
* Signals to the RichText owner that the block can be replaced with two
* blocks as a result of splitting the block by pressing enter, or with
* blocks as a result of splitting the block by pasting block content in the
* instance.
*
* @param {Object} record The rich text value to split.
* @param {Array} pastedBlocks The pasted blocks to insert, if any.
*/
const splitValue = useCallback(
( record, pastedBlocks = [] ) => {
if ( ! onReplace || ! onSplit ) {
return;
}
const blocks = [];
const [ before, after ] = split( record );
const hasPastedBlocks = pastedBlocks.length > 0;
let lastPastedBlockIndex = -1;
// Consider the after value to be the original it is not empty and
// the before value *is* empty.
const isAfterOriginal = isEmpty( before ) && ! isEmpty( after );
// Create a block with the content before the caret if there's no pasted
// blocks, or if there are pasted blocks and the value is not empty.
// We do not want a leading empty block on paste, but we do if split
// with e.g. the enter key.
if ( ! hasPastedBlocks || ! isEmpty( before ) ) {
blocks.push(
onSplit(
toHTMLString( {
value: before,
multilineTag,
} ),
! isAfterOriginal
)
);
lastPastedBlockIndex += 1;
}
if ( hasPastedBlocks ) {
blocks.push( ...pastedBlocks );
lastPastedBlockIndex += pastedBlocks.length;
} else if ( onSplitMiddle ) {
blocks.push( onSplitMiddle() );
}
// If there's pasted blocks, append a block with non empty content
// after the caret. Otherwise, do append an empty block if there
// is no `onSplitMiddle` prop, but if there is and the content is
// empty, the middle block is enough to set focus in.
if (
hasPastedBlocks
? ! isEmpty( after )
: ! onSplitMiddle || ! isEmpty( after )
) {
blocks.push(
onSplit(
toHTMLString( {
value: after,
multilineTag,
} ),
isAfterOriginal
)
);
}
// If there are pasted blocks, set the selection to the last one.
// Otherwise, set the selection to the second block.
const indexToSelect = hasPastedBlocks ? lastPastedBlockIndex : 1;
// If there are pasted blocks, move the caret to the end of the selected block
// Otherwise, retain the default value.
const initialPosition = hasPastedBlocks ? -1 : 0;
onReplace( blocks, indexToSelect, initialPosition );
},
[ onReplace, onSplit, multilineTag, onSplitMiddle ]
);
const onEnter = useCallback(
( { value, onChange, shiftKey } ) => {
const canSplit = onReplace && onSplit;
if ( onReplace ) {
const transforms = getBlockTransforms( 'from' ).filter(
( { type } ) => type === 'enter'
);
const transformation = findTransform( transforms, ( item ) => {
return item.regExp.test( value.text );
} );
if ( transformation ) {
onReplace( [
transformation.transform( { content: value.text } ),
] );
__unstableMarkAutomaticChange();
}
}
if ( multiline ) {
if ( shiftKey ) {
if ( ! disableLineBreaks ) {
onChange( insert( value, '\n' ) );
}
} else if ( canSplit && isEmptyLine( value ) ) {
splitValue( value );
} else {
onChange( insertLineSeparator( value ) );
}
} else {
const { text, start: splitStart, end: splitEnd } = value;
const canSplitAtEnd =
onSplitAtEnd &&
splitStart === splitEnd &&
splitEnd === text.length;
if ( shiftKey || ( ! canSplit && ! canSplitAtEnd ) ) {
if ( ! disableLineBreaks ) {
onChange( insert( value, '\n' ) );
}
} else if ( ! canSplit && canSplitAtEnd ) {
onSplitAtEnd();
} else if ( canSplit ) {
splitValue( value );
}
}
},
[
onReplace,
onSplit,
__unstableMarkAutomaticChange,
multiline,
splitValue,
onSplitAtEnd,
]
);
const onPaste = useCallback(
( {
value,
onChange,
html,
plainText,
isInternal,
files,
activeFormats,
} ) => {
// If the data comes from a rich text instance, we can directly use it
// without filtering the data. The filters are only meant for externally
// pasted content and remove inline styles.
if ( isInternal ) {
const pastedValue = create( {
html,
multilineTag,
multilineWrapperTags:
multilineTag === 'li' ? [ 'ul', 'ol' ] : undefined,
preserveWhiteSpace,
} );
addActiveFormats( pastedValue, activeFormats );
onChange( insert( value, pastedValue ) );
return;
}
if ( pastePlainText ) {
onChange( insert( value, create( { text: plainText } ) ) );
return;
}
// Only process file if no HTML is present.
// Note: a pasted file may have the URL as plain text.
if ( files && files.length && ! html ) {
const content = pasteHandler( {
HTML: filePasteHandler( files ),
mode: 'BLOCKS',
tagName,
preserveWhiteSpace,
} );
// Allows us to ask for this information when we get a report.
// eslint-disable-next-line no-console
window.console.log( 'Received items:\n\n', files );
if ( onReplace && isEmpty( value ) ) {
onReplace( content );
} else {
splitValue( value, content );
}
return;
}
let mode = onReplace && onSplit ? 'AUTO' : 'INLINE';
// Force the blocks mode when the user is pasting
// on a new line & the content resembles a shortcode.
// Otherwise it's going to be detected as inline
// and the shortcode won't be replaced.
if (
mode === 'AUTO' &&
isEmpty( value ) &&
isShortcode( plainText )
) {
mode = 'BLOCKS';
}
const isPastedURL = isURL( plainText.trim() );
const presentEmbedHandlerPicker = () =>
embedHandlerPickerRef.current?.presentPicker( {
createEmbed: () =>
onReplace( content, content.length - 1, -1 ),
createLink: () =>
createLinkInParagraph( plainText.trim(), onReplace ),
} );
if (
__unstableEmbedURLOnPaste &&
isEmpty( value ) &&
isPastedURL
) {
mode = 'BLOCKS';
}
const content = pasteHandler( {
HTML: html,
plainText,
mode,
tagName,
preserveWhiteSpace,
} );
if ( typeof content === 'string' ) {
let valueToInsert = create( { html: content } );
addActiveFormats( valueToInsert, activeFormats );
// If the content should be multiline, we should process text
// separated by a line break as separate lines.
if ( multilineTag ) {
valueToInsert = replace(
valueToInsert,
/\n+/g,
LINE_SEPARATOR
);
}
onChange( insert( value, valueToInsert ) );
} else if ( content.length > 0 ) {
// When an URL is pasted in an empty paragraph then the EmbedHandlerPicker should showcase options allowing the transformation of that URL
// into either an Embed block or a link within the target paragraph. If the paragraph is non-empty, the URL is pasted as text.
const canPasteEmbed =
isPastedURL &&
content.length === 1 &&
content[ 0 ].name === 'core/embed';
if ( onReplace && isEmpty( value ) ) {
if ( canPasteEmbed ) {
onChange(
insert( value, create( { text: plainText } ) )
);
if ( __unstableEmbedURLOnPaste ) {
presentEmbedHandlerPicker();
}
return;
}
onReplace( content, content.length - 1, -1 );
} else {
if ( canPasteEmbed ) {
onChange(
insert( value, create( { text: plainText } ) )
);
return;
}
splitValue( value, content );
}
}
},
[
tagName,
onReplace,
onSplit,
splitValue,
__unstableEmbedURLOnPaste,
multilineTag,
preserveWhiteSpace,
pastePlainText,
]
);
const inputRule = useCallback(
( value, valueToFormat ) => {
if ( ! onReplace ) {
return;
}
const { start: startPosition, text } = value;
const characterBefore = text.slice(
startPosition - 1,
startPosition
);
// The character right before the caret must be a plain space.
if ( characterBefore !== ' ' ) {
return;
}
const trimmedTextBefore = text.slice( 0, startPosition ).trim();
const prefixTransforms = getBlockTransforms( 'from' ).filter(
( { type } ) => type === 'prefix'
);
const transformation = findTransform(
prefixTransforms,
( { prefix } ) => {
return trimmedTextBefore === prefix;
}
);
if ( ! transformation ) {
return;
}
const content = valueToFormat(
slice( value, startPosition, text.length )
);
const block = transformation.transform( content );
onReplace( [ block ] );
__unstableMarkAutomaticChange();
},
[ onReplace, __unstableMarkAutomaticChange ]
);
const mergedRef = useMergeRefs( [ forwardedRef, fallbackRef ] );
const content = (
<RichText
clientId={ clientId }
identifier={ identifier }
ref={ mergedRef }
value={ adjustedValue }
onChange={ adjustedOnChange }
selectionStart={ selectionStart }
selectionEnd={ selectionEnd }
onSelectionChange={ onSelectionChange }
tagName={ tagName }
start={ start }
reversed={ reversed }
placeholder={ placeholder }
allowedFormats={ adjustedAllowedFormats }
withoutInteractiveFormatting={ withoutInteractiveFormatting }
onEnter={ onEnter }
onDelete={ onDelete }
onPaste={ onPaste }
__unstableIsSelected={ isSelected }
__unstableInputRule={ inputRule }
__unstableMultilineTag={ multilineTag }
__unstableOnEnterFormattedText={ enterFormattedText }
__unstableOnExitFormattedText={ exitFormattedText }
__unstableOnCreateUndoLevel={ __unstableMarkLastChangeAsPersistent }
__unstableMarkAutomaticChange={ __unstableMarkAutomaticChange }
__unstableDidAutomaticChange={ didAutomaticChange }
__unstableUndo={ undo }
__unstableDisableFormats={ disableFormats }
preserveWhiteSpace={ preserveWhiteSpace }
disabled={ disabled }
unstableOnFocus={ unstableOnFocus }
__unstableAllowPrefixTransformations={
__unstableAllowPrefixTransformations
}
__unstableMultilineRootTag={ __unstableMultilineRootTag }
// Native props.
{ ...nativeProps }
blockIsSelected={
originalIsSelected !== undefined
? originalIsSelected
: blockIsSelected
}
shouldBlurOnUnmount={ shouldBlurOnUnmount }
__unstableMobileNoFocusOnMount={ __unstableMobileNoFocusOnMount }
deleteEnter={ deleteEnter }
placeholderTextColor={ placeholderTextColor }
textAlign={ textAlign }
selectionColor={ selectionColor }
tagsToEliminate={ tagsToEliminate }
rootTagsToEliminate={ rootTagsToEliminate }
disableEditingMenu={ disableEditingMenu }
fontSize={ fontSize }
fontFamily={ fontFamily }
fontWeight={ fontWeight }
fontStyle={ fontStyle }
minWidth={ minWidth }
maxWidth={ maxWidth }
onBlur={ onBlur }
setRef={ setRef }
// Props to be set on the editable container are destructured on the
// element itself for web (see below), but passed through rich text
// for native.
id={ props.id }
style={ props.style }
>
{ ( {
isSelected: nestedIsSelected,
value,
onChange,
onFocus,
editableProps,
editableTagName: TagName,
} ) => (
<>
{ children && children( { value, onChange, onFocus } ) }
{ nestedIsSelected && hasFormats && (
<FormatToolbarContainer
inline={ inlineToolbar }
anchorRef={ fallbackRef.current }
/>
) }
{ nestedIsSelected && <RemoveBrowserShortcuts /> }
<Autocomplete
onReplace={ onReplace }
completers={ autocompleters }
record={ value }
onChange={ onChange }
isSelected={ nestedIsSelected }
contentRef={ fallbackRef }
>
{ ( { listBoxId, activeId, onKeyDown } ) => (
<TagName
{ ...editableProps }
{ ...props }
style={
props.style
? {
...props.style,
...editableProps.style,
}
: editableProps.style
}
className={ classnames(
classes,
props.className,
editableProps.className
) }
aria-autocomplete={
listBoxId ? 'list' : undefined
}
aria-owns={ listBoxId }
aria-activedescendant={ activeId }
onKeyDown={ ( event ) => {
onKeyDown( event );
editableProps.onKeyDown( event );
} }
/>
) }
</Autocomplete>
<EmbedHandlerPicker ref={ embedHandlerPickerRef } />
</>
) }
</RichText>
);
if ( ! wrapperClassName ) {
return content;
}
deprecated( 'wp.blockEditor.RichText wrapperClassName prop', {
since: '5.4',
alternative: 'className prop or create your own wrapper div',
version: '6.2',
} );
return (
<div className={ classnames( wrapperClasses, wrapperClassName ) }>
{ content }
</div>
);
}
const ForwardedRichTextContainer = forwardRef( RichTextWrapper );
ForwardedRichTextContainer.Content = ( {
value,
tagName: Tag,
multiline,
...props
} ) => {
// Handle deprecated `children` and `node` sources.
if ( Array.isArray( value ) ) {
value = childrenSource.toHTML( value );
}
const MultilineTag = getMultilineTag( multiline );
if ( ! value && MultilineTag ) {
value = `<${ MultilineTag }></${ MultilineTag }>`;
}
const content = <RawHTML>{ value }</RawHTML>;
if ( Tag ) {
return <Tag { ...omit( props, [ 'format' ] ) }>{ content }</Tag>;
}
return content;
};
ForwardedRichTextContainer.isEmpty = ( value ) => {
return ! value || value.length === 0;
};
ForwardedRichTextContainer.Content.defaultProps = {
format: 'string',
value: '',
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/rich-text/README.md
*/
export default ForwardedRichTextContainer;
export { RichTextShortcut } from './shortcut';
export { RichTextToolbarButton } from './toolbar-button';
export { __unstableRichTextInputEvent } from './input-event';