Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ve.DiffMatchPatch.js

raw symbols SCIP
1 /*!
2 * VisualEditor DiffMatchPatch implementation for linear model
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /* global diff_match_patch */
8
9 /**
10 * DiffMatchPatch implementation
11 *
12 * @class
13 * @extends diff_match_patch
14 * @constructor
15 * @param {ve.dm.HashValueStore} oldStore
16 * @param {ve.dm.HashValueStore} newStore
17 */
18 ve.DiffMatchPatch = function VeDiffMatchPatch( oldStore, newStore ) {
19 // Parent constructor
20 ve.DiffMatchPatch.super.call( this );
21
22 this.store = oldStore.slice();
23 this.store.merge( newStore );
24 };
25
26 /* Inheritance */
27
28 OO.inheritClass( ve.DiffMatchPatch, diff_match_patch );
29
30 /* Static properties */
31
32 ve.DiffMatchPatch.static.DIFF_DELETE = -1;
33 ve.DiffMatchPatch.static.DIFF_INSERT = 1;
34 ve.DiffMatchPatch.static.DIFF_EQUAL = 0;
35 ve.DiffMatchPatch.static.DIFF_CHANGE_DELETE = -2;
36 ve.DiffMatchPatch.static.DIFF_CHANGE_INSERT = 2;
37
38 /* Methods */
39
40 ve.DiffMatchPatch.prototype.isEqualChar = function ( a, b ) {
41 return a === b || ve.dm.ElementLinearData.static.compareElements( a, b, this.store, this.store );
42 };
43
44 ve.DiffMatchPatch.prototype.isEqualString = function ( a, b ) {
45 if ( a === b ) {
46 return true;
47 }
48 if ( a === null || b === null ) {
49 return false;
50 }
51 if ( a.length !== b.length ) {
52 return false;
53 }
54
55 for ( let i = 0, l = a.length; i < l; i++ ) {
56 if ( !this.isEqualChar( a[ i ], b[ i ] ) ) {
57 return false;
58 }
59 }
60 return true;
61 };
62
63 ve.DiffMatchPatch.prototype.charsToString = function ( chars ) {
64 return chars.slice();
65 };
66
67 ve.DiffMatchPatch.prototype.getEmptyString = function () {
68 return [];
69 };
70
71 ve.DiffMatchPatch.prototype.indexOf = function indexOf( text, searchValue, fromIndex ) {
72 // fromIndex defaults to 0 and is bounded by 0 and text.length
73 // Note that indexOf( 'foo', '', 99 ) is supposed to return 3 (text.length), which is why we allow
74 // starting the search beyond the end of the string
75 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
76 for (
77 let i = fromIndex === undefined ? 0 : Math.min( Math.max( fromIndex, 0 ), text.length );
78 i <= text.length - searchValue.length;
79 i++
80 ) {
81 let found = true;
82 for ( let j = 0; j < searchValue.length; j++ ) {
83 if ( !this.isEqualChar( text[ i + j ], searchValue[ j ] ) ) {
84 found = false;
85 break;
86 }
87 }
88 if ( found ) {
89 return i;
90 }
91 }
92 return -1;
93 };
94
95 ve.DiffMatchPatch.prototype.lastIndexOf = function lastIndexOf( text, searchValue, fromIndex ) {
96 const iLen = text.length - searchValue.length;
97 // fromIndex defaults to the end, and must be greater than 0
98 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
99 for (
100 let i = fromIndex === undefined ? iLen : Math.min( Math.max( fromIndex, 0 ), iLen );
101 i >= 0;
102 i--
103 ) {
104 let found = true;
105 for ( let j = 0; j < searchValue.length; j++ ) {
106 if ( !this.isEqualChar( text[ i + j ], searchValue[ j ] ) ) {
107 found = false;
108 break;
109 }
110 }
111 if ( found ) {
112 return i;
113 }
114 }
115 return -1;
116 };
117
118 ve.DiffMatchPatch.prototype.getCleanDiff = function ( oldData, newData, options ) {
119 const store = this.store,
120 DIFF_DELETE = this.constructor.static.DIFF_DELETE,
121 DIFF_INSERT = this.constructor.static.DIFF_INSERT,
122 DIFF_EQUAL = this.constructor.static.DIFF_EQUAL,
123 DIFF_CHANGE_DELETE = this.constructor.static.DIFF_CHANGE_DELETE,
124 DIFF_CHANGE_INSERT = this.constructor.static.DIFF_CHANGE_INSERT;
125
126 /**
127 * Remove the close elements from the linear data, to force a balanced diff.
128 *
129 * Otherwise, for example, removing the second of two consecutive comment
130 * nodes could result in a diff where [{type: '/comment'}, {type: 'comment'}]
131 * is removed, which is unbalanced.
132 *
133 * Warning: this step assumes that, within a content branch node, an element
134 * is always immediately followed by its close element.
135 *
136 * @param {Array} data Linear data
137 * @return {Array} Linear data without close elements
138 */
139 function removeCloseElements( data ) {
140 for ( let i = 0, ilen = data.length; i < ilen; i++ ) {
141 if ( data[ i ].type && data[ i ].type[ 0 ] === '/' ) {
142 data.splice( i, 1 );
143 ilen--;
144 i--;
145 }
146 }
147 return data;
148 }
149
150 /**
151 * Get the index of the first or last wordbreak in a data array
152 *
153 * @param {Array} data Linear data
154 * @param {boolean} reversed Get the index of the last wordbreak
155 * @return {number|null} Index of the first or last wordbreak, or null if no
156 * wordbreak was found
157 */
158 function findWordbreaks( data, reversed ) {
159 const dataString = new ve.dm.DataString( data );
160
161 const offset = unicodeJS.wordbreak.moveBreakOffset(
162 reversed ? -1 : 1,
163 dataString,
164 reversed ? data.length : 0
165 );
166
167 if ( ( reversed && offset === 0 ) || ( !reversed && offset === data.length ) ) {
168 return null;
169 } else {
170 return offset;
171 }
172 }
173
174 /**
175 * Determine whether there is a wordbreak at an offset
176 *
177 * @param {Array} data Linear data
178 * @param {number} offset
179 * @return {boolean} There is a wordbreak at the offset
180 */
181 function isBreak( data, offset ) {
182 return !!( unicodeJS.wordbreak.isBreak( new ve.dm.DataString( data ), offset ) );
183 }
184
185 /**
186 * The perfect diff is not always human-friendly, so clean it up.
187 * Make sure retained content spans whole words (no wordbreaks),
188 * and "de-stripe" any sequences of alternating removes and inserts
189 * (with no retains) to look like one continuous removal and one continuous
190 * insert.
191 *
192 * Additionally clean up mistakes made by the linear differ, such as removing
193 * and inserting identical content (insetead of retaining it) and removing,
194 * inserting or retaining an empty content array.
195 *
196 * @param {Array} diff Linear diff, as arrays of inserted, removed and retained
197 * content
198 * @return {Array} A human-friendlier linear diff
199 */
200 function getCleanDiff( diff ) {
201 let previousData = null,
202 previousAction = null,
203 remove = [],
204 insert = [];
205 const cleanDiff = [];
206
207 function equalUnannotated( other, element, index ) {
208 return ve.dm.ElementLinearData.static.compareElementsUnannotated( element, other[ index ] );
209 }
210
211 function equalElements( other, element, index ) {
212 // Non-elements can't be equal to other elements
213 if ( !element.type || !other[ index ].type ) {
214 return false;
215 }
216 if ( ve.dm.LinearData.static.isOpenElementData( element ) ) {
217 return ve.dm.modelRegistry.lookup( element.type ).static.isDiffComparable( element, other[ index ], store, store );
218 } else {
219 // Ignore close elements
220 return true;
221 }
222 }
223
224 function isWhitespace( element ) {
225 const value = Array.isArray( element ) ? element[ 0 ] : element;
226 return typeof value === 'string' && /^\s+$/.test( value );
227 }
228
229 // Where the same data is removed and inserted, replace it with a retain
230 for ( let i = 0; i < diff.length; i++ ) {
231 const action = diff[ i ][ 0 ];
232 const data = diff[ i ][ 1 ];
233 // Should improve on JSON.stringify
234 if ( ( action > 0 || previousAction > 0 ) && action + previousAction === 0 && JSON.stringify( data ) === JSON.stringify( previousData ) ) {
235 diff.splice( i - 1, 2, [ DIFF_EQUAL, data ] );
236 i++;
237 }
238 previousAction = action;
239 previousData = data;
240 }
241 previousData = null;
242 previousAction = null;
243
244 // Join any consecutive actions that are the same
245 for ( let i = 0; i < diff.length; i++ ) {
246 const action = diff[ i ][ 0 ];
247 if ( action === previousAction ) {
248 ve.batchPush( diff[ i - 1 ][ 1 ], diff[ i ][ 1 ] );
249 diff.splice( i, 1 );
250 i--;
251 } else if ( diff[ i ][ 1 ].length === 0 ) {
252 diff.splice( i, 1 );
253 i--;
254 continue;
255 }
256 previousAction = action;
257 }
258
259 // Convert any retains that do not end and start with spaces into remove-
260 // inserts
261 for ( let i = 0; i < diff.length; i++ ) {
262 const action = diff[ i ][ 0 ];
263 const data = diff[ i ][ 1 ];
264 if ( action === DIFF_EQUAL ) {
265 let start = [];
266 let end = [];
267 const firstWordbreak = findWordbreaks( data, false );
268 const lastWordbreak = firstWordbreak === null ? null : findWordbreaks( data, true );
269 const notNextStartsWithWordbreak = i !== diff.length - 1 && !isBreak( data.concat( diff[ i + 1 ][ 1 ] ), data.length );
270 const notPreviousEndsWithWordBreak = i !== 0 && !isBreak( previousData.concat( data ), previousData.length );
271
272 if ( firstWordbreak === null && ( notNextStartsWithWordbreak || notPreviousEndsWithWordBreak ) ) {
273 // If there was no wordbreak, and there are no wordbreaks either side,
274 // the retain should be replaced with a remove-insert
275 diff.splice( i, 1, [ DIFF_DELETE, data ], [ DIFF_INSERT, data ] );
276 i++;
277 } else {
278 if ( notNextStartsWithWordbreak ) {
279 // Unless the next item starts with a wordbreak, replace the portion
280 // after the last wordbreak.
281 end = data.splice( lastWordbreak );
282 }
283 if ( notPreviousEndsWithWordBreak ) {
284 // Unless the previous item ends with a word break,replace the portion
285 // before the first wordbreak.
286 start = data.splice( 0, firstWordbreak );
287 } else {
288 // Skip over close tags to ensure a balanced remove/insert
289 // Word break logic should ensure that there aren't unbalanced
290 // tags on the left of the remove/insert
291 let j = 0;
292 while ( ve.dm.LinearData.static.isCloseElementData( data[ j ] ) ) {
293 j++;
294 }
295 start = data.splice( 0, j );
296 }
297
298 // At this point the only portion we want to retain is what's left of
299 // data (if anything; if firstWordbreak === lastWordbreak !== null, then
300 // data has been spliced away completely).
301 if ( start.length > 0 ) {
302 diff.splice( i, 0, [ DIFF_DELETE, start ], [ DIFF_INSERT, start ] );
303 i += 2;
304 }
305 if ( end.length > 0 ) {
306 diff.splice( i + 1, 0, [ DIFF_DELETE, end ], [ DIFF_INSERT, end ] );
307 i += 2;
308 }
309 }
310 }
311 previousData = data;
312 }
313
314 // In a sequence of -remove-insert-remove-insert- make the removes into a
315 // single action and the inserts into a single action
316 for ( let i = 0, ilen = diff.length; i < ilen; i++ ) {
317 const action = diff[ i ][ 0 ];
318 const data = diff[ i ][ 1 ];
319 if ( action === DIFF_DELETE ) {
320 ve.batchPush( remove, data );
321 } else if ( action === DIFF_INSERT ) {
322 ve.batchPush( insert, data );
323 } else if ( action === DIFF_EQUAL && data.length > 0 ) {
324 if ( data.every( isWhitespace ) ) {
325 ve.batchPush( remove, data );
326 ve.batchPush( insert, data );
327 } else {
328 if ( remove.length > 0 ) {
329 cleanDiff.push( [ DIFF_DELETE, remove ] );
330 }
331 remove = [];
332 if ( insert.length > 0 ) {
333 cleanDiff.push( [ DIFF_INSERT, insert ] );
334 }
335 insert = [];
336 cleanDiff.push( diff[ i ] );
337 }
338 }
339 }
340
341 if ( remove.length > 0 ) {
342 cleanDiff.push( [ DIFF_DELETE, remove ] );
343 }
344 if ( insert.length > 0 ) {
345 cleanDiff.push( [ DIFF_INSERT, insert ] );
346 }
347
348 // Now go over any consecutive remove-inserts (also insert-removes?) and
349 // if they have the same character data, or are modified content nodes,
350 // make them changes instead
351 for ( let i = 0, ilen = cleanDiff.length - 1; i < ilen; i++ ) {
352 const aItem = cleanDiff[ i ];
353 const bItem = cleanDiff[ i + 1 ];
354 const aData = aItem[ 1 ];
355 const bData = bItem[ 1 ];
356 const aAction = aItem[ 0 ];
357 const bAction = bItem[ 0 ];
358 // If they have the same length content and they are a consecutive
359 // remove and insert, and they have the same content then mark the
360 // old one as a change-remove (-2) and the new one as a change-insert
361 // (2)
362 if (
363 aData.length === bData.length &&
364 ( ( aAction === DIFF_DELETE && bAction === DIFF_INSERT ) || ( aAction === DIFF_INSERT && bAction === DIFF_DELETE ) )
365 ) {
366 if ( aData.every( equalUnannotated.bind( this, bData ) ) ) {
367 const aAnnotations = new ve.dm.ElementLinearData( store, aData ).getAnnotationsFromRange( new ve.Range( 0, aData.length ), true );
368 const bAnnotations = new ve.dm.ElementLinearData( store, bData ).getAnnotationsFromRange( new ve.Range( 0, bData.length ), true );
369
370 const annotationChanges = [];
371 bAnnotations.get().forEach( ( b ) => {
372 const sameName = aAnnotations.getAnnotationsByName( b.name );
373 if ( !aAnnotations.containsComparable( b ) ) {
374 if ( sameName.getLength() ) {
375 // Annotations which have the same type, but are non-comparable, e.g. link with a different href
376 annotationChanges.push( { oldAnnotation: sameName.get( 0 ), newAnnotation: b } );
377 } else {
378 annotationChanges.push( { newAnnotation: b } );
379 }
380 }
381 } );
382 aAnnotations.get().forEach( ( a ) => {
383 if ( !(
384 // Check the old annotation hasn't already been described as a insertion...
385 bAnnotations.containsComparable( a ) ||
386 // ...or a change
387 bAnnotations.getAnnotationsByName( a.name ).getLength()
388 ) ) {
389 annotationChanges.push( { oldAnnotation: a } );
390 }
391 } );
392
393 if ( annotationChanges.length ) {
394 cleanDiff[ i + 1 ].annotationChanges = annotationChanges;
395 cleanDiff[ i ][ 0 ] = aAction === DIFF_DELETE ? DIFF_CHANGE_DELETE : DIFF_CHANGE_INSERT;
396 cleanDiff[ i + 1 ][ 0 ] = bAction === DIFF_DELETE ? DIFF_CHANGE_DELETE : DIFF_CHANGE_INSERT;
397 }
398 }
399 if ( aData.every( equalElements.bind( this, bData ) ) ) {
400 const attributeChanges = [];
401 bData.forEach( ( element, n ) => {
402 if ( ve.dm.LinearData.static.isOpenElementData( element ) ) {
403 attributeChanges.push( { oldAttributes: aData[ n ].attributes, newAttributes: element.attributes, index: n } );
404 }
405 } );
406 if ( attributeChanges.length ) {
407 cleanDiff[ i + 1 ].attributeChanges = attributeChanges;
408 cleanDiff[ i ][ 0 ] = aAction === DIFF_DELETE ? DIFF_CHANGE_DELETE : DIFF_CHANGE_INSERT;
409 cleanDiff[ i + 1 ][ 0 ] = bAction === DIFF_DELETE ? DIFF_CHANGE_DELETE : DIFF_CHANGE_INSERT;
410 }
411 }
412
413 // No need to check bItem against the following item
414 i += 1;
415 }
416 }
417
418 return cleanDiff;
419 }
420
421 // Remove the close elements
422 oldData = removeCloseElements( oldData );
423 newData = removeCloseElements( newData );
424
425 // Get the diff
426 const finalDiff = getCleanDiff( this.diff_main( oldData, newData, options ) );
427
428 // Re-insert the close elements
429 for ( let k = 0, klen = finalDiff.length; k < klen; k++ ) {
430 for ( let m = 0; m < finalDiff[ k ][ 1 ].length; m++ ) {
431 if ( finalDiff[ k ][ 1 ][ m ].type ) {
432 finalDiff[ k ][ 1 ].splice( m + 1, 0, {
433 type: '/' + finalDiff[ k ][ 1 ][ m ].type
434 } );
435 m++;
436 }
437 }
438 }
439
440 finalDiff.timedOut = this.lastDiffTimedOut;
441
442 return finalDiff;
443 };