-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
create.js
610 lines (536 loc) · 16.4 KB
/
create.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
/**
* WordPress dependencies
*/
import { select } from '@wordpress/data';
/**
* Internal dependencies
*/
import { store as richTextStore } from './store';
import { createElement } from './create-element';
import { mergePair } from './concat';
import {
LINE_SEPARATOR,
OBJECT_REPLACEMENT_CHARACTER,
ZWNBSP,
} from './special-characters';
/**
* @typedef {Object} RichTextFormat
*
* @property {string} type Format type.
*/
/**
* @typedef {Array<RichTextFormat>} RichTextFormatList
*/
/**
* @typedef {Object} RichTextValue
*
* @property {string} text Text.
* @property {Array<RichTextFormatList>} formats Formats.
* @property {Array<RichTextFormat>} replacements Replacements.
* @property {number|undefined} start Selection start.
* @property {number|undefined} end Selection end.
*/
function createEmptyValue() {
return {
formats: [],
replacements: [],
text: '',
};
}
function simpleFindKey( object, value ) {
for ( const key in object ) {
if ( object[ key ] === value ) {
return key;
}
}
}
function toFormat( { type, attributes } ) {
let formatType;
if ( attributes && attributes.class ) {
formatType = select( richTextStore ).getFormatTypeForClassName(
attributes.class
);
if ( formatType ) {
// Preserve any additional classes.
attributes.class = ` ${ attributes.class } `
.replace( ` ${ formatType.className } `, ' ' )
.trim();
if ( ! attributes.class ) {
delete attributes.class;
}
}
}
if ( ! formatType ) {
formatType = select( richTextStore ).getFormatTypeForBareElement(
type
);
}
if ( ! formatType ) {
return attributes ? { type, attributes } : { type };
}
if (
formatType.__experimentalCreatePrepareEditableTree &&
! formatType.__experimentalCreateOnChangeEditableValue
) {
return null;
}
if ( ! attributes ) {
return { type: formatType.name };
}
const registeredAttributes = {};
const unregisteredAttributes = {};
for ( const name in attributes ) {
const key = simpleFindKey( formatType.attributes, name );
if ( key ) {
registeredAttributes[ key ] = attributes[ name ];
} else {
unregisteredAttributes[ name ] = attributes[ name ];
}
}
return {
type: formatType.name,
attributes: registeredAttributes,
unregisteredAttributes,
};
}
/**
* Create a RichText value from an `Element` tree (DOM), an HTML string or a
* plain text string, with optionally a `Range` object to set the selection. If
* called without any input, an empty value will be created. If
* `multilineTag` is provided, any content of direct children whose type matches
* `multilineTag` will be separated by two newlines. The optional functions can
* be used to filter out content.
*
* A value will have the following shape, which you are strongly encouraged not
* to modify without the use of helper functions:
*
* ```js
* {
* text: string,
* formats: Array,
* replacements: Array,
* ?start: number,
* ?end: number,
* }
* ```
*
* As you can see, text and formatting are separated. `text` holds the text,
* including any replacement characters for objects and lines. `formats`,
* `objects` and `lines` are all sparse arrays of the same length as `text`. It
* holds information about the formatting at the relevant text indices. Finally
* `start` and `end` state which text indices are selected. They are only
* provided if a `Range` was given.
*
* @param {Object} [$1] Optional named arguments.
* @param {Element} [$1.element] Element to create value from.
* @param {string} [$1.text] Text to create value from.
* @param {string} [$1.html] HTML to create value from.
* @param {Range} [$1.range] Range to create value from.
* @param {string} [$1.multilineTag] Multiline tag if the structure is
* multiline.
* @param {Array} [$1.multilineWrapperTags] Tags where lines can be found if
* nesting is possible.
* @param {boolean} [$1.preserveWhiteSpace] Whether or not to collapse white
* space characters.
* @param {boolean} [$1.__unstableIsEditableTree]
*
* @return {RichTextValue} A rich text value.
*/
export function create( {
element,
text,
html,
range,
multilineTag,
multilineWrapperTags,
__unstableIsEditableTree: isEditableTree,
preserveWhiteSpace,
} = {} ) {
if ( typeof text === 'string' && text.length > 0 ) {
return {
formats: Array( text.length ),
replacements: Array( text.length ),
text,
};
}
if ( typeof html === 'string' && html.length > 0 ) {
// It does not matter which document this is, we're just using it to
// parse.
element = createElement( document, html );
}
if ( typeof element !== 'object' ) {
return createEmptyValue();
}
if ( ! multilineTag ) {
return createFromElement( {
element,
range,
isEditableTree,
preserveWhiteSpace,
} );
}
return createFromMultilineElement( {
element,
range,
multilineTag,
multilineWrapperTags,
isEditableTree,
preserveWhiteSpace,
} );
}
/**
* Helper to accumulate the value's selection start and end from the current
* node and range.
*
* @param {Object} accumulator Object to accumulate into.
* @param {Node} node Node to create value with.
* @param {Range} range Range to create value with.
* @param {Object} value Value that is being accumulated.
*/
function accumulateSelection( accumulator, node, range, value ) {
if ( ! range ) {
return;
}
const { parentNode } = node;
const { startContainer, startOffset, endContainer, endOffset } = range;
const currentLength = accumulator.text.length;
// Selection can be extracted from value.
if ( value.start !== undefined ) {
accumulator.start = currentLength + value.start;
// Range indicates that the current node has selection.
} else if ( node === startContainer && node.nodeType === node.TEXT_NODE ) {
accumulator.start = currentLength + startOffset;
// Range indicates that the current node is selected.
} else if (
parentNode === startContainer &&
node === startContainer.childNodes[ startOffset ]
) {
accumulator.start = currentLength;
// Range indicates that the selection is after the current node.
} else if (
parentNode === startContainer &&
node === startContainer.childNodes[ startOffset - 1 ]
) {
accumulator.start = currentLength + value.text.length;
// Fallback if no child inside handled the selection.
} else if ( node === startContainer ) {
accumulator.start = currentLength;
}
// Selection can be extracted from value.
if ( value.end !== undefined ) {
accumulator.end = currentLength + value.end;
// Range indicates that the current node has selection.
} else if ( node === endContainer && node.nodeType === node.TEXT_NODE ) {
accumulator.end = currentLength + endOffset;
// Range indicates that the current node is selected.
} else if (
parentNode === endContainer &&
node === endContainer.childNodes[ endOffset - 1 ]
) {
accumulator.end = currentLength + value.text.length;
// Range indicates that the selection is before the current node.
} else if (
parentNode === endContainer &&
node === endContainer.childNodes[ endOffset ]
) {
accumulator.end = currentLength;
// Fallback if no child inside handled the selection.
} else if ( node === endContainer ) {
accumulator.end = currentLength + endOffset;
}
}
/**
* Adjusts the start and end offsets from a range based on a text filter.
*
* @param {Node} node Node of which the text should be filtered.
* @param {Range} range The range to filter.
* @param {Function} filter Function to use to filter the text.
*
* @return {Object|void} Object containing range properties.
*/
function filterRange( node, range, filter ) {
if ( ! range ) {
return;
}
const { startContainer, endContainer } = range;
let { startOffset, endOffset } = range;
if ( node === startContainer ) {
startOffset = filter( node.nodeValue.slice( 0, startOffset ) ).length;
}
if ( node === endContainer ) {
endOffset = filter( node.nodeValue.slice( 0, endOffset ) ).length;
}
return { startContainer, startOffset, endContainer, endOffset };
}
/**
* Collapse any whitespace used for HTML formatting to one space character,
* because it will also be displayed as such by the browser.
*
* @param {string} string
*/
function collapseWhiteSpace( string ) {
return string.replace( /[\n\r\t]+/g, ' ' );
}
/**
* Removes reserved characters used by rich-text (zero width non breaking spaces added by `toTree` and object replacement characters).
*
* @param {string} string
*/
export function removeReservedCharacters( string ) {
//with the global flag, note that we should create a new regex each time OR reset lastIndex state.
return string.replace(
new RegExp( `[${ ZWNBSP }${ OBJECT_REPLACEMENT_CHARACTER }]`, 'gu' ),
''
);
}
/**
* Creates a Rich Text value from a DOM element and range.
*
* @param {Object} $1 Named argements.
* @param {Element} [$1.element] Element to create value from.
* @param {Range} [$1.range] Range to create value from.
* @param {string} [$1.multilineTag] Multiline tag if the structure is
* multiline.
* @param {Array} [$1.multilineWrapperTags] Tags where lines can be found if
* nesting is possible.
* @param {boolean} [$1.preserveWhiteSpace] Whether or not to collapse white
* space characters.
* @param {Array} [$1.currentWrapperTags]
* @param {boolean} [$1.isEditableTree]
*
* @return {RichTextValue} A rich text value.
*/
function createFromElement( {
element,
range,
multilineTag,
multilineWrapperTags,
currentWrapperTags = [],
isEditableTree,
preserveWhiteSpace,
} ) {
const accumulator = createEmptyValue();
if ( ! element ) {
return accumulator;
}
if ( ! element.hasChildNodes() ) {
accumulateSelection( accumulator, element, range, createEmptyValue() );
return accumulator;
}
const length = element.childNodes.length;
// Optimise for speed.
for ( let index = 0; index < length; index++ ) {
const node = element.childNodes[ index ];
const type = node.nodeName.toLowerCase();
if ( node.nodeType === node.TEXT_NODE ) {
let filter = removeReservedCharacters;
if ( ! preserveWhiteSpace ) {
filter = ( string ) =>
removeReservedCharacters( collapseWhiteSpace( string ) );
}
const text = filter( node.nodeValue );
range = filterRange( node, range, filter );
accumulateSelection( accumulator, node, range, { text } );
// Create a sparse array of the same length as `text`, in which
// formats can be added.
accumulator.formats.length += text.length;
accumulator.replacements.length += text.length;
accumulator.text += text;
continue;
}
if ( node.nodeType !== node.ELEMENT_NODE ) {
continue;
}
if (
isEditableTree &&
// Ignore any placeholders.
( node.getAttribute( 'data-rich-text-placeholder' ) ||
// Ignore any line breaks that are not inserted by us.
( type === 'br' &&
! node.getAttribute( 'data-rich-text-line-break' ) ) )
) {
accumulateSelection( accumulator, node, range, createEmptyValue() );
continue;
}
if ( type === 'script' ) {
const value = {
formats: [ , ],
replacements: [
{
type,
attributes: {
'data-rich-text-script':
node.getAttribute( 'data-rich-text-script' ) ||
encodeURIComponent( node.innerHTML ),
},
},
],
text: OBJECT_REPLACEMENT_CHARACTER,
};
accumulateSelection( accumulator, node, range, value );
mergePair( accumulator, value );
continue;
}
if ( type === 'br' ) {
accumulateSelection( accumulator, node, range, createEmptyValue() );
mergePair( accumulator, create( { text: '\n' } ) );
continue;
}
const format = toFormat( {
type,
attributes: getAttributes( { element: node } ),
} );
if (
multilineWrapperTags &&
multilineWrapperTags.indexOf( type ) !== -1
) {
const value = createFromMultilineElement( {
element: node,
range,
multilineTag,
multilineWrapperTags,
currentWrapperTags: [ ...currentWrapperTags, format ],
isEditableTree,
preserveWhiteSpace,
} );
accumulateSelection( accumulator, node, range, value );
mergePair( accumulator, value );
continue;
}
const value = createFromElement( {
element: node,
range,
multilineTag,
multilineWrapperTags,
isEditableTree,
preserveWhiteSpace,
} );
accumulateSelection( accumulator, node, range, value );
if ( ! format ) {
mergePair( accumulator, value );
} else if ( value.text.length === 0 ) {
if ( format.attributes ) {
mergePair( accumulator, {
formats: [ , ],
replacements: [ format ],
text: OBJECT_REPLACEMENT_CHARACTER,
} );
}
} else {
// Indices should share a reference to the same formats array.
// Only create a new reference if `formats` changes.
function mergeFormats( formats ) {
if ( mergeFormats.formats === formats ) {
return mergeFormats.newFormats;
}
const newFormats = formats
? [ format, ...formats ]
: [ format ];
mergeFormats.formats = formats;
mergeFormats.newFormats = newFormats;
return newFormats;
}
// Since the formats parameter can be `undefined`, preset
// `mergeFormats` with a new reference.
mergeFormats.newFormats = [ format ];
mergePair( accumulator, {
...value,
formats: Array.from( value.formats, mergeFormats ),
} );
}
}
return accumulator;
}
/**
* Creates a rich text value from a DOM element and range that should be
* multiline.
*
* @param {Object} $1 Named argements.
* @param {Element} [$1.element] Element to create value from.
* @param {Range} [$1.range] Range to create value from.
* @param {string} [$1.multilineTag] Multiline tag if the structure is
* multiline.
* @param {Array} [$1.multilineWrapperTags] Tags where lines can be found if
* nesting is possible.
* @param {boolean} [$1.currentWrapperTags] Whether to prepend a line
* separator.
* @param {boolean} [$1.preserveWhiteSpace] Whether or not to collapse white
* space characters.
* @param {boolean} [$1.isEditableTree]
*
* @return {RichTextValue} A rich text value.
*/
function createFromMultilineElement( {
element,
range,
multilineTag,
multilineWrapperTags,
currentWrapperTags = [],
isEditableTree,
preserveWhiteSpace,
} ) {
const accumulator = createEmptyValue();
if ( ! element || ! element.hasChildNodes() ) {
return accumulator;
}
const length = element.children.length;
// Optimise for speed.
for ( let index = 0; index < length; index++ ) {
const node = element.children[ index ];
if ( node.nodeName.toLowerCase() !== multilineTag ) {
continue;
}
const value = createFromElement( {
element: node,
range,
multilineTag,
multilineWrapperTags,
currentWrapperTags,
isEditableTree,
preserveWhiteSpace,
} );
// Multiline value text should be separated by a line separator.
if ( index !== 0 || currentWrapperTags.length > 0 ) {
mergePair( accumulator, {
formats: [ , ],
replacements:
currentWrapperTags.length > 0
? [ currentWrapperTags ]
: [ , ],
text: LINE_SEPARATOR,
} );
}
accumulateSelection( accumulator, node, range, value );
mergePair( accumulator, value );
}
return accumulator;
}
/**
* Gets the attributes of an element in object shape.
*
* @param {Object} $1 Named argements.
* @param {Element} $1.element Element to get attributes from.
*
* @return {Object|void} Attribute object or `undefined` if the element has no
* attributes.
*/
function getAttributes( { element } ) {
if ( ! element.hasAttributes() ) {
return;
}
const length = element.attributes.length;
let accumulator;
// Optimise for speed.
for ( let i = 0; i < length; i++ ) {
const { name, value } = element.attributes[ i ];
if ( name.indexOf( 'data-rich-text-' ) === 0 ) {
continue;
}
const safeName = /^on/i.test( name )
? 'data-disable-rich-text-' + name
: name;
accumulator = accumulator || {};
accumulator[ safeName ] = value;
}
return accumulator;
}