Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Change class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel change.
9 *
10 * A change is a list of transactions to be applied sequentially on top of a certain history
11 * state, together with a set that includes all new store values (annotations and DOM elements)
12 * introduced by those transactions.
13 *
14 * It can be thought of more abstractly as a function f: D1 -> D2 a document in a
15 * specific start state D1, modifying parts of the document to produce a specific end state D2.
16 *
17 * For two changes f: D1 -> D2 and g: D2 -> D3 we define f.concat(g): D1 -> D3 as the change
18 * obtained by applying f then g. By associativity of functions,
19 * a.concat(b.concat(c)) = a.concat(b).concat(c) for any consecutive changes a, b, c. Writing
20 *
21 * x * y := x.concat(y) ,
22 *
23 * we have a * (b * c) = (a * b) * c, so we can just write either as a * b * c.
24 *
25 * For a change f: D1 -> D2 we define f.reversed() as the change D2 -> D1 such that
26 * f.concat(f.reversed()) is the identity change D1 -> D1. Writing
27 *
28 * inv(x) := x.reversed() ,
29 *
30 * we have f * inv(f) = the identity change on D1 .
31 *
32 * Given two changes f: D1 -> D2 and g: D1 -> D3 , We would like to define f.rebasedOnto(g)
33 * ("f rebased onto g") as a change that maps D3 onto some D4: conceptually, it is f
34 * modified so it can be applied after g. This is a useful concept because it allows changes
35 * written in parallel to be sequenced into a linear order. However, for some changes there
36 * is no reasonable way to do this; e.g. when f and g both change the same word to something
37 * different. In this case we make f.rebasedOnto(g) return null and we say it conflicts.
38 *
39 * Given f: D1 -> D2 , g: D2 -> D3, and x: D1 -> D4, we give three guarantees about rebasing:
40 *
41 * 1. x.rebasedOnto(f) conflicts if and only if f.rebasedOnto(x) conflicts.
42 * 2. If there is no conflict, f.concat(x.rebasedOnto(f)) equals x.concat(f.rebasedOnto(x)).
43 * 3. If there is no conflict, x.rebasedOnto(f).rebasedOnto(g) equals x.rebasedOnto(f * g).
44 *
45 * We can consider a conflicting transaction starting at some document D to be 0: D->null,
46 * and regard any two conflicting transactions starting at D to be equal, and just write 0
47 * where D1 is clear from context. Then, writing
48 *
49 * x|y := x.rebasedOnto(y),
50 *
51 * we can write our guarantees. Given f: D1 -> D2 , g: D2 -> D3, and x: D1 -> D4:
52 *
53 * 1. Change conflict well definedness: x|f = 0 if and only if f|x = 0.
54 * 2. Change commutativity: f * g|f equals g * f|g .
55 * 3. Rebasing piecewise: if (x|f)|g != 0, then (x|f)|g equals x|(f * g) .
56 *
57 * These guarantees let us reorder non-conflicting changes without affecting the resulting
58 * document. They also let us move in the inverse direction ("rebase under"), from sequential
59 * changes to parallel ones, for if f: D1 -> D2 and g: D2 -> D3, then g|inv(f)
60 * maps from D1 to some D4, and conceptually it is g modified to apply without f having been
61 * applied.
62 *
63 * Note that rebasing piecewise is *not* equivalent for changes that conflict: if a change
64 * conflicts f, it might not conflict with f*g. For example, if x|f = 0 then
65 *
66 * (x|f)|inv(f) = 0 but x|(f * inv(f)) = x.
67 *
68 * @class
69 * @constructor
70 * @param {number} [start] Length of the history stack at change start
71 * @param {ve.dm.Transaction[]} [transactions] Transactions to apply
72 * @param {ve.dm.HashValueStore[]} [stores] For each transaction, a collection of new store items
73 * @param {Object} [selections] For each author ID (key), latest ve.dm.Selection
74 */
75 ve.dm.Change = function VeDmChange( start, transactions, stores, selections ) {
76 this.start = start || 0;
77 this.transactions = transactions || [];
78 this.store = new ve.dm.HashValueStore();
79 this.storeLengthAtTransaction = [];
80 if ( stores ) {
81 stores.forEach( ( store ) => {
82 this.store.merge( store );
83 this.storeLengthAtTransaction.push( this.store.getLength() );
84 } );
85 }
86 this.selections = selections || {};
87 };
88
89 /* Static methods */
90
91 ve.dm.Change.static = {};
92
93 /**
94 * Deserialize a change from a JSONable object
95 *
96 * Store values can be deserialized, or kept verbatim; the latter is an optimization if the
97 * Change object will be rebased and reserialized without ever being applied to a document.
98 *
99 * @param {Object} data Change serialized as a JSONable object
100 * @param {boolean} [preserveStoreValues] Keep store values verbatim instead of deserializing
101 * @param {boolean} [unsafe] Use unsafe deserialization (skipping DOMPurify), used via #unsafeDeserialize
102 * @return {ve.dm.Change} Deserialized change
103 */
104 ve.dm.Change.static.deserialize = function ( data, preserveStoreValues, unsafe ) {
105 const hasOwn = Object.prototype.hasOwnProperty,
106 getTransactionInfo = this.getTransactionInfo,
107 deserializeValue = this.deserializeValue,
108 selections = {},
109 transactions = [],
110 // If stores is undefined, create an array of nulls
111 stores = data.stores || data.transactions.map( () => null );
112
113 /**
114 * Apply annotations in-place to array of code units
115 *
116 * @param {string[]} items Array of code units
117 * @param {string[]|null} annotations Annotations to apply uniformly, or null
118 */
119 function annotate( items, annotations ) {
120 if ( !annotations || !annotations.length ) {
121 return;
122 }
123 for ( let j = 0, jLen = items.length; j < jLen; j++ ) {
124 items[ j ] = [ items[ j ], annotations.slice() ];
125 }
126 }
127
128 for ( const authorId in data.selections ) {
129 selections[ authorId ] = ve.dm.Selection.static.newFromJSON(
130 data.selections[ authorId ]
131 );
132 }
133 const deserializeStore = ve.dm.HashValueStore.static.deserialize.bind(
134 null,
135 preserveStoreValues ? ( x ) => x : ( x ) => deserializeValue( x, unsafe )
136 );
137 let prevInfo;
138 for ( let i = 0, iLen = data.transactions.length; i < iLen; i++ ) {
139 const txSerialized = data.transactions[ i ];
140 let tx;
141 if ( typeof txSerialized === 'string' ) {
142 const insertion = txSerialized.split( '' );
143 annotate(
144 insertion,
145 prevInfo.uniformInsert && prevInfo.uniformInsert.annotations
146 );
147 tx = new ve.dm.Transaction( [
148 { type: 'retain', length: prevInfo.end },
149 { type: 'replace', remove: [], insert: insertion },
150 { type: 'retain', length: prevInfo.docLength - prevInfo.end }
151 ], prevInfo.authorId );
152 if ( tx.operations[ 2 ].length === 0 ) {
153 tx.operations.pop();
154 }
155 } else {
156 tx = ve.dm.Transaction.static.deserialize( txSerialized );
157 if ( prevInfo && !hasOwn.call( txSerialized, 'authorId' ) ) {
158 tx.authorId = prevInfo.authorId;
159 }
160 }
161 transactions.push( tx );
162 prevInfo = getTransactionInfo( tx );
163 }
164 return new ve.dm.Change(
165 data.start,
166 transactions,
167 stores.map( deserializeStore ),
168 selections
169 );
170 };
171
172 /**
173 * Deserialize a change from a JSONable object without sanitizing DOM nodes
174 *
175 * @param {Object} data
176 * @return {ve.dm.Change} Deserialized change
177 */
178 ve.dm.Change.static.unsafeDeserialize = function ( data ) {
179 return this.deserialize( data, false, true );
180 };
181
182 ve.dm.Change.static.serializeValue = function ( value ) {
183 if ( value instanceof ve.dm.Annotation ) {
184 return { type: 'annotation', value: value.element };
185 } else if ( Array.isArray( value ) && value[ 0 ] instanceof Node ) {
186 return { type: 'domNodes', value: value.map( ve.getNodeHtml ).join( '' ) };
187 } else {
188 return { type: 'plain', value: value };
189 }
190 };
191
192 ve.dm.Change.static.deserializeValue = function ( serialized, unsafe ) {
193 if ( serialized.type === 'annotation' ) {
194 return ve.dm.annotationFactory.createFromElement( serialized.value );
195 } else if ( serialized.type === 'domNodes' ) {
196 if ( unsafe ) {
197 // We can use jQuery here because unsafe sanitization
198 // only happens in browser clients.
199 // eslint-disable-next-line no-undef
200 return $.parseHTML( serialized.value, undefined, true );
201 } else {
202 // Convert NodeList to Array
203 return Array.prototype.slice.call( ve.sanitizeHtml( serialized.value ) );
204 }
205 } else if ( serialized.type === 'plain' ) {
206 return serialized.value;
207 } else {
208 throw new Error( 'Unrecognized type: ' + serialized.type );
209 }
210 };
211
212 /**
213 * Rebase parallel transactions transactionA and transactionB onto each other
214 *
215 * Recalling that a transaction is a mapping from one ve.dm.ElementLinearData state to another,
216 * suppose we have two parallel transactions, i.e.:
217 *
218 * - transactionA mapping docstate0 to some docstateA, and
219 * - transactionB mapping docstate0 to some docstateB .
220 *
221 * Then we want rebasing to give us two new transactions:
222 *
223 * - aRebasedOntoB mapping docstateB to some docstateC, and
224 * - bRebasedOntoA mapping docstateA to docstateC ,
225 *
226 * so that applying transactionA then bRebasedOntoA results in the same document state as
227 * applying transactionB then aRebasedOntoB .
228 *
229 * However, it is useful to regard some transaction pairs as "conflicting" or unrebasable. In
230 * this implementation, transactions are considered to conflict if they have active ranges that
231 * overlap, where a transaction's "active range" means the smallest single range in the *start*
232 * document outside which the contents are unchanged by the transaction. (In practice the
233 * operations within the transaction actually specify which ranges map to where, giving a
234 * natural and unambiguous definition of "active range". Also, the identity transaction on a
235 * document state has no active range but is trivially rebasable with any parallel
236 * transaction).
237 *
238 * For non-conflicting transactions, rebasing of each transaction is performed by resizing the
239 * inactive range either before or after the transaction to accommodate the length difference
240 * caused by the other transaction. There is ambiguity in the case where both transactions have
241 * a zero-length active range at the same position (i.e. two inserts in the same place); in this
242 * case, transactionA's insertion is put before transactionB's.
243 *
244 * It is impossible for rebasing defined this way to create an invalid transaction that breaks
245 * tree validity. This is clear because every position in the rebased transaction's active
246 * range has the same node ancestry as the corresponding position before the rebase (else a
247 * tag must have changed both before and after that position, contradicting the fact that the
248 * transactions' active ranges do not overlap).
249 *
250 * Also it is clear that for a pair of non-conflicting parallel transactions, applying either
251 * one followed by the other rebased will result in the same final document state, as required.
252 *
253 * @param {ve.dm.Transaction} transactionA Transaction A
254 * @param {ve.dm.Transaction} transactionB Transaction B, with the same document start state
255 * @return {any[]} [ aRebasedOntoB, bRebasedOntoA ], or [ null, null ] if conflicting
256 */
257 ve.dm.Change.static.rebaseTransactions = function ( transactionA, transactionB ) {
258 transactionA = transactionA.clone();
259 transactionB = transactionB.clone();
260 const infoA = transactionA.getActiveRangeAndLengthDiff();
261 const infoB = transactionB.getActiveRangeAndLengthDiff();
262
263 if ( infoA.start === undefined || infoB.start === undefined ) {
264 // One of the transactions is a no-op: only need to adjust its retain length.
265 // We can safely adjust both, because the no-op must have diff 0
266 transactionA.adjustRetain( 'start', infoB.diff );
267 transactionB.adjustRetain( 'start', infoA.diff );
268 } else if ( infoA.end <= infoB.start ) {
269 // This includes the case where both transactions are insertions at the same
270 // point
271 transactionB.adjustRetain( 'start', infoA.diff );
272 transactionA.adjustRetain( 'end', infoB.diff );
273 } else if ( infoB.end <= infoA.start ) {
274 transactionA.adjustRetain( 'start', infoB.diff );
275 transactionB.adjustRetain( 'end', infoA.diff );
276 } else {
277 // The active ranges overlap: conflict
278 return [ null, null ];
279 }
280 return [ transactionA, transactionB ];
281 };
282
283 /**
284 * @typedef {Object} RebasedChange
285 * @memberof ve.dm.Change
286 * @property {ve.dm.Change} rebased Rebase onto history of uncommitted (or an initial segment of it)
287 * @property {ve.dm.Change} transposedHistory Rebase of history onto initial segment of uncommitted
288 * @property {ve.dm.Change|null} rejected Unrebasable final segment of uncommitted
289 */
290
291 /**
292 * Rebase a change on top of a parallel committed one
293 *
294 * Since a change is a stack of transactions, we define change rebasing in terms of transaction
295 * rebasing. We require transaction rebasing to meet the three guarantees described above for
296 * change rebasing. To be precise, given any transactions a:D1->D2, b:D2->D3 and x:D1->D4, we
297 * require that:
298 *
299 * 1. Transaction conflict well definedness: a|x = 0 if and only if x|a = 0.
300 * 2. Transaction commutativity: a * x|a equals x * a|x .
301 * 3. Rebasing piecewise: if (x|a)|b != 0, then (x|a)|b equals x|(a * b) .
302 *
303 * Given committed history consisting of transactions a1,a2,…,aN, and an uncommitted update
304 * consisting of transactions b1,b2,…,bM, our approach is to rebase the whole list a1,…,aN
305 * over b1, and at the same time rebase b1 onto a1*…*aN.
306 * Then we repeat the process for b2, and so on. To rebase a1,…,aN over b1, the following
307 * approach would work:
308 *
309 * a1' := a1|b1
310 * a2' := a2|(inv(a1) * b1 * a1')
311 * a3' := a3|(inv(a2) * inv(a1) * b1 * a1' * a2')
312 * â‹®
313 *
314 * That is, rebase a_i under a_i-1,…,a_1, then over b1,…,bM, then over a'1,…,a_i-1' .
315 *
316 * However, because of the way transactions are written, it's not actually easy to implement
317 * transaction concatenation, so we would want to calculate a2' as piecewise rebases
318 *
319 * a2' = ((a2|inv(a1))|b1)|a1'
320 *
321 * which is unsatisfactory because a2|inv(a1) may well conflict even if a2|(inv(a1) * b1 * a1')
322 * as a whole would not conflict (e.g. if b1 modifies only parts of the document distant from a1
323 * and a2).
324 *
325 * So observe that by transaction commutivity we can rewrite a2' as:
326 *
327 * a2' := a2|(inv(a1) * a1 * b1|a1)
328 * = a2|(b1|a1)
329 *
330 * and that b1|a1 conflicts only if a1|b1 conflicts (so this introduces no new conflicts). In
331 * general we can write:
332 *
333 * a1' := a1|b1
334 * b1' := b1|a1
335 * a2' := a2|b1'
336 * b1'' := b1'|a2
337 * a3' := a3|b1''
338 * b1''' := a1''|a3
339 *
340 * Continuing in this way, we obtain a1',…,aN' rebased over b1, and b1''''''' (N primes)
341 * rebased onto a1 * … * aN . Iteratively we can take the same approach to rebase over
342 * b2,…,bM, giving both rebased lists as required.
343 *
344 * If any of the transaction rebases conflict, then we rebase the largest possible
345 * non-conflicting initial segment b1,…,bK onto all of a1,…,aN (so clearly K < M).
346 *
347 * If there are two parallel inserts at the same location, then ordering is ambiguous. We
348 * resolve this by putting the insert for the transaction with the highest author ID
349 * first (Javascript less-than is used, so comparisons with a null author ID do not fail).
350 * If the author IDs are the same, then A's insertion is put before B's.
351 *
352 * @param {ve.dm.Change} history Committed history
353 * @param {ve.dm.Change} uncommitted New transactions, with same start as history
354 * @return {ve.dm.Change.RebasedChange}
355 */
356 ve.dm.Change.static.rebaseUncommittedChange = function ( history, uncommitted ) {
357 if ( history.start !== uncommitted.start ) {
358 throw new Error( 'Different starts: ' + history.start + ' and ' + uncommitted.start );
359 }
360
361 let transactionsA = history.transactions.slice();
362 const transactionsB = uncommitted.transactions.slice();
363 let storesA = history.getStores();
364 const storesB = uncommitted.getStores();
365 const selectionsA = ve.cloneObject( history.selections );
366 let selectionsB = ve.cloneObject( uncommitted.selections );
367 let rejected = null;
368
369 // For each element b_i of transactionsB, rebase the whole list transactionsA over b_i.
370 // To rebase a1, a2, a3, …, aN over b_i, first we rebase a1 onto b_i. Then we rebase
371 // a2 onto some b', defined as
372 //
373 // b_i' := b_i|a1 , that is b_i.rebasedOnto(a1)
374 //
375 // (which as proven above is equivalent to inv(a1) * b_i * a1)
376 //
377 // Similarly we rebase a3 onto b_i'' := b_i'|a2, and so on.
378 //
379 // The rebased a_j are used for the transposed history: they will all get rebased over the
380 // rest of transactionsB in the same way.
381 // The fully rebased b_i forms the i'th element of the rebased transactionsB.
382 //
383 // If any rebase b_i|a_j fails, we stop rebasing at b_i (i.e. finishing with b_{i-1}).
384 // We return
385 // - rebased: (uncommitted sliced up to i) rebased onto history
386 // - transposedHistory: history rebased onto (uncommitted sliced up to i)
387 // - rejected: uncommitted sliced from i onwards
388 bLoop:
389 for ( let i = 0, iLen = transactionsB.length; i < iLen; i++ ) {
390 let b = transactionsB[ i ];
391 let storeB = storesB[ i ];
392 const rebasedTransactionsA = [];
393 const rebasedStoresA = [];
394 for ( let j = 0, jLen = transactionsA.length; j < jLen; j++ ) {
395 const a = transactionsA[ j ];
396 const storeA = storesA[ j ];
397 let rebases;
398 if ( b.authorId < a.authorId ) {
399 rebases = ve.dm.Change.static.rebaseTransactions( b, a ).reverse();
400 } else {
401 rebases = ve.dm.Change.static.rebaseTransactions( a, b );
402 }
403 if ( rebases[ 0 ] === null ) {
404 rejected = uncommitted.mostRecent( uncommitted.start + i );
405 transactionsB.length = i;
406 storesB.length = i;
407 selectionsB = {};
408 break bLoop;
409 }
410 rebasedTransactionsA[ j ] = rebases[ 0 ];
411 rebasedStoresA[ j ] = storeA.difference( storeB );
412 b = rebases[ 1 ];
413 storeB = storeB.difference( storeA );
414 }
415 transactionsA = rebasedTransactionsA;
416 storesA = rebasedStoresA;
417 transactionsB[ i ] = b;
418 storesB[ i ] = storeB;
419 }
420
421 // Length calculations below assume no removal of empty rebased transactions
422 const rebased = new ve.dm.Change(
423 uncommitted.start + transactionsA.length,
424 transactionsB,
425 storesB,
426 {}
427 );
428 const transposedHistory = new ve.dm.Change(
429 history.start + transactionsB.length,
430 transactionsA,
431 storesA,
432 {}
433 );
434 let authorId;
435 for ( authorId in selectionsB ) {
436 authorId = +authorId;
437 rebased.selections[ authorId ] = selectionsB[ authorId ].translateByChange( transposedHistory, authorId );
438 }
439 for ( authorId in selectionsA ) {
440 authorId = +authorId;
441 transposedHistory.selections[ authorId ] = selectionsA[ authorId ].translateByChange( rebased, authorId );
442 }
443 return {
444 rebased: rebased,
445 transposedHistory: transposedHistory,
446 rejected: rejected
447 };
448 };
449
450 /**
451 * @typedef UniformTextInfo
452 * @memberof ve.dm.Change
453 * @property {string} text The code units, in a single string
454 * @property {string} annotations Annotation hashes for all text
455 * @property {string} annotationString Comma-separated annotation hashes
456 */
457
458 /**
459 * @typedef TransactionInfo
460 * @memberof ve.dm.Change
461 * @property {number} start The start offset of the replacement
462 * @property {number} end The end offset of the replacement (after replacement)
463 * @property {number} docLength The total length of the document (after replacement)
464 * @property {number} authorId The author ID
465 * @property {ve.dm.Change.UniformTextInfo|null} uniformInsert The insertion as uniform text, or null if not
466 */
467
468 /**
469 * Get info about a transaction if it is a "simple replacement", or null if not
470 *
471 * A simple replacement transaction is one that has just one retain op
472 *
473 * @param {ve.dm.Transaction} tx The transaction
474 * @return {ve.dm.Change.TransactionInfo|null} Info about the transaction if a simple replacement, else null
475 */
476 ve.dm.Change.static.getTransactionInfo = function ( tx ) {
477 // Copy of ve.dm.ElementLinearData.static.getAnnotationHashesFromItem, but we
478 // don't want to load all of ElementLinearData and its dependencies on the server-side.
479 function getAnnotations( item ) {
480 if ( typeof item === 'string' ) {
481 return [];
482 } else if ( item.annotations ) {
483 return item.annotations.slice();
484 } else if ( item[ 1 ] ) {
485 return item[ 1 ].slice();
486 } else {
487 return [];
488 }
489 }
490
491 /**
492 * Get an item's single code unit (without annotation), or null if not a code unit
493 *
494 * @param {Object|Array|string} item The item
495 * @return {string|null} The single code unit, or null if not a code unit
496 */
497 function getSingleCodeUnit( item ) {
498 if ( typeof item === 'string' && item.length === 1 ) {
499 return item;
500 }
501 if ( Array.isArray( item ) && item[ 0 ].length === 1 ) {
502 return item[ 0 ];
503 }
504 return null;
505 }
506
507 /**
508 * Get info about the "uniform text" from an item array, or null if not uniform text
509 *
510 * The item array is uniform text if all items have the same annotations, and
511 * every item is a single code unit of text
512 *
513 * @param {Array} items The items
514 * @return {ve.dm.Change.UniformTextInfo|null} Info about the uniform text, or null if not uniform text
515 */
516 function getUniformText( items ) {
517 const codeUnits = [];
518 if ( items.length === 0 ) {
519 return null;
520 }
521 let codeUnit = getSingleCodeUnit( items[ 0 ] );
522 if ( codeUnit === null ) {
523 return null;
524 }
525 codeUnits.push( codeUnit );
526 const annotations = getAnnotations( items[ 0 ] );
527 const annotationString = annotations.join( ',' );
528 for ( let i = 1, iLen = items.length; i < iLen; i++ ) {
529 codeUnit = getSingleCodeUnit( items[ i ] );
530 if ( codeUnit === null ) {
531 return null;
532 }
533 codeUnits.push( codeUnit );
534 if ( annotationString !== getAnnotations( items[ i ] ).join( ',' ) ) {
535 return null;
536 }
537 }
538 return {
539 text: codeUnits.join( '' ),
540 annotations: annotations,
541 annotationString: annotationString
542 };
543 }
544
545 const op0 = tx.operations[ 0 ];
546 const op1 = tx.operations[ 1 ];
547 const op2 = tx.operations[ 2 ];
548 let replaceOp, start, end, docLength;
549 if (
550 op0 &&
551 op0.type === 'replace' &&
552 ( !op1 || op1.type === 'retain' ) &&
553 !op2
554 ) {
555 replaceOp = op0;
556 start = 0;
557 end = start + replaceOp.insert.length;
558 docLength = end;
559 } else if (
560 op0 &&
561 op0.type === 'retain' &&
562 op1 &&
563 op1.type === 'replace' &&
564 ( !op2 || op2.type === 'retain' )
565 ) {
566 replaceOp = op1;
567 start = op0.length;
568 end = start + replaceOp.insert.length;
569 docLength = end + ( op2 ? op2.length : 0 );
570 } else {
571 return null;
572 }
573
574 return {
575 start: start,
576 end: end,
577 docLength: docLength,
578 authorId: tx.authorId,
579 uniformInsert: getUniformText( replaceOp.insert )
580 };
581 };
582
583 /* Methods */
584
585 /**
586 * Create a clone of this Change
587 *
588 * @return {ve.dm.Change} Clone of this change
589 */
590 ve.dm.Change.prototype.clone = function () {
591 return this.constructor.static.unsafeDeserialize( this.toJSON() );
592 };
593
594 /**
595 * @return {boolean} True if this change has no transactions or selections
596 */
597 ve.dm.Change.prototype.isEmpty = function () {
598 return this.transactions.length === 0 && Object.keys( this.selections ).length === 0;
599 };
600
601 /**
602 * @return {number} The number of transactions
603 */
604 ve.dm.Change.prototype.getLength = function () {
605 return this.transactions.length;
606 };
607
608 /**
609 * Get the store items introduced by transaction n
610 *
611 * @param {number} n The index of a transaction within the change
612 * @return {ve.dm.HashValueStore} The store items introduced by transaction n
613 */
614 ve.dm.Change.prototype.getStore = function ( n ) {
615 return this.store.slice(
616 n > 0 ? this.storeLengthAtTransaction[ n - 1 ] : 0,
617 this.storeLengthAtTransaction[ n ]
618 );
619 };
620
621 /**
622 * Get the stores for each transaction
623 *
624 * @return {ve.dm.HashValueStore[]} Each transaction's store items (shallow copied store)
625 */
626 ve.dm.Change.prototype.getStores = function () {
627 const stores = [];
628 let start = 0;
629 for ( let i = 0, len = this.getLength(); i < len; i++ ) {
630 const end = this.storeLengthAtTransaction[ i ];
631 stores.push( this.store.slice( start, end ) );
632 start = end;
633 }
634 return stores;
635 };
636
637 /**
638 * @return {number|null} The first author in a transaction or selection change, or null if empty
639 */
640 ve.dm.Change.prototype.firstAuthorId = function () {
641 if ( this.transactions.length ) {
642 return this.transactions[ 0 ].authorId;
643 }
644 const authors = Object.keys( this.selections );
645 if ( authors.length ) {
646 return +authors[ 0 ];
647 }
648 return null;
649 };
650
651 /**
652 * Get a human-readable summary of the change
653 *
654 * @return {string} Human-readable summary
655 */
656 ve.dm.Change.prototype.summarize = function () {
657 return '{ start: ' + this.start + ', txs: [ ' +
658 this.transactions.map( ( tx ) => tx.summarize() ).join( ', ' ) + ' ] }';
659 };
660
661 /**
662 * Get the change that backs out this change.
663 *
664 * Note that applying it will not revert start or remove stored items
665 *
666 * @return {ve.dm.Change} The change that backs out this change
667 */
668 ve.dm.Change.prototype.reversed = function () {
669 return new ve.dm.Change(
670 this.start + this.transactions.length,
671 this.transactions.map( ( tx ) => ve.dm.Transaction.prototype.reversed.call( tx ) ).reverse(),
672 // Empty store for each transaction (reverting cannot possibly add new annotations)
673 this.transactions.map( () => new ve.dm.HashValueStore() ),
674 {}
675 );
676 };
677
678 /**
679 * Rebase this change onto other (ready to apply on top of other)
680 *
681 * @param {ve.dm.Change} other Other change
682 * @return {ve.dm.Change|null} Rebased change applicable on top of other, or null if rebasing fails
683 * @throws {Error} If this change and other have different starts
684 */
685 ve.dm.Change.prototype.rebasedOnto = function ( other ) {
686 const rebases = this.constructor.static.rebaseUncommittedChange( other, this );
687 return rebases.rejected ? null : rebases.rebased;
688 };
689
690 /**
691 * Build a composite change from two consecutive changes
692 *
693 * @param {ve.dm.Change} other Change that starts immediately after this
694 * @return {ve.dm.Change} Composite change
695 * @throws {Error} If other does not start immediately after this
696 */
697 ve.dm.Change.prototype.concat = function ( other ) {
698 if ( other.start !== this.start + this.transactions.length ) {
699 throw new Error( 'this ends at ' + ( this.start + this.transactions.length ) +
700 ' but other starts at ' + other.start );
701 }
702 return new ve.dm.Change(
703 this.start,
704 this.transactions.concat( other.transactions ),
705 this.getStores().concat( other.getStores() ),
706 other.selections
707 );
708 };
709
710 /**
711 * Push a transaction, after having grown the hash value store if required
712 *
713 * @param {ve.dm.Transaction} transaction The transaction
714 * @param {number} storeLength The corresponding store length required
715 */
716 ve.dm.Change.prototype.pushTransaction = function ( transaction, storeLength ) {
717 if ( typeof storeLength !== 'number' ) {
718 throw new Error( 'Expected numerical storeLength argument, not ' + storeLength );
719 }
720 this.transactions.push( transaction );
721 this.storeLengthAtTransaction.push( storeLength );
722 };
723
724 /**
725 * Push another change onto this change
726 *
727 * @param {ve.dm.Change} other Change that starts immediately after this
728 * @throws {Error} If other does not start immediately after this
729 */
730 ve.dm.Change.prototype.push = function ( other ) {
731 if ( other.start !== this.start + this.getLength() ) {
732 throw new Error( 'this ends at ' + ( this.start + this.getLength() ) +
733 ' but other starts at ' + other.start );
734 }
735 const stores = other.getStores();
736 for ( let i = 0, iLen = other.transactions.length; i < iLen; i++ ) {
737 const transaction = other.transactions[ i ];
738 const store = stores[ i ];
739 this.store.merge( store );
740 this.pushTransaction( transaction, this.store.getLength() );
741 }
742 this.selections = ve.cloneObject( other.selections );
743 };
744
745 /**
746 * Build a composite change from two parallel changes
747 *
748 * @param {ve.dm.Change} other Change parallel to this
749 * @return {ve.dm.Change} Composite change
750 * @throws {Error} If this change and other have different starts
751 */
752 ve.dm.Change.prototype.concatRebased = function ( other ) {
753 return this.concat( other.rebasedOnto( this ) );
754 };
755
756 /**
757 * Build a change from the last (most recent) transactions
758 *
759 * @param {number} start Start offset
760 * @return {ve.dm.Change} Subset of this change with only the most recent transactions
761 */
762 ve.dm.Change.prototype.mostRecent = function ( start ) {
763 if ( arguments.length > 1 ) {
764 throw new Error( 'storeStart is no longer needed' );
765 }
766 return new ve.dm.Change(
767 start,
768 this.transactions.slice( start - this.start ),
769 this.getStores().slice( start - this.start ),
770 ve.cloneObject( this.selections )
771 );
772 };
773
774 /**
775 * Build a change from the first (least recent) transactions of this change.
776 *
777 * Always removes selections.
778 *
779 * @param {number} length Number of transactions
780 * @return {ve.dm.Change} Subset of this change with only the least recent transactions
781 */
782 ve.dm.Change.prototype.truncate = function ( length ) {
783 if ( arguments.length > 1 ) {
784 throw new Error( 'storeLength is no longer needed' );
785 }
786 return new ve.dm.Change(
787 this.start,
788 this.transactions.slice( 0, length ),
789 this.getStores().slice( 0, length ),
790 {}
791 );
792 };
793
794 /**
795 * Apply change to surface
796 *
797 * @param {ve.dm.Surface} surface Surface in change start state
798 * @param {boolean} [applySelection] Apply a selection based on the modified range
799 */
800 ve.dm.Change.prototype.applyTo = function ( surface, applySelection ) {
801 const doc = surface.getDocument();
802 if ( this.start !== doc.completeHistory.getLength() ) {
803 throw new Error( 'Change starts at ' + this.start + ', but doc is at ' + doc.completeHistory.getLength() );
804 }
805 this.getStores().forEach( ( store ) => {
806 doc.store.merge( store );
807 } );
808 // Isolate other users' changes from ours with a breakpoint
809 surface.breakpoint();
810 this.transactions.forEach( ( tx ) => {
811 surface.change( tx );
812 // Don't mark as applied: this.start already tracks this
813 tx.applied = false;
814
815 // TODO: This would be better fixed by T202730
816 if ( applySelection ) {
817 const range = tx.getModifiedRange( doc );
818 // If the transaction only touched the internal list, there is no modified range within the main document
819 if ( range ) {
820 const offset = doc.getNearestCursorOffset( range.end, -1 );
821 if ( offset !== -1 ) {
822 surface.setSelection( new ve.dm.LinearSelection( new ve.Range( offset ) ) );
823 }
824 }
825 }
826 } );
827 surface.breakpoint();
828 };
829
830 /**
831 * Unapply change to surface, including truncating history and store
832 *
833 * @param {ve.dm.Surface} surface Surface in change end state
834 */
835 ve.dm.Change.prototype.unapplyTo = function ( surface ) {
836 const doc = surface.getDocument(),
837 historyLength = doc.completeHistory.getLength() - this.getLength();
838 if ( this.start !== historyLength ) {
839 throw new Error( 'Invalid start: change starts at ' + this.start + ', but doc would be at ' + historyLength );
840 }
841 this.transactions.slice().reverse().forEach( ( tx ) => {
842 surface.change( tx.reversed() );
843 } );
844 doc.completeHistory.transactions.length = historyLength;
845 doc.completeHistory.storeLengthAtTransaction.length = historyLength;
846 doc.store.truncate( doc.completeHistory.storeLengthAtTransaction[ historyLength - 1 ] );
847 };
848
849 /**
850 * Append change transactions to history
851 *
852 * @param {ve.dm.Document} documentModel
853 * @throws {Error} If this change does not start at the top of the history
854 */
855 ve.dm.Change.prototype.addToHistory = function ( documentModel ) {
856 documentModel.completeHistory.push( this );
857 };
858
859 /**
860 * Remove change transactions from history
861 *
862 * @param {ve.dm.Document} doc
863 * @throws {Error} If this change does not end at the top of the history
864 */
865 ve.dm.Change.prototype.removeFromHistory = function ( doc ) {
866 if ( this.start + this.getLength() !== doc.completeHistory.getLength() ) {
867 throw new Error( 'this ends at ' + ( this.start + this.getLength() ) +
868 ' but history ends at ' + doc.completeHistory.getLength() );
869 }
870 doc.completeHistory.transactions.length -= this.transactions.length;
871 doc.completeHistory.storeLengthAtTransaction.length -= this.transactions.length;
872 doc.store.truncate( doc.completeHistory.storeLengthAtTransaction[ doc.completeHistory.getLength() - 1 ] );
873 };
874
875 /**
876 * Serialize the change to a JSONable object
877 *
878 * Store values can be serialized, or kept verbatim (which only makes sense if they are serialized
879 * already, i.e. the Change object was created by #deserialize without deserializing store values).
880 *
881 * @param {boolean} [preserveStoreValues] If true, keep store values verbatim instead of serializing
882 * @return {Object} JSONable object
883 */
884 ve.dm.Change.prototype.serialize = function ( preserveStoreValues ) {
885 const getTransactionInfo = this.constructor.static.getTransactionInfo,
886 selections = {},
887 transactions = [];
888
889 // Recursively serialize, so this method is the inverse of deserialize
890 // without having to use JSON.stringify (which is also recursive).
891 for ( const authorId in this.selections ) {
892 selections[ authorId ] = this.selections[ authorId ].toJSON();
893 }
894 const serializeStoreValues = preserveStoreValues ? function noop( x ) {
895 return x;
896 } : this.constructor.static.serializeValue;
897 const serializeStore = function ( store ) {
898 return store.serialize( serializeStoreValues );
899 };
900 let prevInfo;
901 for ( let i = 0, iLen = this.transactions.length; i < iLen; i++ ) {
902 const tx = this.transactions[ i ];
903 const info = getTransactionInfo( tx );
904 if (
905 info &&
906 prevInfo &&
907 info.authorId === prevInfo.authorId &&
908 info.start === prevInfo.end &&
909 info.uniformInsert &&
910 prevInfo.uniformInsert &&
911 info.uniformInsert.annotationString === prevInfo.uniformInsert.annotationString
912 ) {
913 transactions.push( info.uniformInsert.text );
914 } else {
915 const txSerialized = tx.toJSON();
916 if ( i > 0 && tx.authorId === this.transactions[ i - 1 ].authorId ) {
917 delete txSerialized.authorId;
918 }
919 transactions.push( txSerialized );
920 }
921 prevInfo = info;
922 }
923 const stores = this.getStores().map( serializeStore );
924 const data = {
925 start: this.start,
926 transactions: transactions
927 };
928 // Only set stores if at least one is non-null
929 if ( stores.some( ( store ) => store !== null ) ) {
930 data.stores = stores;
931 }
932 if ( Object.keys( selections ).length ) {
933 data.selections = selections;
934 }
935 return data;
936 };
937
938 /**
939 * Called automatically by JSON.stringify, see #serialize.
940 *
941 * @param {string} [key] Key in parent object
942 * @return {Object} JSONable object
943 */
944 ve.dm.Change.prototype.toJSON = function () {
945 // Ensure no native arguments are passed through to #serialize.
946 return this.serialize();
947 };
948
949 /**
950 * Get a Change with all this Change's Transactions compacted into one (or zero)
951 *
952 * The Change has the same effect when applied as this Change does, but it may cause
953 * rebase conflicts where this change does not.
954 *
955 * TODO: introduce a "histLength" feature so the new change can be considered as
956 * having length > 1.
957 *
958 * @return {ve.dm.Change} One-Transaction version of this Change (or empty change)
959 */
960 ve.dm.Change.prototype.squash = function () {
961 if ( this.transactions.length <= 1 ) {
962 return this.clone();
963 }
964 return new ve.dm.Change(
965 this.start,
966 [ ve.dm.TransactionSquasher.static.squash( this.transactions ) ],
967 [ this.store.slice() ],
968 // Shallow clone (the individual selections are immutable so need no cloning)
969 ve.cloneObject( this.selections )
970 );
971 };