Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel VisualDiff class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /* global treeDiffer */
8
9 /**
10 * VisualDiff
11 *
12 * Gets the diff between two VisualEditor DataModel DocumentNodes
13 *
14 * @class
15 * @constructor
16 * @param {ve.dm.Document|ve.dm.BranchNode} oldDocOrNode
17 * @param {ve.dm.Document|ve.dm.BranchNode} newDocOrNode
18 * @param {number} [timeout=1000] Timeout after which to stop performing linear diffs (in ms)
19 */
20 ve.dm.VisualDiff = function VeDmVisualDiff( oldDocOrNode, newDocOrNode, timeout ) {
21 const oldDoc = oldDocOrNode instanceof ve.dm.Document ? oldDocOrNode : oldDocOrNode.getDocument(),
22 newDoc = newDocOrNode instanceof ve.dm.Document ? newDocOrNode : newDocOrNode.getDocument();
23
24 this.oldDoc = oldDoc.cloneFromRange(
25 oldDocOrNode instanceof ve.dm.DocumentNode || oldDocOrNode instanceof ve.dm.Document ?
26 undefined :
27 oldDocOrNode.getRange(),
28 true,
29 'noMetadata'
30 );
31 this.newDoc = newDoc.cloneFromRange(
32 newDocOrNode instanceof ve.dm.DocumentNode || newDocOrNode instanceof ve.dm.Document ?
33 undefined :
34 newDocOrNode.getRange(),
35 true,
36 'noMetadata'
37 );
38
39 // Merge the old internal list into the new document, so that it knows
40 // about removed references
41 const tx = ve.dm.TransactionBuilder.static.newFromDocumentInsertion( this.newDoc, 0, this.oldDoc, new ve.Range( 0 ) );
42 this.newDoc.commit( tx );
43
44 // Set to read-only so that node offsets get cached
45 this.oldDoc.setReadOnly( true );
46 this.newDoc.setReadOnly( true );
47
48 this.treeDiffer = treeDiffer;
49 this.linearDiffer = new ve.DiffMatchPatch( this.oldDoc.getStore(), this.newDoc.getStore() );
50
51 // Minimum ratio of content (same : different) allowed between two corresponding nodes
52 this.diffThreshold = 0.5;
53
54 this.endTime = Date.now() + ( timeout || 1000 );
55 this.timedOut = false;
56
57 // Calling getDocumentNode triggers the DM node tree to be built
58 // so this must happen before things like freezeInternalListIndices
59 const oldDocNode = this.oldDoc.getDocumentNode();
60 const newDocNode = this.newDoc.getDocumentNode();
61
62 this.freezeInternalListIndices( this.oldDoc );
63 this.freezeInternalListIndices( this.newDoc );
64
65 const oldInternalList = this.oldDoc.getInternalList();
66 const newInternalList = this.newDoc.getInternalList();
67
68 this.diff = {
69 docDiff: this.diffDocs( oldDocNode, newDocNode, true ),
70 internalListDiff: this.getInternalListDiff( oldInternalList, newInternalList ),
71 metaListDiff: this.getMetaListDiff( oldDoc.getMetaList(), newDoc.getMetaList() )
72 };
73
74 // Make docs writable again, so they can be modified by DiffElement
75 this.oldDoc.setReadOnly( false );
76 this.newDoc.setReadOnly( false );
77 };
78
79 /* Inheritance */
80
81 OO.initClass( ve.dm.VisualDiff );
82
83 /**
84 * Get the original linear data from a node
85 *
86 * @param {ve.dm.Node} node Node
87 * @param {boolean} innerRange Get the node's inner range
88 * @return {Array} Linear data
89 */
90 ve.dm.VisualDiff.static.getDataFromNode = function ( node, innerRange ) {
91 const doc = node.getRoot().getDocument();
92 return doc.getData( innerRange ? node.getRange() : node.getOuterRange() );
93 };
94
95 /**
96 * Compare the linear data for two nodes
97 *
98 * @param {ve.dm.Node} oldNode Node from the old document
99 * @param {ve.dm.Node} newNode Node from the new document
100 * @return {boolean} The linear data is the same
101 */
102 ve.dm.VisualDiff.static.compareNodes = function ( oldNode, newNode ) {
103 if ( oldNode.length !== newNode.length || !oldNode.isDiffComparable( newNode ) ) {
104 return false;
105 }
106
107 const oldData = this.getDataFromNode( oldNode );
108 const newData = this.getDataFromNode( newNode );
109
110 if ( JSON.stringify( oldData ) === JSON.stringify( newData ) ) {
111 return true;
112 }
113
114 // If strings are not equal, the data may still be the same as far as
115 // we are concerned so should compare them properly.
116 const oldStore = oldNode.getRoot().getDocument().getStore();
117 const newStore = newNode.getRoot().getDocument().getStore();
118
119 for ( let i = 0, ilen = oldData.length; i < ilen; i++ ) {
120 if ( oldData[ i ] !== newData[ i ] &&
121 !ve.dm.ElementLinearData.static.compareElements( oldData[ i ], newData[ i ], oldStore, newStore ) ) {
122 return false;
123 }
124 }
125
126 return true;
127 };
128
129 /**
130 * Attach the internal list indexOrder to each node referenced by the internal
131 * list, ahead of document merge.
132 *
133 * @param {ve.dm.Document} doc
134 */
135 ve.dm.VisualDiff.prototype.freezeInternalListIndices = function ( doc ) {
136 const nodes = doc.getInternalList().nodes,
137 internalListGroups = doc.getInternalList().getNodeGroups();
138
139 for ( const groupName in internalListGroups ) {
140 const group = internalListGroups[ groupName ];
141 const groupIndexOrder = group.indexOrder;
142 for ( let i = 0, ilen = groupIndexOrder.length; i < ilen; i++ ) {
143 const nodeIndex = groupIndexOrder[ i ];
144 const refNodes = nodes[ groupName ].keyedNodes[ nodes[ groupName ].firstNodes[ nodeIndex ].registeredListKey ];
145 for ( let j = 0, jlen = refNodes.length; j < jlen; j++ ) {
146 doc.data.modifyData( refNodes[ j ].getOffset(), ( item ) => {
147 ve.setProp( item, 'internal', 'overrideIndex', i + 1 );
148 } );
149 }
150 }
151 }
152 };
153
154 /**
155 * @typedef {ve.dm.VisualDiff.ListDiff} DocDiff
156 * @memberof ve.dm.VisualDiff
157 * @property {ve.dm.Node} oldRoot
158 * @property {ve.dm.Node} newRoot
159 * @property {ve.dm.VisualDiff.AttributeDiff} attributeChange
160 */
161
162 /**
163 * Diff two nodes as documents, comaparing their children as lists.
164 *
165 * @param {ve.dm.Node} oldRoot Old root
166 * @param {ve.dm.Node} newRoot New root
167 * @param {boolean} skipInternalLists Skip internal list nodes
168 * @return {ve.dm.VisualDiff.DocDiff} Object containing diff information
169 */
170 ve.dm.VisualDiff.prototype.diffDocs = function ( oldRoot, newRoot, skipInternalLists ) {
171 let oldChildren = oldRoot.children;
172 let newChildren = newRoot.children;
173
174 if ( skipInternalLists ) {
175 oldChildren = oldChildren.filter( ( node ) => !( node instanceof ve.dm.InternalListNode ) );
176 newChildren = newChildren.filter( ( node ) => !( node instanceof ve.dm.InternalListNode ) );
177 }
178
179 const diff = this.diffList( oldChildren, newChildren );
180
181 diff.oldRoot = oldRoot;
182 diff.newRoot = newRoot;
183
184 if (
185 oldRoot && newRoot &&
186 // Actual document nodes don't have attributes as they
187 // don'texist in the linear data
188 !( oldRoot instanceof ve.dm.DocumentNode )
189 ) {
190 diff.attributeChange = this.diffAttributes( oldRoot, newRoot );
191 }
192
193 return diff;
194 };
195
196 /**
197 * @typedef {Object} ListDiff
198 * @memberof ve.dm.VisualDiff
199 * @property {ve.dm.Node[]} oldNodes
200 * @property {ve.dm.Node[]} newNodes
201 * @property {Object} oldToNew
202 * @property {Object} newToOld
203 * @property {number[]} remove
204 * @property {number[]} insert
205 */
206
207 /**
208 * Get the diff between two lists of nodes.
209 *
210 * @param {ve.dm.Node[]} oldNodes Nodes from the old document
211 * @param {ve.dm.Node[]} newNodes Nodes from the new document
212 * @return {ve.dm.VisualDiff.ListDiff} Object containing diff information
213 */
214 ve.dm.VisualDiff.prototype.diffList = function ( oldNodes, newNodes ) {
215 const oldNodesToDiff = [],
216 newNodesToDiff = [],
217 diff = {
218 oldNodes: oldNodes,
219 newNodes: newNodes,
220 oldToNew: {},
221 newToOld: {},
222 remove: [],
223 insert: []
224 };
225
226 // STEP 1: Find identical nodes
227
228 for ( let i = 0, ilen = oldNodes.length; i < ilen; i++ ) {
229 for ( let j = 0, jlen = newNodes.length; j < jlen; j++ ) {
230 if ( !Object.prototype.hasOwnProperty.call( diff.newToOld, j ) &&
231 this.constructor.static.compareNodes( oldNodes[ i ], newNodes[ j ] )
232 ) {
233 diff.oldToNew[ i ] = j;
234 diff.newToOld[ j ] = i;
235 break;
236 }
237 // If no new nodes equalled the old node, add it to nodes to diff
238 if ( j === jlen - 1 ) {
239 oldNodesToDiff.push( i );
240 }
241 }
242 }
243
244 for ( let j = 0, jlen = newNodes.length; j < jlen; j++ ) {
245 if ( !Object.prototype.hasOwnProperty.call( diff.newToOld, j ) ) {
246 newNodesToDiff.push( j );
247 }
248 }
249
250 // STEP 2: Find removed, inserted and modified nodes
251
252 if ( oldNodesToDiff.length !== 0 || newNodesToDiff.length !== 0 ) {
253 if ( oldNodesToDiff.length === 0 ) {
254 // Everything new is an insert
255 diff.insert = newNodesToDiff;
256 } else if ( newNodesToDiff.length === 0 ) {
257 // Everything old is a remove
258 diff.remove = oldNodesToDiff;
259 } else {
260 // Find out which remaining docChildren are removed, inserted or modified
261 this.findModifiedNodes(
262 oldNodesToDiff, newNodesToDiff, oldNodes, newNodes, diff
263 );
264 }
265 }
266
267 // STEP 3: Compute moves (up, down, no move)
268 if ( Object.keys( diff.newToOld ).length > 0 ) {
269 diff.moves = this.calculateDiffMoves( diff.oldToNew, diff.newToOld );
270 } else {
271 diff.moves = [];
272 }
273
274 return diff;
275 };
276
277 /**
278 * Calculate how items in a new list have moved, compared to items in the old list.
279 * More specifically, calculate the minimal moves, keeping the maximum possible number
280 * of nodes unmoved. Do this by finding the longest increasing subsequence in the
281 * sequence of oldDoc node indices, sorted by their corresponding newDoc nodes'
282 * indices. Those indices in the longest increasing subsequence represent the unmoved
283 * nodes.
284 *
285 * @param {Object.<number,number|Object>} oldToNew Map of oldDoc nodes to corresponding newDoc nodes.
286 * Keys are indices of nodes in the list. Values are either indices of nodes in the list for
287 * unchanged nodes, or objects where the `node` property is the index for changed nodes.
288 * @param {Object.<number,number|Object>} newToOld Map of newDoc nodes to corresponding oldDoc nodes.
289 * Same format at oldToNew.
290 * @return {Array.<number|string>} Record of whether and how each newDoc node has moved (0, 'up', 'down')
291 */
292 ve.dm.VisualDiff.prototype.calculateDiffMoves = function ( oldToNew, newToOld ) {
293 const oldPermuted = [],
294 unmoved = 0,
295 up = 'up',
296 down = 'down';
297
298 const getIndex = ( obj ) => typeof obj === 'number' ? obj : obj.node;
299
300 // See https://en.wikipedia.org/wiki/Longest_increasing_subsequence
301 function longestIncreasingSubsequence( sequence ) {
302 const mvs = [],
303 // finalIndices[i] holds:
304 // - if i is 0, 0
305 // - if there's an increasing subsequence of length i, the final item in that subsequence
306 // - if i > length of longest increasing subsequence, undefined
307 finalIndices = [],
308 // previousIndices[i] holds:
309 // - if i is in the longest increasing subsequence, the item before i in that subsequence
310 // - otherwise, 0
311 previousIndices = [];
312
313 let currentLength = 0;
314 finalIndices[ 0 ] = 0;
315
316 // Perform algorithm (i.e. populate finalIndices and previousIndices)
317 for ( let j = 0, jlen = sequence.length; j < jlen; j++ ) {
318 let low = 1;
319 let high = currentLength;
320 while ( low <= high ) {
321 const middle = Math.ceil( ( low + high ) / 2 );
322 if ( sequence[ finalIndices[ middle ] ] < sequence[ j ] ) {
323 low = middle + 1;
324 } else {
325 high = middle - 1;
326 }
327 }
328 const newLength = low;
329 previousIndices[ j ] = finalIndices[ newLength - 1 ];
330 finalIndices[ newLength ] = j;
331 if ( newLength > currentLength ) {
332 currentLength = newLength;
333 }
334 }
335
336 // Items in the longest increasing subsequence are oldDoc indices of unmoved nodes.
337 // Mark corresponding newDoc indices of these unmoved nodes, in mvs array.
338 let k = finalIndices[ currentLength ];
339 for ( let j = currentLength, jlen = 0; j > jlen; j-- ) {
340 const newIndex = getIndex( oldToNew[ sequence[ k ] ] );
341 mvs[ newIndex ] = unmoved;
342 k = previousIndices[ k ];
343 }
344
345 return mvs;
346 }
347
348 // Get oldDoc indices, sorted according to their order in the new doc
349 const sortedKeys = Object.keys( newToOld ).sort( ( a, b ) => Number( a ) - Number( b ) );
350 for ( let i = 0, ilen = sortedKeys.length; i < ilen; i++ ) {
351 const oldIndex = getIndex( newToOld[ sortedKeys[ i ] ] );
352 oldPermuted.push( oldIndex );
353 }
354
355 // Record which newDoc nodes have NOT moved. NB nodes inserted at the end of the
356 // newDoc will be treated as not moved by default.
357 const moves = longestIncreasingSubsequence( oldPermuted );
358
359 // Record whether the remaining newDoc nodes have moved up or down
360 // (or not at all, e.g. if they are an insert)
361 let latestUnmoved;
362 for ( let i = 0; i < Number( sortedKeys[ sortedKeys.length - 1 ] ) + 1; i++ ) {
363 if ( !( i in newToOld ) ) {
364 // This node must be an insert, so wasn't moved
365 moves[ i ] = unmoved;
366 } else if ( moves[ i ] === unmoved ) {
367 // This is the latest unmoved node so far
368 latestUnmoved = i;
369 } else {
370 // The node has moved
371 if ( latestUnmoved === undefined ) {
372 // This node comes before any unmoved nodes so must have moved up
373 moves[ i ] = up;
374 } else {
375 // If this node's oldDoc index is higher than the latest unmoved
376 // node's oldDoc index, then it must have moved up; otherwise it
377 // must have moved down
378 const nodeIndex = getIndex( newToOld[ i ] );
379 const latestUnmovedIndex = getIndex( newToOld[ latestUnmoved ] );
380 moves[ i ] = nodeIndex > latestUnmovedIndex ? up : down;
381 }
382 }
383 }
384
385 return moves;
386 };
387
388 /**
389 * Diff each old node against each new node in the list. If the differs decide
390 * that an old node is similar enough to a new node, record these as a change
391 * from the old to the new node and don't diff either of these nodes any more.
392 *
393 * This might not find the optimal diff in some cases (e.g. if the old node is
394 * similar to two of the new nodes), but diffing every old node against every
395 * new node could have a heavy performance cost.
396 *
397 * @param {number[]} oldIndices Indices of the old nodes
398 * @param {number[]} newIndices Indices of the new nodes
399 * @param {ve.dm.Node[]} oldNodes Nodes from the old document
400 * @param {ve.dm.Node[]} newNodes Nodes from the new document
401 * @param {Object} diff Object that will contain information about the diff
402 */
403 ve.dm.VisualDiff.prototype.findModifiedNodes = function ( oldIndices, newIndices, oldNodes, newNodes, diff ) {
404 const ilen = oldIndices.length,
405 jlen = newIndices.length;
406
407 let i, j;
408 for ( i = 0; i < ilen; i++ ) {
409 for ( j = 0; j < jlen; j++ ) {
410 if ( oldIndices[ i ] !== null && newIndices[ j ] !== null ) {
411 const diffResults = this.diffNodes( oldNodes[ oldIndices[ i ] ], newNodes[ newIndices[ j ] ] );
412
413 if ( diffResults && (
414 'linearDiff' in diffResults || diffResults.attributeChange || diffResults.treeDiff ||
415 // List diff
416 this.hasChanges( diffResults )
417 ) ) {
418 diff.oldToNew[ oldIndices[ i ] ] = {
419 node: newIndices[ j ],
420 diff: diffResults
421 };
422 diff.newToOld[ newIndices[ j ] ] = {
423 node: oldIndices[ i ]
424 };
425
426 oldIndices[ i ] = null;
427 newIndices[ j ] = null;
428 break;
429 }
430 }
431 }
432 }
433
434 // Any nodes remaining in the 'toDiff' arrays are removes and inserts
435 for ( i = 0; i < ilen; i++ ) {
436 if ( oldIndices[ i ] !== null ) {
437 diff.remove.push( oldIndices[ i ] );
438 }
439 }
440 for ( j = 0; j < jlen; j++ ) {
441 if ( newIndices[ j ] !== null ) {
442 diff.insert.push( newIndices[ j ] );
443 }
444 }
445 };
446
447 /**
448 * Get the diff between a node from the old document and a node from the new
449 * document.
450 *
451 * @param {ve.dm.Node} oldNode Node from the old document
452 * @param {ve.dm.Node} newNode Node from the new document
453 * @param {boolean} [noTreeDiff] Don't perform a tree diff of the nodes (used internally to avoid recursion)
454 * @return {ve.dm.VisualDiff.LeafDiff|ve.dm.VisualDiff.ListDiff|ve.dm.VisualDiff.DocDiff|ve.dm.VisualDiff.TreeDiff|boolean} The diff, or false if the nodes are too different
455 */
456 ve.dm.VisualDiff.prototype.diffNodes = function ( oldNode, newNode, noTreeDiff ) {
457 // If not diff comparable, return no diff
458 if ( !( oldNode.isDiffComparable( newNode ) ) ) {
459 return false;
460 }
461
462 let diff = false;
463 // Diff according to whether node behaves like a leaf, list, or tree (default)
464 if ( oldNode.isDiffedAsLeaf() ) {
465 diff = this.diffLeafNodes( oldNode, newNode );
466 } else if ( oldNode.isDiffedAsList() ) {
467 diff = this.diffListNodes( oldNode, newNode );
468 } else if ( oldNode.isDiffedAsDocument() ) {
469 diff = this.diffDocs( oldNode, newNode );
470 } else if ( !noTreeDiff ) {
471 diff = this.diffTreeNodes( oldNode, newNode );
472 }
473
474 return diff;
475 };
476
477 /**
478 * @typedef {Object} LeafDiff
479 * @memberof ve.dm.VisualDiff
480 * @property {ve.dm.VisualDiff.AttributeDiff|boolean} attributeChange
481 * @property {Array|boolean} linearDiff
482 */
483
484 /**
485 * Diff two leaf nodes
486 *
487 * @param {ve.dm.Node} oldNode Node from the old document
488 * @param {ve.dm.Node} newNode Node from the new document
489 * @return {ve.dm.VisualDiff.LeafDiff|boolean} Leaf diff, or false if the nodes are too different
490 * or if the diff timed out
491 */
492 ve.dm.VisualDiff.prototype.diffLeafNodes = function ( oldNode, newNode ) {
493 let linearDiff = null;
494
495 if ( oldNode.canContainContent() ) {
496 const changeRecord = {
497 keepLength: oldNode.length,
498 diffLength: 0
499 };
500 linearDiff = this.diffContent( oldNode, newNode );
501 if ( !( linearDiff ) ) {
502 return false;
503 }
504 this.updateChangeRecordLinearDiff( linearDiff, changeRecord );
505 if ( this.underDiffThreshold( changeRecord ) ) {
506 return false;
507 }
508 }
509
510 const diff = {
511 attributeChange: this.diffAttributes( oldNode, newNode ),
512 linearDiff: linearDiff
513 };
514
515 return diff;
516 };
517
518 /**
519 * Diff two list nodes
520 *
521 * @param {ve.dm.Node} oldNode Node from the old document
522 * @param {ve.dm.Node} newNode Node from the new document
523 * @return {ve.dm.VisualDiff.ListDiff|boolean} Leaf diff, or false if the nodes are too different
524 * or if the diff timed out
525 */
526 ve.dm.VisualDiff.prototype.diffListNodes = function ( oldNode, newNode ) {
527 const oldFlatList = {
528 nodes: [],
529 metadata: [],
530 indices: []
531 },
532 newFlatList = {
533 nodes: [],
534 metadata: [],
535 indices: []
536 };
537
538 this.flattenList( oldNode, oldFlatList, 0 );
539 this.flattenList( newNode, newFlatList, 0 );
540
541 let i, ilen;
542 for ( i = 0, ilen = oldFlatList.nodes.length; i < ilen; i++ ) {
543 oldFlatList.indices.push( { indexOrder: i } );
544 }
545 for ( i = 0, ilen = newFlatList.nodes.length; i < ilen; i++ ) {
546 newFlatList.indices.push( { indexOrder: i } );
547 }
548
549 const listDiff = this.diffList( oldFlatList.nodes, newFlatList.nodes );
550 listDiff.oldList = oldFlatList;
551 listDiff.newList = newFlatList;
552
553 // Do metadata diff of all aligned nodes
554 for ( i in listDiff.oldToNew ) {
555 const newItem = listDiff.oldToNew[ i ];
556 const isNewItemIndex = typeof newItem === 'number';
557 const j = isNewItemIndex ? newItem : newItem.node;
558
559 const oldMetadata = oldFlatList.metadata[ i ];
560 const newMetadata = newFlatList.metadata[ j ];
561
562 const listNodeAttributeChange = this.diffAttributes( oldMetadata.listNode, newMetadata.listNode, 'listType' );
563 const listItemAttributeChange = this.diffAttributes( oldMetadata.listItem, newMetadata.listItem );
564 const depthChange = oldMetadata.depth === newMetadata.depth ? false :
565 {
566 oldAttributes: { listItemDepth: oldMetadata.depth },
567 newAttributes: { listItemDepth: newMetadata.depth }
568 };
569
570 if ( listNodeAttributeChange || listItemAttributeChange || depthChange ) {
571 // Some attributes have changed for this item
572 // This item may already have attribute changes (e.g. heading attribute change inlist)
573 const attributeChange = ( !isNewItemIndex && newItem.diff.attributeChange ) || {};
574 if ( listNodeAttributeChange ) {
575 attributeChange.listNodeAttributeChange = listNodeAttributeChange;
576 }
577 if ( listItemAttributeChange ) {
578 attributeChange.listItemAttributeChange = listItemAttributeChange;
579 }
580 if ( depthChange ) {
581 attributeChange.depthChange = depthChange;
582 }
583
584 if ( isNewItemIndex ) {
585 listDiff.oldToNew[ i ] = {
586 node: j,
587 diff: {
588 attributeChange: attributeChange
589 }
590 };
591 } else {
592 listDiff.oldToNew[ i ].diff.attributeChange = attributeChange;
593 }
594 listDiff.newToOld[ j ] = { node: i };
595 }
596 }
597
598 if ( !this.hasChanges( listDiff ) ) {
599 return false;
600 }
601
602 return listDiff;
603 };
604
605 /**
606 * Flatten a (potentially nested) list, ready for diffing. Lists are common, and
607 * tree diffs of lists are expensive, so lists are flattened then diffed as
608 * linear structures.
609 *
610 * Appends information for each list item to a flat list object. Will be called
611 * once for each list node within a nested list.
612 *
613 * Only nested lists at the end of list items are flattened.
614 *
615 * If a list item contains a non-list node that contains a list, that list will
616 * not get flattened out. A list node followed by a non-list node will not be
617 * flattened out either. If a list item contains more than one identical list
618 * node, they will be flattened out to the same depth, and the information that
619 * they were separate lists will be lost.
620 *
621 * If a list item contains more than one un-flattened node, each one of them
622 * will be treated as a separate list item when flattened, but the original
623 * items will be put back together later. (T345891)
624 *
625 * @param {ve.dm.Node} listNode A list node, possibly nested inside another list
626 * @param {Object} flatList Flat structure describing the entire list
627 * @param {number} depth Depth of this list node with respect to the outermost
628 */
629 ve.dm.VisualDiff.prototype.flattenList = function ( listNode, flatList, depth ) {
630 const listItems = listNode.children;
631
632 for ( let i = 0, ilen = listItems.length; i < ilen; i++ ) {
633 const listItem = listItems[ i ];
634
635 // If listItem has no children, make the item itself the contents (e.g. an AlienBlockNode in a list)
636 if ( !listItem.children ) {
637 flatList.metadata.push( {
638 listNode: listNode,
639 listItem: listItem,
640 depth: depth
641 } );
642 flatList.nodes.push( listItem );
643 continue;
644 }
645
646 const listContents = listItem.children;
647
648 // Find the first sub-list
649 let firstListIndex = listContents.length;
650 while ( firstListIndex >= 1 && listContents[ firstListIndex - 1 ].isDiffedAsList() ) {
651 firstListIndex--;
652 }
653
654 for ( let j = 0, jlen = listContents.length; j < jlen; j++ ) {
655 const listContent = listContents[ j ];
656 if ( j >= firstListIndex ) {
657 this.flattenList( listContent, flatList, depth + 1 );
658 } else {
659 flatList.metadata.push( {
660 listNode: listNode,
661 listItem: listItem,
662 depth: depth,
663 isContinued: j > 0
664 } );
665 flatList.nodes.push( listContent );
666 }
667 }
668 }
669 };
670
671 /**
672 * Align two tree structures
673 *
674 * @param {treeDiffer.Tree} oldTree Tree rooted at the old node
675 * @param {treeDiffer.Tree} newTree Tree rooted at the new node
676 * @return {Array|boolean} Corresponding tree node indices, or false if timed out
677 */
678 ve.dm.VisualDiff.prototype.alignTrees = function ( oldTree, newTree ) {
679 const transactions = new this.treeDiffer.Differ( oldTree, newTree ).transactions;
680
681 if ( transactions === null ) {
682 // Tree diff timed out
683 this.timedOut = true;
684 return false;
685 }
686
687 return transactions[ oldTree.orderedNodes.length - 1 ][ newTree.orderedNodes.length - 1 ];
688 };
689
690 /**
691 * @typedef {Object} TreeDiff
692 * @memberof ve.dm.VisualDiff
693 * @property {ve.DiffTreeNode[]} oldTreeOrderedNodes - Nodes of the old tree, deepest first then in document order
694 * @property {ve.DiffTreeNode[]} newTreeOrderedNodes - Nodes of the new tree, deepest first then in document order
695 * @property {Array[]} treeDiff - Node correspondences as indexes in *TreeOrderedNodes
696 * @property {number[]} treeDiff.i - The i'th correspondence [ oldTreeOrderedNodes index, newTreeOrderedNodes index ]
697 * @property {Object|null} diffInfo - Linear diffs applying to each corresponding node pair
698 * @property {Object} diffInfo.i - Linear diff applying to i'th node in newTreeOrderedNodes
699 * @property {Array|boolean} diffInfo.i.linearDiff - Output of #diffContent
700 * @property {ve.dm.VisualDiff.AttributeDiff|boolean} diffInfo.i.attributeChange Attribute diff
701 */
702
703 /**
704 * Do a tree diff. There are three steps: (1) Do a tree diff to find the minimal
705 * transactions between the old tree and the new tree. Allowed transactions
706 * are: remove a node, insert a node, or change an old node to a new node. (The
707 * cost of each transaction is the same, and the change always costs the same,
708 * no matter how similar the nodes are.) The tree differ is not currently aware
709 * of legal relationships between nodes, and ve.dm.ContentBranchNodes are
710 * treated as leaves. (2) Do a linear diff on the linear data of any changed
711 * pair that are both ve.dm.ContentBranchNodes. (3) Find the ratio of the
712 * linear data that has changed to the linear data that is retained. If this is
713 * above a threshold, the nodes are too different and the old node has not
714 * been changed to make the new node, and the diff should be discarded.
715 * Otherwise the diff should be cleaned and returned.
716 *
717 * TODO: It would be possible to discover within-node moves by comparing
718 * removed and inserted nodes from the tree differ.
719 *
720 * @param {ve.dm.Node} oldTreeNode Node from the old document
721 * @param {ve.dm.Node} newTreeNode Node from the new document
722 * @return {ve.dm.VisualDiff.TreeDiff|boolean} Diff object, or false if the nodes are too different or if the diff timed out.
723 */
724 ve.dm.VisualDiff.prototype.diffTreeNodes = function ( oldTreeNode, newTreeNode ) {
725 const changeRecord = {
726 removeLength: 0,
727 insertLength: 0,
728 diffLength: 0,
729 keepLength: 0
730 },
731 diffInfo = [];
732
733 const oldTree = new this.treeDiffer.Tree( oldTreeNode, ve.DiffTreeNode );
734 const newTree = new this.treeDiffer.Tree( newTreeNode, ve.DiffTreeNode );
735
736 const treeDiff = this.alignTrees( oldTree, newTree );
737
738 if ( treeDiff === false ) {
739 // Diff timed out
740 return false;
741 }
742
743 // Length of old content is length of old node minus the open and close
744 // tags for each node
745 changeRecord.keepLength = oldTreeNode.length - 2 * ( oldTree.orderedNodes.length - 1 );
746
747 for ( let i = 0, ilen = treeDiff.length; i < ilen; i++ ) {
748 if ( treeDiff[ i ][ 0 ] !== null && treeDiff[ i ][ 1 ] !== null ) {
749 // There is a change
750 const oldNode = oldTree.orderedNodes[ treeDiff[ i ][ 0 ] ].node;
751 const newNode = newTree.orderedNodes[ treeDiff[ i ][ 1 ] ].node;
752
753 if ( !oldNode.isDiffedAsTree() && !newNode.isDiffedAsTree() ) {
754 diffInfo[ i ] = this.diffNodes( oldNode, newNode, true );
755 } else if ( oldNode.isDiffComparable( newNode ) ) {
756 const attributeChange = this.diffAttributes( oldNode, newNode );
757 if ( attributeChange ) {
758 diffInfo[ i ] = {
759 linearDiff: null,
760 attributeChange: this.diffAttributes( oldNode, newNode )
761 };
762 }
763 }
764
765 } else if ( treeDiff[ i ][ 0 ] !== null ) {
766 // Node was removed
767 const oldNode = oldTree.orderedNodes[ treeDiff[ i ][ 0 ] ].node;
768 if ( !oldNode.isDiffedAsTree() ) {
769 this.updateChangeRecord( oldNode.length, true, changeRecord );
770 }
771
772 } else {
773 // Node was inserted
774 const newNode = newTree.orderedNodes[ treeDiff[ i ][ 1 ] ].node;
775 if ( !newNode.isDiffedAsTree() ) {
776 this.updateChangeRecord( newNode.length, false, changeRecord );
777 }
778 }
779 }
780
781 // Only return the diff if a high enough proportion of the content is
782 // unchanged; otherwise, these nodes don't correspond and shouldn't be
783 // diffed.
784 if ( this.underDiffThreshold( changeRecord ) ) {
785 return false;
786 }
787
788 return {
789 treeDiff: treeDiff,
790 diffInfo: diffInfo,
791 oldTreeOrderedNodes: oldTree.orderedNodes,
792 newTreeOrderedNodes: newTree.orderedNodes,
793 correspondingNodes: this.treeDiffer.Differ.prototype.getCorrespondingNodes(
794 treeDiff, oldTree.orderedNodes.length, newTree.orderedNodes.length
795 )
796 };
797 };
798
799 /**
800 * @typedef {Object} AttributeDiff
801 * @memberof ve.dm.VisualDiff
802 * @property {Object} oldAttributes
803 * @property {Object} newAttributes
804 */
805
806 /**
807 * Find the difference between attributes of two nodes
808 *
809 * @param {ve.dm.Node} oldNode Node from the old document
810 * @param {ve.dm.Node} newNode Node from the new document
811 * @param {string} [diffTypeAsAttribute] Diff the type of the node as an attribute with this name
812 * @return {ve.dm.VisualDiff.AttributeDiff|boolean} The attributes diff, or false if unchanged
813 */
814 ve.dm.VisualDiff.prototype.diffAttributes = function ( oldNode, newNode, diffTypeAsAttribute ) {
815 const oldAttributes = oldNode.getAttributes();
816 const newAttributes = newNode.getAttributes();
817 if ( diffTypeAsAttribute ) {
818 oldAttributes[ diffTypeAsAttribute ] = oldNode.getType();
819 newAttributes[ diffTypeAsAttribute ] = newNode.getType();
820 }
821 const attributesUnchanged = ve.compare( oldNode.getAttributes(), newNode.getAttributes() );
822
823 if ( attributesUnchanged ) {
824 return false;
825 }
826 return {
827 oldAttributes: oldAttributes,
828 newAttributes: newAttributes
829 };
830 };
831
832 /**
833 * Find the difference between linear data in two content branch nodes
834 *
835 * @param {ve.dm.ContentBranchNode} oldNode Node from the old document
836 * @param {ve.dm.ContentBranchNode} newNode Node from the new document
837 * @return {Array|boolean} The linear diff, or false if timed out
838 */
839 ve.dm.VisualDiff.prototype.diffContent = function ( oldNode, newNode ) {
840 let linearDiff;
841
842 if ( Date.now() < this.endTime ) {
843 linearDiff = this.linearDiffer.getCleanDiff(
844 this.constructor.static.getDataFromNode( oldNode, true ),
845 this.constructor.static.getDataFromNode( newNode, true ),
846 { keepOldText: false }
847 );
848 this.timedOut = !!linearDiff.timedOut;
849 } else {
850 this.timedOut = true;
851 return false;
852 }
853
854 return linearDiff;
855 };
856
857 /**
858 * Increment the record of the length of changed and unchanged content for
859 * a node, given the length the removed or inserted content in one of its
860 * descendants
861 *
862 * @param {number} length Length of removed or inserted content
863 * @param {boolean} removed The content was removed (if false, was inserted)
864 * @param {Object} changeRecord Record of the running totals for changed and
865 * unchanged content
866 */
867 ve.dm.VisualDiff.prototype.updateChangeRecord = function ( length, removed, changeRecord ) {
868 changeRecord.diffLength += length;
869 if ( removed ) {
870 changeRecord.keepLength -= length;
871 }
872 };
873
874 /**
875 * Increment the record of the length of changed and unchanged content for
876 * a node, given the linear diff for one of its descendants
877 *
878 * @param {Array} linearDiff Diff of the content
879 * @param {Object} changeRecord Record of the running totals for changed and
880 * unchanged content
881 */
882 ve.dm.VisualDiff.prototype.updateChangeRecordLinearDiff = function ( linearDiff, changeRecord ) {
883 const DIFF_INSERT = ve.DiffMatchPatch.static.DIFF_INSERT,
884 DIFF_DELETE = ve.DiffMatchPatch.static.DIFF_DELETE;
885
886 for ( let i = 0, ilen = linearDiff.length; i < ilen; i++ ) {
887 if ( linearDiff[ i ][ 0 ] === DIFF_INSERT ) {
888 this.updateChangeRecord( linearDiff[ i ][ 1 ].length, false, changeRecord );
889 } else if ( linearDiff[ i ][ 0 ] === DIFF_DELETE ) {
890 this.updateChangeRecord( linearDiff[ i ][ 1 ].length, true, changeRecord );
891 }
892 }
893 };
894
895 /**
896 * Check whether the proportion of changed content between two nodes is under
897 * the threshold for accepting that the two nodes correspond.
898 *
899 * @param {Object} changeRecord Record for the proportion of content changed
900 * @return {boolean} The proportion of changed content is under the threshold
901 */
902 ve.dm.VisualDiff.prototype.underDiffThreshold = function ( changeRecord ) {
903 return changeRecord.keepLength < this.diffThreshold * changeRecord.diffLength;
904 };
905
906 /**
907 * @typedef {Object} MetaListDiff
908 * @memberof ve.dm.VisualDiff
909 * @property {Object.<string,ve.dm.VisualDiff.ListDiff>} groups List diffs, indexed by group
910 */
911
912 /**
913 * Calculate a meta list diff
914 *
915 * @param {ve.dm.MetaList} oldMetaList
916 * @param {ve.dm.MetaList} newMetaList
917 * @return {ve.dm.VisualDiff.MetaListDiff}
918 */
919 ve.dm.VisualDiff.prototype.getMetaListDiff = function ( oldMetaList, newMetaList ) {
920 const oldItemsByGroup = {};
921 oldMetaList.items.forEach( ( metaItem ) => {
922 const group = metaItem.getGroup();
923 oldItemsByGroup[ group ] = oldItemsByGroup[ group ] || [];
924 oldItemsByGroup[ group ].push( metaItem );
925 } );
926 const newItemsByGroup = {};
927 newMetaList.items.forEach( ( metaItem ) => {
928 const group = metaItem.getGroup();
929 newItemsByGroup[ group ] = newItemsByGroup[ group ] || [];
930 newItemsByGroup[ group ].push( metaItem );
931 } );
932 const groups = OO.simpleArrayUnion(
933 Object.keys( oldItemsByGroup ),
934 Object.keys( newItemsByGroup )
935 );
936 const groupDiffs = {};
937 groups.forEach( ( group ) => {
938 groupDiffs[ group ] = this.diffList(
939 oldItemsByGroup[ group ] || [],
940 newItemsByGroup[ group ] || []
941 );
942 } );
943 return groupDiffs;
944 };
945
946 /**
947 * @typedef {Object} InternalListDiff
948 * @memberof ve.dm.VisualDiff
949 * @property {Object.<string,ve.dm.VisualDiff.ListDiff>} groups List diffs, indexed by group
950 * @property {ve.dm.InternalListNode} oldDocInternalListNode
951 * @property {ve.dm.InternalListNode} newDocInternalListNode
952 */
953
954 /*
955 * Get the diff between the old document's internal list and the new document's
956 * internal list. The diff is grouped by list group, and each node in each list
957 * group is marked as removed, inserted, the same, or changed (in which case the
958 * linear diff is given).
959 *
960 * @param {ve.dm.InternalList} oldInternalList
961 * @param {ve.dm.InternalList} newInternalList
962 * @return {ve.dm.VisualDiff.InternalListDiff} Internal list diff object
963 */
964 ve.dm.VisualDiff.prototype.getInternalListDiff = function ( oldInternalList, newInternalList ) {
965 const oldDocNodeGroups = oldInternalList.getNodeGroups(),
966 newDocNodeGroups = newInternalList.getNodeGroups(),
967 oldDocInternalListNode = oldInternalList.getListNode(),
968 newDocInternalListNode = newInternalList.getListNode(),
969 groups = [],
970 groupDiffs = {};
971 let oldDocInternalListItems,
972 newDocInternalListItems;
973
974 function getInternalListItemsToDiff( indexOrder, nodes, action ) {
975 const internalListItems = {
976 toDiff: [],
977 indices: []
978 };
979
980 for ( let j = 0, jlen = indexOrder.length; j < jlen; j++ ) {
981 const nodeIndex = indexOrder[ j ];
982 if ( nodeIndex !== null ) {
983 internalListItems.toDiff.push( nodes[ nodeIndex ] );
984 internalListItems.indices.push( {
985 diff: action,
986 indexOrder: j,
987 nodeIndex: nodeIndex
988 } );
989 }
990 }
991
992 return internalListItems;
993 }
994
995 // Find all groups common to old and new docs
996 // Also find inserted groups
997 for ( const group in newDocNodeGroups ) {
998 if ( group in oldDocNodeGroups ) {
999 groups.push( {
1000 group: group,
1001 action: 'diff'
1002 } );
1003 } else {
1004 groups.push( {
1005 group: group,
1006 action: 'insert'
1007 } );
1008 }
1009 }
1010
1011 // Find removed groups
1012 for ( const group in oldDocNodeGroups ) {
1013 if ( !( group in newDocNodeGroups ) ) {
1014 groups.push( {
1015 group: group,
1016 action: 'remove'
1017 } );
1018 }
1019 }
1020
1021 // Diff the internal list items for each group
1022 for ( let i = 0, ilen = groups.length; i < ilen; i++ ) {
1023 const group = groups[ i ];
1024
1025 let diff = null;
1026 switch ( group.action ) {
1027 case 'diff':
1028 // Get old and new doc internal list items for this group
1029 oldDocInternalListItems = getInternalListItemsToDiff(
1030 oldDocNodeGroups[ group.group ].indexOrder,
1031 oldDocInternalListNode.children
1032 );
1033 newDocInternalListItems = getInternalListItemsToDiff(
1034 newDocNodeGroups[ group.group ].indexOrder,
1035 newDocInternalListNode.children
1036 );
1037
1038 // Diff internal list items
1039 diff = this.diffList(
1040 oldDocInternalListItems.toDiff,
1041 newDocInternalListItems.toDiff
1042 );
1043
1044 if ( !this.hasChanges( diff, true ) ) {
1045 diff = null;
1046 }
1047 break;
1048
1049 case 'insert': {
1050 // Get new doc internal list items for this group and mark as inserted
1051 const listItems = getInternalListItemsToDiff(
1052 newDocNodeGroups[ group.group ].indexOrder,
1053 newDocInternalListNode.children,
1054 1
1055 );
1056 diff = listItems.indices;
1057 diff.newNodes = listItems.toDiff;
1058 break;
1059 }
1060
1061 case 'remove': {
1062 // Get old doc internal list items for this group and mark as removed
1063 const listItems = getInternalListItemsToDiff(
1064 oldDocNodeGroups[ group.group ].indexOrder,
1065 oldDocInternalListNode.children,
1066 -1
1067 );
1068 diff = listItems.indices;
1069 diff.oldNodes = listItems.toDiff;
1070 break;
1071 }
1072 }
1073
1074 if ( diff ) {
1075 diff.changes = true;
1076 diff.oldList = oldDocInternalListNode;
1077 diff.newList = newDocInternalListNode;
1078 groupDiffs[ group.group ] = diff;
1079 }
1080 }
1081
1082 return {
1083 groups: groupDiffs,
1084 oldNode: oldDocInternalListNode,
1085 newNode: newDocInternalListNode
1086 };
1087 };
1088
1089 /**
1090 * Check if a list diff object has any changes
1091 *
1092 * @param {Object} diff Diff object
1093 * @param {boolean} isInternalListDiff Is an internal list diff
1094 * @return {boolean} The diff object has changes
1095 */
1096 ve.dm.VisualDiff.prototype.hasChanges = function ( diff, isInternalListDiff ) {
1097 function containsDiff( diffObject ) {
1098 for ( const n in diffObject ) {
1099 if ( typeof diffObject[ n ] !== 'number' ) {
1100 return true;
1101 }
1102 }
1103 return false;
1104 }
1105
1106 // Do not match within-document lists that have no corresponding list items
1107 if ( !isInternalListDiff && ve.isEmptyObject( diff.oldToNew ) ) {
1108 return false;
1109 }
1110
1111 // Check there actually are any changes
1112 return ( diff.remove.length > 0 || diff.insert.length > 0 ) ||
1113 ( containsDiff( diff.oldToNew ) || containsDiff( diff.moves ) );
1114 };