Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/elements/ve.ui.DiffElement.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface DiffElement class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Creates a ve.ui.DiffElement object.
10 *
11 * @class
12 * @extends OO.ui.Element
13 *
14 * @constructor
15 * @param {ve.dm.VisualDiff} [visualDiff] Diff to visualize
16 * @param {Object} [config]
17 */
18 ve.ui.DiffElement = function VeUiDiffElement( visualDiff, config ) {
19 const diff = visualDiff.diff;
20
21 // Parent constructor
22 ve.ui.DiffElement.super.call( this, config );
23
24 this.elementId = 0;
25
26 this.$overlays = $( '<div>' ).addClass( 've-ui-diffElement-overlays' );
27 this.$content = $( '<div>' ).addClass( 've-ui-diffElement-content' );
28 this.$messages = $( '<div>' ).addClass( 've-ui-diffElement-messages' );
29 this.$document = $( '<div>' ).addClass( 've-ui-diffElement-document' );
30 this.$sidebar = $( '<div>' ).addClass( 've-ui-diffElement-sidebar' );
31
32 this.descriptions = new ve.ui.ChangeDescriptionsSelectWidget();
33 this.descriptions.connect( this, { highlight: 'onDescriptionsHighlight' } );
34 // Set to an empty array before a series of diff computations to collect descriptions.
35 // Set back to null after collecting values.
36 this.descriptionItemsStack = null;
37
38 this.$document.on( {
39 mousemove: this.onDocumentMouseMove.bind( this )
40 } );
41
42 this.renderDiff( diff.docDiff, diff.internalListDiff, diff.metaListDiff, visualDiff.newDoc.getHtmlDocument() );
43
44 if ( visualDiff.timedOut ) {
45 const warning = new OO.ui.MessageWidget( {
46 type: 'warning',
47 classes: [ 've-ui-diffElement-warning' ],
48 label: ve.msg( 'visualeditor-diff-timed-out' )
49 } );
50 this.$messages.append( warning.$element );
51 }
52
53 // DOM
54 this.$element
55 .append(
56 this.$messages,
57 this.$content.append( this.$document, this.$overlays ),
58 this.$sidebar.append( this.descriptions.$element )
59 )
60 .addClass( 've-ui-diffElement' );
61 };
62
63 /* Inheritance */
64
65 OO.inheritClass( ve.ui.DiffElement, OO.ui.Element );
66
67 /* Static methods */
68
69 /**
70 * Compare attribute sets between two elements
71 *
72 * @param {Object} oldAttributes Old attributes
73 * @param {Object} newAttributes New attributes
74 * @return {Object} Keyed set of attributes
75 */
76 ve.ui.DiffElement.static.compareAttributes = function ( oldAttributes, newAttributes ) {
77 function compareKeys( a, b ) {
78 if ( typeof a === 'object' && typeof b === 'object' ) {
79 return ve.compare( a, b );
80 } else {
81 return a === b;
82 }
83 }
84
85 const attributeChanges = {};
86 for ( const key in oldAttributes ) {
87 if ( !compareKeys( oldAttributes[ key ], newAttributes[ key ] ) ) {
88 attributeChanges[ key ] = { from: oldAttributes[ key ], to: newAttributes[ key ] };
89 }
90 }
91 for ( const key in newAttributes ) {
92 if ( !Object.prototype.hasOwnProperty.call( oldAttributes, key ) && newAttributes[ key ] !== undefined ) {
93 attributeChanges[ key ] = { from: oldAttributes[ key ], to: newAttributes[ key ] };
94 }
95 }
96 return attributeChanges;
97 };
98
99 /**
100 * Get the original linear data from a node
101 *
102 * @param {ve.dm.Node} node Node
103 * @return {Array} Linear data
104 */
105 ve.ui.DiffElement.static.getDataFromNode = function ( node ) {
106 const doc = node.getRoot().getDocument();
107 return doc.getData( node.getOuterRange() );
108 };
109
110 /* Methods */
111
112 /**
113 * Get a diff element in the document from its elementId
114 *
115 * @param {number} elementId ID
116 * @return {jQuery} Element
117 */
118 ve.ui.DiffElement.prototype.getDiffElementById = function ( elementId ) {
119 return this.$document.find( '[data-diff-id=' + elementId + ']' );
120 };
121
122 /**
123 * Handle description item hightlight events
124 *
125 * @param {OO.ui.OptionWidget} item Description item
126 */
127 ve.ui.DiffElement.prototype.onDescriptionsHighlight = function ( item ) {
128 if ( this.lastItem ) {
129 this.getDiffElementById( this.lastItem.getData() ).css( 'outline', '' );
130 this.$overlays.empty();
131 }
132 if ( item ) {
133 const overlayRect = this.$overlays[ 0 ].getBoundingClientRect();
134 const elementRects = ve.ce.FocusableNode.static.getRectsForElement( this.getDiffElementById( item.getData() ), overlayRect ).rects;
135 for ( let i = 0, l = elementRects.length; i < l; i++ ) {
136 this.$overlays.append(
137 $( '<div>' ).addClass( 've-ui-diffElement-highlight' ).css( {
138 top: elementRects[ i ].top,
139 left: elementRects[ i ].left,
140 width: elementRects[ i ].width,
141 height: elementRects[ i ].height
142 } )
143 );
144 }
145 this.lastItem = item;
146 }
147 };
148
149 /**
150 * Handle document mouse move events
151 *
152 * @param {jQuery.Event} e Mouse move event
153 */
154 ve.ui.DiffElement.prototype.onDocumentMouseMove = function ( e ) {
155 const elementId = $( e.target ).closest( '[data-diff-id]' ).attr( 'data-diff-id' );
156 if ( elementId !== undefined ) {
157 this.descriptions.highlightItem(
158 this.descriptions.findItemFromData( +elementId )
159 );
160 } else {
161 this.descriptions.highlightItem();
162 }
163 };
164
165 /**
166 * Reposition the description items so they are not above their position in the document
167 */
168 ve.ui.DiffElement.prototype.positionDescriptions = function () {
169 this.descriptions.getItems().forEach( ( item ) => {
170 item.$element.css( 'margin-top', '' );
171
172 const itemRect = item.$element[ 0 ].getBoundingClientRect();
173 const $element = this.getDiffElementById( item.getData() );
174 if ( !$element.length ) {
175 // Changed element isn't visible - probably shouldn't happen
176 return;
177 }
178 const elementRect = ve.ce.FocusableNode.static.getRectsForElement( $element ).boundingRect;
179
180 // elementRect can currently be null for meta items, e.g. <link>
181 if ( elementRect && elementRect.top > itemRect.top ) {
182 item.$element.css( 'margin-top', elementRect.top - itemRect.top - 5 );
183 }
184 } );
185 this.$document.css( 'min-height', this.$sidebar.height() );
186 };
187
188 /**
189 * Process a diff queue, skipping over sequential nodes with no changes
190 *
191 * @param {Array[]} queue Diff queue
192 * @return {Array.<Array|null>}
193 */
194 ve.ui.DiffElement.prototype.processQueue = function processQueue( queue ) {
195 let hasChanges = false,
196 lastItemSpacer = false,
197 needsSpacer = false,
198 headingContext = null,
199 headingContextSpacer = false;
200 const processedQueue = [];
201
202 function isUnchanged( item ) {
203 return !item || ( item[ 2 ] === 'none' && !item[ 3 ] );
204 }
205
206 function addSpacer() {
207 processedQueue.push( null );
208 lastItemSpacer = true;
209 }
210
211 function addItem( item ) {
212 processedQueue.push( item );
213 lastItemSpacer = false;
214 }
215
216 function isHeading( item ) {
217 switch ( item[ 0 ] ) {
218 case 'getNodeData':
219 case 'getNodeElements':
220 return item[ 1 ] instanceof ve.dm.HeadingNode;
221 case 'getChangedNodeData':
222 case 'getChangedNodeElements':
223 return item[ 3 ] instanceof ve.dm.HeadingNode;
224 }
225 }
226
227 for ( let k = 0, klen = queue.length; k < klen; k++ ) {
228 if (
229 !isUnchanged( queue[ k - 1 ] ) ||
230 !isUnchanged( queue[ k ] ) ||
231 !isUnchanged( queue[ k + 1 ] )
232 ) {
233 hasChanges = true;
234 if ( headingContext ) {
235 // Don't render headingContext if current or next node is a heading
236 if ( !isHeading( queue[ k ] ) && !isHeading( queue[ k + 1 ] ) ) {
237 if ( headingContextSpacer ) {
238 addSpacer();
239 }
240 addItem( headingContext );
241 } else if ( isHeading( queue[ k + 1 ] ) ) {
242 // Skipping the context header becuase the next node is a heading
243 // so reinstate the spacer.
244 needsSpacer = true;
245 }
246 headingContext = null;
247 }
248 if ( needsSpacer && !lastItemSpacer ) {
249 addSpacer();
250 needsSpacer = false;
251 }
252 addItem( queue[ k ] );
253
254 if ( isHeading( queue[ k ] ) ) {
255 // Heading was rendered, no need to show it as context
256 headingContext = null;
257 }
258 } else {
259 // Heading skipped, maybe show as context later
260 if ( isHeading( queue[ k ] ) ) {
261 headingContext = isUnchanged( queue[ k ] ) ? queue[ k ] : null;
262 headingContextSpacer = needsSpacer;
263 needsSpacer = false;
264 } else {
265 needsSpacer = true;
266 }
267 }
268 }
269
270 // Trailing spacer
271 if ( hasChanges && needsSpacer && !lastItemSpacer ) {
272 addSpacer();
273 }
274
275 return processedQueue;
276 };
277
278 /**
279 * @param {Array.<Array|null>} queue Diff queue
280 * @param {HTMLElement} parentNode Parent node to render to
281 * @param {HTMLElement} spacerNode Spacer node template
282 */
283 ve.ui.DiffElement.prototype.renderQueue = function ( queue, parentNode, spacerNode ) {
284 queue.forEach( ( item ) => {
285 if ( item ) {
286 const elements = this[ item[ 0 ] ].apply( this, item.slice( 1 ) );
287 while ( elements.length ) {
288 parentNode.appendChild(
289 parentNode.ownerDocument.adoptNode( elements[ 0 ] )
290 );
291 elements.shift();
292 }
293 } else {
294 parentNode.appendChild(
295 parentNode.ownerDocument.adoptNode( spacerNode.cloneNode( true ) )
296 );
297 }
298 } );
299 };
300
301 /**
302 * Render the diff
303 *
304 * @param {Object} diff Object describing the diff
305 * @param {Object} internalListDiff Object describing the diff of the internal list
306 * @param {Object} metaListDiff Object describing the diff of the meta list
307 * @param {HTMLDocument} newHtmlDocument HTML document of context, for resolving attributes
308 */
309 ve.ui.DiffElement.prototype.renderDiff = function ( diff, internalListDiff, metaListDiff, newHtmlDocument ) {
310 const documentNode = this.$document[ 0 ],
311 diffQueue = [];
312
313 let internalListDiffQueue = [];
314
315 const documentSpacerNode = document.createElement( 'div' );
316 documentSpacerNode.setAttribute( 'class', 've-ui-diffElement-spacer' );
317 documentSpacerNode.appendChild( document.createTextNode( 'â‹®' ) );
318
319 const internalListSpacerNode = document.createElement( 'li' );
320 internalListSpacerNode.setAttribute( 'class', 've-ui-diffElement-internalListSpacer' );
321 internalListSpacerNode.appendChild( documentSpacerNode.cloneNode( true ) );
322
323 const referencesListDiffs = {};
324 Object.keys( internalListDiff.groups ).forEach( ( group ) => {
325 const referencesListContainer = document.createElement( 'ol' );
326 const internalListGroup = internalListDiff.groups[ group ];
327
328 this.iterateDiff( internalListGroup, {
329 insert: function ( newNode, newIndex ) {
330 internalListDiffQueue.push( [ 'getInternalListNodeElements', newNode, 'insert', null, newIndex ] );
331 },
332 remove: function ( oldNode, oldIndex ) {
333 internalListDiffQueue.push( [ 'getInternalListNodeElements', oldNode, 'remove', null, oldIndex ] );
334 },
335 move: function ( newNode, move, newIndex ) {
336 internalListDiffQueue.push( [ 'getInternalListNodeElements', newNode, 'none', move, newIndex ] );
337 },
338 changed: function ( nodeDiff, oldNode, newNode, move, oldIndex, newIndex ) {
339 internalListDiffQueue.push( [ 'getInternalListChangedNodeElements', nodeDiff, oldNode, newNode, move, newIndex ] );
340 }
341 } );
342
343 this.descriptionItemsStack = [];
344 this.renderQueue(
345 this.processQueue( internalListDiffQueue ),
346 referencesListContainer, internalListSpacerNode
347 );
348 referencesListDiffs[ group ] = {
349 element: referencesListContainer,
350 action: internalListGroup.changes ? 'change' : 'none',
351 descriptionItemsStack: this.descriptionItemsStack,
352 shown: false
353 };
354 this.descriptionItemsStack = null;
355
356 internalListDiffQueue = [];
357 } );
358
359 this.descriptionItemsStack = [];
360 let referencesListDiff;
361
362 function handleRefList( node, move ) {
363 if (
364 node.type === 'mwReferencesList' &&
365 ( referencesListDiff = referencesListDiffs[ node.element.attributes.listGroup ] )
366 ) {
367 // New node is a references list node. If a reference has
368 // changed, the references list nodes appear unchanged,
369 // because of how the internal list works. However, we
370 // already have the HTML for the diffed references list,
371 // (which contains details of changes if there are any) so
372 // just get that.
373 diffQueue.push( [ 'getRefListNodeElements', referencesListDiff.element, referencesListDiff.action, move, referencesListDiff.descriptionItemsStack ] );
374 referencesListDiff.shown = true;
375 return true;
376 }
377 return false;
378 }
379
380 this.iterateDiff( diff, {
381 insert: function ( newNode ) {
382 if ( !handleRefList( newNode, null ) ) {
383 diffQueue.push( [ 'getNodeElements', newNode, 'insert', null ] );
384 }
385 },
386 remove: function ( oldNode ) {
387 if ( !handleRefList( oldNode, null ) ) {
388 diffQueue.push( [ 'getNodeElements', oldNode, 'remove', null ] );
389 }
390 },
391 move: function ( newNode, move ) {
392 diffQueue.push( [ 'getNodeElements', newNode, 'none', move ] );
393 },
394 preChanged: function ( oldNode, newNode, move ) {
395 return handleRefList( newNode, move );
396 },
397 changed: function ( nodeDiff, oldNode, newNode, move ) {
398 diffQueue.push( [ 'getChangedNodeElements', nodeDiff, oldNode, newNode, move ] );
399 }
400 } );
401
402 // Show any ref list diffs that weren't picked up by the main diff loop above,
403 // e.g. during a section diff.
404 Object.keys( referencesListDiffs ).forEach( ( group ) => {
405 referencesListDiff = referencesListDiffs[ group ];
406 if ( !referencesListDiff.shown ) {
407 diffQueue.push( [ 'getRefListNodeElements', referencesListDiff.element, referencesListDiff.action, null, referencesListDiff.descriptionItemsStack ] );
408 }
409 } );
410
411 this.renderQueue(
412 this.processQueue( diffQueue ),
413 documentNode, documentSpacerNode
414 );
415
416 this.renderMetaListDiff( metaListDiff, documentNode, documentSpacerNode );
417
418 this.descriptions.addItems( this.descriptionItemsStack );
419 this.descriptionItemsStack = null;
420
421 ve.resolveAttributes( documentNode, newHtmlDocument, ve.dm.Converter.static.computedAttributes );
422
423 if ( !documentNode.children.length ) {
424 const noChanges = document.createElement( 'div' );
425 noChanges.setAttribute( 'class', 've-ui-diffElement-no-changes' );
426 noChanges.appendChild( document.createTextNode( ve.msg( 'visualeditor-diff-no-changes' ) ) );
427 documentNode.innerHTML = '';
428 documentNode.appendChild( noChanges );
429 }
430
431 this.$element
432 .toggleClass( 've-ui-diffElement-hasDescriptions', !this.descriptions.isEmpty() );
433 };
434
435 ve.ui.DiffElement.prototype.renderMetaListDiff = function ( metaListDiff, documentNode, documentSpacerNode ) {
436 Object.keys( metaListDiff ).forEach( ( group ) => {
437 const handler = ve.ui.metaListDiffRegistry.lookup( group );
438 if ( handler ) {
439 const diffQueue = [];
440 this.iterateDiff( metaListDiff[ group ], {
441 insert: ( newNode ) => {
442 diffQueue.push( [ 'getNodeElements', newNode, 'insert', null ] );
443 },
444 remove: ( oldNode ) => {
445 diffQueue.push( [ 'getNodeElements', oldNode, 'remove', null ] );
446 },
447 move: ( newNode, move ) => {
448 diffQueue.push( [ 'getNodeElements', newNode, 'none', move ] );
449 },
450 changed: ( nodeDiff, oldNode, newNode, move ) => {
451 diffQueue.push( [ 'getChangedNodeElements', nodeDiff, oldNode, newNode, move ] );
452 }
453 } );
454 handler( this, diffQueue, documentNode, documentSpacerNode );
455 }
456 } );
457 };
458
459 /**
460 * Get the HTML for the diff of a removed, inserted, or unchanged-but-moved node.
461 *
462 * @param {ve.dm.Node} node The node being diffed. Will be from the old
463 * document if it has been removed, or the new document if it has been inserted
464 * or moved
465 * @param {string} action 'remove', 'insert' or, if moved, 'none'
466 * @param {string|null} move 'up' or 'down' if the node has moved
467 * @return {HTMLElement[]} Elements (not owned by window.document)
468 */
469 ve.ui.DiffElement.prototype.getNodeElements = function ( node, action, move ) {
470 const nodeData = this.getNodeData( node, action, move );
471
472 return this.wrapNodeData( node.getRoot().getDocument(), nodeData );
473 };
474
475 /**
476 * Get the DOM from linear data and wrap it for the diff.
477 *
478 * @param {ve.dm.Document} nodeDoc Node's document model
479 * @param {Array} nodeData Linear data for the diff
480 * @return {HTMLElement[]} Elements (not owned by window.document)
481 */
482 ve.ui.DiffElement.prototype.wrapNodeData = function ( nodeDoc, nodeData ) {
483 const documentSlice = nodeDoc.cloneWithData( nodeData );
484 documentSlice.getStore().merge( nodeDoc.getStore() );
485 const nodeElements = ve.dm.converter.getDomFromModel( documentSlice, ve.dm.Converter.static.PREVIEW_MODE ).body;
486
487 // Convert NodeList to real array
488 return Array.prototype.slice.call( nodeElements.childNodes );
489 };
490
491 /**
492 * Get the linear data for the diff of a removed, inserted, or
493 * unchanged-but-moved node.
494 *
495 * @param {ve.dm.Node} node
496 * @param {string} action 'remove', 'insert' or, if moved, 'none'
497 * @param {string|null} move 'up' or 'down' if the node has moved
498 * @return {Array} Linear Data
499 */
500 ve.ui.DiffElement.prototype.getNodeData = function ( node, action, move ) {
501 // Get the linear model for the node
502 const nodeData = this.constructor.static.getDataFromNode( node );
503
504 // Add the classes to the outer element
505 this.addAttributesToElement( nodeData, 0, { 'data-diff-action': action } );
506 this.markMove( move, nodeData );
507
508 return nodeData;
509 };
510
511 /**
512 * Get the HTML for the diff of a node that has been changed.
513 *
514 * @param {Object} diff Object describing the diff
515 * @param {ve.dm.Node} oldNode Node from the old document
516 * @param {ve.dm.Node} newNode Corresponding node from the new document
517 * @param {string|null} move 'up' or 'down' if the node has moved
518 * @return {HTMLElement[]} Elements (not owned by window.document)
519 */
520 ve.ui.DiffElement.prototype.getChangedNodeElements = function ( diff, oldNode, newNode, move ) {
521 const nodeData = this.getChangedNodeData( diff, oldNode, newNode, move );
522
523 return this.wrapNodeData( newNode.getRoot().getDocument(), nodeData );
524 };
525
526 /**
527 * Get the linear data for the diff of a node that has been changed.
528 *
529 * @param {Object} diff Object describing the diff
530 * @param {ve.dm.Node} oldNode Node from the old document
531 * @param {ve.dm.Node} newNode Corresponding node from the new document
532 * @param {string|null} move 'up' or 'down' if the node has moved
533 * @param {boolean} [noTreeDiff] Don't perform a tree diff of the nodes (used internally to avoid recursion)
534 * @return {Array|boolean} Linear data for the diff, or false
535 */
536 ve.ui.DiffElement.prototype.getChangedNodeData = function ( diff, oldNode, newNode, move, noTreeDiff ) {
537 let nodeData;
538
539 // Choose the appropriate method for the type of node
540 if ( newNode.isDiffedAsLeaf() ) {
541 nodeData = this.getChangedLeafNodeData( newNode, diff, move );
542 } else if ( newNode.isDiffedAsList() ) {
543 nodeData = this.getChangedListNodeData( newNode, diff );
544 } else if ( newNode.isDiffedAsDocument() ) {
545 nodeData = this.getChangedDocListData( newNode, diff );
546 } else if ( !noTreeDiff ) {
547 nodeData = this.getChangedTreeNodeData( oldNode, newNode, diff );
548 } else {
549 return false;
550 }
551
552 this.markMove( move, nodeData );
553
554 return nodeData;
555 };
556
557 /**
558 * Get the linear data for the diff of a leaf-like node that has been changed.
559 *
560 * @param {ve.dm.Node} newNode Corresponding node from the new document
561 * @param {Object} diff Object describing the diff
562 * @return {Array} Linear data for the diff
563 */
564 ve.ui.DiffElement.prototype.getChangedLeafNodeData = function ( newNode, diff ) {
565 const nodeData = this.constructor.static.getDataFromNode( newNode ),
566 linearDiff = diff.linearDiff,
567 attributeChange = diff.attributeChange;
568
569 if ( linearDiff ) {
570 // If there is a content change, splice it in
571 const annotatedData = this.annotateNode( linearDiff, newNode );
572 ve.batchSplice( nodeData, 1, newNode.length, annotatedData );
573 }
574 if ( attributeChange ) {
575 // If there is no content change, just add change class
576 this.addAttributesToElement(
577 nodeData, 0, { 'data-diff-action': 'structural-change' }
578 );
579 const item = this.compareNodeAttributes( nodeData, 0, attributeChange );
580 if ( item ) {
581 this.descriptionItemsStack.push( item );
582 }
583 }
584
585 return nodeData;
586 };
587
588 /**
589 * Append list item
590 *
591 * @private
592 * @param {Array} diffData
593 * @param {number} insertIndex
594 * @param {ve.dm.ListNode} listNode
595 * @param {Array} listNodeData List node opening
596 * @param {Array} listItemData
597 * @param {number} depthChange
598 * @return {number}
599 */
600 ve.ui.DiffElement.prototype.appendListItem = function ( diffData, insertIndex, listNode, listNodeData, listItemData, depthChange ) {
601 if ( depthChange === 0 ) {
602 // Current list item belongs to the same list as the previous list item
603 ve.batchSplice( diffData, insertIndex, 0, listItemData );
604 insertIndex += listItemData.length;
605
606 } else if ( depthChange > 0 ) {
607 // Begin a new nested list, with this node's ancestor nodes
608 const linearData = [];
609 linearData.unshift( listNodeData[ 0 ] );
610
611 let k, klen;
612 const doc = listNode.getRoot().getDocument();
613 // Nested list may be nested by multiple levels
614 for ( k = 0, klen = depthChange - 1; k < klen; k++ ) {
615 const listItemNode = listNode.parent;
616 linearData.unshift( doc.data.data[ listItemNode.getOuterRange().from ] );
617 listNode = listItemNode.parent;
618 linearData.unshift( doc.data.data[ listNode.getOuterRange().from ] );
619 }
620
621 // Splice in the content, and splice that into the diff data
622 ve.batchSplice( linearData, linearData.length, 0, listItemData );
623 for ( k = 0, klen = depthChange - 1; k < klen; k++ ) {
624 linearData.push( { type: '/list' } );
625 linearData.push( { type: '/listItem' } );
626 }
627 linearData.push( { type: '/list' } );
628
629 // Splice into previous list item
630 insertIndex -= 1;
631 ve.batchSplice( diffData, insertIndex, 0, linearData );
632
633 // Adjust the insertIndex to be at the end of this content
634 insertIndex += 2 * ( depthChange - 1 ) + 1 + listItemData.length;
635
636 } else if ( depthChange < 0 ) {
637 // Skip over close elements to get out of nested list(s)
638 insertIndex += 2 * -depthChange;
639
640 // Splice in the data and adjust the insert index
641 ve.batchSplice( diffData, insertIndex, 0, listItemData );
642 insertIndex += listItemData.length;
643 }
644
645 return insertIndex;
646 };
647
648 /**
649 * Get the linear data for a document-like node that has been changed
650 *
651 * @param {ve.dm.Node} newDoclistNode Node from new document
652 * @param {Object} diff Object describing the diff
653 * @param {boolean} neverProcess Never process the diffQueue (always show the whole document)
654 * @return {Array} Linear data for the diff
655 */
656 ve.ui.DiffElement.prototype.getChangedDocListData = function ( newDoclistNode, diff, neverProcess ) {
657 const diffData = [];
658 let diffQueue = [];
659
660 const spacerData = [ { type: 'div' }, 'â‹®', { type: '/div' } ];
661 this.addAttributesToElement( spacerData, 0, { class: 've-ui-diffElement-spacer' } );
662
663 this.iterateDiff( diff, {
664 insert: ( newNode ) => {
665 diffQueue.push( [ 'getNodeData', newNode, 'insert', null ] );
666 },
667 remove: ( oldNode ) => {
668 diffQueue.push( [ 'getNodeData', oldNode, 'remove', null ] );
669 },
670 move: ( newNode, move ) => {
671 diffQueue.push( [ 'getNodeData', newNode, 'none', move ] );
672 },
673 changed: ( nodeDiff, oldNode, newNode, move ) => {
674 diffQueue.push( [ 'getChangedNodeData', nodeDiff, oldNode, newNode, move ] );
675 }
676 } );
677
678 let hasAttributeChanges = false;
679 const newDoclistNodeData = this.constructor.static.getDataFromNode( newDoclistNode );
680 if ( diff.attributeChange ) {
681 const item = this.compareNodeAttributes( newDoclistNodeData, 0, diff.attributeChange );
682 if ( item ) {
683 this.descriptionItemsStack.push( item );
684 hasAttributeChanges = true;
685 }
686 }
687
688 // When the doc cotainer has attribute changes, show the whole node.
689 // Otherwise use processQueue to filter out unchanged context
690 if ( !neverProcess && !hasAttributeChanges ) {
691 diffQueue = this.processQueue( diffQueue );
692 }
693 diffQueue.forEach( ( diffItem ) => {
694 if ( diffItem ) {
695 ve.batchPush( diffData, this[ diffItem[ 0 ] ].apply( this, diffItem.slice( 1 ) ) );
696 } else {
697 ve.batchPush( diffData, spacerData.slice() );
698 }
699 } );
700
701 // Wrap in newDocListNode
702 diffData.unshift( newDoclistNodeData[ 0 ] );
703 diffData.push( newDoclistNodeData[ newDoclistNodeData.length - 1 ] );
704
705 return diffData;
706 };
707
708 /**
709 * Iterate over a diff object and run more meaningful callbacks
710 *
711 * @param {Object|Array} diff Diff object, or array (InternalListDiff)
712 * @param {Object} callbacks Callbacks
713 * @param {Function} callbacks.insert Node inserted, arguments:
714 * {ve.dm.Node} newNode
715 * {number} newIndex
716 * @param {Function} callbacks.remove Node removed, arguments:
717 * {ve.dm.Node} oldNode
718 * {number} oldIndex
719 * @param {Function} callbacks.move Node moved, arguments:
720 * {ve.dm.Node} newNode
721 * {number} newIndex
722 * {string|null} move
723 * @param {Function} callbacks.changed Node changed, arguments:
724 * {Object} nodeDiff
725 * {ve.dm.Node} oldNode
726 * {ve.dm.Node} newNode
727 * {number} oldIndex
728 * {number} newIndex
729 * {string|null} move
730 */
731 ve.ui.DiffElement.prototype.iterateDiff = function ( diff, callbacks ) {
732 // Internal list diffs set 'diff' to a number to shortcut computing the list diff
733 // for fully inserted/removed lists.
734 // TODO: Remove this special case and use a regular list diff
735 if ( Array.isArray( diff ) ) {
736 diff.forEach( ( item ) => {
737 let node;
738 switch ( item.diff ) {
739 case 1:
740 node = diff.newList.children[ item.nodeIndex ];
741 callbacks.insert( node, item.indexOrder );
742 break;
743 case -1:
744 node = diff.oldList.children[ item.nodeIndex ];
745 callbacks.remove( node, item.indexOrder );
746 break;
747 }
748 } );
749 return;
750 }
751
752 const len = Math.max( diff.oldNodes.length, diff.newNodes.length );
753
754 for ( let i = 0, j = 0; i < len || j < len; i++, j++ ) {
755 const move = diff.moves[ j ] === 0 ? null : diff.moves[ j ];
756
757 if ( diff.oldNodes[ i ] === undefined ) {
758 // Everything else in the new doc list is an insert
759 while ( j < diff.newNodes.length ) {
760 callbacks.insert( diff.newNodes[ j ], j );
761 j++;
762 }
763 } else if ( diff.newNodes[ j ] === undefined ) {
764 // Everything else in the old doc is a remove
765 while ( i < diff.oldNodes.length ) {
766 callbacks.remove( diff.oldNodes[ i ], i );
767 i++;
768 }
769 } else if ( diff.remove.indexOf( i ) !== -1 ) {
770 // The old node is a remove. Decrement the new node index
771 // to compare the same new node to the next old node
772 callbacks.remove( diff.oldNodes[ i ], i );
773 j--;
774 } else if ( diff.insert.indexOf( j ) !== -1 ) {
775 // The new node is an insert. Decrement the old node index
776 // to compare the same old node to the next new node
777 callbacks.insert( diff.newNodes[ j ], j );
778 i--;
779 } else if (
780 callbacks.preChanged &&
781 callbacks.preChanged( diff.oldNodes[ i ], diff.newNodes[ j ], move, i, j )
782 ) {
783 // preChanged ran
784 } else if ( typeof diff.newToOld[ j ] === 'number' ) {
785 // The old and new node are exactly the same
786 callbacks.move( diff.newNodes[ j ], move, j );
787 } else {
788 const oldNodeIndex = diff.newToOld[ j ].node;
789 const oldNode = diff.oldNodes[ oldNodeIndex ];
790 const newNode = diff.newNodes[ diff.oldToNew[ oldNodeIndex ].node ];
791 const nodeDiff = diff.oldToNew[ oldNodeIndex ].diff;
792
793 // The new node is modified from the old node
794 callbacks.changed( nodeDiff, oldNode, newNode, move, i, j );
795 }
796 }
797 };
798
799 /**
800 * Get the linear data for the diff of a list-like node that has been changed.
801 *
802 * @param {ve.dm.Node} newListNode Corresponding node from the new document
803 * @param {Object} diff Object describing the diff
804 * @return {Array} Linear data for the diff
805 */
806 ve.ui.DiffElement.prototype.getChangedListNodeData = function ( newListNode, diff ) {
807 const diffData = [];
808
809 // These will be adjusted for each item
810 let insertIndex = 1;
811 let depth = -1;
812 const listNodesInfoCache = new Map();
813
814 const listDiffItems = [];
815
816 this.iterateDiff( diff, {
817 insert: ( newNode, index ) => {
818 listDiffItems.push( {
819 node: newNode,
820 metadata: diff.newList.metadata[ index ],
821 action: 'insert'
822 } );
823 },
824 remove: ( oldNode, index ) => {
825 listDiffItems.push( {
826 node: oldNode,
827 metadata: diff.oldList.metadata[ index ],
828 action: 'remove'
829 } );
830 },
831 move: ( newNode, move, index ) => {
832 listDiffItems.push( {
833 node: newNode,
834 metadata: diff.newList.metadata[ index ],
835 action: 'none',
836 move: move
837 } );
838 },
839 changed: ( nodeDiff, oldNode, newNode, move, oldIndex, newIndex ) => {
840 listDiffItems.push( {
841 node: newNode,
842 metadata: diff.newList.metadata[ newIndex ],
843 diff: nodeDiff,
844 move: move
845 } );
846 }
847 } );
848
849 const processedListDiffItems = [];
850
851 let lastItemSpacer = false;
852 let lastShownDepth = 0;
853 const lastItemAtDepth = {};
854 listDiffItems.forEach( ( item, i ) => {
855 function isUnchanged( queueItem ) {
856 return !queueItem || ( queueItem.action === 'none' && !queueItem.move );
857 }
858
859 if (
860 isUnchanged( item ) &&
861 isUnchanged( listDiffItems[ i - 1 ] ) &&
862 isUnchanged( listDiffItems[ i + 1 ] )
863 ) {
864 if ( !lastItemSpacer ) {
865 processedListDiffItems.push( {
866 node: null,
867 metadata: item.metadata,
868 action: 'none'
869 } );
870 lastItemSpacer = true;
871 }
872 } else {
873 while ( lastShownDepth < item.metadata.depth - 1 ) {
874 lastShownDepth++;
875 if ( lastItemAtDepth[ lastShownDepth ] ) {
876 processedListDiffItems.push( {
877 node: null,
878 metadata: lastItemAtDepth[ lastShownDepth ].metadata,
879 action: 'none'
880 } );
881 }
882 }
883 processedListDiffItems.push( item );
884 lastItemSpacer = false;
885 lastShownDepth = item.metadata.depth;
886 }
887
888 lastItemAtDepth[ item.metadata.depth ] = item;
889 } );
890
891 // Splice in each item with its diff annotations
892 processedListDiffItems.forEach( ( item ) => {
893 let contentData;
894 let isSpacer = false;
895
896 if ( !item.diff ) {
897 if ( !item.node ) {
898 contentData = [ { type: 'paragraph' }, '…', { type: '/paragraph' } ];
899 isSpacer = true;
900 this.addAttributesToElement( contentData, 0, { 'data-diff-action': 'none' } );
901 } else {
902 // Get the linear data for the list item's content
903 contentData = this.getNodeData( item.node, item.action, item.move || null );
904 }
905 } else {
906 // Item is changed. Get the linear data for the diff
907 contentData = this.getChangedNodeData(
908 item.diff,
909 null,
910 item.node,
911 item.move || null
912 );
913 }
914
915 // Calculate the change in depth
916 const newDepth = item.metadata.depth;
917 const depthChange = newDepth - depth;
918
919 // Get linear data. Also get list node, since may need ancestors
920 const listNode = item.metadata.listNode;
921 let listNodeInfo;
922 if ( !listNodesInfoCache.has( listNode ) ) {
923 // Only re-fetch list node data once per list
924 listNodeInfo = {
925 data: [ this.constructor.static.getDataFromNode( listNode )[ 0 ] ],
926 changeDone: false
927 };
928 listNodesInfoCache.set( listNode, listNodeInfo );
929 } else {
930 listNodeInfo = listNodesInfoCache.get( listNode );
931 }
932
933 const listItemNode = item.metadata.listItem;
934 // Get linear data of list item
935 let listItemData = this.constructor.static.getDataFromNode( listItemNode );
936 if ( isSpacer ) {
937 this.addAttributesToElement( listItemData, 0, { 'data-diff-list-spacer': '' } );
938 } else {
939 // TODO: Make this a node property, instead of a magic attribute
940 if ( listNode.getAttribute( 'style' ) === 'number' ) {
941 // Manually number list items for <ol>'s which contain removals
942 // TODO: Consider if the <ol> contains a `start` attribute (not currently handled by DM)
943 const indexInOwnList = listNode.children.indexOf( listItemNode );
944 this.addAttributesToElement( listItemData, 0, { value: indexInOwnList + 1 } );
945 }
946 if ( item.action === 'none' && !item.move ) {
947 this.addAttributesToElement( listItemData, 0, {
948 'data-diff-list-none': ''
949 } );
950 }
951 }
952
953 // e.g. AlienBlockNode, content node is same as 'listItem', so don't duplicate content
954 if ( item.node === listItemNode ) {
955 listItemData = contentData;
956 } else {
957 ve.batchSplice( listItemData, 1, listItemData.length - 2, contentData );
958 }
959
960 // Check for attribute changes
961 if ( item.diff && item.diff.attributeChange ) {
962 const attributeChange = {
963 oldAttributes: {},
964 newAttributes: {}
965 };
966
967 [ 'listNodeAttributeChange', 'depthChange', 'listItemAttributeChange' ].forEach( ( listChangeType ) => {
968 if ( item.diff.attributeChange[ listChangeType ] ) {
969 if ( listChangeType === 'listNodeAttributeChange' && depthChange > 0 ) {
970 const change = this.compareNodeAttributes( listNodeInfo.data, 0, item.diff.attributeChange[ listChangeType ] );
971 if ( change ) {
972 this.descriptionItemsStack.push( change );
973 listNodeInfo.changeDone = true;
974 }
975 } else if ( listChangeType !== 'listNodeAttributeChange' || !listNodeInfo.changeDone ) {
976 ve.extendObject( attributeChange.oldAttributes, item.diff.attributeChange[ listChangeType ].oldAttributes );
977 ve.extendObject( attributeChange.newAttributes, item.diff.attributeChange[ listChangeType ].newAttributes );
978 }
979 }
980 } );
981
982 const listItemChange = this.compareNodeAttributes( listItemData, 0, attributeChange );
983 if ( listItemChange ) {
984 this.descriptionItemsStack.push( listItemChange );
985 }
986 }
987
988 if ( item.metadata.isContinued ) {
989 ve.batchSplice( diffData, insertIndex - 1, 0, contentData );
990 insertIndex += contentData.length;
991
992 } else {
993 // Record the index to splice in the next list item data into the diffData
994 insertIndex = this.appendListItem(
995 diffData, insertIndex, listNode, listNodeInfo.data, listItemData, depthChange
996 );
997 }
998
999 depth = newDepth;
1000 } );
1001
1002 return diffData;
1003 };
1004
1005 /**
1006 * Get the linear data for the diff of a tree-like node that has been changed.
1007 * Any node that is not leaf-like or list-like is treated as tree-like.
1008 *
1009 * @param {ve.dm.Node} oldTreeNode Node from the old document
1010 * @param {ve.dm.Node} newTreeNode Corresponding node from the new document
1011 * @param {Object} diff Object describing the diff
1012 * @return {Array} Linear data for the diff
1013 */
1014 ve.ui.DiffElement.prototype.getChangedTreeNodeData = function ( oldTreeNode, newTreeNode, diff ) {
1015 const nodeData = this.constructor.static.getDataFromNode( newTreeNode ),
1016 nodeRange = newTreeNode.getOuterRange(),
1017 treeDiff = diff.treeDiff,
1018 diffInfo = diff.diffInfo,
1019 oldNodes = diff.oldTreeOrderedNodes,
1020 newNodes = diff.newTreeOrderedNodes,
1021 correspondingNodes = diff.correspondingNodes,
1022 structuralRemoves = [],
1023 highestRemovedAncestors = {};
1024
1025 /**
1026 * Splice in the removed data for the subtree rooted at this node, from the old
1027 * document.
1028 *
1029 * @param {number} nodeIndex The index of this node in the subtree rooted at
1030 * this document child
1031 */
1032 const highlightRemovedNode = ( nodeIndex ) => {
1033
1034 const findRemovedAncestor = ( n ) => {
1035 if ( !n.parent || structuralRemoves.indexOf( n.parent.index ) === -1 ) {
1036 return n.index;
1037 } else {
1038 return findRemovedAncestor( n.parent );
1039 }
1040 };
1041
1042 const getRemoveData = ( n, index ) => {
1043 const data = this.constructor.static.getDataFromNode( n.node );
1044 this.addAttributesToElement( data, 0, {
1045 'data-diff-action': 'remove'
1046 } );
1047
1048 while ( n && n.index !== index ) {
1049 n = n.parent;
1050 const tempData = this.constructor.static.getDataFromNode( n.node );
1051 data.unshift( tempData[ 0 ] );
1052 data.push( tempData[ tempData.length - 1 ] );
1053 this.addAttributesToElement( data, 0, {
1054 'data-diff-action': 'structural-remove'
1055 } );
1056 }
1057
1058 return data;
1059 };
1060
1061 const orderedNode = oldNodes[ nodeIndex ];
1062 const node = orderedNode.node;
1063
1064 if ( node.isDiffedAsTree() && node.hasChildren() ) {
1065 // Record that the node has been removed, but don't display it, for now
1066 // TODO: describe the change for the attribute diff
1067 structuralRemoves.push( nodeIndex );
1068
1069 } else {
1070 // Display the removed node, and all its ancestors, up to the first ancestor that
1071 // hasn't been removed.
1072 const highestRemovedAncestor = oldNodes[ findRemovedAncestor( orderedNode ) ];
1073 const removeData = getRemoveData( orderedNode, highestRemovedAncestor.index );
1074 let insertIndex;
1075
1076 // Work out where to insert the removed subtree
1077 if ( highestRemovedAncestor.index in highestRemovedAncestors ) {
1078 // The highest removed ancestor has already been spliced into nodeData, so remove
1079 // it from this subtree and splice the rest of this subtree in
1080 removeData.shift();
1081 removeData.pop();
1082 insertIndex = highestRemovedAncestors[ highestRemovedAncestor.index ];
1083
1084 } else if ( !highestRemovedAncestor.parent ) {
1085 // If this node is a child of the document node, then it won't have a "previous
1086 // node" (see below), in which case, insert it just before its corresponding
1087 // node in the new document.
1088 insertIndex = newNodes[ correspondingNodes.oldToNew[ highestRemovedAncestor.index ] ]
1089 .node.getOuterRange().from - nodeRange.from;
1090
1091 } else {
1092 // Find the node that corresponds to the "previous node" of this node. The
1093 // "previous node" is either:
1094 // - the rightmost left sibling that corresponds to a node in the new document
1095 // - or if there isn't one, then this node's parent (which must correspond to
1096 // a node in the new document, or this node would have been marked already
1097 // processed)
1098 const siblingNodes = highestRemovedAncestor.parent.children;
1099 let newPreviousNodeIndex;
1100 for ( let x = 0, xlen = siblingNodes.length; x < xlen; x++ ) {
1101 if ( siblingNodes[ x ].index === highestRemovedAncestor.index ) {
1102 break;
1103 } else {
1104 const oldPreviousNodeIndex = siblingNodes[ x ].index;
1105 if ( correspondingNodes.oldToNew[ oldPreviousNodeIndex ] !== undefined ) {
1106 newPreviousNodeIndex = correspondingNodes.oldToNew[ oldPreviousNodeIndex ];
1107 }
1108 }
1109 }
1110
1111 // If previous node was found among siblings, insert the removed subtree just
1112 // after its corresponding node in the new document. Otherwise insert the
1113 // removed subtree just inside its parent node's corresponding node.
1114 if ( newPreviousNodeIndex !== undefined ) {
1115 insertIndex = newNodes[ newPreviousNodeIndex ].node.getOuterRange().to - nodeRange.from;
1116 } else {
1117 newPreviousNodeIndex = correspondingNodes.oldToNew[ highestRemovedAncestor.parent.index ];
1118 insertIndex = newNodes[ newPreviousNodeIndex ].node.getRange().from - nodeRange.from;
1119 }
1120
1121 // If more content branch node descendants of the highest removed node have
1122 // also been removed, record the index where their subtrees will need to be
1123 // spliced in.
1124 highestRemovedAncestors[ highestRemovedAncestor.index ] = insertIndex + 1;
1125 }
1126
1127 ve.batchSplice( nodeData, insertIndex, 0, removeData );
1128 }
1129 };
1130
1131 /**
1132 * Mark this node as inserted.
1133 *
1134 * @param {number} nodeIndex The index of this node in the subtree rooted at
1135 * this document child
1136 */
1137 const highlightInsertedNode = ( nodeIndex ) => {
1138 // Find index of first data element for this node
1139 const node = newNodes[ nodeIndex ].node;
1140 const nodeRangeStart = node.getOuterRange().from - nodeRange.from;
1141
1142 // Add insert class
1143 this.addAttributesToElement(
1144 nodeData, nodeRangeStart, {
1145 'data-diff-action': ( node.isDiffedAsTree() && node.hasChildren() ) ? 'structural-insert' : 'insert'
1146 }
1147 );
1148 };
1149
1150 /**
1151 * Mark this node as changed and, if it is a content branch node, splice in
1152 * the diff data.
1153 *
1154 * @param {number} oldIdx Old node index
1155 * @param {number} newIdx New node index
1156 * @param {Object} info Diff information relating to this node's change
1157 */
1158 const highlightChangedNode = ( oldIdx, newIdx, info ) => {
1159 // The new node was changed.
1160 // Get data for this node
1161 const oldNode = oldNodes[ oldIdx ].node;
1162 const newNode = newNodes[ newIdx ].node;
1163 const nodeRangeStart = newNode.getOuterRange().from - nodeRange.from;
1164
1165 let nodeDiffData = this.getChangedNodeData( info, oldNode, newNode, null, true );
1166 if ( nodeDiffData ) {
1167 // Diff was handled e.g. by leaf/list/doc differ
1168 ve.batchSplice( nodeData, nodeRangeStart, newNode.getOuterLength(), nodeDiffData );
1169 // TODO: Check if there were actually changes in the sub-diff
1170 } else {
1171 if ( info.linearDiff ) {
1172 // If there is a content change, splice it in
1173 nodeDiffData = info.linearDiff;
1174 const annotatedData = this.annotateNode( nodeDiffData, newNode );
1175 ve.batchSplice( nodeData, nodeRangeStart + 1, newNode.getLength(), annotatedData );
1176 }
1177 if ( info.attributeChange ) {
1178 // If there is no content change, just add change class
1179 this.addAttributesToElement(
1180 nodeData, nodeRangeStart, { 'data-diff-action': 'structural-change' }
1181 );
1182 const item = this.compareNodeAttributes( nodeData, nodeRangeStart, info.attributeChange );
1183 if ( item ) {
1184 this.descriptionItemsStack.push( item );
1185 }
1186 }
1187 }
1188 };
1189
1190 // Iterate backwards over trees so that changes are made from right to left
1191 // of the data, to avoid having to update ranges
1192 const len = Math.max( oldNodes.length, newNodes.length );
1193
1194 for ( let i = 0, j = 0; i < len && j < len; i++, j++ ) {
1195 const newIndex = newNodes.length - 1 - i;
1196 const oldIndex = oldNodes.length - 1 - j;
1197
1198 if ( newIndex < 0 ) {
1199 // The rest of the nodes have been removed
1200 highlightRemovedNode( oldIndex );
1201
1202 } else if ( oldIndex < 0 ) {
1203 // The rest of the nodes have been inserted
1204 highlightInsertedNode( newIndex );
1205
1206 } else if ( correspondingNodes.newToOld[ newIndex ] === oldIndex ) {
1207 // The new node was changed.
1208 for ( let k = 0, klen = treeDiff.length; k < klen; k++ ) {
1209 if ( treeDiff[ k ][ 0 ] === oldIndex && treeDiff[ k ][ 1 ] === newIndex ) {
1210 if ( !diffInfo[ k ] ) {
1211 // We are treating these nodes as removed and inserted
1212 highlightInsertedNode( newIndex );
1213 highlightRemovedNode( oldIndex );
1214 } else {
1215 // There could be any combination of content, attribute and type changes
1216 highlightChangedNode( oldIndex, newIndex, diffInfo[ k ] );
1217 }
1218 }
1219 }
1220
1221 } else if ( correspondingNodes.newToOld[ newIndex ] === undefined ) {
1222 // The new node was inserted.
1223 highlightInsertedNode( newIndex );
1224 j--;
1225
1226 } else if ( correspondingNodes.newToOld[ newIndex ] < oldIndex ) {
1227 // The old node was removed.
1228 highlightRemovedNode( oldIndex );
1229 i--;
1230 }
1231 }
1232
1233 // Push new description items from the queue
1234 this.descriptions.addItems( this.descriptionItemsStack );
1235 this.descriptionItemsStack = [];
1236
1237 return nodeData;
1238 };
1239
1240 /**
1241 * Add the relevant attributes to references list node HTML, whether changed or
1242 * unchanged (but not inserted or removed - in these cases we just use
1243 * getNodeElements).
1244 *
1245 * @param {HTMLElement} referencesListContainer Div containing the references list
1246 * @param {string} action 'change' or 'none'
1247 * @param {string|null} move 'up' or 'down' if the node has moved
1248 * @param {OO.ui.OptionWidget[]} items Change descriptions for the reference list
1249 * @return {HTMLElement[]} Elements to display
1250 */
1251 ve.ui.DiffElement.prototype.getRefListNodeElements = function ( referencesListContainer, action, move, items ) {
1252 this.markMove( move, referencesListContainer );
1253 this.descriptionItemsStack.push.apply( this.descriptionItemsStack, items );
1254
1255 return [ referencesListContainer ];
1256 };
1257
1258 /**
1259 * Get the HTML for the diff of a single internal list item that has been removed
1260 * from the old document, inserted into the new document, or that is unchanged.
1261 *
1262 * @param {ve.dm.InternalItemNode} internalListItemNode Internal list item node
1263 * @param {string} action 'remove', 'insert' or 'none'
1264 * @param {string|null} move 'up' or 'down' if the node has moved
1265 * @param {number} index
1266 * @return {HTMLElement[]} Elements (not owned by window.document)
1267 */
1268 ve.ui.DiffElement.prototype.getInternalListNodeElements = function ( internalListItemNode, action, move, index ) {
1269 const contents = internalListItemNode.children,
1270 listItemNode = document.createElement( 'li' );
1271
1272 if ( contents.length ) {
1273 contents.forEach( ( node ) => {
1274 const elements = this.getNodeElements( node, action, move );
1275
1276 listItemNode.appendChild(
1277 listItemNode.ownerDocument.adoptNode( elements[ 0 ] )
1278 );
1279 } );
1280 } else {
1281 // TODO: This is MW-Cite-specific behaviour that VE core
1282 // should know nothing about. Move to MWDiffElement?
1283 $( listItemNode ).append(
1284 $( '<span>' )
1285 .addClass( 've-ce-mwReferencesListNode-muted' )
1286 .text( ve.msg( 'cite-ve-referenceslist-missingref-in-list' ) )
1287 ).attr( 'data-diff-action', action );
1288 }
1289 listItemNode.setAttribute( 'value', index + 1 );
1290
1291 return [ listItemNode ];
1292 };
1293
1294 /**
1295 * Get the HTML for the linear diff of a single internal list item that has changed
1296 * from the old document to the new document.
1297 *
1298 * @param {Object} diff List item diff
1299 * @param {ve.dm.InternalItemNode} oldNode
1300 * @param {ve.dm.InternalItemNode} newNode
1301 * @param {string|null} move 'up' or 'down' if the node has moved
1302 * @param {number} newIndex
1303 * @return {HTMLElement[]} HTML elements to display the linear diff
1304 */
1305 ve.ui.DiffElement.prototype.getInternalListChangedNodeElements = function ( diff, oldNode, newNode, move, newIndex ) {
1306 const listItemNode = document.createElement( 'li' );
1307 let data = this.getChangedDocListData( newNode, diff, true );
1308
1309 // Remove internal list wrapper
1310 data = data.slice( 1, data.length - 2 );
1311
1312 this.markMove( move, listItemNode );
1313 const newDoc = newNode.getRoot().getDocument();
1314 const documentSlice = newDoc.cloneWithData( data, true, true );
1315 const body = ve.dm.converter.getDomFromModel( documentSlice, ve.dm.Converter.static.PREVIEW_MODE ).body;
1316 while ( body.childNodes.length ) {
1317 listItemNode.appendChild(
1318 listItemNode.ownerDocument.adoptNode( body.childNodes[ 0 ] )
1319 );
1320 }
1321
1322 listItemNode.setAttribute( 'value', newIndex + 1 );
1323
1324 return [ listItemNode ];
1325 };
1326
1327 /**
1328 * Compare attributes of two nodes
1329 *
1330 * @param {Array} data Linear data containing new node
1331 * @param {number} offset Offset in data
1332 * @param {Object} attributeChange Attribute change object containing oldAttributes and newAttributes
1333 * @return {OO.ui.OptionWidget|null} Change description item, or null if nothing to describe
1334 */
1335 ve.ui.DiffElement.prototype.compareNodeAttributes = function ( data, offset, attributeChange ) {
1336 const attributeChanges = this.constructor.static.compareAttributes( attributeChange.oldAttributes, attributeChange.newAttributes );
1337
1338 const changes = ve.dm.modelRegistry.lookup( data[ offset ].type ).static.describeChanges( attributeChanges, attributeChange.newAttributes, data[ offset ] );
1339
1340 // Don't describe the same change twice
1341 if ( changes.length && (
1342 !( data[ offset ].internal ) ||
1343 !( data[ offset ].internal.diff ) ||
1344 data[ offset ].internal.diff[ 'data-diff-id' ] === undefined )
1345 ) {
1346 const item = this.getChangeDescriptionItem( changes );
1347 this.addAttributesToElement( data, offset, { 'data-diff-id': item.getData() } );
1348 return item;
1349 }
1350
1351 return null;
1352 };
1353
1354 /**
1355 * Get a change description item from a set of changes
1356 *
1357 * @param {Array} changes List of changes, each change being either text or a Node array
1358 * @param {string[]} classes Additional classes
1359 * @return {OO.ui.OptionWidget} Change description item
1360 */
1361 ve.ui.DiffElement.prototype.getChangeDescriptionItem = function ( changes, classes ) {
1362 const elementId = this.elementId;
1363 let $label = $( [] );
1364
1365 for ( let i = 0, l = changes.length; i < l; i++ ) {
1366 const $change = $( '<div>' );
1367 if ( typeof changes[ i ] === 'string' ) {
1368 $change.text( changes[ i ] );
1369 } else {
1370 // changes[ i ] is definitely not an HTML string in this branch
1371 // eslint-disable-next-line no-jquery/no-append-html
1372 $change.append( changes[ i ] );
1373 }
1374 $label = $label.add( $change );
1375 }
1376 // eslint-disable-next-line mediawiki/class-doc
1377 const item = new OO.ui.OptionWidget( {
1378 label: $label,
1379 data: elementId,
1380 classes: [ 've-ui-diffElement-attributeChange', ...classes || [] ]
1381 } );
1382 this.elementId++;
1383 return item;
1384 };
1385
1386 /**
1387 * Mark an element with attributes to be added later by the converter.
1388 *
1389 * @param {Array} data Data containing element to be marked
1390 * @param {number} offset Offset of element to be marked
1391 * @param {Object} attributes Attributes to set
1392 */
1393 ve.ui.DiffElement.prototype.addAttributesToElement = function ( data, offset, attributes ) {
1394 const newElement = ve.copy( data[ offset ] );
1395
1396 // NB we modify the linear data here, but then this is a cloned document.
1397 for ( const key in attributes ) {
1398 if ( attributes[ key ] !== undefined ) {
1399 ve.setProp( newElement, 'internal', 'diff', key, attributes[ key ] );
1400 }
1401 }
1402
1403 // Don't let any nodes get unwrapped
1404 ve.deleteProp( newElement, 'internal', 'generated' );
1405
1406 data.splice( offset, 1, newElement );
1407 };
1408
1409 /**
1410 * Mark an HTML element or data element as moved
1411 *
1412 * @param {string|null} move 'up' or 'down' if the node has moved
1413 * @param {HTMLElement|Array} elementOrData Linear data or HTMLElement
1414 * @param {number} [offset=0] Linear mode offset
1415 */
1416 ve.ui.DiffElement.prototype.markMove = function ( move, elementOrData, offset ) {
1417 if ( !move ) {
1418 return;
1419 }
1420 // The following messages are used here:
1421 // * visualeditor-diff-moved-up
1422 // * visualeditor-diff-moved-down
1423 // The following classes are used here:
1424 // * ve-ui-diffElement-moved-up
1425 // * ve-ui-diffElement-moved-down
1426 const item = this.getChangeDescriptionItem( [ ve.msg( 'visualeditor-diff-moved-' + move ) ], [ 've-ui-diffElement-moved-' + move ] );
1427 if ( Array.isArray( elementOrData ) ) {
1428 this.addAttributesToElement( elementOrData, offset || 0, { 'data-diff-move': move, 'data-diff-id': item.getData() } );
1429 } else {
1430 elementOrData.setAttribute( 'data-diff-move', move );
1431 elementOrData.setAttribute( 'data-diff-id', item.getData() );
1432 }
1433 this.descriptionItemsStack.push( item );
1434 };
1435
1436 /**
1437 * Annotate some data to highlight diff
1438 *
1439 * @param {Array} linearDiff Linear diff, mapping arrays of linear data to diff
1440 * actions (remove, insert or retain)
1441 * @param {ve.dm.Node} newNode Node from the new document
1442 * @return {Array} Data with annotations added
1443 */
1444 ve.ui.DiffElement.prototype.annotateNode = function ( linearDiff, newNode ) {
1445 const DIFF_DELETE = ve.DiffMatchPatch.static.DIFF_DELETE,
1446 DIFF_INSERT = ve.DiffMatchPatch.static.DIFF_INSERT,
1447 DIFF_CHANGE_DELETE = ve.DiffMatchPatch.static.DIFF_CHANGE_DELETE,
1448 DIFF_CHANGE_INSERT = ve.DiffMatchPatch.static.DIFF_CHANGE_INSERT,
1449 items = [],
1450 newDoc = newNode.getRoot().getDocument();
1451 let start = 0; // The starting index for a range for building an annotation
1452
1453 // Make a new document from the diff
1454 const diffDocData = linearDiff[ 0 ][ 1 ].slice();
1455 const ilen = linearDiff.length;
1456 for ( let i = 1; i < ilen; i++ ) {
1457 ve.batchPush( diffDocData, linearDiff[ i ][ 1 ] );
1458 }
1459 const diffDoc = newDoc.cloneWithData( diffDocData );
1460
1461 // Add spans with the appropriate attributes for removes and inserts
1462 // TODO: do insert and remove outside of loop
1463 for ( let i = 0; i < ilen; i++ ) {
1464 const end = start + linearDiff[ i ][ 1 ].length;
1465 if ( start !== end ) {
1466 const range = new ve.Range( start, end );
1467 const type = linearDiff[ i ][ 0 ];
1468 if ( type !== 0 ) {
1469 let typeAsString, domElementType, annType;
1470 switch ( type ) {
1471 case DIFF_DELETE:
1472 typeAsString = 'remove';
1473 domElementType = 'del';
1474 annType = 'textStyle/delete';
1475 break;
1476 case DIFF_INSERT:
1477 typeAsString = 'insert';
1478 domElementType = 'ins';
1479 annType = 'textStyle/insert';
1480 break;
1481 case DIFF_CHANGE_DELETE:
1482 typeAsString = 'change-remove';
1483 domElementType = 'span';
1484 annType = 'textStyle/span';
1485 break;
1486 case DIFF_CHANGE_INSERT:
1487 typeAsString = 'change-insert';
1488 domElementType = 'span';
1489 annType = 'textStyle/span';
1490 break;
1491 }
1492 const domElement = document.createElement( domElementType );
1493 domElement.setAttribute( 'data-diff-action', typeAsString );
1494 const domElements = [ domElement ];
1495
1496 const changes = [];
1497 if ( linearDiff[ i ].annotationChanges ) {
1498 linearDiff[ i ].annotationChanges.forEach( ( annotationChange ) => {
1499 let attributeChanges;
1500 if ( annotationChange.oldAnnotation && annotationChange.newAnnotation ) {
1501 attributeChanges = this.constructor.static.compareAttributes(
1502 annotationChange.oldAnnotation.getAttributes(),
1503 annotationChange.newAnnotation.getAttributes()
1504 );
1505 ve.batchPush( changes, ve.dm.modelRegistry.lookup( annotationChange.newAnnotation.getType() ).static.describeChanges(
1506 attributeChanges, annotationChange.newAnnotation.getAttributes(), annotationChange.newAnnotation.getElement()
1507 ) );
1508 } else if ( annotationChange.newAnnotation ) {
1509 ve.batchPush( changes, annotationChange.newAnnotation.describeAdded() );
1510 } else if ( annotationChange.oldAnnotation ) {
1511 ve.batchPush( changes, annotationChange.oldAnnotation.describeRemoved() );
1512 }
1513 } );
1514 }
1515 if ( linearDiff[ i ].attributeChanges ) {
1516 const element = linearDiff[ i ][ 1 ][ 0 ];
1517 linearDiff[ i ].attributeChanges.forEach( ( attributeChange ) => {
1518 const attributeChanges = this.constructor.static.compareAttributes(
1519 attributeChange.oldAttributes,
1520 attributeChange.newAttributes
1521 );
1522 ve.batchPush( changes, ve.dm.modelRegistry.lookup( element.type ).static.describeChanges(
1523 attributeChanges, element.attributes, element
1524 ) );
1525 } );
1526 }
1527 if ( changes.length ) {
1528 const item = this.getChangeDescriptionItem( changes );
1529 domElement.setAttribute( 'data-diff-id', item.getData() );
1530 items.push( item );
1531 }
1532
1533 const originalDomElementsHash = diffDoc.getStore().hash(
1534 domElements,
1535 domElements.map( ve.getNodeHtml ).join( '' )
1536 );
1537 const annHash = diffDoc.getStore().hash(
1538 ve.dm.annotationFactory.create( annType, {
1539 type: annType,
1540 originalDomElementsHash: originalDomElementsHash
1541 } )
1542 );
1543
1544 // Insert annotation above annotations that span the entire range
1545 // and at least one character more
1546 const annHashLists = [];
1547 for (
1548 let j = Math.max( 0, range.start - 1 );
1549 j < Math.min( range.end + 1, diffDoc.data.getLength() );
1550 j++
1551 ) {
1552 annHashLists[ j ] =
1553 diffDoc.data.getAnnotationHashesFromOffset( j );
1554 }
1555 const height = Math.min(
1556 ve.getCommonStartSequenceLength(
1557 annHashLists.slice(
1558 Math.max( 0, range.start - 1 ),
1559 range.end
1560 )
1561 ),
1562 ve.getCommonStartSequenceLength(
1563 annHashLists.slice(
1564 range.start,
1565 Math.min( range.end + 1, diffDoc.data.getLength() )
1566 )
1567 )
1568 );
1569 for ( let j = range.start; j < range.end; j++ ) {
1570 annHashLists[ j ].splice( height, 0, annHash );
1571 diffDoc.data.setAnnotationHashesAtOffset(
1572 j,
1573 annHashLists[ j ]
1574 );
1575 }
1576 }
1577 }
1578 start = end;
1579 }
1580 this.descriptionItemsStack.push.apply( this.descriptionItemsStack, items );
1581
1582 // Merge the stores and get the data
1583 newDoc.getStore().merge( diffDoc.getStore() );
1584 const annotatedLinearDiff = diffDoc.getData( { start: 0, end: diffDoc.getLength() } );
1585
1586 return annotatedLinearDiff;
1587 };
1588
1589 ve.ui.metaListDiffRegistry = new OO.Registry();