All files / src ve.DiffMatchPatch.js

93.75% Statements 195/208
89.39% Branches 118/132
94.44% Functions 17/18
93.46% Lines 186/199

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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