Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel TreeModifier class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel tree modifier, following the algorithm in T162762.
9 *
10 * The top-level process() method applies a transaction to the document in two stages. First,
11 * calculateTreeOperations() translates the linear transaction into tree operations; then,
12 * applyTreeOperations() updates both the linear model and the document tree simultaneously.
13 *
14 * Each tree operation takes one of the following forms:
15 *
16 * { type: 'insertNode', isContent: {boolean}, at: {Path}, element: {OpenElementLinModItem} }
17 * { type: 'removeNode', isContent: {boolean}, at: {Path}, element: {OpenElementLinModItem} }
18 * { type: 'moveNode', isContent: {boolean}, from: {Path}, to: {Path} }
19 * { type: 'insertText', isContent: true, at: {Path}, data: {TextLinModItem[]} }
20 * { type: 'removeText', isContent: true, at: {Path}, data: {TextLinModItem[]} }
21 * { type: 'moveText', isContent: true, from: {Path}, to: {Path}, length: {number} }
22 *
23 * Note that moveNode/moveText do not specify what content is being moved, and all the Node
24 * operations always operate on a single node at a time.
25 *
26 * {Path} is number[] representing the tree path from the DocumentNode to the position, except
27 * that within ContentBranchNodes, the offset is the linearized offset of the position.
28 *
29 * {OpenElementLinModItem} is the linear model value representing the node being inserted or
30 * removed, like { type: 'paragraph' } .
31 *
32 * {TextLinModItem[]} is the linear model values representing the text, like
33 * [ 'y', 'o', 'u', ' ', [ 'm', [ 'he4e7c54e2204d10b ] ], [ 'e' 'he4e7c54e2204d10b ] ] .
34 *
35 * The isContent flag is true if the operation is taking place inside a ContentBranchNode
36 * (so it is always true for text).
37 *
38 * NOTE: Instances of this class are not recyclable: you can only call .process( tx ) on them once.
39 *
40 * @class
41 * @constructor
42 */
43 ve.dm.TreeModifier = function VeDmTreeModifier() {
44 // XXX we only need these two for dump() in tests
45 this.document = null;
46 this.insertions = null;
47
48 /**
49 * @property {Array} data Live document linear data
50 */
51 this.data = null;
52
53 /**
54 * @property {ve.dm.Node[]} deletions Array (acting as set) of removed nodes
55 */
56 this.deletions = null;
57
58 /**
59 * @property {ve.dm.TreeCursor} remover Tree cursor for removals
60 */
61 this.remover = null;
62
63 /**
64 * @property {ve.dm.TreeCursor} inserter Tree cursor for insertions
65 */
66 this.inserter = null;
67
68 /**
69 * @property {Object[]} treeOps Array of tree ops being built
70 */
71 this.treeOps = null;
72
73 /**
74 * @property {number[]} insertedNodes Nodes to be inserted at context
75 */
76 this.insertedNodes = null;
77
78 /**
79 * @property {number[]} insertedPositions Position within nodes to be inserted
80 */
81 this.insertedPositions = null;
82
83 /**
84 * @property {Object} adjustmentTree Sparse tree, paths as indexes
85 * @property {number} adjustmentTree.inserted Child items inserted at this position
86 * @property {number} adjustmentTree.removed Child items removed at this position
87 * @property {Object} adjustmentTree.i Subtree at position i
88 */
89 this.adjustmentTree = null;
90 };
91
92 OO.initClass( ve.dm.TreeModifier );
93
94 // Static methods
95
96 /**
97 * Apply tree operations to document tree and linear data simultaneously
98 *
99 * @param {boolean} isReversed Whether the transaction is an undo
100 * @param {ve.dm.Document} document The document to modify
101 * @param {Object[]} treeOps The tree operations
102 */
103 ve.dm.TreeModifier.static.applyTreeOperations = function ( isReversed, document, treeOps ) {
104 for ( let i = 0, iLen = treeOps.length; i < iLen; i++ ) {
105 this.applyTreeOperation( isReversed, document, treeOps[ i ] );
106 }
107 };
108
109 /**
110 * Throw an exception if two pieces of linear data are not equal
111 *
112 * @param {Array} actual Document linear data to test
113 * @param {Array} expected Expected linear data to test against
114 */
115 ve.dm.TreeModifier.static.checkEqualData = function ( actual, expected ) {
116 function replacer( name, value ) {
117 // TODO: replace this check with data equality class method checks
118 if (
119 name === 'generated' ||
120 name === 'changesSinceLoad' ||
121 name === 'originalDomElementsHash' ||
122 name === 'originalMw' ||
123 name === 'originalVariantInfo' ||
124 name === 'mw' ||
125 name === 'contentsUsed'
126 ) {
127 return undefined;
128 }
129 // Drop .internal that would become empty after the replacements above
130 if ( name === 'internal' && JSON.stringify( value, replacer ) === '{}' ) {
131 return undefined;
132 }
133 return value;
134 }
135
136 const jActual = JSON.stringify( actual, replacer );
137 const jExpected = JSON.stringify( expected, replacer );
138
139 if ( jActual !== jExpected ) {
140 throw new Error( 'Expected ' + jExpected + ' but got ' + jActual );
141 }
142 };
143
144 /**
145 * Apply a tree operation to document tree and linear data simultaneously
146 *
147 * @param {boolean} isReversed Whether the transaction is an undo
148 * @param {ve.dm.Document} document The document to modify
149 * @param {Object} treeOp The tree operation
150 */
151 ve.dm.TreeModifier.static.applyTreeOperation = function ( isReversed, document, treeOp ) {
152 const removedNodes = [],
153 addedNodes = [],
154 changedBranchNodes = [];
155
156 function splice( parentNode ) {
157 const removed = parentNode.splice.apply( parentNode, Array.prototype.slice.call( arguments, 1 ) );
158 ve.batchPush( removedNodes, removed );
159 ve.batchPush( addedNodes, Array.prototype.slice.call( arguments, 3 ) );
160 return removed;
161 }
162
163 function ensureText( position ) {
164 const node = position.node,
165 offset = position.offset;
166 if ( node.type === 'text' ) {
167 return position;
168 }
169 const pre = node.children[ offset - 1 ];
170 const post = node.children[ offset ];
171 if ( post && post.type === 'text' ) {
172 // Prefer post to pre, because we might want to remove text. (We shouldn't
173 // really have two adjacent text nodes, though)
174 return { node: post, offset: 0 };
175 }
176 if ( pre && pre.type === 'text' ) {
177 return { node: pre, offset: pre.length };
178 }
179 // There are no adjacent text nodes; insert one
180 if ( !node.hasChildren() ) {
181 throw new Error( 'Cannot add a child to ' + node.type + ' node' );
182 }
183 const newNode = new ve.dm.TextNode( 0 );
184 splice( node, offset, 0, newNode );
185 return { node: newNode, offset: 0 };
186 }
187
188 function ensureNotText( position ) {
189 const node = position.node,
190 offset = position.offset;
191 if ( node.type !== 'text' ) {
192 return position;
193 }
194 const parentNode = node.parent;
195 const parentOffset = node.parent.children.indexOf( node );
196 if ( offset === 0 ) {
197 // Position before the text node
198 return { node: parentNode, offset: parentOffset };
199 }
200 if ( offset === node.length ) {
201 return { node: parentNode, offset: parentOffset + 1 };
202 }
203 // Else we must split the text node
204 const length = node.length - offset;
205 node.adjustLength( -length );
206 const newNode = new ve.dm.TextNode( length );
207 splice( parentNode, parentOffset + 1, 0, newNode );
208 return { node: parentNode, offset: parentOffset + 1 };
209 }
210
211 function findContentPosition( node, contentOffset ) {
212 let i, offset, childLength, child;
213
214 if ( contentOffset === 0 ) {
215 return { node: node, offset: 0 };
216 }
217 // Find the child that will take us up to or past the contentOffset
218 offset = 0;
219 for ( i = 0; ; i++ ) {
220 child = node.children[ i ];
221 if ( !child ) {
222 throw new Error( 'Node does not reach offset' );
223 }
224 childLength = child.getOuterLength();
225 offset += childLength;
226 if ( offset >= contentOffset ) {
227 break;
228 }
229 }
230 if ( offset === contentOffset ) {
231 return { node: node, offset: i + 1 };
232 }
233 return { node: child, offset: contentOffset - offset + childLength };
234 }
235
236 function prepareSplice( pathAndOffset, isContent, wantText ) {
237 const path = pathAndOffset.slice( 0, -1 ),
238 offset = pathAndOffset[ pathAndOffset.length - 1 ];
239 let node = document.documentNode;
240
241 // Find node
242 for ( let i = 0, iLen = path.length; i < iLen; i++ ) {
243 node = node.children[ path[ i ] ];
244 }
245 let position;
246 if ( isContent ) {
247 // Determine position from (linearized) content offset
248 if ( wantText ) {
249 position = ensureText( findContentPosition( node, offset ) );
250 } else {
251 position = ensureNotText( findContentPosition( node, offset ) );
252 }
253 } else {
254 position = { node: node, offset: offset };
255 }
256 // Get linear offset
257 if ( position.node.type === 'text' || position.offset === 0 ) {
258 position.linearOffset = position.node.getRange().start + position.offset;
259 } else {
260 position.linearOffset = position.node.children[ position.offset - 1 ].getOuterRange().end;
261 }
262 return position;
263 }
264
265 // Increment the change counter on the closest containing branch node at this offset
266 // (This is used when converting to/from HTML, to decide whether loaded metadata offsets
267 // need round tripping)
268 function markBranchNodeChanged( offset ) {
269 const adj = isReversed ? -1 : 1;
270 let i = offset - 1;
271
272 while ( i >= 0 ) {
273 const item = document.data.getData( i-- );
274 if ( !(
275 ve.dm.LinearData.static.isOpenElementData( item ) &&
276 ve.dm.nodeFactory.lookup(
277 ve.dm.LinearData.static.getType( item )
278 ).prototype instanceof ve.dm.BranchNode
279 ) ) {
280 continue;
281 }
282 if ( item.internal && item.internal.changesSinceLoad !== undefined ) {
283 // Guard against marking the same node twice
284 if ( changedBranchNodes.indexOf( item ) === -1 ) {
285 const newItem = ve.copy( item );
286 changedBranchNodes.push( newItem );
287 newItem.internal.changesSinceLoad += adj;
288 document.data.splice( i + 1, 1, ve.deepFreeze( newItem ) );
289 }
290 }
291 // This is a branch node boundary, so go no further
292 break;
293 }
294 }
295
296 function spliceLinear( offset, remove, insert ) {
297 const content = ve.batchSplice( document.data, offset, remove, insert ? ve.deepFreeze( insert, true ) : [] );
298 markBranchNodeChanged( offset );
299 return content;
300 }
301
302 // Removes empty text node, or joins consecutive text nodes, at offset
303 function healTextNodes( node, offset ) {
304 const pre = node.children[ offset - 1 ];
305 let post = node.children[ offset ];
306
307 if ( post && post.type === 'text' && post.length === 0 ) {
308 // Remove empty text node
309 splice( node, offset, 1 );
310 post = node.children[ offset ];
311 }
312 if ( pre && post && pre.type === 'text' && post.type === 'text' ) {
313 pre.adjustLength( post.length );
314 splice( node, offset, 1 );
315 }
316 }
317
318 const isTextOp = treeOp.type.slice( -4 ) === 'Text';
319 const f = treeOp.from && prepareSplice( treeOp.from, treeOp.isContent, isTextOp );
320 const t = treeOp.to && prepareSplice( treeOp.to, treeOp.isContent, isTextOp );
321 // eslint-disable-next-line es-x/no-array-string-prototype-at
322 const a = treeOp.at && prepareSplice( treeOp.at, treeOp.isContent, isTextOp );
323
324 // Always adjust linear data before tree, to ensure consistency when node events
325 // are emitted.
326 switch ( treeOp.type ) {
327 case 'removeNode': {
328 // The node should have no contents, so its outer length should be 2
329 const data = spliceLinear( a.linearOffset, 2 );
330 this.checkEqualData( data, [ treeOp.element, { type: '/' + treeOp.element.type } ] );
331 splice( a.node, a.offset, 1 );
332 healTextNodes( a.node, a.offset );
333 break;
334 }
335 case 'insertNode': {
336 spliceLinear( a.linearOffset, 0, [ treeOp.element, { type: '/' + treeOp.element.type } ] );
337 const nodeToInsert = ve.dm.nodeFactory.createFromElement( treeOp.element );
338 if ( nodeToInsert instanceof ve.dm.BranchNode ) {
339 nodeToInsert.setupBlockSlugs();
340 }
341 splice( a.node, a.offset, 0, nodeToInsert );
342 break;
343 }
344 case 'moveNode': {
345 const data = spliceLinear( f.linearOffset, f.node.children[ f.offset ].getOuterLength() );
346 // No need to use local splice function as we know the node is going
347 // to be re-inserted immediately.
348 const movedNode = f.node.splice( f.offset, 1 )[ 0 ];
349 const adjustment = t.linearOffset > f.linearOffset ? data.length : 0;
350 spliceLinear( t.linearOffset - adjustment, 0, data );
351 t.node.splice( t.offset, 0, movedNode );
352 break;
353 }
354 case 'removeText': {
355 const data = spliceLinear( a.linearOffset, treeOp.data.length );
356 this.checkEqualData( data, treeOp.data );
357 a.node.adjustLength( -treeOp.data.length );
358 healTextNodes( a.node.parent, a.node.parent.children.indexOf( a.node ) );
359 break;
360 }
361 case 'insertText': {
362 spliceLinear( a.linearOffset, 0, treeOp.data );
363 a.node.adjustLength( treeOp.data.length );
364 break;
365 }
366 case 'moveText': {
367 const data = spliceLinear( f.linearOffset, treeOp.length );
368 f.node.adjustLength( -treeOp.length );
369 healTextNodes( f.node.parent, f.node.parent.children.indexOf( f.node ) );
370 const adjustment = t.linearOffset > f.linearOffset ? data.length : 0;
371 spliceLinear( t.linearOffset - adjustment, 0, data );
372 t.node.adjustLength( treeOp.length );
373 break;
374 }
375 default:
376 throw new Error( 'Unknown tree op type: ' + treeOp.type );
377 }
378
379 if ( addedNodes.length || removedNodes.length ) {
380 document.updateNodesByType( addedNodes, removedNodes );
381 }
382 };
383
384 /**
385 * The top level method: modify document tree according to transaction
386 *
387 * @param {ve.dm.Document} document The document
388 * @param {ve.dm.Transaction} transaction The transaction
389 */
390 ve.dm.TreeModifier.prototype.process = function ( document, transaction ) {
391 this.setup( document );
392 this.calculateTreeOperations( transaction );
393 // Prior rollback logic removed: treeOps is now guaranteed to work
394 this.constructor.static.applyTreeOperations( transaction.isReversed, document, this.treeOps );
395 };
396
397 /**
398 * Setup state variables
399 *
400 * @param {ve.dm.Document} document The document to be processed
401 */
402 ve.dm.TreeModifier.prototype.setup = function ( document ) {
403 // XXX we only need these two properties for dump() in tests
404 this.document = document;
405 this.insertions = [];
406
407 // Initialize state
408 this.data = document.data;
409 this.deletions = [];
410 this.remover = new ve.dm.TreeCursor( document.getDocumentNode(), [] );
411 this.inserter = new ve.dm.TreeCursor( document.getDocumentNode(), this.deletions );
412 this.treeOps = [];
413 this.insertedNodes = [];
414 this.insertedPositions = [];
415 this.adjustmentTree = { offsetsUsed: [] };
416 };
417
418 /**
419 * Transform linear operations into tree operations
420 *
421 * @param {ve.dm.Transaction} transaction The transaction
422 */
423 ve.dm.TreeModifier.prototype.calculateTreeOperations = function ( transaction ) {
424 const linearOps = transaction.operations;
425 for ( let i = 0, iLen = linearOps.length; i < iLen; i++ ) {
426 this.processLinearOperation( linearOps[ i ] );
427 }
428 this.processImplicitFinalRetain();
429 };
430
431 /**
432 * Translate a linear operation into tree operations
433 *
434 * #processImplicitFinalRetain should be called once all operations have been processed
435 *
436 * @param {Object} linearOp The linear operation
437 */
438 ve.dm.TreeModifier.prototype.processLinearOperation = function ( linearOp ) {
439 if ( linearOp.type === 'retain' ) {
440 let retainLength = linearOp.length;
441 while ( retainLength > 0 ) {
442 retainLength -= this.processRetain( retainLength );
443 }
444 } else if ( linearOp.type === 'replace' ) {
445 let i, iLen, item, data;
446 for ( i = 0, iLen = linearOp.remove.length; i < iLen; i++ ) {
447 item = linearOp.remove[ i ];
448 if ( item.type ) {
449 this.processRemove( item );
450 continue;
451 }
452 // Group the whole current run of text, and process it
453 data = [ item ];
454 while ( ++i < iLen && !linearOp.remove[ i ].type ) {
455 item = linearOp.remove[ i ];
456 data.push( item );
457 }
458 i--;
459 this.processRemove( data );
460 }
461 for ( i = 0, iLen = linearOp.insert.length; i < iLen; i++ ) {
462 item = linearOp.insert[ i ];
463 if ( item.type ) {
464 this.processInsert( item );
465 continue;
466 }
467 // Group the whole current run of text, and process it
468 data = [ item ];
469 while ( ++i < iLen && !linearOp.insert[ i ].type ) {
470 item = linearOp.insert[ i ];
471 data.push( item );
472 }
473 i--;
474 this.processInsert( data );
475 }
476 }
477 // Else the linear operation type must be 'attribute': do nothing
478 };
479
480 /**
481 * Retain to the end of the content
482 */
483 ve.dm.TreeModifier.prototype.processImplicitFinalRetain = function () {
484 // Pretend there is an implicit retain to the end of the document
485 // TODO: fix our tests so this is unnecessary, then check for exhaustion instead
486 while ( true ) {
487 const node = this.remover.node;
488 if ( !node || (
489 node === this.remover.root &&
490 this.remover.offset === node.children.length
491 ) ) {
492 return;
493 }
494 let retainLength;
495 if ( node.type === 'text' ) {
496 // Retain all remaining text; if there is no remaining text then
497 // retain a single offset.
498 retainLength = Math.max( 1, node.length - this.remover.offset );
499 } else if ( !node.hasChildren() ) {
500 retainLength = 1;
501 } else {
502 const item = node.children[ this.remover.offset ];
503 retainLength = item ? item.getOuterLength() : 1;
504 }
505 this.processRetain( retainLength );
506 }
507 };
508
509 /**
510 * Test whether both pointers point to the same location
511 *
512 * @return {boolean} True if the paths and offsets are identical
513 */
514 ve.dm.TreeModifier.prototype.cursorsMatch = function () {
515 if ( this.insertedPositions.length > 0 ) {
516 return false;
517 }
518 const rawRemoverPosition = this.getRawRemoverPosition( {
519 path: this.remover.path,
520 offset: this.remover.offset,
521 node: this.remover.node
522 } );
523 const rawInserterPosition = this.getRawInserterPosition();
524 const adjustedRemoverPosition = this.adjustRemoverPosition( rawRemoverPosition );
525 const adjustedInserterPosition = this.adjustInserterPosition( rawInserterPosition );
526
527 // Optimization: adjustedRemoverPosition and adjustedInserterPosition are very
528 // often arrays of length 1. This simple check is much faster than a full
529 // JSON.stringify comparison.
530 if (
531 adjustedRemoverPosition.length === 1 && adjustedInserterPosition.length === 1 &&
532 adjustedRemoverPosition[ 0 ] === adjustedInserterPosition[ 0 ]
533 ) {
534 return true;
535 }
536
537 return JSON.stringify( adjustedRemoverPosition ) === JSON.stringify( adjustedInserterPosition );
538 };
539
540 /**
541 * Process the retention of content passed by one step of the remover
542 *
543 * If the inserter and remover are at the same place, just skip content.
544 *
545 * Else the remover *feeds* the inserter:
546 * - The inserter plans insertions in the (imagined, hypothetical) document
547 * - But the only move it can make in the (immutable) real document is to step out of nodes
548 * - It cannot skip past nodes (other than skipping remaining siblings when stepping out)
549 * - If the remover steps into a node, the inserter creates a node of the same type
550 * - If the remover crosses content, it is moved to the inserter
551 * - If the remover steps out of a node, the inserter steps out of its node
552 *
553 * @param {number} maxLength The maximum amount of content to retain
554 * @return {number} The amount of content retained
555 */
556 ve.dm.TreeModifier.prototype.processRetain = function ( maxLength ) {
557 const remover = this.remover,
558 inserter = this.inserter;
559
560 if ( this.insertedPositions.length === 0 ) {
561 this.inserter.crossIgnoredNodes();
562 }
563 let removerStep, inserterStep;
564 if ( this.cursorsMatch() ) {
565 // Pointers are in the same location, so advance them together.
566 // This is the only way both pointers can ever enter the same node;
567 // in any other case, a node entered at an 'open' tag by one pointer
568 // is marked as either as a deletion or a creation, so the other
569 // pointer will not follow.
570 removerStep = remover.stepAtMost( maxLength );
571 inserterStep = inserter.stepAtMost( maxLength );
572 if ( !removerStep ) {
573 throw new Error( 'Remover past end' );
574 }
575 if ( !inserterStep ) {
576 throw new Error( 'Inserter past end' );
577 }
578 if ( !this.cursorsMatch() ) {
579 throw new Error( 'Remover and inserter unexpectedly diverged' );
580 }
581 return removerStep.length;
582 }
583 // Else pointers are not in the same location (in fact they cannot lie in the
584 // same node)
585 removerStep = remover.stepAtMost( maxLength );
586 switch ( removerStep.type ) {
587 case 'crosstext':
588 this.pushMoveTextOp( removerStep );
589 if ( this.insertedPositions.length ) {
590 this.insertedPositions[ this.insertedPositions.length - 1 ] += removerStep.length;
591 }
592 break;
593 case 'cross':
594 if ( removerStep.item.type === 'text' ) {
595 this.pushMoveTextOp( removerStep );
596 if ( this.insertedPositions.length ) {
597 this.insertedPositions[ this.insertedPositions.length - 1 ] += removerStep.item.length;
598 }
599 } else {
600 this.deletions.push( removerStep.item );
601 this.pushMoveNodeOp( removerStep );
602 if ( this.insertedPositions.length ) {
603 this.insertedPositions[ this.insertedPositions.length - 1 ] +=
604 this.isInsertionContent() ? 2 : 1;
605 }
606 }
607 break;
608 case 'open': {
609 this.deletions.push( removerStep.item );
610 // Clone last open and step in
611 const element = removerStep.item.getClonedElement( true );
612 this.pushInsertNodeOp( element );
613 this.insertedNodes.push( element );
614 // This 0 position is invalid if element is content (because the offset should be
615 // linearized), but it will get popped immediately
616 this.insertedPositions.push( 0 );
617 break;
618 }
619 case 'close':
620 if ( this.insertedPositions.length ) {
621 this.insertedNodes.pop();
622 this.insertedPositions.pop();
623 if ( this.insertedPositions.length ) {
624 this.insertedPositions[ this.insertedPositions.length - 1 ] +=
625 this.isInsertionContent() ? 2 : 1;
626 }
627 } else {
628 if ( inserter.node.type === 'text' ) {
629 inserter.stepOut();
630 }
631 inserterStep = inserter.stepOut();
632 if ( inserterStep.item.type !== removerStep.item.type ) {
633 throw new Error( 'Expected ' + removerStep.item.type + ', not ' +
634 inserterStep.item.type );
635 }
636 }
637 this.pushRemoveLastIfInDeletions();
638 break;
639 }
640 return removerStep.length;
641 };
642
643 /**
644 * Process the removal of some items
645 *
646 * @param {Object|Array} itemOrData An open tag, a close tag, or an array of text items
647 */
648 ve.dm.TreeModifier.prototype.processRemove = function ( itemOrData ) {
649 const cursorsMatch = this.cursorsMatch(),
650 length = itemOrData.length || 1,
651 step = this.remover.stepAtMost( length );
652
653 if ( cursorsMatch && ( step.type === 'cross' || step.type === 'crosstext' ) ) {
654 this.inserter.stepAtMost( length );
655 }
656
657 if ( step.type === 'crosstext' ) {
658 this.pushRemoveTextOp( step );
659 } else if ( step.type === 'cross' ) {
660 this.pushRemoveLast();
661 } else if ( step.type === 'open' ) {
662 this.deletions.push( step.item );
663 } else if ( step.type === 'close' ) {
664 this.pushRemoveLastIfInDeletions();
665 }
666 };
667
668 /**
669 * Process the insertion an open tag, a close tag, or an array of text items
670 *
671 * @param {Object|Array} itemOrData An open tag, a close tag, or an array of text items
672 */
673 ve.dm.TreeModifier.prototype.processInsert = function ( itemOrData ) {
674 const inserter = this.inserter;
675
676 let item, type, data;
677 if ( itemOrData.type ) {
678 item = itemOrData;
679 type = item.type.charAt( 0 ) === '/' ? 'close' : 'open';
680 } else {
681 data = itemOrData;
682 type = 'crosstext';
683 }
684
685 if ( type === 'open' ) {
686 if ( inserter.node.type === 'text' ) {
687 // Step past the end of the text node, even if that skips past some
688 // content (in which case the remover logically must later cross that
689 // content in either processRemove or processRetain).
690 inserter.stepOut();
691 }
692 const element = ve.copy( item );
693 this.pushInsertNodeOp( element );
694 this.insertedNodes.push( element );
695 // This 0 position is invalid if element is content (because the offset should be
696 // linearized), but it will get popped immediately
697 this.insertedPositions.push( 0 );
698 } else if ( type === 'crosstext' ) {
699 this.pushInsertTextOp( ve.copy( data ) );
700 if ( this.insertedPositions.length ) {
701 this.insertedPositions[ this.insertedPositions.length - 1 ] += data.length;
702 }
703 } else if ( type === 'close' ) {
704 if ( this.insertedPositions.length ) {
705 const insertedNode = this.insertedNodes.pop();
706 if ( insertedNode.type !== item.type.slice( 1 ) ) {
707 throw new Error( 'Expected closing for ' + insertedNode.type +
708 ' but got closing for ' + item.type.slice( 1 ) );
709 }
710 this.insertedPositions.pop();
711 if ( this.insertedPositions.length ) {
712 this.insertedPositions[ this.insertedPositions.length - 1 ] +=
713 this.isInsertionContent() ? 2 : 1;
714 }
715 } else {
716 // Step past the next close tag, even if that skips past some content (in which
717 // case the remover logically must later cross that content in either
718 // processRemove or processRetain).
719 if ( inserter.node.type === 'text' ) {
720 inserter.stepOut();
721 }
722 const step = inserter.stepOut();
723 if ( step.item.type !== item.type.slice( 1 ) ) {
724 throw new Error( 'Expected closing for ' + step.item.type +
725 ' but got closing for ' + item.type.slice( 1 ) );
726 }
727 }
728 }
729 };
730
731 /**
732 * Push into treeOps the removal of the last remover step, which must be 'cross' or 'close'
733 */
734 ve.dm.TreeModifier.prototype.pushRemoveLast = function () {
735 const step = this.remover.lastStep;
736 if ( step.item.type === 'text' ) {
737 this.pushRemoveTextOp( step );
738 } else {
739 this.pushRemoveNodeOp( step );
740 }
741 };
742
743 /**
744 * Push into treeOps the removal of the last remover step, if that item marked as deleted
745 */
746 ve.dm.TreeModifier.prototype.pushRemoveLastIfInDeletions = function () {
747 const i = this.deletions.indexOf( this.remover.lastStep.item );
748 if ( i !== -1 ) {
749 this.pushRemoveLast();
750 }
751 };
752
753 /**
754 * Push into treeOps the node insertion at the current inserter position
755 *
756 * @param {ve.dm.Node} element The element to insert (inserted into treeOps without copying)
757 */
758 ve.dm.TreeModifier.prototype.pushInsertNodeOp = function ( element ) {
759 const isContent = this.isInsertionContent(),
760 rawInserterPosition = this.getRawInserterPosition();
761
762 this.checkCanInsertNodeType( element.type );
763
764 this.treeOps.push( {
765 type: 'insertNode',
766 isContent: isContent,
767 at: this.adjustInserterPosition( rawInserterPosition ),
768 element: element
769 } );
770 if ( this.insertedPositions.length === 0 ) {
771 this.modifyAdjustmentTree( rawInserterPosition, isContent ? 2 : 1, false );
772 }
773 };
774
775 /**
776 * Push into treeOps the text insertion at the current inserter position
777 *
778 * @param {Array} data The text data to insert
779 */
780 ve.dm.TreeModifier.prototype.pushInsertTextOp = function ( data ) {
781 const rawInserterPosition = this.getRawInserterPosition();
782
783 this.checkCanInsertText();
784
785 this.treeOps.push( {
786 type: 'insertText',
787 isContent: true,
788 at: this.adjustInserterPosition( rawInserterPosition ),
789 data: data
790 } );
791 if ( this.insertedPositions.length === 0 ) {
792 this.modifyAdjustmentTree( rawInserterPosition, data.length, false );
793 }
794 };
795
796 /**
797 * Push into treeOps a move of a node to the current inserter position
798 *
799 * @param {ve.dm.TreeCursor.Step} removerStep The remover step over the node
800 */
801 ve.dm.TreeModifier.prototype.pushMoveNodeOp = function ( removerStep ) {
802 const rawRemoverPosition = this.getRawRemoverPosition( removerStep ),
803 rawInserterPosition = this.getRawInserterPosition(),
804 isContent = this.doesTypeTakeContent( removerStep.node.type );
805
806 this.checkCanInsertNodeType( removerStep.item.type );
807
808 this.treeOps.push( {
809 type: 'moveNode',
810 isContent: isContent,
811 from: this.adjustRemoverPosition( rawRemoverPosition ),
812 to: this.adjustInserterPosition( rawInserterPosition )
813 } );
814 this.modifyAdjustmentTree( rawRemoverPosition, isContent ? -2 : -1, true );
815 if ( this.insertedPositions.length === 0 ) {
816 this.modifyAdjustmentTree( rawInserterPosition, isContent ? 2 : 1, false );
817 }
818 };
819
820 /**
821 * Push into treeOps a move of some text to the current inserter position
822 *
823 * @param {ve.dm.TreeCursor.Step} removerStep The remover step over the text
824 */
825 ve.dm.TreeModifier.prototype.pushMoveTextOp = function ( removerStep ) {
826 const length = removerStep.type === 'crosstext' ?
827 removerStep.length :
828 removerStep.item.getLength(),
829 rawRemoverPosition = this.getRawRemoverPosition( removerStep ),
830 rawInserterPosition = this.getRawInserterPosition();
831
832 this.checkCanInsertText();
833
834 this.treeOps.push( {
835 type: 'moveText',
836 isContent: true,
837 from: this.adjustRemoverPosition( rawRemoverPosition ),
838 to: this.adjustInserterPosition( rawInserterPosition ),
839 length: length
840 } );
841 this.modifyAdjustmentTree( rawRemoverPosition, -length, false );
842 if ( this.insertedPositions.length === 0 ) {
843 this.modifyAdjustmentTree( rawInserterPosition, length, false );
844 }
845 };
846
847 /**
848 * Push into treeOps a removal of a node
849 *
850 * @param {ve.dm.TreeCursor.Step} removerStep The remover step over the node
851 */
852 ve.dm.TreeModifier.prototype.pushRemoveNodeOp = function ( removerStep ) {
853 const rawRemoverPosition = this.getRawRemoverPosition( removerStep ),
854 isContent = this.doesTypeTakeContent( removerStep.node.type );
855 this.treeOps.push( {
856 type: 'removeNode',
857 isContent: isContent,
858 at: this.adjustRemoverPosition( rawRemoverPosition ),
859 element: removerStep.item.getClonedElement( true )
860 } );
861 this.modifyAdjustmentTree( rawRemoverPosition, isContent ? -2 : -1, true );
862 };
863
864 /**
865 * Push into treeOps a removal of some text
866 *
867 * @param {ve.dm.TreeCursor.Step} removerStep The remover step over the text
868 */
869 ve.dm.TreeModifier.prototype.pushRemoveTextOp = function ( removerStep ) {
870 const rawRemoverPosition = this.getRawRemoverPosition( removerStep );
871 let start, end;
872 if ( removerStep.type === 'crosstext' ) {
873 start = removerStep.node.getRange().start + removerStep.offset;
874 end = start + removerStep.length;
875 } else {
876 start = removerStep.item.getRange().start;
877 end = removerStep.item.getRange().end;
878 }
879 this.treeOps.push( {
880 type: 'removeText',
881 isContent: true,
882 at: this.adjustRemoverPosition( rawRemoverPosition ),
883 data: ve.copy( this.data.slice( start, end ) )
884 } );
885 this.modifyAdjustmentTree( rawRemoverPosition, start - end, false );
886 };
887
888 /**
889 * Return adjustment tree node at a given offset path, inserting it if necessary
890 *
891 * @param {number[]} position Offset path in the adjustment tree
892 * @return {Object} The adjustment tree node
893 */
894 ve.dm.TreeModifier.prototype.findOrCreateAdjustmentNode = function ( position ) {
895 let adjustmentNode = this.adjustmentTree;
896 for ( let i = 0, len = position.length; i < len; i++ ) {
897 const offset = position[ i ];
898 if ( !adjustmentNode[ offset ] ) {
899 adjustmentNode[ offset ] = { offsetsUsed: [] };
900 adjustmentNode.offsetsUsed.push( offset );
901 }
902 adjustmentNode = adjustmentNode[ offset ];
903 }
904 return adjustmentNode;
905 };
906
907 /**
908 * Modify the adjustment in the adjustment tree at a given offset path
909 *
910 * @param {number[]} rawPosition Unadjusted offset path
911 * @param {number} diff Adjustment at rawPosition
912 * @param {boolean} deleteDescendants If true, delete all adjustments at paths descending from here
913 */
914 ve.dm.TreeModifier.prototype.modifyAdjustmentTree = function ( rawPosition, diff, deleteDescendants ) {
915 const adjustmentNode = this.findOrCreateAdjustmentNode( rawPosition );
916 if ( diff > 0 ) {
917 adjustmentNode.inserted = ( adjustmentNode.inserted || 0 ) + diff;
918 } else {
919 adjustmentNode.removed = ( adjustmentNode.removed || 0 ) - diff;
920 }
921 if ( deleteDescendants ) {
922 adjustmentNode.offsetsUsed.forEach( ( i ) => {
923 delete adjustmentNode[ i ];
924 } );
925 adjustmentNode.offsetsUsed = [];
926 }
927 };
928
929 /**
930 * Get the raw position of a node stepped over by the remover
931 *
932 * @param {ve.dm.TreeCursor.Step} step Remover step
933 * @return {number[]} The pathAndOffset, with offsets inside a ContentBranchNode linearized
934 */
935 ve.dm.TreeModifier.prototype.getRawRemoverPosition = function ( step ) {
936 return this.getRawPosition( step.path, step.offset, step.node );
937 };
938
939 /**
940 * Get the raw position at the inserter
941 *
942 * @return {number[]} The pathAndOffset, with offsets inside a ContentBranchNode linearized
943 */
944 ve.dm.TreeModifier.prototype.getRawInserterPosition = function () {
945 return this.getRawPosition( this.inserter.path, this.inserter.offset, this.inserter.node );
946 };
947
948 /**
949 * Get the adjusted position of a raw remover position
950 *
951 * @param {number[]} rawPosition The raw remover position
952 * @return {number[]} Adjusted pathAndOffset, with offsets inside a ContentBranchNode linearized
953 */
954 ve.dm.TreeModifier.prototype.adjustRemoverPosition = function ( rawPosition ) {
955 return this.getAdjustedPosition( rawPosition, false );
956 };
957
958 /**
959 * Get the adjusted position of a raw inserter position, XXX
960 *
961 * @param {number[]} rawPosition The raw inserter position (must be its current position)
962 * @return {number[]} Adjusted pathAndOffset, with offsets inside a ContentBranchNode linearized, and including current position within nodes to be inserted, if any
963 */
964 ve.dm.TreeModifier.prototype.adjustInserterPosition = function ( rawPosition ) {
965 // getAdjustedPosition returns a brand new array, so we can safely modify
966 // it with batchPush, which is much faster than concat (which creates a new array)
967 const positions = this.getAdjustedPosition( rawPosition, true );
968 ve.batchPush( positions, this.insertedPositions );
969 return positions;
970 };
971
972 /**
973 * Get the raw position of a node, with offsets inside a ContentBranchNode linearized
974 *
975 * @param {number[]} path Path to a node
976 * @param {number} offset Offset within the node
977 * @param {ve.dm.Node} node The node
978 * @return {number[]} The pathAndOffset, with offsets inside a ContentBranchNode linearized
979 */
980 ve.dm.TreeModifier.prototype.getRawPosition = function ( path, offset, node ) {
981 let i, linearizedOffset;
982 // No need to check node.parent.hasChildren() below as node.parent
983 // is a parent so must have children.
984 if ( node.parent && node.parent.canContainContent() ) {
985 const numNodesBefore = path[ path.length - 1 ];
986 linearizedOffset = offset;
987 for ( i = 0; i < numNodesBefore; i++ ) {
988 linearizedOffset += node.parent.children[ i ].getOuterLength();
989 }
990 path = path.slice( 0, -1 );
991 } else if ( node.canContainContent() && node.hasChildren() ) {
992 linearizedOffset = 0;
993 for ( i = 0; i < offset; i++ ) {
994 linearizedOffset += node.children[ i ].getOuterLength();
995 }
996 } else {
997 linearizedOffset = offset;
998 }
999 if ( !path.length ) {
1000 // Optimization, path is often empty
1001 return [ linearizedOffset ];
1002 }
1003 path = path.slice();
1004 // slice+push is faster than concat
1005 path.push( linearizedOffset );
1006 return path;
1007 };
1008
1009 /**
1010 * Get the adjusted position of a raw position
1011 *
1012 * @param {number[]} position The raw position
1013 * @param {boolean} isInserter True for an inserter position; false for a remover position
1014 * @return {number[]} Adjusted pathAndOffset, with offsets inside a ContentBranchNode linearized
1015 */
1016 ve.dm.TreeModifier.prototype.getAdjustedPosition = function ( position, isInserter ) {
1017 let node = this.adjustmentTree;
1018
1019 position = position.slice();
1020 // Adjust each offset in the path so inserted nodes are counted
1021 for ( let i = 0, iLen = position.length; i < iLen; i++ ) {
1022 const positionI = position[ i ];
1023
1024 // The loop below is equivalent to:
1025 //
1026 // for ( j = 0, jLen = positionI + 1; j < jLen; j++ ) {
1027 // childNode = node[ j ];
1028 // if ( !childNode ) {
1029 // continue;
1030 // }
1031 // ...
1032 // }
1033 //
1034 // However as `node` is very sparse, it is slow to iterate over
1035 // every position, so just iterate over the positions we have,
1036 // then check the loop conditions later. (T261634)
1037 // An offsetsUsed property is stored on every node instead of
1038 // using a for..in loop as a for..in loop has to re-calculate
1039 // the list of indexes to iterate over.
1040
1041 const jLen = positionI + 1;
1042 const offsetsUsed = node.offsetsUsed;
1043 for ( let k = 0, kLen = offsetsUsed.length; k < kLen; k++ ) {
1044 const j = offsetsUsed[ k ];
1045 if ( j >= jLen ) {
1046 continue;
1047 }
1048
1049 const childNode = node[ j ];
1050
1051 const inserted = childNode.inserted || 0;
1052 const removed = childNode.removed || 0;
1053
1054 if ( i < iLen - 1 || j < jLen - 1 ) {
1055 // This offset is strictly before position
1056 position[ i ] += inserted - removed;
1057 } else {
1058 // This offset is exactly at position
1059 // Don't adjust for removals
1060 position[ i ] += inserted;
1061 // Adjust for insertions, except if we are the inserter and the insertion is incomplete
1062 // (note if insertedNodes.length > 0, then also inserted > 0)
1063 if ( isInserter && this.insertedNodes.length > 0 ) {
1064 // Incomplete means we are inside a (non text) node
1065 position[ i ]--;
1066 }
1067 }
1068 }
1069 node = node[ positionI ];
1070 if ( !node ) {
1071 break;
1072 }
1073 }
1074 return position;
1075 };
1076
1077 /**
1078 * Test whether a node type takes content
1079 *
1080 * @param {string} type The name of a ve.dm.Node type
1081 * @return {boolean} Whether that type takes content
1082 */
1083 ve.dm.TreeModifier.prototype.doesTypeTakeContent = function ( type ) {
1084 return !!ve.dm.nodeFactory.canNodeContainContent( type );
1085 };
1086
1087 /**
1088 * Test whether the inserter is at a content position
1089 *
1090 * @return {boolean} Whether the inserter is at a content position
1091 */
1092 ve.dm.TreeModifier.prototype.isInsertionContent = function () {
1093 return this.doesTypeTakeContent( this.getTypeAtInserter() );
1094 };
1095
1096 /**
1097 * Get the type of the node in which the inserter lies
1098 *
1099 * @return {string} The node type
1100 */
1101 ve.dm.TreeModifier.prototype.getTypeAtInserter = function () {
1102 return this.insertedNodes.length > 0 ?
1103 this.insertedNodes[ this.insertedNodes.length - 1 ].type :
1104 this.inserter.node.type;
1105 };
1106
1107 /**
1108 * Throw an error if the inserter is not in a content position
1109 *
1110 * @throws {Error} Cannot insert text into a foo node
1111 */
1112 ve.dm.TreeModifier.prototype.checkCanInsertText = function () {
1113 const parentType = this.getTypeAtInserter();
1114
1115 if ( parentType === 'text' ) {
1116 return;
1117 }
1118 if ( !ve.dm.nodeFactory.canNodeContainContent( parentType ) ) {
1119 throw new Error( 'Cannot insert text into a ' + parentType + ' node' );
1120 }
1121 };
1122
1123 /**
1124 * Throw an error if the inserter node cannot take a child of a specified type
1125 *
1126 * @param {string} nodeType The node type
1127 * @throws {Error} Cannot add child
1128 */
1129 ve.dm.TreeModifier.prototype.checkCanInsertNodeType = function ( nodeType ) {
1130 const parentType = this.getTypeAtInserter(),
1131 nodeClass = ve.dm.nodeFactory.lookup( nodeType ),
1132 parentClass = ve.dm.nodeFactory.lookup( parentType ),
1133 childNodeTypes = parentClass.static.childNodeTypes;
1134
1135 if ( Array.isArray( childNodeTypes ) && childNodeTypes.length === 0 ) {
1136 throw new Error( 'Cannot add a child to ' + parentType + ' node' );
1137 }
1138
1139 if ( nodeClass.static.isContent && !parentClass.static.canContainContent ) {
1140 throw new Error( 'Cannot add content node (' + nodeType + ') to a ' + parentType + ' node' );
1141 }
1142
1143 if ( !nodeClass.static.isMetaData ) {
1144 if ( !nodeClass.static.isContent && parentClass.static.canContainContent ) {
1145 throw new Error( 'Cannot add structure node (' + nodeType + ') to a ' + parentType + ' node' );
1146 }
1147
1148 if ( Array.isArray( childNodeTypes ) && childNodeTypes.indexOf( nodeType ) === -1 ) {
1149 throw new Error( 'Cannot add a ' + nodeType + ' node to ' + parentType + ' node' );
1150 }
1151 }
1152 };
1153
1154 /* Initialization */
1155
1156 ve.dm.treeModifier = new ve.dm.TreeModifier();