Debian Codegraph @

extensions/VisualEditor/lib/ve/src/dm/lineardata/ve.dm.ElementLinearData.js

raw symbols SCIP
1 /*!
2 * VisualEditor ElementLinearData classes.
3 *
4 * Class containing element linear data and an hash-value store.
5 *
6 * @copyright See AUTHORS.txt
7 */
8
9 /**
10 * Element linear data storage
11 *
12 * @class
13 * @extends ve.dm.FlatLinearData
14 * @constructor
15 * @param {ve.dm.HashValueStore} store Hash-value store
16 * @param {Array} [data] Linear data
17 */
18 ve.dm.ElementLinearData = function VeDmElementLinearData() {
19 // Parent constructor
20 ve.dm.ElementLinearData.super.apply( this, arguments );
21 };
22
23 /* Inheritance */
24
25 OO.inheritClass( ve.dm.ElementLinearData, ve.dm.FlatLinearData );
26
27 /* Static Members */
28
29 ve.dm.ElementLinearData.static.startWordRegExp = new RegExp(
30 '^(' + unicodeJS.characterclass.patterns.word + ')'
31 );
32
33 ve.dm.ElementLinearData.static.endWordRegExp = new RegExp(
34 '(' + unicodeJS.characterclass.patterns.word + ')$'
35 );
36
37 /* Static Methods */
38
39 /**
40 * Compare two elements' basic properties
41 *
42 * Elements are comparable if they have the same type and attributes, or
43 * have the same text data. Anything semantically irrelevant is filtered
44 * out first.
45 *
46 * When changing, ensure that ve.dm.Transaction.static.compareElementsForTranslate
47 * is also updated.
48 *
49 * @param {Object|Array|string} a First element
50 * @param {Object|Array|string} b Second element
51 * @return {boolean} Elements are comparable
52 */
53 ve.dm.ElementLinearData.static.compareElementsUnannotated = function ( a, b ) {
54 let aPlain = a,
55 bPlain = b;
56
57 if ( a === b ) {
58 return true;
59 }
60
61 if ( Array.isArray( a ) ) {
62 aPlain = a[ 0 ];
63 }
64 if ( Array.isArray( b ) ) {
65 bPlain = b[ 0 ];
66 }
67 if ( typeof aPlain === 'string' && typeof bPlain === 'string' ) {
68 return aPlain === bPlain;
69 }
70
71 if ( typeof a !== typeof b ) {
72 // Different types
73 return false;
74 }
75
76 // By this point, both must be objects, so must have equal types
77 if ( a.type !== b.type ) {
78 return false;
79 }
80
81 // Both objects are open elements, so compare hashes.
82 // (NB we only need to check one as they have equal .type)
83 if ( ve.dm.LinearData.static.isOpenElementData( a ) ) {
84 // As we are using hashes, we don't need to worry about annotations
85 aPlain = ve.dm.modelRegistry.lookup( a.type ).static.getHashObject( a );
86 delete aPlain.originalDomElementsHash;
87
88 bPlain = ve.dm.modelRegistry.lookup( b.type ).static.getHashObject( b );
89 delete bPlain.originalDomElementsHash;
90
91 return ve.compare( aPlain, bPlain );
92 } else {
93 // Both objects are close elements, no need to compare attributes
94 return true;
95 }
96 };
97
98 /**
99 * Compare two elements' basic properties and annotations
100 *
101 * Elements are comparable if they have the same type, attributes,
102 * text data and annotations, as determined by
103 * ve.dm.AnnotationSet#compareTo .
104 *
105 * @param {Object|Array|string} a First element
106 * @param {Object|Array|string} b Second element
107 * @param {ve.dm.HashValueStore} aStore First element's store
108 * @param {ve.dm.HashValueStore} [bStore] Second element's store, if different
109 * @return {boolean} Elements are comparable
110 */
111 ve.dm.ElementLinearData.static.compareElements = function ( a, b, aStore, bStore ) {
112 if ( a === b ) {
113 return true;
114 }
115
116 const typeofA = typeof a;
117
118 if ( typeofA !== typeof b ) {
119 // Different types
120 return false;
121 }
122 if ( typeofA === 'string' ) {
123 // Both strings, and not equal
124 return false;
125 }
126 if ( !this.compareElementsUnannotated( a, b ) ) {
127 return false;
128 }
129 let aAnnotations, bAnnotations;
130 // Elements are equal without annotations, now compare annotations:
131 if ( Array.isArray( a ) ) {
132 aAnnotations = a[ 1 ];
133 }
134 if ( Array.isArray( b ) ) {
135 bAnnotations = b[ 1 ];
136 }
137 if ( a && a.type ) {
138 aAnnotations = a.annotations;
139 }
140 if ( b && b.type ) {
141 bAnnotations = b.annotations;
142 }
143
144 const aSet = new ve.dm.AnnotationSet( aStore, aAnnotations || [] );
145 const bSet = new ve.dm.AnnotationSet( bStore || aStore, bAnnotations || [] );
146
147 return aSet.compareTo( bSet );
148 };
149
150 /**
151 * Read the array of annotation store hashes from an item of linear data
152 *
153 * @param {string|Array|Object} item Item of linear data
154 * @return {string[]} An array of annotation store hashes
155 */
156 ve.dm.ElementLinearData.static.getAnnotationHashesFromItem = function ( item ) {
157 if ( typeof item === 'string' ) {
158 return [];
159 } else if ( item.annotations ) {
160 return item.annotations.slice();
161 } else if ( item[ 1 ] ) {
162 return item[ 1 ].slice();
163 } else {
164 return [];
165 }
166 };
167
168 /**
169 * Set annotations' store hashes at a specified offset.
170 *
171 * Cleans up data structure if hashes array is empty.
172 *
173 * @param {string|Array|Object} item Item of linear data
174 * @param {string[]} hashes Annotations' store hashes
175 * @return {string|Array|Object} Deep-copied, modified item
176 */
177 ve.dm.ElementLinearData.static.replaceAnnotationHashesForItem = function ( item, hashes ) {
178 const isElement = ve.dm.LinearData.static.isElementData( item );
179 item = ve.copy( item );
180 hashes = hashes.slice();
181 if ( hashes.length > 0 ) {
182 if ( isElement ) {
183 // New element annotation
184 item.annotations = hashes;
185 } else {
186 // New character annotation
187 const character = ve.dm.ElementLinearData.static.getCharacterDataFromItem( item );
188 item = [ character, hashes ];
189 }
190 } else {
191 if ( isElement ) {
192 // Cleanup empty element annotation
193 delete item.annotations;
194 } else {
195 // Cleanup empty character annotation
196 item = ve.dm.ElementLinearData.static.getCharacterDataFromItem( item );
197 }
198 }
199 return item;
200 };
201
202 /**
203 * Get character data from an item
204 *
205 * @param {string|Array|Object} item Item to get character data from
206 * @return {string} Character data, or '' if no character data
207 */
208 ve.dm.ElementLinearData.static.getCharacterDataFromItem = function ( item ) {
209 const data = Array.isArray( item ) ? item[ 0 ] : item;
210 return typeof data === 'string' ? data : '';
211 };
212
213 /* Methods */
214
215 /**
216 * Check if content can be inserted at an offset in document data.
217 *
218 * This method assumes that any value that has a type property that's a string is an element object.
219 *
220 * Content offsets:
221 *
222 * <heading> a </heading> <paragraph> b c <img> </img> </paragraph>
223 * . ^ ^ . ^ ^ ^ . ^ .
224 *
225 * Content offsets:
226 *
227 * <list> <listItem> </listItem> <list>
228 * . . . . .
229 *
230 * @param {number} offset Document offset
231 * @return {boolean} Content can be inserted at offset
232 */
233 ve.dm.ElementLinearData.prototype.isContentOffset = function ( offset ) {
234 // Edges are never content
235 if ( offset === 0 || offset === this.getLength() ) {
236 return false;
237 }
238 const left = this.getData( offset - 1 );
239 const right = this.getData( offset );
240 const factory = ve.dm.nodeFactory;
241 return (
242 // Data exists at offsets
243 ( left !== undefined && right !== undefined ) &&
244 (
245 // If there's content on the left or the right of the offset than we are good
246 // <paragraph>|a|</paragraph>
247 ( typeof left === 'string' || typeof right === 'string' ) ||
248 // Same checks but for annotated characters - isArray is slower, try it next
249 ( Array.isArray( left ) || Array.isArray( right ) ) ||
250 // The most expensive test are last, these deal with elements
251 (
252 // Right of a leaf
253 // <paragraph><image></image>|</paragraph>
254 (
255 // Is an element
256 typeof left.type === 'string' &&
257 // Is a closing
258 left.type.charAt( 0 ) === '/' &&
259 // Is a leaf
260 factory.isNodeContent( left.type.slice( 1 ) )
261 ) ||
262 // Left of a leaf
263 // <paragraph>|<image></image></paragraph>
264 (
265 // Is an element
266 typeof right.type === 'string' &&
267 // Is not a closing
268 right.type.charAt( 0 ) !== '/' &&
269 // Is a leaf
270 factory.isNodeContent( right.type )
271 ) ||
272 // Inside empty content branch
273 // <paragraph>|</paragraph>
274 (
275 // Inside empty element
276 '/' + left.type === right.type &&
277 // Both are content branches (right is the same type)
278 factory.canNodeContainContent( left.type )
279 )
280 )
281 )
282 );
283 };
284
285 /**
286 * Check if structure can be inserted at an offset in document data.
287 *
288 * If the {unrestricted} param is true than only offsets where any kind of element can be inserted
289 * will return true. This can be used to detect the difference between a location that a paragraph
290 * can be inserted, such as between two tables but not directly inside a table.
291 *
292 * This method assumes that any value that has a type property that's a string is an element object.
293 *
294 * Structural offsets (unrestricted = false):
295 *
296 * <heading> a </heading> <paragraph> b c <img> </img> </paragraph>
297 * ^ . . ^ . . . . . ^
298 *
299 * Structural offsets (unrestricted = true):
300 *
301 * <heading> a </heading> <paragraph> b c <img> </img> </paragraph>
302 * ^ . . ^ . . . . . ^
303 *
304 * Structural offsets (unrestricted = false):
305 *
306 * <list> <listItem> </listItem> <list>
307 * ^ ^ ^ ^ ^
308 *
309 * Content branch offsets (unrestricted = true):
310 *
311 * <list> <listItem> </listItem> <list>
312 * ^ . ^ . ^
313 *
314 * @param {number} offset Document offset
315 * @param {boolean} [unrestricted] Only return true if any kind of element can be inserted at offset
316 * @return {boolean} Structure can be inserted at offset
317 */
318 ve.dm.ElementLinearData.prototype.isStructuralOffset = function ( offset, unrestricted ) {
319 // Edges are always structural
320 if ( offset === 0 || offset === this.getLength() ) {
321 return true;
322 }
323 // Offsets must be within range and both sides must be elements
324 const left = this.getData( offset - 1 );
325 const right = this.getData( offset );
326 const factory = ve.dm.nodeFactory;
327 return (
328 (
329 left !== undefined &&
330 right !== undefined &&
331 typeof left.type === 'string' &&
332 typeof right.type === 'string'
333 ) &&
334 (
335 // Right of a branch
336 // <list><listItem><paragraph>a</paragraph>|</listItem>|</list>|
337 (
338 // Is a closing
339 left.type.charAt( 0 ) === '/' &&
340 // Is a branch or non-content leaf
341 (
342 factory.canNodeHaveChildren( left.type.slice( 1 ) ) ||
343 !factory.isNodeContent( left.type.slice( 1 ) )
344 ) &&
345 (
346 // Only apply this rule in unrestricted mode
347 !unrestricted ||
348 // Right of an unrestricted branch
349 // <list><listItem><paragraph>a</paragraph>|</listItem></list>|
350 // Both are non-content branches that can have any kind of child
351 factory.getParentNodeTypes( left.type.slice( 1 ) ) === null
352 )
353 ) ||
354 // Left of a branch
355 // |<list>|<listItem>|<paragraph>a</paragraph></listItem></list>
356 (
357 // Is not a closing
358 right.type.charAt( 0 ) !== '/' &&
359 // Is a branch or non-content leaf
360 (
361 factory.canNodeHaveChildren( right.type ) ||
362 !factory.isNodeContent( right.type )
363 ) &&
364 (
365 // Only apply this rule in unrestricted mode
366 !unrestricted ||
367 // Left of an unrestricted branch
368 // |<list><listItem>|<paragraph>a</paragraph></listItem></list>
369 // Both are non-content branches that can have any kind of child
370 factory.getParentNodeTypes( right.type ) === null
371 )
372 ) ||
373 // Inside empty non-content branch
374 // <list>|</list> or <list><listItem>|</listItem></list>
375 (
376 // Inside empty element
377 '/' + left.type === right.type &&
378 // Both are non-content branches (right is the same type)
379 factory.canNodeHaveChildrenNotContent( left.type ) &&
380 (
381 // Only apply this rule in unrestricted mode
382 !unrestricted ||
383 // Both are non-content branches that can have any kind of child
384 factory.getChildNodeTypes( left.type ) === null
385 )
386 )
387 )
388 );
389 };
390
391 /**
392 * Check for non-content elements in data.
393 *
394 * This method assumes that any value that has a type property that's a string is an element object.
395 * Elements are discovered by iterating through the entire data array.
396 *
397 * @return {boolean} True if all elements in data are content elements
398 */
399 ve.dm.ElementLinearData.prototype.isContentData = function () {
400 let i = this.getLength();
401 while ( i-- ) {
402 const item = this.getData( i );
403 if ( item.type !== undefined &&
404 item.type.charAt( 0 ) !== '/' &&
405 !ve.dm.nodeFactory.isNodeContent( item.type )
406 ) {
407 return false;
408 }
409 }
410 return true;
411 };
412
413 /**
414 * Check if an annotation can be applied at a specific offset
415 *
416 * @param {number} offset
417 * @param {ve.dm.Annotation} annotation
418 * @param {boolean} [ignoreClose] Ignore close elements, otherwise check if their open element is annotatable
419 * @return {boolean} Annotation can be applied at this offset
420 */
421 ve.dm.ElementLinearData.prototype.canTakeAnnotationAtOffset = function ( offset, annotation, ignoreClose ) {
422 if ( this.isElementData( offset ) ) {
423 if ( ignoreClose && this.isCloseElementData( offset ) ) {
424 return false;
425 }
426 const type = this.getType( offset );
427 // Structural nodes are never annotatable
428 // Disallowed annotations can't be set
429 return ve.dm.nodeFactory.isNodeContent( type ) && ve.dm.nodeFactory.canNodeTakeAnnotation( type, annotation );
430 } else {
431 // Text is always annotatable
432 return true;
433 }
434 };
435
436 /**
437 * Get annotations' store hashes covered by an offset.
438 *
439 * @param {number} offset Offset to get annotations for
440 * @param {boolean} [ignoreClose] Ignore annotations on close elements
441 * @return {string[]} An array of annotation store hashes the offset is covered by
442 * @throws {Error} offset out of bounds
443 */
444 ve.dm.ElementLinearData.prototype.getAnnotationHashesFromOffset = function ( offset, ignoreClose ) {
445 if ( offset < 0 || offset > this.getLength() ) {
446 throw new Error( 'offset ' + offset + ' out of bounds' );
447 }
448
449 // Since annotations are not stored on a closing leaf node,
450 // rewind offset by 1 to return annotations for that structure
451 if (
452 !ignoreClose &&
453 this.isCloseElementData( offset ) &&
454 !ve.dm.nodeFactory.canNodeHaveChildren( this.getType( offset ) ) // Leaf node
455 ) {
456 offset = this.getRelativeContentOffset( offset, -1 );
457 if ( offset === -1 ) {
458 return [];
459 }
460 }
461
462 const item = this.getData( offset );
463 return this.constructor.static.getAnnotationHashesFromItem( item ) || [];
464 };
465
466 /**
467 * Get annotations covered by an offset.
468 *
469 * The returned AnnotationSet is a clone of the one in the data.
470 *
471 * @param {number} offset Offset to get annotations for
472 * @param {boolean} [ignoreClose] Ignore annotations on close elements
473 * @return {ve.dm.AnnotationSet} A set of all annotation objects offset is covered by
474 * @throws {Error} offset out of bounds
475 */
476 ve.dm.ElementLinearData.prototype.getAnnotationsFromOffset = function ( offset, ignoreClose ) {
477 return new ve.dm.AnnotationSet( this.getStore(), this.getAnnotationHashesFromOffset( offset, ignoreClose ) );
478 };
479
480 /**
481 * Set annotations of data at a specified offset.
482 *
483 * Cleans up data structure if annotation set is empty.
484 *
485 * @param {number} offset Offset to set annotations at
486 * @param {ve.dm.AnnotationSet} annotations Annotations to set
487 */
488 ve.dm.ElementLinearData.prototype.setAnnotationsAtOffset = function ( offset, annotations ) {
489 this.setAnnotationHashesAtOffset( offset, this.getStore().hashAll( annotations.get() ) );
490 };
491
492 /**
493 * Set annotations' store hashes at a specified offset.
494 *
495 * Cleans up data structure if hashes array is empty.
496 *
497 * @param {number} offset Offset to set annotation hashes at
498 * @param {string[]} hashes Annotations' store hashes
499 */
500 ve.dm.ElementLinearData.prototype.setAnnotationHashesAtOffset = function ( offset, hashes ) {
501 let item = this.getData( offset );
502 item = this.constructor.static.replaceAnnotationHashesForItem( item, hashes );
503 this.setData( offset, item );
504 };
505
506 /**
507 * Set or unset an attribute at a specified offset.
508 *
509 * @param {number} offset Offset to set/unset attribute at
510 * @param {string} key Attribute name
511 * @param {any} value Value to set, or undefined to unset
512 */
513 ve.dm.ElementLinearData.prototype.setAttributeAtOffset = function ( offset, key, value ) {
514 if ( !this.isElementData( offset ) ) {
515 return;
516 }
517 this.modifyData( offset, ( item ) => {
518 if ( value === undefined ) {
519 // Clear
520 if ( item.attributes ) {
521 delete item.attributes[ key ];
522 }
523 } else {
524 // Automatically initialize attributes object
525 if ( !item.attributes ) {
526 item.attributes = {};
527 }
528 // Set
529 item.attributes[ key ] = value;
530 }
531 } );
532 };
533
534 /**
535 * Get character data at a specified offset
536 *
537 * @param {number} offset Offset to get character data from
538 * @return {string} Character data
539 */
540 ve.dm.ElementLinearData.prototype.getCharacterData = function ( offset ) {
541 const item = this.getData( offset );
542 return ve.dm.ElementLinearData.static.getCharacterDataFromItem( item );
543 };
544
545 /**
546 * Gets the range of content surrounding a given offset that's covered by a given annotation.
547 *
548 * @param {number} offset Offset to begin looking forward and backward from
549 * @param {Object} annotation Annotation to test for coverage with
550 * @return {ve.Range|null} Range of content covered by annotation, or null if offset is not covered
551 */
552 ve.dm.ElementLinearData.prototype.getAnnotatedRangeFromOffset = function ( offset, annotation ) {
553 let start = offset,
554 end = offset;
555 if ( this.getAnnotationsFromOffset( offset ).contains( annotation ) === false ) {
556 return null;
557 }
558 while ( start > 0 ) {
559 start--;
560 if ( this.getAnnotationsFromOffset( start ).contains( annotation ) === false ) {
561 start++;
562 break;
563 }
564 }
565 while ( end < this.getLength() ) {
566 if ( this.getAnnotationsFromOffset( end ).contains( annotation ) === false ) {
567 break;
568 }
569 end++;
570 }
571 return new ve.Range( start, end );
572 };
573
574 /**
575 * Get the range of an annotation found within a range.
576 *
577 * @param {ve.Range} range Range to begin looking forward and backward from
578 * @param {ve.dm.Annotation} annotation Annotation to test for coverage with
579 * @return {ve.Range|null} Range of content covered by annotation, or a copy of the range
580 */
581 ve.dm.ElementLinearData.prototype.getAnnotatedRangeFromSelection = function ( range, annotation ) {
582 let start = range.start,
583 end = range.end;
584 while ( start > 0 ) {
585 start--;
586 if ( this.getAnnotationsFromOffset( start ).contains( annotation ) === false ) {
587 start++;
588 break;
589 }
590 }
591 while ( end < this.getLength() ) {
592 if ( this.getAnnotationsFromOffset( end ).contains( annotation ) === false ) {
593 break;
594 }
595 end++;
596 }
597 return new ve.Range( start, end );
598 };
599
600 /**
601 * Get annotations common to all content in a range.
602 *
603 * @param {ve.Range} range Range to get annotations for
604 * @param {boolean} [all=false] Get all annotations found within the range, not just those that cover it
605 * @param {boolean} [nullIfContentEmpty=false] Returns null (instead of an empty ve.dm.AnnotationSet) if
606 * there is no content in the range.
607 * @return {ve.dm.AnnotationSet|null} All annotation objects range is covered by.
608 */
609 ve.dm.ElementLinearData.prototype.getAnnotationsFromRange = function ( range, all, nullIfContentEmpty ) {
610 let ignoreChildrenDepth = 0;
611 let left, right;
612 // Iterator over the range, looking for annotations, starting at the 2nd character
613 for ( let i = range.start; i < range.end; i++ ) {
614 if ( this.isElementData( i ) ) {
615 if ( ve.dm.nodeFactory.shouldIgnoreChildren( this.getType( i ) ) ) {
616 ignoreChildrenDepth += this.isOpenElementData( i ) ? 1 : -1;
617 }
618 // Skip non-content data
619 if ( !ve.dm.nodeFactory.isNodeContent( this.getType( i ) ) ) {
620 continue;
621 }
622 }
623 // Ignore things inside ignoreChildren nodes
624 if ( ignoreChildrenDepth > 0 ) {
625 continue;
626 }
627 if ( !left ) {
628 // Look at left side of range for annotations
629 left = this.getAnnotationsFromOffset( i );
630 // Shortcut for single character and zero-length ranges
631 if ( range.getLength() === 0 || range.getLength() === 1 ) {
632 return left;
633 }
634 continue;
635 }
636 // Current character annotations
637 right = this.getAnnotationsFromOffset( i );
638 if ( all && !right.isEmpty() ) {
639 left.addSet( right );
640 } else if ( !all ) {
641 // A non annotated character indicates there's no full coverage
642 if ( right.isEmpty() ) {
643 return new ve.dm.AnnotationSet( this.getStore() );
644 }
645 // Exclude comparable annotations that are in left but not right
646 left = left.getComparableAnnotationsFromSet( right );
647 // If we've reduced left down to nothing, just stop looking
648 if ( left.isEmpty() ) {
649 break;
650 }
651 }
652 }
653 return left || ( nullIfContentEmpty ? null : new ve.dm.AnnotationSet( this.getStore() ) );
654 };
655
656 /**
657 * Get the insertion annotations that should apply to a range.
658 *
659 * The semantics are intended to match Chromium's behaviour.
660 * TODO: This cannot match Firefox behaviour, which depends on the cursor's annotation
661 * boundary side, and performs a union of the annotations at each end of the selection;
662 * see https://phabricator.wikimedia.org/T113869 .
663 *
664 * @param {ve.Range} range The range into which text would be inserted
665 * @param {boolean} [startAfterAnnotations] Use annotations after cursor if collapsed
666 * @return {ve.dm.AnnotationSet} The insertion annotations that should apply
667 */
668 ve.dm.ElementLinearData.prototype.getInsertionAnnotationsFromRange = function ( range, startAfterAnnotations ) {
669 let start;
670 // Get position for start annotations
671 if ( range.isCollapsed() && !startAfterAnnotations ) {
672 // Use the position just before the cursor
673 start = Math.max( 0, range.start - 1 );
674 } else {
675 // If uncollapsed, use the first character of the selection
676 // If collapsed, use the first position after the cursor
677 start = range.start;
678 }
679
680 let startAnnotations;
681 // Get startAnnotations: the annotations that apply at the selection start
682 if ( this.isContentOffset( start ) ) {
683 startAnnotations = this.getAnnotationsFromOffset( start );
684 } else {
685 startAnnotations = new ve.dm.AnnotationSet( this.getStore() );
686 }
687
688 let afterAnnotations;
689 // Get afterAnnotations: the annotations that apply straight after the selection
690 if ( this.isContentOffset( range.end ) ) {
691 afterAnnotations = this.getAnnotationsFromOffset( range.end );
692 } else {
693 // Use the empty set
694 afterAnnotations = new ve.dm.AnnotationSet( this.getStore() );
695 }
696
697 // Return those startAnnotations that either continue in afterAnnotations or
698 // should get added to appended content
699 return startAnnotations.filter( ( annotation ) => annotation.constructor.static.applyToAppendedContent ||
700 afterAnnotations.containsComparable( annotation ) );
701 };
702
703 /**
704 * Check if the range has any annotations
705 *
706 * @param {ve.Range} range Range to check for annotations
707 * @return {boolean} The range contains at least one annotation
708 */
709 ve.dm.ElementLinearData.prototype.hasAnnotationsInRange = function ( range ) {
710 for ( let i = range.start; i < range.end; i++ ) {
711 if ( this.getAnnotationHashesFromOffset( i, true ).length ) {
712 return true;
713 }
714 }
715 return false;
716 };
717
718 /**
719 * Get a range without any whitespace content at the beginning and end.
720 *
721 * @param {ve.Range} range Range to trim
722 * @return {Object} Trimmed range
723 */
724 ve.dm.ElementLinearData.prototype.trimOuterSpaceFromRange = function ( range ) {
725 let start = range.start,
726 end = range.end;
727 while ( /^\s+$/.test( this.getCharacterData( end - 1 ) ) ) {
728 end--;
729 }
730 while ( start < end && /^\s+$/.test( this.getCharacterData( start ) ) ) {
731 start++;
732 }
733 return range.to < range.end ? new ve.Range( end, start ) : new ve.Range( start, end );
734 };
735
736 /**
737 * Check if the data is just text
738 *
739 * @param {ve.Range} [range] Range to get the data for. The whole data set if not specified.
740 * @param {boolean} [ignoreNonContentNodes] Ignore all non-content nodes, e.g. paragraphs, headings, lists
741 * @param {string[]} [ignoredTypes] Only ignore specific non-content types
742 * @param {boolean} [ignoreCoveringAnnotations] Ignore covering annotations
743 * @param {boolean} [ignoreAllAnnotations] Ignore all annotations
744 * @return {boolean} The data is plain text
745 */
746 ve.dm.ElementLinearData.prototype.isPlainText = function ( range, ignoreNonContentNodes, ignoredTypes, ignoreCoveringAnnotations, ignoreAllAnnotations ) {
747 range = range || new ve.Range( 0, this.getLength() );
748
749 let annotations;
750 if ( ignoreCoveringAnnotations ) {
751 annotations = this.getAnnotationsFromRange( range );
752 }
753
754 for ( let i = range.start; i < range.end; i++ ) {
755 if ( typeof this.data[ i ] === 'string' ) {
756 // Un-annotated text
757 continue;
758 } else if ( Array.isArray( this.data[ i ] ) ) {
759 // Annotated text
760 if ( ignoreAllAnnotations ) {
761 continue;
762 }
763 if (
764 ignoreCoveringAnnotations &&
765 annotations.containsAllOf( this.getAnnotationsFromOffset( i ) )
766 ) {
767 continue;
768 }
769 } else if ( ignoreNonContentNodes || ignoredTypes ) {
770 // Element data
771 const type = this.getType( i );
772 if ( ignoredTypes && ignoredTypes.indexOf( type ) !== -1 ) {
773 continue;
774 }
775 if ( ignoreNonContentNodes && !ve.dm.nodeFactory.isNodeContent( type ) ) {
776 continue;
777 }
778 }
779 return false;
780 }
781 return true;
782 };
783
784 /**
785 * Execute a callback function for each group of consecutive content data (text or content element).
786 *
787 * @param {ve.Range} range Range in which to search
788 * @param {Function} callback Function called with the following parameters:
789 * @param {number} callback.offset Offset of the first datum of the run.
790 * @param {string} callback.text Text of the run (with content element opening/closing data
791 * replaced with U+FFFC).
792 */
793 ve.dm.ElementLinearData.prototype.forEachRunOfContent = function ( range, callback ) {
794 let text = '';
795 for ( let i = range.start; i < range.end; i++ ) {
796 if ( !this.isElementData( i ) ) {
797 text += this.getCharacterData( i );
798 } else if ( ve.dm.nodeFactory.isNodeContent( this.getType( i ) ) ) {
799 text += '\uFFFC'; // U+FFFC OBJECT REPLACEMENT CHARACTER
800 } else {
801 if ( text ) {
802 callback( i - text.length, text );
803 }
804 text = '';
805 }
806 }
807 if ( text ) {
808 callback( range.end - text.length, text );
809 }
810 };
811
812 /**
813 * Get the data as plain text
814 *
815 * @param {boolean} [maintainIndices] Maintain data offset to string index alignment by replacing elements with line breaks
816 * @param {ve.Range} [range] Range to get the data for. The whole data set if not specified.
817 * @return {string} Data as plain text
818 */
819 ve.dm.ElementLinearData.prototype.getText = function ( maintainIndices, range ) {
820 range = range || new ve.Range( 0, this.getLength() );
821
822 let text = '';
823 for ( let i = range.start; i < range.end; i++ ) {
824 if ( !this.isElementData( i ) ) {
825 text += this.getCharacterData( i );
826 } else if ( maintainIndices ) {
827 text += '\n';
828 }
829 }
830 return text;
831 };
832
833 /**
834 * Get the data as original source text (source mode only)
835 *
836 * Split paragraphs are converted to single line breaks. It is assumed the
837 * document contains nothing but plain text and paragraph elements.
838 *
839 * @param {ve.Range} [range] Range to get the data for. The whole data set if not specified.
840 * @return {string} Data as original source text
841 */
842 ve.dm.ElementLinearData.prototype.getSourceText = function ( range ) {
843 return ve.dm.sourceConverter.getSourceTextFromDataRange( this.data, range );
844 };
845
846 /**
847 * Get an offset at a distance to an offset that passes a validity test.
848 *
849 * - If {offset} is not already valid, one step will be used to move it to a valid one.
850 * - If {offset} is already valid and cannot be moved in the direction of {distance} and still be
851 * valid, it will be left where it is
852 * - If {distance} is zero the result will either be {offset} if it's already valid or the
853 * nearest valid offset to the right if possible and to the left otherwise.
854 * - If {offset} is after the last valid offset and {distance} is >= 1, or if {offset} if
855 * before the first valid offset and {distance} <= 1 than the result will be the nearest
856 * valid offset in the opposite direction.
857 * - If the data does not contain a single valid offset the result will be -1
858 *
859 * Nodes that want their children to be ignored (see ve.dm.Node#static-ignoreChildren) are not
860 * descended into. Giving a starting offset inside an ignoreChildren node will give unpredictable
861 * results.
862 *
863 * @param {number} offset Offset to start from
864 * @param {number} distance Number of valid offsets to move
865 * @param {Function} callback Function to call to check if an offset is valid which will be
866 * given initial argument of offset
867 * @param {...any} [args] Additional arguments to pass to the callback
868 * @return {number} Relative valid offset or -1 if there are no valid offsets in data
869 */
870 ve.dm.ElementLinearData.prototype.getRelativeOffset = function ( offset, distance, callback, ...args ) {
871 // If offset is already a structural offset and distance is zero than no further work is needed,
872 // otherwise distance should be 1 so that we can get out of the invalid starting offset
873 if ( distance === 0 ) {
874 if ( callback.call( this, offset, ...args ) ) {
875 return offset;
876 } else {
877 distance = 1;
878 }
879 }
880 // Initial values
881 let direction = (
882 offset <= 0 ? 1 : (
883 offset >= this.getLength() ? -1 : (
884 distance > 0 ? 1 : -1
885 )
886 )
887 );
888 distance = Math.abs( distance );
889 const start = offset;
890 let i = start + direction;
891 offset = -1;
892 let steps = 0;
893 let ignoreChildrenDepth = 0;
894 let turnedAround = false;
895 // Iteration
896 while ( i >= 0 && i <= this.getLength() ) {
897 // Detect when the search for a valid offset enters a node whose children should be
898 // ignored, and don't return an offset inside such a node. This clearly won't work
899 // if you start inside such a node, but you shouldn't be doing that to being with
900 const dataOffset = i + ( direction > 0 ? -1 : 0 );
901 if (
902 this.isElementData( dataOffset ) &&
903 ve.dm.nodeFactory.shouldIgnoreChildren( this.getType( dataOffset ) )
904 ) {
905 const isOpen = this.isOpenElementData( dataOffset );
906 // We have entered a node if we step right over an open, or left over a close.
907 // Otherwise we have left a node
908 if ( ( direction > 0 && isOpen ) || ( direction < 0 && !isOpen ) ) {
909 ignoreChildrenDepth++;
910 } else {
911 ignoreChildrenDepth--;
912 if ( ignoreChildrenDepth < 0 ) {
913 return -1;
914 }
915 }
916 }
917 if ( callback.call( this, i, ...args ) ) {
918 if ( !ignoreChildrenDepth ) {
919 steps++;
920 offset = i;
921 if ( distance === steps ) {
922 return offset;
923 }
924 }
925 } else if (
926 // Don't keep turning around over and over
927 !turnedAround &&
928 // Only turn around if not a single step could be taken
929 steps === 0 &&
930 // Only turn around if we're about to reach the edge
931 ( ( direction < 0 && i === 0 ) || ( direction > 0 && ( i === this.getLength() || this.getType( i - 1 ) === 'internalList' ) ) )
932 ) {
933 // Before we turn around, let's see if we are at a valid position
934 if ( callback.call( this, start, ...args ) ) {
935 // Stay where we are
936 return start;
937 }
938 // Start over going in the opposite direction
939 direction *= -1;
940 i = start;
941 distance = 1;
942 turnedAround = true;
943 ignoreChildrenDepth = 0;
944 }
945 i += direction;
946 }
947 return offset;
948 };
949
950 /**
951 * Get a content offset at a distance from an offset.
952 *
953 * This method is a wrapper around {getRelativeOffset}, using {isContentOffset} as
954 * the offset validation callback.
955 *
956 * @param {number} offset Offset to start from
957 * @param {number} distance Number of content offsets to move
958 * @return {number} Relative content offset or -1 if there are no valid offsets in data
959 */
960 ve.dm.ElementLinearData.prototype.getRelativeContentOffset = function ( offset, distance ) {
961 return this.getRelativeOffset( offset, distance, this.constructor.prototype.isContentOffset );
962 };
963
964 /**
965 * Get the nearest content offset to an offset.
966 *
967 * If the offset is already a valid offset, it will be returned unchanged. This method differs from
968 * calling {getRelativeContentOffset} with a zero length difference because the direction can be
969 * controlled without necessarily moving the offset if it's already valid. Also, if the direction
970 * is 0 or undefined than nearest offsets will be found to the left and right and the one with the
971 * shortest distance will be used.
972 *
973 * @param {number} offset Offset to start from
974 * @param {number} [direction] Direction to prefer matching offset in, -1 for left and 1 for right
975 * @return {number} Nearest content offset or -1 if there are no valid offsets in data
976 */
977 ve.dm.ElementLinearData.prototype.getNearestContentOffset = function ( offset, direction ) {
978 if ( this.isContentOffset( offset ) ) {
979 return offset;
980 }
981 if ( direction === undefined ) {
982 const left = this.getRelativeContentOffset( offset, -1 );
983 const right = this.getRelativeContentOffset( offset, 1 );
984 return offset - left < right - offset ? left : right;
985 } else {
986 return this.getRelativeContentOffset( offset, direction > 0 ? 1 : -1 );
987 }
988 };
989
990 /**
991 * Get a structural offset at a distance from an offset.
992 *
993 * This method is a wrapper around {getRelativeOffset}, using {this.isStructuralOffset} as
994 * the offset validation callback.
995 *
996 * @param {number} offset Offset to start from
997 * @param {number} distance Number of structural offsets to move
998 * @param {boolean} [unrestricted] Only consider offsets where any kind of element can be inserted
999 * @return {number} Relative structural offset
1000 */
1001 ve.dm.ElementLinearData.prototype.getRelativeStructuralOffset = function ( offset, distance, unrestricted ) {
1002 // Optimization: start and end are always unrestricted structural offsets
1003 if ( distance === 0 && ( offset === 0 || offset === this.getLength() ) ) {
1004 return offset;
1005 }
1006 return this.getRelativeOffset(
1007 offset, distance, this.constructor.prototype.isStructuralOffset, unrestricted
1008 );
1009 };
1010
1011 /**
1012 * Get the nearest structural offset to an offset.
1013 *
1014 * If the offset is already a valid offset, it will be returned unchanged. This method differs from
1015 * calling {getRelativeStructuralOffset} with a zero length difference because the direction can be
1016 * controlled without necessarily moving the offset if it's already valid. Also, if the direction
1017 * is 0 or undefined than nearest offsets will be found to the left and right and the one with the
1018 * shortest distance will be used.
1019 *
1020 * @param {number} offset Offset to start from
1021 * @param {number} [direction] Direction to prefer matching offset in, -1 for left and 1 for right
1022 * @param {boolean} [unrestricted] Only consider offsets where any kind of element can be inserted
1023 * @return {number} Nearest structural offset
1024 */
1025 ve.dm.ElementLinearData.prototype.getNearestStructuralOffset = function ( offset, direction, unrestricted ) {
1026 if ( this.isStructuralOffset( offset, unrestricted ) ) {
1027 return offset;
1028 }
1029 if ( !direction ) {
1030 const left = this.getRelativeStructuralOffset( offset, -1, unrestricted );
1031 const right = this.getRelativeStructuralOffset( offset, 1, unrestricted );
1032 return offset - left < right - offset ? left : right;
1033 } else {
1034 return this.getRelativeStructuralOffset( offset, direction > 0 ? 1 : -1, unrestricted );
1035 }
1036 };
1037
1038 /**
1039 * Get the range of the word at offset (else a collapsed range)
1040 *
1041 * First, if the offset is not a content offset then it will be moved to the nearest one.
1042 * Then, if the offset is inside a word, it will be expanded to that word;
1043 * else if the offset is at the end of a word, it will be expanded to that word;
1044 * else if the offset is at the start of a word, it will be expanded to that word;
1045 * else the offset is not adjacent to any word and is returned as a collapsed range.
1046 *
1047 * @param {number} offset Offset to start from; must not be inside a surrogate pair
1048 * @return {ve.Range} Boundaries of the adjacent word (else offset as collapsed range)
1049 */
1050 ve.dm.ElementLinearData.prototype.getWordRange = function ( offset ) {
1051 const dataString = new ve.dm.DataString( this.getData() );
1052
1053 offset = this.getNearestContentOffset( offset );
1054
1055 let range;
1056 if ( unicodeJS.wordbreak.isBreak( dataString, offset ) ) {
1057 // The cursor offset is not inside a word. See if there is an adjacent word
1058 // codepoint (checking two chars to allow surrogate pairs). If so, expand in that
1059 // direction only (preferring backwards if there are word codepoints on both
1060 // sides).
1061
1062 if ( this.constructor.static.endWordRegExp.exec(
1063 ( dataString.read( offset - 2 ) || ' ' ) +
1064 ( dataString.read( offset - 1 ) || ' ' )
1065 ) ) {
1066 // Cursor is immediately after a word codepoint: expand backwards
1067 range = new ve.Range(
1068 unicodeJS.wordbreak.prevBreakOffset( dataString, offset ),
1069 offset
1070 );
1071 } else if ( this.constructor.static.startWordRegExp.exec(
1072 ( dataString.read( offset ) || ' ' ) +
1073 ( dataString.read( offset + 1 ) || ' ' )
1074 ) ) {
1075 // Cursor is immediately before a word codepoint: expand forwards
1076 range = new ve.Range(
1077 offset,
1078 unicodeJS.wordbreak.nextBreakOffset( dataString, offset )
1079 );
1080 } else {
1081 // Cursor is not adjacent to a word codepoint: do not expand
1082 return new ve.Range( offset );
1083 }
1084 } else {
1085 // Cursor is inside a word: expand both backwards and forwards
1086 range = new ve.Range(
1087 unicodeJS.wordbreak.prevBreakOffset( dataString, offset ),
1088 unicodeJS.wordbreak.nextBreakOffset( dataString, offset )
1089 );
1090 }
1091 // Range expanded to all whitespace: collapse
1092 if ( this.getText( false, range ).trim().length === 0 ) {
1093 return new ve.Range( offset );
1094 }
1095 return range;
1096 };
1097
1098 /**
1099 * Finds all instances of items being stored in the hash-value store for this data store
1100 *
1101 * Currently this is just all annotations still in use.
1102 *
1103 * @param {ve.Range} [range] Optional range to get store values for
1104 * @return {Object} Object containing all store values, keyed by store hash
1105 */
1106 ve.dm.ElementLinearData.prototype.getUsedStoreValues = function ( range ) {
1107 const store = this.getStore(),
1108 valueStore = {};
1109
1110 range = range || new ve.Range( 0, this.data.length );
1111
1112 for ( let i = range.start; i < range.end; i++ ) {
1113 // Annotations
1114 // Use ignoreClose to save time; no need to count every element annotation twice
1115 const hashes = this.getAnnotationHashesFromOffset( i, true );
1116 let j = hashes.length;
1117 while ( j-- ) {
1118 const hash = hashes[ j ];
1119 if ( !Object.prototype.hasOwnProperty.call( valueStore, hash ) ) {
1120 valueStore[ hash ] = store.value( hash );
1121 }
1122 }
1123 if ( this.data[ i ].originalDomElementsHash !== undefined ) {
1124 valueStore[ this.data[ i ].originalDomElementsHash ] = store.value( this.data[ i ].originalDomElementsHash );
1125 }
1126 }
1127 return valueStore;
1128 };
1129
1130 /**
1131 * Remap the internal list indexes used in this linear data.
1132 *
1133 * Calls remapInternalListIndexes() for each node.
1134 *
1135 * @param {Object} mapping Mapping from internal list indexes to internal list indexes
1136 * @param {ve.dm.InternalList} internalList Internal list the indexes are being mapped into.
1137 * Used for refreshing attribute values that were computed with getNextUniqueNumber().
1138 */
1139 ve.dm.ElementLinearData.prototype.remapInternalListIndexes = function ( mapping, internalList ) {
1140 for ( let i = 0, ilen = this.data.length; i < ilen; i++ ) {
1141 if ( this.isOpenElementData( i ) ) {
1142 const nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
1143 this.modifyData( i, ( item ) => {
1144 nodeClass.static.remapInternalListIndexes( item, mapping, internalList );
1145 } );
1146 }
1147 }
1148 };
1149
1150 /**
1151 * Remap the internal list keys used in this linear data.
1152 *
1153 * Calls remapInternalListKeys() for each node.
1154 *
1155 * @param {ve.dm.InternalList} internalList Internal list the keys are being mapped into.
1156 */
1157 ve.dm.ElementLinearData.prototype.remapInternalListKeys = function ( internalList ) {
1158 for ( let i = 0, ilen = this.data.length; i < ilen; i++ ) {
1159 if ( this.isOpenElementData( i ) ) {
1160 const nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
1161 this.modifyData( i, ( item ) => {
1162 nodeClass.static.remapInternalListKeys( item, internalList );
1163 } );
1164 }
1165 }
1166 };
1167
1168 /**
1169 * Remap an annotation hash when it changes
1170 *
1171 * @param {string} oldHash Old hash to replace
1172 * @param {string} newHash New hash to replace it with
1173 */
1174 ve.dm.ElementLinearData.prototype.remapAnnotationHash = function ( oldHash, newHash ) {
1175 function remap( annotations ) {
1176 let spliceAt;
1177 while ( ( spliceAt = annotations.indexOf( oldHash ) ) !== -1 ) {
1178 if ( annotations.indexOf( newHash ) === -1 ) {
1179 annotations.splice( spliceAt, 1, newHash );
1180 } else {
1181 annotations.splice( spliceAt, 1 );
1182 }
1183 }
1184 }
1185 for ( let i = 0, ilen = this.data.length; i < ilen; i++ ) {
1186 if ( this.data[ i ] === undefined || typeof this.data[ i ] === 'string' ) {
1187 // Common case, cheap, avoid the isArray check
1188 continue;
1189 } else {
1190 this.modifyData( i, ( item ) => {
1191 if ( Array.isArray( item ) ) {
1192 remap( item[ 1 ] );
1193 } else if ( item.annotations !== undefined ) {
1194 remap( item.annotations );
1195 }
1196 if ( ve.getProp( item, 'internal', 'metaItems' ) ) {
1197 const data = ve.getProp( item, 'internal', 'metaItems' );
1198 for ( let j = 0, jlen = data.length; j < jlen; j++ ) {
1199 if ( data[ j ].annotations !== undefined ) {
1200 remap( data[ j ].annotations );
1201 }
1202 }
1203 }
1204 } );
1205 }
1206 }
1207 };
1208
1209 /**
1210 * Sanitize data according to a set of rules.
1211 *
1212 * @param {Object} rules Sanitization rules
1213 * @param {string[]} [rules.blacklist] Blacklist of model types which aren't allowed
1214 * @param {Object} [rules.conversions] Model type conversions to apply, e.g. { heading: 'paragraph' }
1215 * @param {boolean} [rules.removeOriginalDomElements] Remove references to DOM elements data was converted from
1216 * @param {boolean} [rules.plainText] Remove all formatting for plain text import
1217 * @param {boolean} [rules.allowBreaks] Allow <br> line breaks, otherwise the node will be split
1218 * @param {boolean} [rules.preserveHtmlWhitespace] Preserve non-semantic HTML whitespace
1219 * @param {boolean} [rules.nodeSanitization] Apply per-type node sanitizations via ve.dm.Node#sanitize
1220 * @param {boolean} [rules.keepEmptyContentBranches] Preserve empty content branch nodes
1221 * @param {boolean} [rules.singleLine] Don't allow more that one ContentBranchNode
1222 * @param {boolean} [rules.allowMetaData] Don't strip metadata
1223 */
1224 ve.dm.ElementLinearData.prototype.sanitize = function ( rules ) {
1225 const elementStack = [],
1226 store = this.getStore(),
1227 allAnnotations = this.getAnnotationsFromRange( new ve.Range( 0, this.getLength() ), true );
1228
1229 let emptySet, setToRemove;
1230 if ( rules.plainText ) {
1231 emptySet = new ve.dm.AnnotationSet( store );
1232 } else {
1233 if ( rules.removeOriginalDomElements ) {
1234 // Remove originalDomElements from annotations
1235 for ( let i = 0, len = allAnnotations.getLength(); i < len; i++ ) {
1236 const ann = allAnnotations.get( i );
1237 if ( ann.element.originalDomElementsHash !== undefined ) {
1238 // This changes the hash of the value, so we have to
1239 // update that. If we don't do this, other assumptions
1240 // that values fetched from the store are actually in the
1241 // store will fail.
1242 const oldHash = store.hashOfValue( ann );
1243 delete allAnnotations.get( i ).element.originalDomElementsHash;
1244 const newHash = store.replaceHash( oldHash, ann );
1245 this.remapAnnotationHash( oldHash, newHash );
1246 if ( allAnnotations.storeHashes.indexOf( newHash ) !== -1 ) {
1247 // New annotation-value was already in the set, which
1248 // just reduces the effective-length of the set.
1249 allAnnotations.storeHashes.splice( i, 1 );
1250 i--;
1251 len--;
1252 } else {
1253 allAnnotations.storeHashes.splice( i, 1, newHash );
1254 }
1255 }
1256 }
1257 }
1258
1259 // Create annotation set to remove from blacklist
1260 setToRemove = allAnnotations.filter( ( annotation ) => (
1261 rules.blacklist && rules.blacklist[ annotation.name ]
1262 ) || (
1263 // If original DOM element references are being removed, remove spans
1264 annotation.name === 'textStyle/span' && rules.removeOriginalDomElements
1265 ) );
1266 }
1267
1268 let contentElement;
1269 for ( let i = 0, len = this.getLength(); i < len; i++ ) {
1270 if ( this.isElementData( i ) ) {
1271 let type = this.getType( i );
1272 const canContainContent = ve.dm.nodeFactory.canNodeContainContent( type );
1273 const isOpen = this.isOpenElementData( i );
1274
1275 if ( isOpen ) {
1276 elementStack.push( this.getData( i ) );
1277 } else {
1278 elementStack.pop();
1279 }
1280 // Apply type conversions
1281 if ( rules.conversions && rules.conversions[ type ] ) {
1282 type = rules.conversions[ type ];
1283 this.modifyData( i, ( item ) => {
1284 item.type = ( !isOpen ? '/' : '' ) + type;
1285 } );
1286 }
1287
1288 // Convert content-containing non-paragraph nodes to paragraphs in plainText mode
1289 if ( rules.plainText && type !== 'paragraph' && canContainContent ) {
1290 type = 'paragraph';
1291 this.setData( i, {
1292 type: ( this.isCloseElementData( i ) ? '/' : '' ) + type
1293 } );
1294 }
1295
1296 // Remove blacklisted nodes, and metadata if disallowed
1297 if (
1298 ( rules.blacklist && rules.blacklist[ type ] ) ||
1299 ( rules.plainText && type !== 'paragraph' && type !== 'internalList' ) ||
1300 ( !rules.allowMetadata && ve.dm.nodeFactory.isMetaData( type ) )
1301 ) {
1302 this.splice( i, 1 );
1303 len--;
1304 // Make sure you haven't just unwrapped a wrapper paragraph
1305 if ( isOpen ) {
1306 this.modifyData( i, ( item ) => {
1307 ve.deleteProp( item, 'internal', 'generated' );
1308 } );
1309 }
1310 // Move pointer back and continue
1311 i--;
1312 continue;
1313 }
1314
1315 // Split on breaks
1316 if ( !rules.allowBreaks && type === 'break' && contentElement ) {
1317 if ( this.isOpenElementData( i - 1 ) && this.isCloseElementData( i + 2 ) ) {
1318 // If the break is the only element in another element it was likely added
1319 // to force it open, so remove it.
1320 this.splice( i, 2 );
1321 len -= 2;
1322 } else {
1323 this.splice( i, 2, { type: '/' + contentElement.type }, ve.copy( contentElement ) );
1324 }
1325 // Move pointer back and continue
1326 i--;
1327 continue;
1328 }
1329
1330 // If a node is empty but can contain content, then just remove it
1331 if (
1332 !rules.keepEmptyContentBranches &&
1333 isOpen && this.isCloseElementData( i + 1 ) &&
1334 !ve.getProp( this.getData( i ), 'internal', 'generated' ) &&
1335 canContainContent
1336 ) {
1337 this.splice( i, 2 );
1338 len -= 2;
1339 // Move pointer back and continue
1340 i--;
1341 continue;
1342 }
1343
1344 if ( !rules.preserveHtmlWhitespace ) {
1345 this.modifyData( i, ( item ) => {
1346 ve.deleteProp( item, 'internal', 'whitespace' );
1347 } );
1348 }
1349
1350 if ( canContainContent && !isOpen && rules.singleLine ) {
1351 i++;
1352 const start = i;
1353 while ( i < len && !( this.isOpenElementData( i ) && this.getType( i ) === 'internalList' ) ) {
1354 i++;
1355 }
1356 this.splice( start, i - start );
1357 break;
1358 }
1359
1360 // Store the current contentElement for splitting
1361 if ( canContainContent ) {
1362 contentElement = isOpen ? this.getData( i ) : null;
1363 }
1364 } else {
1365 // Support: Firefox
1366 // Remove plain newline characters, as they are semantically meaningless
1367 // and will confuse the user. Firefox adds these automatically when copying
1368 // line-wrapped HTML. T104790
1369 // However, don't remove them if we're in a situation where they might
1370 // actually be meaningful -- i.e. if we're inside a <pre>. T132006
1371 if (
1372 this.getCharacterData( i ) === '\n' &&
1373 // Get last open type from the stack
1374 !ve.dm.nodeFactory.doesNodeHaveSignificantWhitespace( elementStack[ elementStack.length - 1 ].type )
1375 ) {
1376 if ( /^\s+$/.test( this.getCharacterData( i + 1 ) ) ||
1377 /^\s+$/.test( this.getCharacterData( i - 1 ) )
1378 ) {
1379 // If whitespace-adjacent, remove the newline to avoid double spaces
1380 this.splice( i, 1 );
1381 len--;
1382 // Move pointer back and continue
1383 i--;
1384 continue;
1385 } else {
1386 // …otherwise replace it with a space
1387 if ( typeof this.getData( i ) === 'string' ) {
1388 this.setData( i, ' ' );
1389 } else {
1390 this.modifyData( i, ( item ) => {
1391 item[ 0 ] = ' ';
1392 } );
1393 }
1394 }
1395 }
1396 // Support: Chrome, Safari
1397 // Sometimes all spaces are replaced with NBSP by the browser, so replace those
1398 // which aren't adjacent to plain spaces. T183647
1399 if (
1400 this.getCharacterData( i ) === '\u00a0' &&
1401 // Get last open type from the stack
1402 !ve.dm.nodeFactory.doesNodeHaveSignificantWhitespace( elementStack[ elementStack.length - 1 ].type )
1403 ) {
1404 if ( !( this.getCharacterData( i + 1 ) === ' ' || this.getCharacterData( i - 1 ) === ' ' ) ) {
1405 // Replace with a space
1406 if ( typeof this.getData( i ) === 'string' ) {
1407 this.setData( i, ' ' );
1408 } else {
1409 this.modifyData( i, ( item ) => {
1410 item[ 0 ] = ' ';
1411 } );
1412 }
1413 }
1414 }
1415 }
1416 const annotations = this.getAnnotationsFromOffset( i, true );
1417 if ( !annotations.isEmpty() ) {
1418 if ( rules.plainText ) {
1419 this.setAnnotationsAtOffset( i, emptySet );
1420 } else if ( setToRemove.getLength() ) {
1421 // Remove blacklisted annotations
1422 annotations.removeSet( setToRemove );
1423 this.setAnnotationsAtOffset( i, annotations );
1424 }
1425 }
1426 if ( this.isOpenElementData( i ) ) {
1427 if ( rules.nodeSanitization ) {
1428 const nodeClass = ve.dm.modelRegistry.lookup( this.getType( i ) );
1429 // Perform per-class sanitizations:
1430 this.modifyData( i, ( item ) => {
1431 nodeClass.static.sanitize( item, rules );
1432 } );
1433 }
1434 if ( rules.removeOriginalDomElements ) {
1435 this.modifyData( i, ( item ) => {
1436 // Remove originalDomElements from nodes
1437 delete item.originalDomElementsHash;
1438 } );
1439 }
1440 // Remove metadata if disallowed (moved metadata)
1441 if ( !rules.allowMetadata ) {
1442 this.modifyData( i, ( item ) => {
1443 ve.deleteProp( item, 'internal', 'metaItems' );
1444 } );
1445 }
1446 }
1447 }
1448 };
1449
1450 /**
1451 * Run all elements through getClonedElement(). This should be done if
1452 * you intend to insert the sliced data back into the document as a copy
1453 * of the original data (e.g. for copy and paste).
1454 *
1455 * @param {boolean} preserveGenerated Preserve internal.generated properties of elements
1456 */
1457 ve.dm.ElementLinearData.prototype.cloneElements = function ( preserveGenerated ) {
1458 const store = this.getStore();
1459 for ( let i = 0, len = this.getLength(); i < len; i++ ) {
1460 if ( this.isOpenElementData( i ) ) {
1461 const nodeClass = ve.dm.nodeFactory.lookup( this.getType( i ) );
1462 if ( nodeClass ) {
1463 this.setData( i, nodeClass.static.cloneElement( this.getData( i ), store, preserveGenerated ) );
1464 }
1465 }
1466 }
1467 };
1468
1469 /**
1470 * Counts all elements that aren't between internalList and /internalList
1471 *
1472 * @param {number} [limit] Number of elements after which to stop counting
1473 * @return {number} Number of elements that aren't in an internalList
1474 */
1475 ve.dm.ElementLinearData.prototype.countNonInternalElements = function ( limit ) {
1476 let internalDepth = 0,
1477 count = 0;
1478 for ( let i = 0, l = this.getLength(); i < l; i++ ) {
1479 const type = this.getType( i );
1480 if ( type && ve.dm.nodeFactory.isNodeInternal( type ) ) {
1481 if ( this.isOpenElementData( i ) ) {
1482 internalDepth++;
1483 } else {
1484 internalDepth--;
1485 }
1486 } else if ( !internalDepth ) {
1487 count++;
1488 if ( limit && count >= limit ) {
1489 return count;
1490 }
1491 }
1492 }
1493 return count;
1494 };
1495
1496 /**
1497 * Checks if the document has content that's not part of an internalList.
1498 *
1499 * @return {boolean} The document has content
1500 */
1501 ve.dm.ElementLinearData.prototype.hasContent = function () {
1502 // Two or less elements (<p>, </p>) is considered an empty document
1503 // For performance, abort the count when we reach 3.
1504 return this.countNonInternalElements( 3 ) > 2 ||
1505 // Also check that the element is not a content branch node, e.g. a blockImage
1506 // and also that is not the internal list
1507 (
1508 this.isElementData( 0 ) &&
1509 !ve.dm.nodeFactory.canNodeContainContent( this.getType( 0 ) ) &&
1510 !ve.dm.nodeFactory.isNodeInternal( this.getType( 0 ) )
1511 );
1512 };
1513
1514 /**
1515 * Get the length of the common start sequence of annotations that applies to a whole range
1516 *
1517 * @param {ve.Range} range The document range
1518 * @return {number} Common start sequence length (0 if the range is empty)
1519 */
1520 ve.dm.ElementLinearData.prototype.getCommonAnnotationArrayLength = function ( range ) {
1521 const annotationHashesForOffset = [];
1522 for ( let i = range.start; i < range.end; i++ ) {
1523 annotationHashesForOffset.push( this.getAnnotationHashesFromOffset( i ) );
1524 }
1525 return ve.getCommonStartSequenceLength( annotationHashesForOffset );
1526 };