Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel TransactionSquasher class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Squasher to create one transaction from multiple transactions applicable in turn
9 *
10 * The squashed transaction has the same effect on a document as applying the original
11 * transactions in turn, but it may cause rebase conflicts where the original sequence
12 * of transactions would not have.
13 *
14 * Suppose we have linmod arrays A, B, C, D. Note that (x,A->B,m) then (x,C->D,n) becomes
15 * (x,A.concat(C*)->D.concat(B*),min(m,n)) Where len = min(B.length, C.length) and
16 * C*=C.slice(len) and B*=B.slice(len). I.e. "A->B then C->D" becomes "remove A, remove C*,
17 * insert D, insert B*". Examples:
18 * 1234Aa5678 (4,Aa->Bb,4) 1234Bb5678 (4,B->D,5) 1234Db5678 --> (4,Aa->Db,4)
19 * 1234Aa5678 (4,Aa->Bb,4) 1234Bb5678 (4,Bb5->Dd,3) 1234Dd678 --> (4,Aa5->Dd,3)
20 *
21 * The same sort of thing happens if the starts are not the same, e.g.
22 * helloworld (2,ll>LL,1,wo>WO,3) heLLoWOrld (3,LoW>HI,4) heLHIrld --> (2,llowo>LHI,3)
23 * hiwed (1,i>ello,1,e>orl,1) helloworld (2,llowor>a,2) heald --> (1,iwe>eal,1)
24 *
25 * However, removal followed by reinsertion cannot be stripped out entirely, because then
26 * the squashed transaction, considered as a partial function between documents, would have
27 * a larger preimage than the composition of the original transactions. This can probably
28 * break things like associativity). Example:
29 *
30 * hello! (1,ello>iworld,1) hiworld! (1,i>ello,6) helloworld! --> (1,ello>elloworld,1)
31 *
32 * For annotations in the follow-up transaction, two forms of processing are needed: annotating
33 * previously-inserted content, and adding the annotations operation into the transaction for
34 * retained ranges.
35 *
36 * @class
37 * @constructor
38 * @param {ve.dm.Transaction} transaction Base transaction to clone then squash others onto
39 */
40 ve.dm.TransactionSquasher = function VeDmTransactionSquasher( transaction ) {
41 /**
42 * @property {ve.dm.Transaction} transaction Transaction being squashed together
43 */
44 this.transaction = transaction.clone();
45
46 /**
47 * @property {Object[]} operations Reference to .operations within the tx
48 */
49 this.operations = this.transaction.operations;
50
51 /**
52 * @property {Object} op During squashIn, the current op within operations
53 */
54 this.op = this.operations[ 0 ];
55
56 /**
57 * @property {number} index During squashIn, index of current op within operations
58 */
59 this.index = 0;
60
61 /**
62 * During squashIn, post-transaction offset within the current op
63 *
64 * @property {number} offset During squashIn, post-tx linmod offset within current op.
65 * "Post transaction" means that for replacements, the offset is within the insert
66 * block. The reason we care about post-transaction offsets is that the match the
67 * pre-transaction offsets of the next transaction.
68 */
69 this.offset = 0;
70
71 /**
72 * @property {number} globalOffset During squashIn, global offset over all operations
73 */
74 this.globalOffset = 0;
75
76 /**
77 * @property {Object} attributeOperations During squashIn, live references to attribute
78 * operations at current offset, keyed by attribute name, or null if at an open element
79 */
80 this.attributeOperations = {};
81 };
82
83 /* Inheritance */
84
85 OO.initClass( ve.dm.TransactionSquasher );
86
87 /* Static methods */
88
89 /**
90 * Test whether two linmod items have equal values
91 *
92 * @param {any} item1 A data item
93 * @param {any} item2 Another data item
94 * @return {boolean} Whether the items have equal values
95 */
96 ve.dm.TransactionSquasher.static.equalItems = function ( item1, item2 ) {
97 function stringifyItem( item ) {
98 return JSON.stringify( item, ( key, value ) => key === 'changesSinceLoad' ? undefined : value );
99 }
100 // Compare serializations, so that reference types need not be reference-equal
101 return stringifyItem( item1 ) === stringifyItem( item2 );
102 };
103
104 /**
105 * Squash an array of consecutive transactions into a single transaction
106 *
107 * @param {ve.dm.Transaction[]} transactions Non-empty array of consecutive transactions
108 * @return {ve.dm.Transaction} Single transaction with the same content as the transaction array
109 */
110 ve.dm.TransactionSquasher.static.squash = function ( transactions ) {
111 if ( transactions.length === 0 ) {
112 throw new Error( 'Cannot squash empty transaction array' );
113 }
114 const squasher = new ve.dm.TransactionSquasher( transactions[ 0 ] );
115 for ( let i = 1, iLen = transactions.length; i < iLen; i++ ) {
116 squasher.squashIn( transactions[ i ] );
117 }
118 return squasher.getTransaction();
119 };
120
121 /* Methods */
122
123 /**
124 * Get the Transaction as-is
125 *
126 * @return {ve.dm.Transaction} The transaction
127 */
128 ve.dm.TransactionSquasher.prototype.getTransaction = function () {
129 return this.transaction;
130 };
131
132 /**
133 * Modify our Transaction in-place to incorporate a follow-up transaction
134 *
135 * Applying the modified transaction has the same effect as applying the original
136 * transaction then the follow-up, but it may cause rebase conflicts where the original
137 * pair of transactions would not have.
138 *
139 * @param {ve.dm.Transaction} tx Follow-up transaction (that can apply immediately after this)
140 */
141 ve.dm.TransactionSquasher.prototype.squashIn = function ( tx ) {
142 // Walk over the document offsets in our transaction, modifying operations in-place
143 // to incorporate the operations in tx
144 this.index = 0;
145 this.offset = 0;
146 this.globalOffset = 0;
147 this.op = this.operations[ this.index ];
148 this.changes = [];
149 this.oldChanges = [];
150 this.readAttributes();
151 // Do not cache length, as we may splice the list
152 for ( let i = 0; i < tx.operations.length; i++ ) {
153 const op = tx.operations[ i ];
154 if ( op.type === 'retain' ) {
155 let retainLength = op.length;
156 while ( retainLength > 0 ) {
157 const consumed = this.processRetain( retainLength );
158 retainLength -= consumed;
159 }
160 } else if ( op.type === 'replace' ) {
161 let items = JSON.parse( JSON.stringify( op.remove ) );
162 while ( items.length > 0 ) {
163 const consumed = this.processRemove( items );
164 items.splice( 0, consumed );
165 }
166 items = JSON.parse( JSON.stringify( op.insert ) );
167 while ( items.length > 0 ) {
168 const consumed = this.processInsert( items );
169 items.splice( 0, consumed );
170 }
171 } else if ( op.type === 'attribute' ) {
172 this.processAttribute( op.key, op.from, op.to );
173 } else {
174 throw new Error( 'Unknown operation type ' + op.type );
175 }
176 }
177 };
178
179 /**
180 * Process the retention of content, stopping part-way if convenient
181 *
182 * @private
183 * @param {number} maxLength The maximum amount of content to retain
184 * @return {number} The amount of content retained
185 */
186 ve.dm.TransactionSquasher.prototype.processRetain = function ( maxLength ) {
187 this.normalizePosition();
188 if ( !this.op ) {
189 throw new Error( 'Past end of transaction' );
190 }
191
192 if ( this.op.type === 'retain' ) {
193 const len = Math.min( maxLength, this.op.length - this.offset );
194 this.offset += len;
195 this.globalOffset += len;
196 this.attributeOperations = {};
197 return len;
198 }
199 if ( this.op.type === 'replace' ) {
200 // Apply annotation changes to inserted content
201 const len = Math.min( maxLength, this.op.insert.length - this.offset );
202
203 // There is never any need to adjust spliceAt, because the splices are always
204 // applied in the same order in which they were generated
205
206 this.offset += len;
207 this.globalOffset += len;
208 this.readAttributes();
209 return len;
210 }
211 if ( this.op.type === 'attribute' ) {
212 // Do nothing
213 this.index++;
214 this.op = this.operations[ this.index ];
215 // By assumption, this.offset is already 0
216 this.attributeOperations[ this.op.key ] = this.op;
217 return 0;
218 }
219 throw new Error( 'Unknown op type: ' + this.op.type );
220 };
221
222 /**
223 * Process the removal of some items, stopping part-way if convenient
224 *
225 * If some of the removal is undoing an insertion in this.transaction, then the "cancelled"
226 * content is stripped out entirely from the squashed transaction.
227 *
228 * @private
229 * @param {Object[]} items Items to remove some of; can be modified in place (annotated)
230 * @return {number} The length of the initial slice of items that was removed
231 */
232 ve.dm.TransactionSquasher.prototype.processRemove = function ( items ) {
233 let tryUnsplit = false;
234
235 this.normalizePosition();
236 if ( !this.op ) {
237 throw new Error( 'Past end of transaction' );
238 }
239 if ( this.op.type === 'retain' ) {
240 this.splitIfInterior();
241 // Now we must be at the start of a retain
242 const len = Math.min( items.length, this.op.length );
243 this.op.length -= len;
244 if ( this.op.length === 0 ) {
245 tryUnsplit = true;
246 // Remove empty retain
247 this.operations.splice( this.index, 1 );
248 // this.op may become undefined; ok
249 this.op = this.operations[ this.index ];
250 }
251 const removal = items.slice( 0, len );
252 if ( this.offset === 0 && this.op && this.op.type === 'replace' ) {
253 // If we're at the start of a replace op, prepend to it
254 ve.batchSplice(
255 this.op.remove,
256 0,
257 0,
258 removal
259 );
260 } else {
261 // Get the immediately preceding replace op, or insert an empty one
262 let replaceOp = this.operations[ this.index - 1 ];
263 if ( !replaceOp || replaceOp.type !== 'replace' ) {
264 replaceOp = { type: 'replace', remove: [], insert: [] };
265 this.operations.splice( this.index, 0, replaceOp );
266 this.index++;
267 }
268 ve.batchSplice(
269 replaceOp.remove,
270 replaceOp.remove.length,
271 0,
272 removal
273 );
274 }
275 if ( tryUnsplit ) {
276 this.tryUnsplit();
277 }
278 this.readAttributes();
279 return len;
280 }
281 if ( this.op.type === 'replace' ) {
282 // Check removal against insertion, then cancel them out
283 const len = Math.min( items.length, this.op.insert.length - this.offset );
284 // len must be greater than zero, since we're not at the end of this op
285 const removal = items.slice( 0, len );
286 for ( let i = 0; i < len; i++ ) {
287 if ( !this.constructor.static.equalItems(
288 removal[ i ],
289 this.op.insert[ this.offset + i ]
290 ) ) {
291 throw new Error( 'Remove does not match insert' );
292 }
293 }
294 this.op.insert.splice( this.offset, len );
295 if ( this.op.remove.length === 0 && this.op.insert.length === 0 ) {
296 // Empty replacement: delete it
297 this.operations.splice( this.index, 1 );
298 this.op = this.operations[ this.index ];
299 // By assumption, this.offset is already 0
300 this.tryUnsplit();
301 }
302 this.readAttributes();
303 return len;
304 }
305 if ( this.op.type === 'attribute' ) {
306 // Apply the reversed attribute change to the item being removed
307 this.changeElement( items[ 0 ], this.op.key, this.op.to, this.op.from );
308 this.operations.splice( this.index, 1 );
309 this.op = this.operations[ this.index ];
310 // By assumption, this.offset is already 0
311 this.tryUnsplit();
312 return 0;
313 }
314 throw new Error( 'Unknown operation type ' + this.op.type );
315 };
316
317 /**
318 * Process the insertion of some items, stopping part-way if convenient
319 *
320 * If some of the insertion is undoing a removal in this.transaction, then the "cancelled"
321 * content effectively becomes part of an identity replacement: replace 'foo' with 'foo'.
322 * (The content cannot be stripped out entirely from the squashed transaction, because then
323 * the squashed transaction, considered as a partial function between documents, would have
324 * a larger preimage than the composition of the original transactions. This can probably
325 * break things like associativity).
326 *
327 * @private
328 * @param {Object[]} items Items to insert some of
329 * @return {number} The length of the initial slice of items that was inserted
330 */
331 ve.dm.TransactionSquasher.prototype.processInsert = function ( items ) {
332 this.normalizePosition();
333 if ( !this.op || this.op.type === 'retain' || this.op.type === 'attribute' ) {
334 if ( this.op && this.op.type === 'retain' ) {
335 // in a retain
336 this.splitIfInterior();
337 }
338 // We must be at the start of this.op (or at the end if !this.op)
339 // Get the immediately preceding replace op, or insert an empty one
340 let replaceOp = this.operations[ this.index - 1 ];
341 if ( !replaceOp || replaceOp.type !== 'replace' ) {
342 replaceOp = { type: 'replace', remove: [], insert: [] };
343 this.operations.splice( this.index, 0, replaceOp );
344 this.index++;
345 // By hypothesis, this.offset is already zero
346 }
347 ve.batchSplice(
348 replaceOp.insert,
349 replaceOp.insert.length,
350 0,
351 items
352 );
353 this.globalOffset += items.length;
354 this.attributeOperations = {};
355 return items.length;
356 }
357 if ( this.op.type === 'replace' ) {
358 // Do *not* try to cancel insertions against a matching prior removal,
359 // because it would cause the squashed transaction to "forget" prior
360 // linmod content that the original transaction pair requires. This
361 // breaks useful properties like associativity.
362 ve.batchSplice( this.op.insert, this.offset, 0, items );
363 this.offset += items.length;
364 this.globalOffset += items.length;
365 this.attributeOperations = {};
366 return items.length;
367 }
368 throw new Error( 'Unknown operation type ' + this.op.type );
369 };
370
371 /**
372 * Process the setting of an attribute
373 *
374 * The case from === to is possible. An identity attribute change still proves there is
375 * an open element at this position, so cannot be stripped
376 *
377 * @private
378 * @param {string} key The attribute key
379 * @param {any} from The old value
380 * @param {any} to The new value
381 */
382 ve.dm.TransactionSquasher.prototype.processAttribute = function ( key, from, to ) {
383 this.normalizePosition();
384 if ( this.op && this.op.type === 'replace' && this.offset < this.op.insert.length ) {
385 // If we're at some insert content, then the attribute should apply to it
386 const item = this.op.insert[ this.offset ];
387 if ( !item || !item.type || item.type[ 0 ] === '/' ) {
388 throw new Error( 'Expected open element' );
389 }
390 this.changeElement( this.op.insert[ this.offset ], key, from, to );
391 } else {
392 let op = this.attributeOperations[ key ];
393 if ( op ) {
394 if ( !this.constructor.static.equalItems( op.to, from ) ) {
395 throw new Error( 'Unexpected prior attribute value' );
396 }
397 // Modify in place
398 op.to = to;
399 } else {
400 op = {
401 type: 'attribute',
402 key: key,
403 from: from,
404 to: to
405 };
406 this.splitIfInterior();
407 this.operations.splice( this.index, 0, op );
408 this.attributeOperations[ key ] = op;
409 this.index++;
410 }
411 }
412 };
413
414 /**
415 * Change an attribute in an open element
416 *
417 * @private
418 * @param {Object} openElement The open element
419 * @param {string} key The attribute name
420 * @param {any} from Old value, or undefined if the attribute is being created
421 * @param {any} to New value, or undefined if the attribute is being removed
422 */
423 ve.dm.TransactionSquasher.prototype.changeElement = function ( openElement, key, from, to ) {
424 if ( !openElement.attributes ) {
425 openElement.attributes = {};
426 }
427 if ( !this.constructor.static.equalItems(
428 openElement.attributes[ key ],
429 from
430 ) ) {
431 throw new Error( 'Unexpected prior attribute value' );
432 }
433 if ( to === undefined ) {
434 delete openElement.attributes[ key ];
435 if ( !Object.keys( openElement.attributes ).length ) {
436 delete openElement.attributes;
437 }
438 } else {
439 openElement.attributes[ key ] = to;
440 }
441 };
442
443 /**
444 * Normalize .index, .offset and .op so we're not at the end of a replace/retain
445 *
446 * @private
447 */
448 ve.dm.TransactionSquasher.prototype.normalizePosition = function () {
449 while ( this.op && (
450 ( this.op.type === 'retain' && this.offset === this.op.length ) ||
451 ( this.op.type === 'replace' && this.offset === this.op.insert.length )
452 ) ) {
453 this.index++;
454 this.offset = 0;
455 // op may become undefined; ok
456 this.op = this.operations[ this.index ];
457 this.readAttributes();
458 }
459 };
460
461 /**
462 * Read the open element at the current offset (if any)
463 *
464 * Sets this.openElement to the open element (or null)
465 * Sets this.attribute to an object containing attribute key-values (or {})
466 *
467 * @private
468 */
469 ve.dm.TransactionSquasher.prototype.readAttributes = function () {
470 let index = this.index,
471 op = this.operations[ index ],
472 offset = this.offset;
473
474 this.attributeOperations = {};
475 while ( true ) {
476 if ( !op ) {
477 return;
478 }
479 if ( op.type === 'replace' ) {
480 if ( offset < op.insert.length ) {
481 // At an openElement, so there should be no attributeOperations
482 return;
483 }
484 } else if ( op.type === 'attribute' ) {
485 this.attributeOperations[ op.key ] = op;
486 } else if ( op.type === 'retain' && offset < op.length ) {
487 return;
488 }
489 // Else at the start of an insert / retain: step backwards
490 index++;
491 offset = 0;
492 op = this.operations[ index ];
493 }
494 };
495
496 /**
497 * If in the interior of a retain operation, split it here without moving.
498 *
499 * For retain, the length is split at the current offset (throws an error if at the end)
500 * For all other operations, throws an error if not at the start
501 *
502 * Afterwards, this.offset is guaranteed to be 0.
503 *
504 * @private
505 */
506 ve.dm.TransactionSquasher.prototype.splitIfInterior = function () {
507 const type = this.op && this.op.type;
508 if ( this.offset === 0 ) {
509 // No need to split
510 return;
511 }
512 if ( type !== 'retain' ) {
513 throw new Error( 'Non-zero offset, but op type is ' + type );
514 }
515 const len = this.op.length;
516 const remainder = len - this.offset;
517 if ( remainder < 0 ) {
518 throw new Error( 'Beyond the end of retain' );
519 }
520 if ( remainder === 0 ) {
521 throw new Error( 'Cannot split at the end of retain' );
522 }
523 this.op.length = this.offset;
524 this.index++;
525 this.offset = 0;
526 this.op = { type: 'retain', length: remainder };
527 this.operations.splice( this.index, 0, this.op );
528 };
529
530 /**
531 * If this operation and the previous one are retains, join them
532 *
533 * @private
534 */
535 ve.dm.TransactionSquasher.prototype.tryUnsplit = function () {
536 const prevOp = this.operations[ this.index - 1 ];
537 if ( !this.op || !prevOp ) {
538 return;
539 }
540 if ( prevOp.type === 'retain' && this.op.type === 'retain' ) {
541 this.offset += prevOp.length;
542 prevOp.length += this.op.length;
543 this.operations.splice( this.index, 1 );
544 this.index--;
545 this.op = prevOp;
546 } else if ( prevOp.type === 'replace' && this.op.type === 'replace' ) {
547 this.offset += prevOp.insert.length;
548 ve.batchSplice(
549 prevOp.remove,
550 prevOp.remove.length,
551 0,
552 this.op.remove
553 );
554 ve.batchSplice(
555 prevOp.insert,
556 prevOp.insert.length,
557 0,
558 this.op.insert
559 );
560 this.operations.splice( this.index, 1 );
561 this.index--;
562 this.op = prevOp;
563 }
564 // Else do nothing
565 };