-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
576 lines (527 loc) · 14.8 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
/**
* External dependencies
*/
import clsx from 'clsx';
/**
* WordPress dependencies
*/
import {
useRef,
useCallback,
forwardRef,
createContext,
useContext,
} from '@wordpress/element';
import { useDispatch, useRegistry, useSelect } from '@wordpress/data';
import { useMergeRefs, useInstanceId } from '@wordpress/compose';
import {
__unstableUseRichText as useRichText,
removeFormat,
} from '@wordpress/rich-text';
import { Popover } from '@wordpress/components';
import { store as blocksStore } from '@wordpress/blocks';
import deprecated from '@wordpress/deprecated';
import { __, sprintf } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { useBlockEditorAutocompleteProps } from '../autocomplete';
import { useBlockEditContext } from '../block-edit';
import { blockBindingsKey, isPreviewModeKey } from '../block-edit/context';
import FormatToolbarContainer from './format-toolbar-container';
import { store as blockEditorStore } from '../../store';
import { useMarkPersistent } from './use-mark-persistent';
import { useFormatTypes } from './use-format-types';
import { useEventListeners } from './event-listeners';
import FormatEdit from './format-edit';
import { getAllowedFormats } from './utils';
import { Content, valueToHTMLString } from './content';
import { withDeprecations } from './with-deprecations';
import { unlock } from '../../lock-unlock';
import { canBindBlock } from '../../hooks/use-bindings-attributes';
import BlockContext from '../block-context';
export const keyboardShortcutContext = createContext();
export const inputEventContext = createContext();
const instanceIdKey = Symbol( 'instanceId' );
/**
* Removes props used for the native version of RichText so that they are not
* passed to the DOM element and log warnings.
*
* @param {Object} props Props to filter.
*
* @return {Object} Filtered props.
*/
function removeNativeProps( props ) {
const {
__unstableMobileNoFocusOnMount,
deleteEnter,
placeholderTextColor,
textAlign,
selectionColor,
tagsToEliminate,
disableEditingMenu,
fontSize,
fontFamily,
fontWeight,
fontStyle,
minWidth,
maxWidth,
disableSuggestions,
disableAutocorrection,
...restProps
} = props;
return restProps;
}
export function RichTextWrapper(
{
children,
tagName = 'div',
value: adjustedValue = '',
onChange: adjustedOnChange,
isSelected: originalIsSelected,
multiline,
inlineToolbar,
wrapperClassName,
autocompleters,
onReplace,
placeholder,
allowedFormats,
withoutInteractiveFormatting,
onRemove,
onMerge,
onSplit,
__unstableOnSplitAtEnd: onSplitAtEnd,
__unstableOnSplitAtDoubleLineEnd: onSplitAtDoubleLineEnd,
identifier,
preserveWhiteSpace,
__unstablePastePlainText: pastePlainText,
__unstableEmbedURLOnPaste,
__unstableDisableFormats: disableFormats,
disableLineBreaks,
__unstableAllowPrefixTransformations,
readOnly,
...props
},
forwardedRef
) {
props = removeNativeProps( props );
if ( onSplit ) {
deprecated( 'wp.blockEditor.RichText onSplit prop', {
since: '6.4',
alternative: 'block.json support key: "splitting"',
} );
}
const instanceId = useInstanceId( RichTextWrapper );
const anchorRef = useRef();
const context = useBlockEditContext();
const { clientId, isSelected: isBlockSelected, name: blockName } = context;
const blockBindings = context[ blockBindingsKey ];
const blockContext = useContext( BlockContext );
const registry = useRegistry();
const selector = ( select ) => {
// Avoid subscribing to the block editor store if the block is not
// selected.
if ( ! isBlockSelected ) {
return { isSelected: false };
}
const { getSelectionStart, getSelectionEnd } =
select( blockEditorStore );
const selectionStart = getSelectionStart();
const selectionEnd = getSelectionEnd();
let isSelected;
if ( originalIsSelected === undefined ) {
isSelected =
selectionStart.clientId === clientId &&
selectionEnd.clientId === clientId &&
( identifier
? selectionStart.attributeKey === identifier
: selectionStart[ instanceIdKey ] === instanceId );
} else if ( originalIsSelected ) {
isSelected = selectionStart.clientId === clientId;
}
return {
selectionStart: isSelected ? selectionStart.offset : undefined,
selectionEnd: isSelected ? selectionEnd.offset : undefined,
isSelected,
};
};
const { selectionStart, selectionEnd, isSelected } = useSelect( selector, [
clientId,
identifier,
instanceId,
originalIsSelected,
isBlockSelected,
] );
const { disableBoundBlock, bindingsPlaceholder, bindingsLabel } = useSelect(
( select ) => {
if (
! blockBindings?.[ identifier ] ||
! canBindBlock( blockName )
) {
return {};
}
const relatedBinding = blockBindings[ identifier ];
const { getBlockBindingsSource } = unlock( select( blocksStore ) );
const blockBindingsSource = getBlockBindingsSource(
relatedBinding.source
);
const _disableBoundBlock =
! blockBindingsSource?.canUserEditValue?.( {
select,
context: blockContext,
args: relatedBinding.args,
} );
// Don't modify placeholders if value is not empty.
if ( adjustedValue.length > 0 ) {
return {
disableBoundBlock: _disableBoundBlock,
// Null values will make them fall back to the default behavior.
bindingsPlaceholder: null,
bindingsLabel: null,
};
}
const { getBlockAttributes } = select( blockEditorStore );
const blockAttributes = getBlockAttributes( clientId );
const fieldsList = blockBindingsSource?.getFieldsList?.( {
registry,
context: blockContext,
} );
const bindingKey =
fieldsList?.[ relatedBinding?.args?.key ]?.label ??
blockBindingsSource?.label;
const _bindingsPlaceholder = _disableBoundBlock
? bindingKey
: sprintf(
/* translators: %s: connected field label or source label */
__( 'Add %s' ),
bindingKey
);
const _bindingsLabel = _disableBoundBlock
? relatedBinding?.args?.key || blockBindingsSource?.label
: sprintf(
/* translators: %s: source label or key */
__( 'Empty %s; start writing to edit its value' ),
relatedBinding?.args?.key || blockBindingsSource?.label
);
return {
disableBoundBlock: _disableBoundBlock,
bindingsPlaceholder:
blockAttributes?.placeholder || _bindingsPlaceholder,
bindingsLabel: _bindingsLabel,
};
},
[
blockBindings,
identifier,
blockName,
blockContext,
registry,
adjustedValue,
]
);
const shouldDisableEditing = readOnly || disableBoundBlock;
const { getSelectionStart, getSelectionEnd, getBlockRootClientId } =
useSelect( blockEditorStore );
const { selectionChange } = useDispatch( blockEditorStore );
const adjustedAllowedFormats = getAllowedFormats( {
allowedFormats,
disableFormats,
} );
const hasFormats =
! adjustedAllowedFormats || adjustedAllowedFormats.length > 0;
const onSelectionChange = useCallback(
( start, end ) => {
const selection = {};
const unset = start === undefined && end === undefined;
const baseSelection = {
clientId,
[ identifier ? 'attributeKey' : instanceIdKey ]: identifier
? identifier
: instanceId,
};
if ( typeof start === 'number' || unset ) {
// If we are only setting the start (or the end below), which
// means a partial selection, and we're not updating a selection
// with the same client ID, abort. This means the selected block
// is a parent block.
if (
end === undefined &&
getBlockRootClientId( clientId ) !==
getBlockRootClientId( getSelectionEnd().clientId )
) {
return;
}
selection.start = {
...baseSelection,
offset: start,
};
}
if ( typeof end === 'number' || unset ) {
if (
start === undefined &&
getBlockRootClientId( clientId ) !==
getBlockRootClientId( getSelectionStart().clientId )
) {
return;
}
selection.end = {
...baseSelection,
offset: end,
};
}
selectionChange( selection );
},
[
clientId,
getBlockRootClientId,
getSelectionEnd,
getSelectionStart,
identifier,
instanceId,
selectionChange,
]
);
const {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies,
} = useFormatTypes( {
clientId,
identifier,
withoutInteractiveFormatting,
allowedFormats: adjustedAllowedFormats,
} );
function addEditorOnlyFormats( value ) {
return valueHandlers.reduce(
( accumulator, fn ) => fn( accumulator, value.text ),
value.formats
);
}
function removeEditorOnlyFormats( value ) {
formatTypes.forEach( ( formatType ) => {
// Remove formats created by prepareEditableTree, because they are editor only.
if ( formatType.__experimentalCreatePrepareEditableTree ) {
value = removeFormat(
value,
formatType.name,
0,
value.text.length
);
}
} );
return value.formats;
}
function addInvisibleFormats( value ) {
return prepareHandlers.reduce(
( accumulator, fn ) => fn( accumulator, value.text ),
value.formats
);
}
const {
value,
getValue,
onChange,
ref: richTextRef,
} = useRichText( {
value: adjustedValue,
onChange( html, { __unstableFormats, __unstableText } ) {
adjustedOnChange( html );
Object.values( changeHandlers ).forEach( ( changeHandler ) => {
changeHandler( __unstableFormats, __unstableText );
} );
},
selectionStart,
selectionEnd,
onSelectionChange,
placeholder: bindingsPlaceholder || placeholder,
__unstableIsSelected: isSelected,
__unstableDisableFormats: disableFormats,
preserveWhiteSpace,
__unstableDependencies: [ ...dependencies, tagName ],
__unstableAfterParse: addEditorOnlyFormats,
__unstableBeforeSerialize: removeEditorOnlyFormats,
__unstableAddInvisibleFormats: addInvisibleFormats,
} );
const autocompleteProps = useBlockEditorAutocompleteProps( {
onReplace,
completers: autocompleters,
record: value,
onChange,
} );
useMarkPersistent( { html: adjustedValue, value } );
const keyboardShortcuts = useRef( new Set() );
const inputEvents = useRef( new Set() );
function onFocus() {
let element = anchorRef.current;
if ( ! element ) {
return;
}
// Writing flow might be editable, so we should make sure focus goes to
// the root editable element.
while ( element.parentElement?.isContentEditable ) {
element = element.parentElement;
}
element.focus();
}
const TagName = tagName;
return (
<>
{ isSelected && (
<keyboardShortcutContext.Provider value={ keyboardShortcuts }>
<inputEventContext.Provider value={ inputEvents }>
<Popover.__unstableSlotNameProvider value="__unstable-block-tools-after">
{ children &&
children( { value, onChange, onFocus } ) }
<FormatEdit
value={ value }
onChange={ onChange }
onFocus={ onFocus }
formatTypes={ formatTypes }
forwardedRef={ anchorRef }
/>
</Popover.__unstableSlotNameProvider>
</inputEventContext.Provider>
</keyboardShortcutContext.Provider>
) }
{ isSelected && hasFormats && (
<FormatToolbarContainer
inline={ inlineToolbar }
editableContentElement={ anchorRef.current }
/>
) }
<TagName
// Overridable props.
role="textbox"
aria-multiline={ ! disableLineBreaks }
aria-readonly={ shouldDisableEditing }
{ ...props }
aria-label={
bindingsLabel || props[ 'aria-label' ] || placeholder
}
{ ...autocompleteProps }
ref={ useMergeRefs( [
// Rich text ref must be first because its focus listener
// must be set up before any other ref calls .focus() on
// mount.
richTextRef,
forwardedRef,
autocompleteProps.ref,
props.ref,
useEventListeners( {
registry,
getValue,
onChange,
__unstableAllowPrefixTransformations,
formatTypes,
onReplace,
selectionChange,
isSelected,
disableFormats,
value,
tagName,
onSplit,
__unstableEmbedURLOnPaste,
pastePlainText,
onMerge,
onRemove,
removeEditorOnlyFormats,
disableLineBreaks,
onSplitAtEnd,
onSplitAtDoubleLineEnd,
keyboardShortcuts,
inputEvents,
} ),
anchorRef,
] ) }
contentEditable={ ! shouldDisableEditing }
suppressContentEditableWarning
className={ clsx(
'block-editor-rich-text__editable',
props.className,
'rich-text'
) }
// Setting tabIndex to 0 is unnecessary, the element is already
// focusable because it's contentEditable. This also fixes a
// Safari bug where it's not possible to Shift+Click multi
// select blocks when Shift Clicking into an element with
// tabIndex because Safari will focus the element. However,
// Safari will correctly ignore nested contentEditable elements.
tabIndex={
props.tabIndex === 0 && ! shouldDisableEditing
? null
: props.tabIndex
}
data-wp-block-attribute-key={ identifier }
/>
</>
);
}
// This is the private API for the RichText component.
// It allows access to all props, not just the public ones.
export const PrivateRichText = withDeprecations(
forwardRef( RichTextWrapper )
);
PrivateRichText.Content = Content;
PrivateRichText.isEmpty = ( value ) => {
return ! value || value.length === 0;
};
// This is the public API for the RichText component.
// We wrap the PrivateRichText component to hide some props from the public API.
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/rich-text/README.md
*/
const PublicForwardedRichTextContainer = forwardRef( ( props, ref ) => {
const context = useBlockEditContext();
const isPreviewMode = context[ isPreviewModeKey ];
if ( isPreviewMode ) {
// Remove all non-content props.
const {
children,
tagName: Tag = 'div',
value,
onChange,
isSelected,
multiline,
inlineToolbar,
wrapperClassName,
autocompleters,
onReplace,
placeholder,
allowedFormats,
withoutInteractiveFormatting,
onRemove,
onMerge,
onSplit,
__unstableOnSplitAtEnd,
__unstableOnSplitAtDoubleLineEnd,
identifier,
preserveWhiteSpace,
__unstablePastePlainText,
__unstableEmbedURLOnPaste,
__unstableDisableFormats,
disableLineBreaks,
__unstableAllowPrefixTransformations,
readOnly,
...contentProps
} = removeNativeProps( props );
return (
<Tag
{ ...contentProps }
dangerouslySetInnerHTML={ {
__html: valueToHTMLString( value, multiline ),
} }
/>
);
}
return <PrivateRichText ref={ ref } { ...props } readOnly={ false } />;
} );
PublicForwardedRichTextContainer.Content = Content;
PublicForwardedRichTextContainer.isEmpty = ( value ) => {
return ! value || value.length === 0;
};
export default PublicForwardedRichTextContainer;
export { RichTextShortcut } from './shortcut';
export { RichTextToolbarButton } from './toolbar-button';
export { __unstableRichTextInputEvent } from './input-event';