Debian Codegraph @

extensions/VisualEditor/lib/ve/src/dm/ve.dm.Node.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Node class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Generic DataModel node.
9 *
10 * @abstract
11 * @extends ve.dm.Model
12 * @mixes OO.EventEmitter
13 * @mixes ve.Node
14 *
15 * @constructor
16 * @param {Object} [element] Reference to element in linear model
17 */
18 ve.dm.Node = function VeDmNode( element ) {
19 // Parent constructor
20 ve.dm.Node.super.apply( this, arguments );
21
22 // Mixin constructors
23 ve.Node.call( this );
24 OO.EventEmitter.call( this );
25
26 // Properties
27 this.length = 0;
28 this.offset = null;
29 this.element = element;
30 };
31
32 /**
33 * @event ve.dm.Node#attributeChange
34 * @param {string} key
35 * @param {any} oldValue
36 * @param {any} newValue
37 */
38
39 /**
40 * @event ve.dm.Node#lengthChange
41 * @param {number} diff
42 */
43
44 /**
45 * @event ve.dm.Node#update
46 */
47
48 /* Inheritance */
49
50 OO.inheritClass( ve.dm.Node, ve.dm.Model );
51
52 OO.mixinClass( ve.dm.Node, ve.Node );
53
54 OO.mixinClass( ve.dm.Node, OO.EventEmitter );
55
56 /* Static Properties */
57
58 /**
59 * Whether this node handles its own children. After converting a DOM node to a linear model
60 * node of this type, the converter checks this property. If it's false, the converter will descend
61 * into the DOM node's children, recursively convert them, and attach the resulting nodes as
62 * children of the linear model node. If it's true, the converter will not descend, and will
63 * expect the node's toDataElement() to have handled the entire DOM subtree.
64 *
65 * The same is true when converting from linear model data to DOM: if this property is true,
66 * toDomElements() will be passed the node's data element and all of its children and will be
67 * expected to convert the entire subtree. If it's false, the converter will descend into the
68 * child nodes and convert each one individually.
69 *
70 * If .static.childNodeTypes is set to [], this property is ignored and will be assumed to be true.
71 *
72 * @static
73 * @property {boolean}
74 * @inheritable
75 */
76 ve.dm.Node.static.handlesOwnChildren = false;
77
78 /**
79 * Whether this node's children should be ignored when iterating over the model, for example
80 * content which is stored inline, but is actually conceptually out-of-band data, such as a
81 * reference node which contains the reference content (like `<ref>` tags in MediaWiki).
82 *
83 * This property should not be used for data which isn't out-of-band but is less accessible in
84 * the view, e.g. content in table cells or image captions.
85 *
86 * If true, this node will be treated as a leaf node even if it has children.
87 * Often used in combination with handlesOwnChildren.
88 *
89 * @static
90 * @property {boolean}
91 * @inheritable
92 */
93 ve.dm.Node.static.ignoreChildren = false;
94
95 /**
96 * Whether this node can be deleted. If false, ve.dm.Transaction#newFromRemoval will silently
97 * ignore any attepts to delete this node.
98 *
99 * @static
100 * @property {boolean}
101 * @inheritable
102 */
103 ve.dm.Node.static.isDeletable = true;
104
105 /**
106 * Whether this node type is internal. Internal node types are ignored by the converter.
107 *
108 * @static
109 * @property {boolean}
110 * @inheritable
111 */
112 ve.dm.Node.static.isInternal = false;
113
114 /**
115 * Whether this node type has a wrapping element in the linear model. Most node types are wrapped,
116 * only special node types are not wrapped.
117 *
118 * @static
119 * @property {boolean}
120 * @inheritable
121 */
122 ve.dm.Node.static.isWrapped = true;
123
124 /**
125 * Whether this node type can be unwrapped by user input (e.g. backspace to unwrap a list item)
126 *
127 * @static
128 * @property {boolean}
129 * @inheritable
130 */
131 ve.dm.Node.static.isUnwrappable = true;
132
133 /**
134 * Whether this node type is a content node type. This means the node represents content, cannot
135 * have children, and can only appear as children of a content container node. Content nodes are
136 * also known as inline nodes.
137 *
138 * @static
139 * @property {boolean}
140 * @inheritable
141 */
142 ve.dm.Node.static.isContent = false;
143
144 /**
145 * Whether this node type is a metadata node. This means the node represents a leaf node that
146 * has no explicit view representation, and should be treated differently for the purposes of
147 * round-tripping, copy/paste etc.
148 *
149 * @static
150 * @property {boolean}
151 * @inheritable
152 */
153 ve.dm.Node.static.isMetaData = false;
154
155 /**
156 * For a non-content node type, whether this node type can be serialized in a content
157 * position (e.g. for round tripping). This value is ignored if isContent is true.
158 *
159 * @static
160 * @property {boolean}
161 * @inheritable
162 */
163 ve.dm.Node.static.canSerializeAsContent = false;
164
165 /**
166 * Whether this node type can be focused. Focusable nodes react to selections differently.
167 *
168 * @static
169 * @property {boolean}
170 * @inheritable
171 */
172 ve.dm.Node.static.isFocusable = false;
173
174 /**
175 * Whether this node type is alignable.
176 *
177 * @static
178 * @property {boolean}
179 * @inheritable
180 */
181 ve.dm.Node.static.isAlignable = false;
182
183 /**
184 * Whether this node type can behave as a table cell.
185 *
186 * @static
187 * @property {boolean}
188 * @inheritable
189 */
190 ve.dm.Node.static.isCellable = false;
191
192 /**
193 * Whether this node type can contain content. The children of content container nodes must be
194 * content nodes.
195 *
196 * @static
197 * @property {boolean}
198 * @inheritable
199 */
200 ve.dm.Node.static.canContainContent = false;
201
202 /**
203 * Whether this node type behaves like a list when diffing.
204 *
205 * @static
206 * @property {boolean}
207 * @inheritable
208 */
209 ve.dm.Node.static.isDiffedAsList = false;
210
211 /**
212 * Whether this node type behaves like a leaf when diffing.
213 *
214 * @static
215 * @property {boolean}
216 * @inheritable
217 */
218 ve.dm.Node.static.isDiffedAsLeaf = false;
219
220 /**
221 * Whether this node type has significant whitespace. Only applies to content container nodes
222 * (i.e. can only be true if canContainContent is also true).
223 *
224 * If a content node has significant whitespace, the text inside it is not subject to whitespace
225 * stripping and preservation.
226 *
227 * @static
228 * @property {boolean}
229 * @inheritable
230 */
231 ve.dm.Node.static.hasSignificantWhitespace = false;
232
233 /**
234 * Array of allowed child node types for this node type.
235 *
236 * An empty array means no children are allowed. null means any node type is allowed as a child.
237 *
238 * @static
239 * @property {string[]|null}
240 * @inheritable
241 */
242 ve.dm.Node.static.childNodeTypes = null;
243
244 /**
245 * Array of allowed parent node types for this node type.
246 *
247 * An empty array means this node type cannot be the child of any node. null means this node type
248 * can be the child of any node type.
249 *
250 * @static
251 * @property {string[]|null}
252 * @inheritable
253 */
254 ve.dm.Node.static.parentNodeTypes = null;
255
256 /**
257 * Array of suggested parent node types for this node type.
258 *
259 * These parent node types are allowed but the editor will avoid creating them.
260 *
261 * An empty array means this node type should not be the child of any node. null means this node type
262 * can be the child of any node type.
263 *
264 * @static
265 * @property {string[]|null}
266 * @inheritable
267 */
268 ve.dm.Node.static.suggestedParentNodeTypes = null;
269
270 /**
271 * Array of annotation types which can't be applied to this node
272 *
273 * @static
274 * @property {string[]}
275 * @inheritable
276 */
277 ve.dm.Node.static.disallowedAnnotationTypes = [];
278
279 /**
280 * Default attributes to set for newly created linear model elements. These defaults will be used
281 * when creating a new element in ve.dm.NodeFactory#getDataElement when there is no DOM node or
282 * existing linear model element to base the attributes on.
283 *
284 * This property is an object with attribute names as keys and attribute values as values.
285 * Attributes may be omitted, in which case they'll simply be undefined.
286 *
287 * @static
288 * @property {Object}
289 * @inheritable
290 */
291 ve.dm.Node.static.defaultAttributes = {};
292
293 /**
294 * Sanitize the node's linear model data, typically if it was generated from an external source (e.g. copied HTML)
295 *
296 * @param {Object} dataElement Linear model element, modified in place
297 */
298 ve.dm.Node.static.sanitize = function () {
299 };
300
301 /**
302 * Remap the internal list indexes stored in a linear model data element.
303 *
304 * The default implementation is empty. Nodes should override this if they store internal list
305 * indexes in attributes. To remap, do something like
306 * dataElement.attributes.foo = mapping[dataElement.attributes.foo];
307 *
308 * @static
309 * @inheritable
310 * @param {Object} dataElement Data element (opening) to remap. Will be modified.
311 * @param {Object} mapping Object mapping old internal list indexes to new internal list indexes
312 * @param {ve.dm.InternalList} internalList Internal list the indexes are being mapped into.
313 * Used for refreshing attribute values that were computed with getNextUniqueNumber().
314 */
315 ve.dm.Node.static.remapInternalListIndexes = function () {
316 };
317
318 /**
319 * Remap the internal list keys stored in a linear model data element.
320 *
321 * The default implementation is empty. Nodes should override this if they store internal list
322 * keys in attributes.
323 *
324 * @static
325 * @inheritable
326 * @param {Object} dataElement Data element (opening) to remap. Will be modified.
327 * @param {ve.dm.InternalList} internalList Internal list the keys are being mapped into.
328 */
329 ve.dm.Node.static.remapInternalListKeys = function () {
330 };
331
332 /**
333 * Determine if a hybrid element is inline and allowed to be inline in this context
334 *
335 * We generate block elements for block tags and inline elements for inline
336 * tags; unless we're in a content location, in which case we have no choice
337 * but to generate an inline element.
338 *
339 * @static
340 * @param {HTMLElement[]} domElements DOM elements being converted
341 * @param {ve.dm.Converter} converter
342 * @return {boolean} The element is inline
343 */
344 ve.dm.Node.static.isHybridInline = function ( domElements, converter ) {
345 let allTagsInline = true;
346
347 for ( let i = 0, length = domElements.length; i < length; i++ ) {
348 if ( ve.isBlockElement( domElements[ i ] ) ) {
349 allTagsInline = false;
350 break;
351 }
352 }
353
354 // Force inline in content locations (but not wrappers)
355 return ( converter.isExpectingContent() && !converter.isInWrapper() ) ||
356 // ..also force inline in wrappers that we can't close
357 ( converter.isInWrapper() && !converter.canCloseWrapper() ) ||
358 // ..otherwise just look at the tag names
359 allTagsInline;
360 };
361
362 /**
363 * Get a clone of the node's document data element.
364 *
365 * The attributes object will be deep-copied and the .internal.generated
366 * property will be removed if present.
367 *
368 * @static
369 * @param {Object} element
370 * @param {ve.dm.HashValueStore} store Hash-value store used by element
371 * @param {boolean} preserveGenerated Preserve internal.generated property of element
372 * @param {boolean} resetAttributes Reset attributes for an empty clone, as defined in #static-resetForClone
373 * @return {Object} Cloned element object
374 */
375 ve.dm.Node.static.cloneElement = function ( element, store, preserveGenerated, resetAttributes ) {
376 const clone = ve.copy( element );
377 let modified = false;
378
379 if ( !preserveGenerated ) {
380 ve.deleteProp( clone, 'internal', 'generated' );
381 }
382 const originalDomElements = store.value( clone.originalDomElementsHash );
383 // Generate a new about attribute to prevent about grouping of cloned nodes
384 if ( originalDomElements ) {
385 // TODO: The '#mwtNNN' is required by Parsoid. Make the name used here
386 // more generic and specify the #mwt pattern in MW code.
387 const about = '#mwt' + Math.floor( 1000000000 * Math.random() );
388 const domElements = originalDomElements.map( ( el ) => {
389 const elClone = el.cloneNode( true );
390 // Check for hasAttribute as comments don't have them
391 if ( elClone.hasAttribute && elClone.hasAttribute( 'about' ) ) {
392 elClone.setAttribute( 'about', about );
393 modified = true;
394 }
395 return elClone;
396 } );
397 if ( modified ) {
398 clone.originalDomElementsHash = store.hash( domElements, domElements.map( ve.getNodeHtml ).join( '' ) );
399 }
400 }
401 if ( resetAttributes ) {
402 this.resetAttributesForClone( clone, store );
403 }
404 return clone;
405 };
406
407 /**
408 * Reset attributes for a cloned element.
409 *
410 * This will be used when an element needs to have certain attributes cleared
411 * when creating a clone, e.g. when splitting a content branch node by pressing
412 * enter, some attributes are preserved (list style) but some are cleared
413 * (check list item state).
414 *
415 * @static
416 * @param {Object} clonedElement Cloned element, modified in place
417 * @param {ve.dm.HashValueStore} store Hash-value store used by element
418 */
419 ve.dm.Node.static.resetAttributesForClone = function () {};
420
421 /* Methods */
422
423 /**
424 * @inheritdoc
425 */
426 ve.dm.Node.prototype.getStore = function () {
427 return this.doc && this.doc.store;
428 };
429
430 /**
431 * @see #static-cloneElement
432 * Implementations should override the static method, not this one
433 *
434 * @param {boolean} preserveGenerated Preserve internal.generated property of element
435 * @param {boolean} resetAttributes Reset attributes for an empty clone, as defined in #static-resetForClone
436 * @return {Object} Cloned element object
437 */
438 ve.dm.Node.prototype.getClonedElement = function ( preserveGenerated, resetAttributes ) {
439 const store = this.getStore();
440 if ( !store ) {
441 throw new Error( 'Node must be attached to the document to be cloned.' );
442 }
443 return this.constructor.static.cloneElement( this.element, store, preserveGenerated, resetAttributes );
444 };
445
446 // eslint-disable-next-line jsdoc/require-returns
447 /**
448 * @see ve.Node
449 */
450 ve.dm.Node.prototype.getChildNodeTypes = function () {
451 return this.constructor.static.childNodeTypes;
452 };
453
454 // eslint-disable-next-line jsdoc/require-returns
455 /**
456 * @see ve.Node
457 */
458 ve.dm.Node.prototype.getParentNodeTypes = function () {
459 return this.constructor.static.parentNodeTypes;
460 };
461
462 // eslint-disable-next-line jsdoc/require-returns
463 /**
464 * @see ve.Node
465 */
466 ve.dm.Node.prototype.getSuggestedParentNodeTypes = function () {
467 return this.constructor.static.suggestedParentNodeTypes;
468 };
469
470 // eslint-disable-next-line jsdoc/require-returns
471 /**
472 * @see ve.Node
473 */
474 ve.dm.Node.prototype.canHaveChildren = function () {
475 return ve.dm.nodeFactory.canNodeHaveChildren( this.type );
476 };
477
478 // eslint-disable-next-line jsdoc/require-returns
479 /**
480 * @see ve.Node
481 */
482 ve.dm.Node.prototype.canHaveChildrenNotContent = function () {
483 return ve.dm.nodeFactory.canNodeHaveChildrenNotContent( this.type );
484 };
485
486 // eslint-disable-next-line jsdoc/require-returns
487 /**
488 * @see ve.Node
489 */
490 ve.dm.Node.prototype.isInternal = function () {
491 return this.constructor.static.isInternal;
492 };
493
494 // eslint-disable-next-line jsdoc/require-returns
495 /**
496 * @see ve.Node
497 */
498 ve.dm.Node.prototype.isMetaData = function () {
499 return this.constructor.static.isMetaData;
500 };
501
502 // eslint-disable-next-line jsdoc/require-returns
503 /**
504 * @see ve.Node
505 */
506 ve.dm.Node.prototype.isWrapped = function () {
507 return this.constructor.static.isWrapped;
508 };
509
510 // eslint-disable-next-line jsdoc/require-returns
511 /**
512 * @see ve.Node
513 */
514 ve.dm.Node.prototype.isUnwrappable = function () {
515 return this.isWrapped() && this.constructor.static.isUnwrappable;
516 };
517
518 // eslint-disable-next-line jsdoc/require-returns
519 /**
520 * @see ve.Node
521 */
522 ve.dm.Node.prototype.canContainContent = function () {
523 return this.constructor.static.canContainContent;
524 };
525
526 // eslint-disable-next-line jsdoc/require-returns
527 /**
528 * @see ve.Node
529 */
530 ve.dm.Node.prototype.isContent = function () {
531 return this.constructor.static.isContent;
532 };
533
534 // eslint-disable-next-line jsdoc/require-returns
535 /**
536 * @see ve.Node
537 */
538 ve.dm.Node.prototype.isFocusable = function () {
539 return this.constructor.static.isFocusable;
540 };
541
542 // eslint-disable-next-line jsdoc/require-returns
543 /**
544 * @see ve.Node
545 */
546 ve.dm.Node.prototype.isAlignable = function () {
547 return this.constructor.static.isAlignable;
548 };
549
550 // eslint-disable-next-line jsdoc/require-returns
551 /**
552 * @see ve.Node
553 */
554 ve.dm.Node.prototype.isCellable = function () {
555 return this.constructor.static.isCellable;
556 };
557
558 // eslint-disable-next-line jsdoc/require-returns
559 /**
560 * @see ve.Node
561 */
562 ve.dm.Node.prototype.isCellEditable = function () {
563 return this.constructor.static.isCellEditable;
564 };
565
566 // eslint-disable-next-line jsdoc/require-returns
567 /**
568 * @see ve.Node
569 */
570 ve.dm.Node.prototype.isDiffedAsList = function () {
571 return this.constructor.static.isDiffedAsList;
572 };
573
574 // eslint-disable-next-line jsdoc/require-returns
575 /**
576 * @see ve.Node
577 */
578 ve.dm.Node.prototype.isDiffedAsLeaf = function () {
579 return this.constructor.static.isDiffedAsLeaf;
580 };
581
582 // eslint-disable-next-line jsdoc/require-returns
583 /**
584 * @see ve.Node
585 */
586 ve.dm.Node.prototype.isDiffedAsDocument = function () {
587 return this.getChildNodeTypes() === null;
588 };
589
590 /**
591 * Check if the node can have a slug before it.
592 *
593 * @return {boolean} Whether the node can have a slug before it
594 */
595 ve.dm.Node.prototype.canHaveSlugBefore = function () {
596 return !this.canContainContent() && this.getParentNodeTypes() === null;
597 };
598
599 /**
600 * Check if the node can have a slug after it.
601 *
602 * @method
603 * @return {boolean} Whether the node can have a slug after it
604 */
605 ve.dm.Node.prototype.canHaveSlugAfter = ve.dm.Node.prototype.canHaveSlugBefore;
606
607 /**
608 * A string identifier used to suppress slugs
609 *
610 * If sequential nodes have the same non-null suppressSlugType, then
611 * no slug is shown, e.g. two floated images can return 'float' to
612 * suppress the slug between them.
613 *
614 * @return {string|null} Type
615 */
616 ve.dm.Node.prototype.suppressSlugType = function () {
617 return null;
618 };
619
620 // eslint-disable-next-line jsdoc/require-returns
621 /**
622 * @see ve.Node
623 */
624 ve.dm.Node.prototype.hasSignificantWhitespace = function () {
625 return this.constructor.static.hasSignificantWhitespace;
626 };
627
628 // eslint-disable-next-line jsdoc/require-returns
629 /**
630 * @see ve.Node
631 */
632 ve.dm.Node.prototype.handlesOwnChildren = function () {
633 return this.constructor.static.handlesOwnChildren;
634 };
635
636 // eslint-disable-next-line jsdoc/require-returns
637 /**
638 * @see ve.Node
639 */
640 ve.dm.Node.prototype.shouldIgnoreChildren = function () {
641 return this.constructor.static.ignoreChildren;
642 };
643
644 /**
645 * Check if the node can be the root of a branch exposed in a ve.ce.Surface
646 *
647 * @return {boolean} Node can be the root of a surfaced branch
648 */
649 ve.dm.Node.prototype.isSurfaceable = function () {
650 return this.hasChildren() && !this.canContainContent() && !this.isMetaData() && !this.getChildNodeTypes();
651 };
652
653 /**
654 * Find the first ancestor with matching type and attribute values.
655 *
656 * @param {string} type Node type to match
657 * @param {Object} [attributes] Node attributes to match
658 * @return {ve.dm.Node|null} Ancestor with matching type and attribute values
659 */
660 ve.dm.Node.prototype.findMatchingAncestor = function ( type, attributes ) {
661 return this.traverseUpstream( ( node ) => !node.matches( type, attributes ) );
662 };
663
664 /**
665 * Check if the node has an ancestor with matching type and attribute values.
666 *
667 * @param {string} type Node type to match
668 * @param {Object} [attributes] Node attributes to match
669 * @return {boolean} Node has an ancestor with matching type and attribute values
670 */
671 ve.dm.Node.prototype.hasMatchingAncestor = function ( type, attributes ) {
672 return !!this.findMatchingAncestor( type, attributes );
673 };
674
675 /**
676 * Check if the node matches type and attribute values.
677 *
678 * @param {string} type Node type to match
679 * @param {Object} [attributes] Node attributes to match
680 * @return {boolean} Node matches type and attribute values
681 */
682 ve.dm.Node.prototype.matches = function ( type, attributes ) {
683 if ( this.getType() !== type ) {
684 return false;
685 }
686
687 if ( attributes ) {
688 return this.compareAttributes( attributes );
689 }
690 return true;
691 };
692
693 /**
694 * Check if specific attributes match those in the node
695 *
696 * @param {Object} attributes Node attributes to match
697 * @return {boolean} Attributes sepcified match those in the node
698 */
699 ve.dm.Node.prototype.compareAttributes = function ( attributes ) {
700 for ( const key in attributes ) {
701 if ( this.getAttribute( key ) !== attributes[ key ] ) {
702 return false;
703 }
704 }
705 return true;
706 };
707
708 // eslint-disable-next-line jsdoc/require-returns
709 /**
710 * @see ve.Node
711 */
712 ve.dm.Node.prototype.getLength = function () {
713 return this.length;
714 };
715
716 /**
717 * Set the inner length of the node.
718 *
719 * This should only be called after a relevant change to the document data. Calling this method will
720 * not change the document data.
721 *
722 * @param {number} length Length of content
723 * @fires ve.dm.Node#lengthChange
724 * @fires ve.dm.Node#update
725 * @throws {Error} Invalid content length error if length is less than 0
726 */
727 ve.dm.Node.prototype.setLength = function ( length ) {
728 if ( length < 0 ) {
729 throw new Error( 'Length cannot be negative' );
730 }
731 // Compute length adjustment from old length
732 const diff = length - this.length;
733 // Set new length
734 this.length = length;
735 // Adjust the parent's length
736 if ( this.parent ) {
737 this.parent.adjustLength( diff );
738 }
739 // Emit events
740 this.emit( 'lengthChange', diff );
741 this.emit( 'update' );
742 };
743
744 /**
745 * Adjust the length.
746 *
747 * This should only be called after a relevant change to the document data. Calling this method will
748 * not change the document data.
749 *
750 * @param {number} adjustment Amount to adjust length by
751 * @throws {Error} Invalid adjustment error if resulting length is less than 0
752 */
753 ve.dm.Node.prototype.adjustLength = function ( adjustment ) {
754 this.setLength( this.length + adjustment );
755 };
756
757 // eslint-disable-next-line jsdoc/require-returns
758 /**
759 * @see ve.Node
760 */
761 ve.dm.Node.prototype.getOffset = function () {
762 if ( !this.parent ) {
763 return 0;
764 }
765
766 if ( this.doc.isReadOnly() && this.offset !== null ) {
767 return this.offset;
768 }
769
770 // Find our index in the parent and add up lengths while we do so
771 const siblings = this.parent.children;
772 let offset = this.parent.getOffset() + ( this.parent === this.root ? 0 : 1 );
773 let i, len;
774 for ( i = 0, len = siblings.length; i < len; i++ ) {
775 if ( siblings[ i ] === this ) {
776 break;
777 }
778 offset += siblings[ i ].getOuterLength();
779 }
780 if ( i === len ) {
781 throw new Error( 'Node not found in parent\'s children array' );
782 }
783 if ( this.doc.isReadOnly() ) {
784 // Cache offset, only used in read-only mode (when the offset can't change)
785 // This cache is additionally cleared when leaving read-only mode in ve.dm.Document#setReadOnly
786 this.offset = offset;
787 }
788 return offset;
789 };
790
791 /**
792 * Check if the node can be merged with another.
793 *
794 * For two nodes to be mergeable, the two nodes must either be the same node or:
795 * - Are comparable according to #compareForMerging (by default, have the same type)
796 * - Have the same depth
797 * - Have similar ancestry (each node upstream must have the same type)
798 *
799 * @param {ve.dm.Node} node Node to consider merging with
800 * @return {boolean} Nodes can be merged
801 */
802 ve.dm.Node.prototype.canBeMergedWith = function ( node ) {
803 let n1 = this,
804 n2 = node;
805
806 // Content node can be merged with node that can contain content, for instance: TextNode
807 // and ParagraphNode. When this method is called for such case (one node is a content node and
808 // the other one can contain content) make sure to start traversal from node that can contain
809 // content (instead of content node itself).
810 if ( n1.canContainContent() && n2.isContent() ) {
811 n2 = n2.getParent();
812 } else if ( n2.canContainContent() && n1.isContent() ) {
813 n1 = n1.getParent();
814 }
815 // Move up from n1 and n2 simultaneously until we find a common ancestor
816 while ( n1 !== n2 ) {
817 if (
818 // Check if we have reached a root (means there's no common ancestor or unequal depth)
819 ( n1 === null || n2 === null ) ||
820 // Ensure that nodes are comparable for merging
821 !n1.compareForMerging( n2 )
822 ) {
823 return false;
824 }
825 // Move up
826 n1 = n1.getParent();
827 n2 = n2.getParent();
828 }
829 return true;
830 };
831
832 /**
833 * Compare with another node for merging (see #canBeMergedWidth)
834 *
835 * The default implementation just compares node types.
836 *
837 * @param {ve.dm.Node} otherNode Other node to compare with
838 * @return {boolean} Nodes are comparable
839 */
840 ve.dm.Node.prototype.compareForMerging = function ( otherNode ) {
841 return this.getType() === otherNode.getType();
842 };