Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Transaction builder class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Transaction builder: build transactions based on current ve.dm.Document state
9 *
10 * @class
11 * @constructor
12 */
13 ve.dm.TransactionBuilder = function VeDmTransactionBuilder() {
14 // TODO: rewrite to store the current ve.dm.Document as a property
15 this.transaction = new ve.dm.Transaction();
16 };
17
18 /* Inheritance */
19
20 OO.initClass( ve.dm.TransactionBuilder );
21
22 /* Static Methods */
23
24 /**
25 * Generate a transaction that replaces data in a range.
26 *
27 * @param {ve.dm.Document} doc Document in pre-transaction state
28 * @param {ve.Range} range Range of data to remove
29 * @param {Array} data Data to insert
30 * @param {boolean} [removeMetadata=false] Remove metadata instead of collapsing it
31 * @return {ve.dm.Transaction} Transaction that replaces data
32 * @throws {Error} Invalid range
33 */
34 ve.dm.TransactionBuilder.static.newFromReplacement = function ( doc, range, data, removeMetadata ) {
35 const txBuilder = new ve.dm.TransactionBuilder();
36 let endOffset = txBuilder.pushRemoval( doc, 0, range, removeMetadata );
37 endOffset = txBuilder.pushInsertion( doc, endOffset, endOffset, data );
38 txBuilder.pushFinalRetain( doc, endOffset );
39 return txBuilder.getTransaction();
40 };
41
42 /**
43 * Generate a transaction that inserts data at an offset.
44 *
45 * @static
46 * @param {ve.dm.Document} doc Document in pre-transaction state
47 * @param {number} offset Offset to insert at
48 * @param {Array} data Data to insert
49 * @return {ve.dm.Transaction} Transaction that inserts data
50 */
51 ve.dm.TransactionBuilder.static.newFromInsertion = function ( doc, offset, data ) {
52 const txBuilder = new ve.dm.TransactionBuilder(),
53 endOffset = txBuilder.pushInsertion( doc, 0, offset, data );
54 // Retain to end of document, if needed (for completeness)
55 txBuilder.pushFinalRetain( doc, endOffset );
56 return txBuilder.getTransaction();
57 };
58
59 /**
60 * Generate a transaction that removes data from a range.
61 *
62 * There are three possible results from a removal:
63 *
64 * - Remove content only
65 * - Occurs when the range starts and ends on elements of different type, depth or ancestry
66 * - Remove entire elements and their content
67 * - Occurs when the range spans across an entire element
68 * - Merge two elements by removing the end of one and the beginning of another
69 * - Occurs when the range starts and ends on elements of similar type, depth and ancestry
70 *
71 * This function uses the following logic to decide what to actually remove:
72 *
73 * 1. Elements are only removed if range being removed covers the entire element
74 * 2. Elements can only be merged if {@link ve.dm.Node#canBeMergedWith} returns true
75 * 3. Merges take place at the highest common ancestor
76 *
77 * @param {ve.dm.Document} doc Document in pre-transaction state
78 * @param {ve.Range} range Range of data to remove
79 * @param {boolean} [removeMetadata=false] Remove metadata instead of collapsing it
80 * @return {ve.dm.Transaction} Transaction that removes data
81 * @throws {Error} Invalid range
82 */
83 ve.dm.TransactionBuilder.static.newFromRemoval = function ( doc, range, removeMetadata ) {
84 const txBuilder = new ve.dm.TransactionBuilder();
85
86 let endOffset = txBuilder.pushRemoval( doc, 0, range, removeMetadata );
87 // Ensure no transaction leaves the document in a completely empty state
88 if ( range.start === 0 && range.end >= doc.getDocumentRange().end ) {
89 endOffset = txBuilder.pushInsertion( doc, endOffset, endOffset, [
90 { type: 'paragraph' },
91 { type: '/paragraph' }
92 ] );
93 }
94
95 // Retain to end of document, if needed (for completeness)
96 txBuilder.pushFinalRetain( doc, endOffset );
97 return txBuilder.getTransaction();
98 };
99
100 /**
101 * Build a transaction that inserts the contents of a document at a given offset.
102 *
103 * This is typically used to merge changes to a document slice back into the main document. If newDoc
104 * is a document slice of doc, it's assumed that there were no changes to doc's internal list since
105 * the slice, so any differences between internal items that doc and newDoc have in common will
106 * be resolved in newDoc's favor.
107 *
108 * @param {ve.dm.Document} doc Main document in the state to which the transaction start applies
109 * @param {number} offset Offset to insert at
110 * @param {ve.dm.Document} newDoc Document to insert
111 * @param {ve.Range} [newDocRange] Range from the new document to insert (defaults to entire document)
112 * @return {ve.dm.Transaction} Transaction that inserts the nodes and updates the internal list
113 */
114 ve.dm.TransactionBuilder.static.newFromDocumentInsertion = function ( doc, offset, newDoc, newDocRange ) {
115 const listNode = doc.internalList.getListNode(),
116 listNodeRange = listNode.getRange(),
117 newListNode = newDoc.internalList.getListNode(),
118 newListNodeRange = newListNode.getRange(),
119 newListNodeOuterRange = newListNode.getOuterRange();
120
121 let data;
122 if ( newDocRange ) {
123 data = new ve.dm.ElementLinearData( doc.getStore(), newDoc.getData( newDocRange, true ) );
124 } else {
125 // Get the data, but skip over the internal list
126 data = new ve.dm.ElementLinearData( doc.getStore(),
127 newDoc.getData( new ve.Range( 0, newListNodeOuterRange.start ), true ).concat(
128 newDoc.getData( new ve.Range( newListNodeOuterRange.end, newDoc.data.getLength() ), true )
129 )
130 );
131 }
132
133 // Merge the stores
134 doc.getStore().merge( newDoc.getStore() );
135
136 const listMerge = doc.internalList.merge( newDoc.internalList, newDoc.origInternalListLength || 0 );
137 // Remap the indexes in the data
138 data.remapInternalListIndexes( listMerge.mapping, doc.internalList );
139 // Get data for the new internal list
140 let linearData, listData;
141 if ( newDoc.origInternalListLength !== null ) {
142 // newDoc is a document slice based on doc, so all the internal list items present in doc
143 // when it was cloned are also in newDoc. We need to get the newDoc version of these items
144 // so that changes made in newDoc are reflected.
145 let oldEndOffset, newEndOffset;
146 if ( newDoc.origInternalListLength > 0 ) {
147 oldEndOffset = doc.internalList.getItemNode( newDoc.origInternalListLength - 1 ).getOuterRange().end;
148 newEndOffset = newDoc.internalList.getItemNode( newDoc.origInternalListLength - 1 ).getOuterRange().end;
149 } else {
150 oldEndOffset = listNodeRange.start;
151 newEndOffset = newListNodeRange.start;
152 }
153 linearData = new ve.dm.ElementLinearData(
154 doc.getStore(),
155 newDoc.getData( new ve.Range( newListNodeRange.start, newEndOffset ), true )
156 );
157 listData = linearData.data
158 .concat( doc.getData( new ve.Range( oldEndOffset, listNodeRange.end ), true ) );
159 } else {
160 // newDoc is brand new, so use doc's internal list as a base
161 listData = doc.getData( listNodeRange, true );
162 }
163 for ( let i = 0, len = listMerge.newItemRanges.length; i < len; i++ ) {
164 linearData = new ve.dm.ElementLinearData(
165 doc.getStore(),
166 newDoc.getData( listMerge.newItemRanges[ i ], true )
167 );
168 ve.batchPush( listData, linearData.data );
169 }
170
171 const txBuilder = new ve.dm.TransactionBuilder();
172
173 let insertion;
174 if ( offset <= listNodeRange.start ) {
175 // offset is before listNodeRange
176 // First replace the node, then the internal list
177
178 // Fix up the node insertion
179 insertion = doc.fixupInsertion( data.data, offset );
180 txBuilder.pushRetain( insertion.offset );
181 txBuilder.pushReplacement( doc, insertion.offset, insertion.remove, insertion.data, true );
182 txBuilder.pushRetain( listNodeRange.start - ( insertion.offset + insertion.remove ) );
183 txBuilder.pushReplacement( doc, listNodeRange.start, listNodeRange.end - listNodeRange.start,
184 listData, true
185 );
186 txBuilder.pushFinalRetain( doc, listNodeRange.end );
187 } else if ( offset >= listNodeRange.end ) {
188 // offset is after listNodeRange
189 // First replace the internal list, then the node
190
191 // Fix up the node insertion
192 insertion = doc.fixupInsertion( data.data, offset );
193 txBuilder.pushRetain( listNodeRange.start );
194 txBuilder.pushReplacement( doc, listNodeRange.start, listNodeRange.end - listNodeRange.start,
195 listData, true
196 );
197 txBuilder.pushRetain( insertion.offset - listNodeRange.end );
198 txBuilder.pushReplacement( doc, insertion.offset, insertion.remove, insertion.data, true );
199 txBuilder.pushFinalRetain( doc, insertion.offset + insertion.remove );
200 } else if ( offset >= listNodeRange.start && offset <= listNodeRange.end ) {
201 // offset is within listNodeRange
202 // Merge data into listData, then only replace the internal list
203 // Find the internalItem we are inserting into
204 let i = 0;
205 // Find item node in doc
206 let spliceItemRange;
207 while (
208 ( spliceItemRange = doc.internalList.getItemNode( i ).getRange() ) &&
209 offset > spliceItemRange.end
210 ) {
211 i++;
212 }
213
214 let spliceListNodeRange;
215 if ( newDoc.origInternalListLength !== null ) {
216 // Get spliceItemRange from newDoc
217 spliceItemRange = newDoc.internalList.getItemNode( i ).getRange();
218 spliceListNodeRange = newListNodeRange;
219 } else {
220 // Get spliceItemRange from doc; the while loop has already set it
221 spliceListNodeRange = listNodeRange;
222 }
223 ve.batchSplice( listData, spliceItemRange.start - spliceListNodeRange.start,
224 spliceItemRange.end - spliceItemRange.start, data.data );
225
226 txBuilder.pushRetain( listNodeRange.start );
227 txBuilder.pushReplacement( doc, listNodeRange.start, listNodeRange.end - listNodeRange.start,
228 listData, true
229 );
230 txBuilder.pushFinalRetain( doc, listNodeRange.end );
231 }
232 return txBuilder.getTransaction();
233 };
234
235 /**
236 * Generate a transaction that changes one or more attributes.
237 *
238 * @static
239 * @param {ve.dm.Document} doc Document in pre-transaction state
240 * @param {number} offset Offset of element
241 * @param {Object.<string,any>} attr List of attribute key and value pairs, use undefined value
242 * to remove an attribute
243 * @return {ve.dm.Transaction} Transaction that changes an element
244 * @throws {Error} Cannot set attributes to non-element data
245 * @throws {Error} Cannot set attributes on closing element
246 */
247 ve.dm.TransactionBuilder.static.newFromAttributeChanges = function ( doc, offset, attr ) {
248 const txBuilder = new ve.dm.TransactionBuilder(),
249 data = doc.getData();
250 // Verify element exists at offset
251 if ( data[ offset ].type === undefined ) {
252 throw new Error( 'Cannot set attributes to non-element data' );
253 }
254 // Verify element is not a closing
255 if ( data[ offset ].type.charAt( 0 ) === '/' ) {
256 throw new Error( 'Cannot set attributes on closing element' );
257 }
258 // Retain up to element
259 txBuilder.pushRetain( offset );
260 // Change attributes
261 txBuilder.pushAttributeChanges( attr, data[ offset ].attributes || {} );
262 // Retain to end of document
263 txBuilder.pushFinalRetain( doc, offset );
264 return txBuilder.getTransaction();
265 };
266
267 /**
268 * Generate a transaction that annotates content.
269 *
270 * @static
271 * @param {ve.dm.Document} doc Document in pre-transaction state
272 * @param {ve.Range} range Range to annotate
273 * @param {string} method Annotation mode
274 * - `set`: Adds annotation to all content in range
275 * - `clear`: Removes instances of annotation from content in range
276 * @param {ve.dm.Annotation} annotation Annotation to set or clear
277 * @return {ve.dm.Transaction} Transaction that annotates content
278 */
279 ve.dm.TransactionBuilder.static.newFromAnnotation = function ( doc, range, method, annotation ) {
280 const clear = method === 'clear',
281 runs = [],
282 data = doc.data,
283 hash = doc.getStore().hash( annotation );
284
285 let run = null,
286 insideContentNode = false,
287 ignoreChildrenDepth = 0;
288
289 let i;
290
291 /**
292 * Return the array index of the annotation in the annotation array for the offset
293 *
294 * @param {number} offset Document offset
295 * @return {number} Index in the annotation array (-1 if not present)
296 */
297 function findAnnotation() {
298 return data.getAnnotationHashesFromOffset( i ).lastIndexOf( hash );
299 }
300
301 function startRun() {
302 run = {
303 start: i,
304 end: null,
305 data: null,
306 spliceAt: clear ? findAnnotation() : null
307 };
308 }
309
310 function endRun() {
311 run.end = i;
312 if ( !clear ) {
313 run.spliceAt = data.getCommonAnnotationArrayLength(
314 new ve.Range( run.start, i )
315 );
316 }
317 run.data = doc.getData( new ve.Range( run.start, run.end ) );
318 for ( let j = 0, jLen = run.data.length; j < jLen; j++ ) {
319 let item = ve.copy( run.data[ j ] );
320 const anns = new ve.dm.AnnotationSet(
321 doc.getStore(),
322 ve.dm.ElementLinearData.static.getAnnotationHashesFromItem( item )
323 );
324 if ( clear ) {
325 anns.remove( annotation );
326 } else {
327 anns.add( annotation, run.spliceAt );
328 }
329 item = ve.dm.ElementLinearData.static.replaceAnnotationHashesForItem( item, anns.getHashes() );
330 run.data[ j ] = item;
331 }
332 runs.push( run );
333 run = null;
334 }
335
336 let covered, arrayIndex;
337 // Iterate over all data in range, finding "runs" to annotate
338 for ( i = range.start; i < range.end; i++ ) {
339 if ( data.isElementData( i ) && ve.dm.nodeFactory.shouldIgnoreChildren( data.getType( i ) ) ) {
340 ignoreChildrenDepth += data.isOpenElementData( i ) ? 1 : -1;
341 }
342 const annotatable = !ignoreChildrenDepth && data.canTakeAnnotationAtOffset( i, annotation );
343
344 if (
345 !annotatable ||
346 ( insideContentNode && !data.isCloseElementData( i ) )
347 ) {
348 // Structural element opening or closing, or entering a content node
349 if ( run ) {
350 endRun();
351 }
352 continue;
353 }
354
355 if ( data.isCloseElementData( i ) ) {
356 // Content closing, skip
357 insideContentNode = false;
358 continue;
359 }
360
361 if ( insideContentNode ) {
362 continue;
363 }
364
365 // Else we're annotatable, not inside a content node, and have character or
366 // content element opening
367 if ( data.isElementData( i ) ) {
368 insideContentNode = true;
369 }
370 if ( !clear ) {
371 // Don't re-apply matching annotation
372 covered = data.getAnnotationsFromOffset( i ).containsComparable( annotation );
373 } else {
374 // Expect comparable annotations to be removed individually otherwise
375 // we might try to remove more than one annotation per character, which
376 // a single transaction can't do.
377 arrayIndex = findAnnotation();
378 }
379 if ( run && (
380 ( clear && arrayIndex !== run.spliceAt ) ||
381 ( !clear && covered )
382 ) ) {
383 // Inside a run and:
384 // - if clearing, annotation is absent entirely or at a new array index
385 // - if setting, Matching annotation is present already
386 endRun();
387 }
388 if ( !run && (
389 ( clear && arrayIndex > -1 ) ||
390 ( !clear && !covered )
391 ) ) {
392 // Not inside a run, and:
393 // - if clearing, annotation is present
394 // - if setting, annotation is not present
395 startRun();
396 }
397 }
398 if ( run ) {
399 endRun();
400 }
401
402 const txBuilder = new ve.dm.TransactionBuilder();
403 let iLen;
404 for ( i = 0, iLen = runs.length; i < iLen; i++ ) {
405 run = runs[ i ];
406 txBuilder.pushRetain( run.start - ( i > 0 ? runs[ i - 1 ].end : 0 ) );
407 txBuilder.pushReplacement( doc, run.start, run.end - run.start, run.data, false );
408 }
409 txBuilder.pushFinalRetain( doc, runs.length > 0 ? runs[ runs.length - 1 ].end : 0 );
410 return txBuilder.getTransaction();
411 };
412
413 /**
414 * Generate a transaction that converts elements that can contain content.
415 *
416 * @static
417 * @param {ve.dm.Document} doc Document in pre-transaction state
418 * @param {ve.Range} range Range to convert
419 * @param {string} type Symbolic name of element type to convert to
420 * @param {Object} [attr] Attributes to initialize element with
421 * @param {Object} [internal] Internal attributes to initialize element with
422 * @return {ve.dm.Transaction} Transaction that converts content branches
423 */
424 ve.dm.TransactionBuilder.static.newFromContentBranchConversion = function ( doc, range, type, attr, internal ) {
425 const txBuilder = new ve.dm.TransactionBuilder(),
426 selection = doc.selectNodes( range, 'leaves' ),
427 opening = { type: type },
428 closing = { type: '/' + type };
429 let previousBranch,
430 previousBranchOuterRange;
431
432 // Add attributes to opening if needed
433 if ( attr ) {
434 if ( !ve.isEmptyObject( attr ) ) {
435 opening.attributes = attr;
436 }
437 } else {
438 // Set to empty object for comparison
439 attr = {};
440 }
441 if ( internal ) {
442 if ( !ve.isEmptyObject( internal ) ) {
443 opening.internal = internal;
444 }
445 } else {
446 // Set to empty object for comparison
447 internal = {};
448 }
449
450 // Replace the wrappings of each content branch in the range
451 for ( let i = 0, len = selection.length; i < len; i++ ) {
452 const selected = selection[ i ];
453 // TODO: This duplicates the logic of ve.dm.SurfaceFragment#getSelectedLeafNodes
454 // This could perhaps be a new mode in ve.Document#selectNodes?
455 if ( !( len === 1 || !selected.range || !selected.range.isCollapsed() ) ) {
456 continue;
457 }
458
459 const branch = selected.node.isContent() ? selected.node.getParent() : selected.node;
460 if ( branch.canContainContent() ) {
461 // Skip branches that are already of the target type and have matching attributes
462 if (
463 branch.getType() === type &&
464 ve.compare( attr, branch.getAttributes() ) &&
465 ve.compare( internal, branch.element.internal || {} )
466 ) {
467 continue;
468 }
469 const branchOuterRange = branch.getOuterRange();
470 // Don't convert the same branch twice
471 if ( branch === previousBranch ) {
472 continue;
473 }
474
475 // Retain up to this branch, considering where the previous one left off
476 txBuilder.pushRetain(
477 branchOuterRange.start - ( previousBranch ? previousBranchOuterRange.end : 0 )
478 );
479 if (
480 branch.getType() === type &&
481 ve.compare( internal, branch.element.internal || {} )
482 ) {
483 // Same type and internal, different attributes, so we only need an attribute change
484 txBuilder.pushAttributeChanges( attr, branch.getAttributes() );
485 // Retain the branch, including its opening and closing
486 txBuilder.pushRetain( branch.getOuterLength() );
487 } else {
488 // Types or internal differ, so we need to replace the opening and closing
489 // Replace the opening
490 txBuilder.pushReplacement( doc, branchOuterRange.start, 1, [ ve.copy( opening ) ] );
491 // Retain the contents
492 txBuilder.pushRetain( branch.getLength() );
493 // Replace the closing
494 txBuilder.pushReplacement( doc, branchOuterRange.end - 1, 1, [ ve.copy( closing ) ] );
495 }
496 // Remember this branch and its range for next time
497 previousBranch = branch;
498 previousBranchOuterRange = branchOuterRange;
499 }
500 }
501 // Retain until the end
502 txBuilder.pushFinalRetain( doc, previousBranch ? previousBranchOuterRange.end : 0 );
503 return txBuilder.getTransaction();
504 };
505
506 /**
507 * Generate a transaction that wraps, unwraps or replaces structure.
508 *
509 * The unwrap parameters are checked against the actual model data, and
510 * an exception is thrown if the type fields don't match. This means you
511 * can omit attributes from the unwrap parameters, those are automatically
512 * picked up from the model data instead.
513 *
514 * NOTE: This function currently does not fix invalid parent/child relationships, so it will
515 * happily convert paragraphs to listItems without wrapping them in a list if that's what you
516 * ask it to do. We'll probably fix this later but for now the caller is responsible for giving
517 * valid instructions.
518 *
519 * Changing a paragraph to a header:
520 * Before: [ {type: 'paragraph'}, 'a', 'b', 'c', {type: '/paragraph'} ]
521 * newFromWrap( new ve.Range( 1, 4 ), [ {type: 'paragraph'} ], [ {type: 'heading', level: 1 } ] );
522 * After: [ {type: 'heading', level: 1 }, 'a', 'b', 'c', {type: '/heading'} ]
523 *
524 * Changing a set of paragraphs to a list:
525 * Before: [ {type: 'paragraph'}, 'a', {type: '/paragraph'}, {'type':'paragraph'}, 'b', {'type':'/paragraph'} ]
526 * newFromWrap( new ve.Range( 0, 6 ), [], [ {type: 'list' } ], [], [ {type: 'listItem', attributes: {styles: ['bullet']}} ] );
527 * After: [ {type: 'list'}, {type: 'listItem', attributes: {styles: ['bullet']}}, {'type':'paragraph'} 'a',
528 * {type: '/paragraph'}, {type: '/listItem'}, {type: 'listItem', attributes: {styles: ['bullet']}},
529 * {type: 'paragraph'}, 'b', {type: '/paragraph'}, {type: '/listItem'}, {type: '/list'} ]
530 *
531 * @param {ve.dm.Document} doc Document in pre-transaction state
532 * @param {ve.Range} range Range to wrap/unwrap/replace around
533 * @param {Array} unwrapOuter Opening elements to unwrap. These must be immediately *outside* the range
534 * @param {Array} wrapOuter Opening elements to wrap around the range
535 * @param {Array} unwrapEach Opening elements to unwrap from each top-level element in the range
536 * @param {Array} wrapEach Opening elements to wrap around each top-level element in the range
537 * @return {ve.dm.Transaction}
538 */
539 ve.dm.TransactionBuilder.static.newFromWrap = function ( doc, range, unwrapOuter, wrapOuter, unwrapEach, wrapEach ) {
540 const txBuilder = new ve.dm.TransactionBuilder();
541 let depth = 0;
542
543 /**
544 * Match items before/after an offset, skipping over MetaItems
545 *
546 * @param {string} direction Direction of match, backwards|forwards
547 * @param {number} offset First boundary for the matching items
548 * @param {Object[]} matchList List of objects with .type properties to compare
549 * @param {string} matchName Description of the match, for error messages
550 * @return {number} Other slice boundary for the matching items
551 * @throws {Error} Unmatched item foo in matchName [(found bar)]
552 */
553 function match( direction, offset, matchList, matchName ) {
554 let start, stop, step;
555 if ( direction === 'forwards' ) {
556 start = 0;
557 stop = matchList.length;
558 step = 1;
559 // Inclusive 'from' slice boundary
560 offset--;
561 } else {
562 start = matchList.length - 1;
563 stop = -1;
564 step = -1;
565 }
566 for ( let j = start; j !== stop; j += step ) {
567 let item;
568 // Move to next item, skipping MetaItems
569 while ( true ) {
570 offset += step;
571 item = doc.data.data[ offset ];
572 if ( !(
573 ve.dm.LinearData.static.isElementData( item ) &&
574 ve.dm.nodeFactory.isMetaData(
575 ve.dm.LinearData.static.getType( item )
576 )
577 ) ) {
578 break;
579 }
580 }
581 if ( !item || item.type !== matchList[ j ].type ) {
582 throw new Error( 'Unmatched item ' + matchList[ j ].type + ' in ' +
583 matchName + ' (found ' + ( item && item.type ) + ')' );
584 }
585 }
586 if ( direction === 'forwards' ) {
587 // Exclusive 'to' slice boundary
588 offset++;
589 }
590 return offset;
591 }
592
593 // Function to generate arrays of closing elements in reverse order
594 function closingArray( openings ) {
595 const closings = [];
596 for ( let j = 0, jlen = openings.length; j < jlen; j++ ) {
597 closings[ closings.length ] = { type: '/' + openings[ jlen - j - 1 ].type };
598 }
599 return closings;
600 }
601
602 const closingUnwrapEach = closingArray( unwrapEach );
603 const closingWrapEach = closingArray( wrapEach );
604
605 // TODO: check for and fix nesting validity like fixupInsertion does
606
607 // Verify the data before range.start matches unwrapOuter, and find where to retain up to
608 let ptr = match( 'backwards', range.start, unwrapOuter, 'unwrapOuter' );
609 txBuilder.pushRetain( ptr );
610 // Replace wrapper (retaining any metadata)
611 txBuilder.pushReplacement( doc, ptr, range.start - ptr, ve.copy( wrapOuter ) );
612 ptr = range.start;
613
614 if ( wrapEach.length === 0 && unwrapEach.length === 0 ) {
615 // There is no wrapEach/unwrapEach to be done, just retain
616 // up to the end of the range
617 txBuilder.pushRetain( range.end - range.start );
618 ptr = range.end;
619 } else {
620 // Visit each top-level child and wrap/unwrap it
621 // TODO figure out if we should use the tree/node functions here
622 // rather than iterating over offsets, it may or may not be faster
623 let startOffset;
624 for ( let i = range.start; i < range.end; i++ ) {
625 if ( !doc.data.isElementData( i ) ) {
626 continue;
627 }
628 if ( doc.data.isOpenElementData( i ) ) {
629 depth++;
630 if (
631 depth !== 1 ||
632 ve.dm.nodeFactory.isMetaData(
633 ve.dm.LinearData.static.getType(
634 doc.data.data[ i ]
635 )
636 )
637 ) {
638 continue;
639 }
640 // Retain any outstanding top level items (which must be MetaItems)
641 txBuilder.pushRetain( i - ptr );
642 // This is the start of a top-level element
643 ptr = match( 'forwards', i, unwrapEach, 'unwrapEach' );
644 // Replace wrapper (retaining any metadata)
645 txBuilder.pushReplacement( doc, i, ptr - i, ve.copy( wrapEach ) );
646 startOffset = ptr;
647 continue;
648 }
649 // Else this is a closing element
650 depth--;
651 if (
652 depth !== 0 ||
653 ve.dm.nodeFactory.isMetaData(
654 ve.dm.LinearData.static.getType( doc.data.data[ i ] )
655 )
656 ) {
657 continue;
658 }
659 // This is the end of a top-level element
660 ptr = match( 'backwards', i + 1, closingUnwrapEach, 'closingUnwrapEach' );
661 // ptr is the range end of the unwrapped data (i.e. the offset after it)
662 txBuilder.pushRetain( ptr - startOffset );
663 // Replace the closing elements (retaining any metadata)
664 txBuilder.pushReplacement( doc, ptr, i + 1 - ptr, ve.copy( closingWrapEach ) );
665 ptr = i + 1;
666 }
667 }
668
669 // Retain any outstanding top level items (which must be MetaItems)
670 txBuilder.pushRetain( range.end - ptr );
671
672 ptr = match( 'forwards', range.end, closingArray( unwrapOuter ), 'unwrapOuter' );
673 txBuilder.pushReplacement( doc, range.end, ptr - range.end, closingArray( wrapOuter ) );
674
675 // Retain up to the end of the document
676 txBuilder.pushFinalRetain( doc, ptr );
677
678 return txBuilder.getTransaction();
679 };
680
681 /* Methods */
682
683 /**
684 * Get the transaction
685 *
686 * @return {ve.dm.Transaction} The transaction
687 */
688 ve.dm.TransactionBuilder.prototype.getTransaction = function () {
689 return this.transaction;
690 };
691
692 /**
693 * Add a final retain operation to finish off a transaction (internal helper).
694 *
695 * @private
696 * @param {ve.dm.Document} doc The document in the state to which the transaction applies
697 * @param {number} offset Final offset edited by the transaction up to this point.
698 */
699 ve.dm.TransactionBuilder.prototype.pushFinalRetain = function ( doc, offset ) {
700 if ( offset < doc.data.getLength() ) {
701 this.pushRetain( doc.data.getLength() - offset );
702 }
703 };
704
705 /**
706 * Add a retain operation.
707 *
708 * @param {number} length Length of content data to retain
709 * @throws {Error} Cannot retain backwards
710 */
711 ve.dm.TransactionBuilder.prototype.pushRetain = function ( length ) {
712 if ( length < 0 ) {
713 throw new Error( 'Invalid retain length, cannot retain backwards:' + length );
714 }
715 if ( length ) {
716 const end = this.transaction.operations.length - 1;
717 if (
718 this.transaction.operations.length &&
719 this.transaction.operations[ end ].type === 'retain'
720 ) {
721 this.transaction.operations[ end ].length += length;
722 } else {
723 this.transaction.pushRetainOp( length );
724 }
725 }
726 };
727
728 /**
729 * Adds a replace op to remove the desired range and, where required, splices in retain ops
730 * to prevent the deletion of undeletable nodes.
731 *
732 * @param {ve.dm.Document} doc The document in the state to which the transaction applies
733 * @param {number} removeStart Offset to start removing from
734 * @param {number} removeEnd Offset to remove to
735 * @param {boolean} [removeMetadata=false] Remove metadata instead of collapsing it
736 * @return {number} End offset of the removal
737 */
738 ve.dm.TransactionBuilder.prototype.addSafeRemoveOps = function ( doc, removeStart, removeEnd, removeMetadata ) {
739 let retainStart = removeStart,
740 undeletableStackDepth = 0;
741 // Iterate over removal range and use a stack counter to determine if
742 // we are inside an undeletable node
743 let queuedRetain;
744 for ( let i = removeStart; i < removeEnd; i++ ) {
745 if ( doc.data.isElementData( i ) && !ve.dm.nodeFactory.isNodeDeletable( doc.data.getType( i ) ) ) {
746 if ( !doc.data.isCloseElementData( i ) ) {
747 if ( undeletableStackDepth === 0 ) {
748 if ( queuedRetain ) {
749 this.pushRetain( queuedRetain );
750 }
751 this.pushReplacement( doc, removeStart, i - removeStart, [], removeMetadata );
752 retainStart = i;
753 }
754 undeletableStackDepth++;
755 } else {
756 undeletableStackDepth--;
757 if ( undeletableStackDepth === 0 ) {
758 queuedRetain = i + 1 - retainStart;
759 removeStart = i + 1;
760 }
761 }
762 }
763 }
764 if ( removeEnd - removeStart ) {
765 if ( queuedRetain ) {
766 this.pushRetain( queuedRetain );
767 }
768 this.pushReplacement( doc, removeStart, removeEnd - removeStart, [], removeMetadata );
769 retainStart = removeEnd;
770 }
771 return retainStart;
772 };
773
774 /**
775 * Add a replace operation (internal helper).
776 *
777 * @private
778 * @param {Array} remove Data removed.
779 * @param {Array} insert Data to insert.
780 * @param {number} [insertedDataOffset] Inserted data offset
781 * @param {number} [insertedDataLength] Inserted data length
782 */
783 ve.dm.TransactionBuilder.prototype.pushReplaceInternal = function ( remove, insert, insertedDataOffset, insertedDataLength ) {
784 if ( remove.length === 0 && insert.length === 0 ) {
785 return; // No-op
786 }
787 this.transaction.pushReplaceOp( remove, insert, insertedDataOffset, insertedDataLength );
788 };
789
790 /**
791 * Add a replace operation
792 *
793 * If metadata is collapsed instead of removed, it will be shifted backwards if necessary to
794 * reach a legal position for metadata in the new document structure.
795 *
796 * @param {ve.dm.Document} doc The document in the state to which the transaction applies
797 * @param {number} offset Offset to start at
798 * @param {number} removeLength Number of data items to remove
799 * @param {Array} insert Data to insert
800 * @param {boolean} removeMetadata Remove metadata instead of collapsing it
801 * @param {number} [insertedDataOffset] Offset of the originally inserted data in the resulting operation data
802 * @param {number} [insertedDataLength] Length of the originally inserted data in the resulting operation data
803 */
804 ve.dm.TransactionBuilder.prototype.pushReplacement = function ( doc, offset, removeLength, insert, removeMetadata, insertedDataOffset, insertedDataLength ) {
805 let remove = doc.getData( new ve.Range( offset, offset + removeLength ) );
806 const collapse = removeMetadata ? [] : remove.filter( ( item ) => {
807 const type = ve.dm.LinearData.static.isElementData( item ) &&
808 ve.dm.LinearData.static.getType( item );
809 return type &&
810 ve.dm.nodeFactory.isMetaData( type ) &&
811 !ve.dm.nodeFactory.isRemovableMetaData( type );
812 } );
813 if ( removeLength === collapse.length && insert.length === 0 ) {
814 // Push retain instead of no-op replace
815 this.pushRetain( collapse.length );
816 return;
817 }
818
819 if ( collapse.length > 0 ) {
820 // Push collapsed metadata, moved backwards if this position has become invalid
821 // for metadata
822 this.pushMeta( doc, offset, collapse );
823 }
824 // Merge with previous replace, if any (which may have come from the pushMeta above)
825 const lastOp = this.transaction.operations[ this.transaction.operations.length - 1 ];
826 if (
827 lastOp &&
828 lastOp.type === 'replace' &&
829 !lastOp.insertedDataOffset &&
830 !insertedDataOffset
831 ) {
832 this.transaction.operations.pop();
833 remove = lastOp.remove.concat( remove );
834 insert = lastOp.insert.concat( insert );
835 }
836
837 const op = {
838 type: 'replace',
839 remove: remove,
840 insert: insert
841 };
842 if ( insertedDataOffset !== undefined ) {
843 op.insertedDataOffset = insertedDataOffset;
844 }
845 if ( insertedDataLength !== undefined ) {
846 op.insertedDataLength = insertedDataLength;
847 }
848 this.transaction.operations.push( op );
849 };
850
851 /**
852 * Add an element attribute change operation.
853 *
854 * @param {string} key Name of attribute to change
855 * @param {any} from Value change attribute from, or undefined if not previously set
856 * @param {any} to Value to change attribute to, or undefined to remove
857 */
858 ve.dm.TransactionBuilder.prototype.pushReplaceElementAttribute = function ( key, from, to ) {
859 this.transaction.pushAttributeOp( key, from, to );
860 };
861
862 /**
863 * Add a series of element attribute change operations.
864 *
865 * @param {Object} changes Object mapping attribute names to new values
866 * @param {Object} oldAttrs Object mapping attribute names to old values
867 */
868 ve.dm.TransactionBuilder.prototype.pushAttributeChanges = function ( changes, oldAttrs ) {
869 for ( const key in changes ) {
870 if ( oldAttrs[ key ] !== changes[ key ] ) {
871 this.pushReplaceElementAttribute( key,
872 ve.copy( oldAttrs[ key ] ),
873 ve.copy( changes[ key ] )
874 );
875 }
876 }
877 };
878
879 /**
880 * Internal helper method for newFromInsertion and newFromReplacement.
881 * Adds an insertion to an existing transaction object.
882 *
883 * @private
884 * @param {ve.dm.Document} doc The document in the state to which the transaction applies
885 * @param {number} currentOffset Offset up to which the transaction has gone already
886 * @param {number} insertOffset Offset to insert at
887 * @param {Array} data Linear model data to insert
888 * @return {number} End offset of the insertion
889 */
890 ve.dm.TransactionBuilder.prototype.pushInsertion = function ( doc, currentOffset, insertOffset, data ) {
891 // Fix up the insertion
892 const insertion = doc.fixupInsertion( data, insertOffset );
893 // Retain up to insertion point, if needed
894 this.pushRetain( insertion.offset - currentOffset );
895 // Insert data
896 this.pushReplacement(
897 doc, insertion.offset, insertion.remove, insertion.data, false,
898 insertion.insertedDataOffset, insertion.insertedDataLength
899 );
900 return insertion.offset + insertion.remove;
901 };
902
903 /**
904 * Internal helper method for newFromRemoval and newFromReplacement.
905 * Adds a removal to an existing transaction object.
906 *
907 * @private
908 * @param {ve.dm.Document} doc The document in the state to which the transaction applies
909 * @param {number} currentOffset Offset up to which the transaction has gone already
910 * @param {ve.Range} range Range to remove
911 * @param {boolean} [removeMetadata=false] Remove metadata instead of collapsing it
912 * @return {number} End offset of the removal
913 */
914 ve.dm.TransactionBuilder.prototype.pushRemoval = function ( doc, currentOffset, range, removeMetadata ) {
915 let offset = currentOffset,
916 removeStart = null,
917 removeEnd = null;
918 // Validate range
919 if ( range.isCollapsed() ) {
920 // Empty range, nothing to remove
921 this.pushRetain( range.start - currentOffset );
922 return range.start;
923 }
924 // Select nodes and validate selection
925 const selection = doc.selectNodes( range, 'covered' );
926 if ( selection.length === 0 ) {
927 // Empty selection? Something is wrong!
928 throw new Error( 'Invalid range, cannot remove from ' + range.start + ' to ' + range.end );
929 }
930 const first = selection[ 0 ];
931 const last = selection[ selection.length - 1 ];
932 // If the first and last node are mergeable, merge them
933 if ( first.node.canBeMergedWith( last.node ) ) {
934 if ( !first.range && !last.range ) {
935 // First and last node are both completely covered, remove them
936 removeStart = first.nodeOuterRange.start;
937 removeEnd = last.nodeOuterRange.end;
938 } else {
939 // Either the first node or the last node is partially covered, so remove
940 // the selected content. The other node might be fully covered, in which case
941 // we remove its contents (nodeRange). For fully covered content nodes, we must
942 // remove the entire node (nodeOuterRange).
943 removeStart = (
944 first.range ||
945 ( first.node.isContent() ? first.nodeOuterRange : first.nodeRange )
946 ).start;
947 removeEnd = (
948 last.range ||
949 ( last.node.isContent() ? last.nodeOuterRange : last.nodeRange )
950 ).end;
951 }
952 this.pushRetain( removeStart - currentOffset );
953 removeEnd = this.addSafeRemoveOps( doc, removeStart, removeEnd, removeMetadata );
954 // All done
955 return removeEnd;
956 }
957
958 // The selection wasn't mergeable, so remove nodes that are completely covered, and strip
959 // nodes that aren't
960 for ( let i = 0; i < selection.length; i++ ) {
961 let nodeStart, nodeEnd;
962 if ( !selection[ i ].range ) {
963 // Entire node is covered, remove it
964 nodeStart = selection[ i ].nodeOuterRange.start;
965 nodeEnd = selection[ i ].nodeOuterRange.end;
966 } else {
967 // Part of the node is covered, remove that range
968 nodeStart = selection[ i ].range.start;
969 nodeEnd = selection[ i ].range.end;
970 }
971
972 // Merge contiguous removals. Only apply a removal when a gap appears, or at the
973 // end of the loop
974 if ( removeEnd === null ) {
975 // First removal
976 removeStart = nodeStart;
977 removeEnd = nodeEnd;
978 } else if ( removeEnd === nodeStart ) {
979 // Merge this removal into the previous one
980 removeEnd = nodeEnd;
981 } else {
982 // There is a gap between the previous removal and this one
983
984 // Push the previous removal first
985 this.pushRetain( removeStart - offset );
986 offset = this.addSafeRemoveOps( doc, removeStart, removeEnd, removeMetadata );
987
988 // Now start this removal
989 removeStart = nodeStart;
990 removeEnd = nodeEnd;
991 }
992 }
993 // Apply the last removal, if any
994 if ( removeEnd !== null ) {
995 this.pushRetain( removeStart - offset );
996 offset = this.addSafeRemoveOps( doc, removeStart, removeEnd, removeMetadata );
997 }
998 return offset;
999 };
1000
1001 /**
1002 * Insert meta items, as near to the current transaction end as is legal
1003 *
1004 * @param {ve.dm.Document} doc Document in pre-transaction state
1005 * @param {number} offset Offset of the end of the current (partial) operations list
1006 * @param {Array} metaItems linear data containing just meta items
1007 */
1008 ve.dm.TransactionBuilder.prototype.pushMeta = function ( doc, offset, metaItems ) {
1009 const ops = this.transaction.operations;
1010 let position = null,
1011 relDepth = 0;
1012
1013 if ( ops.length === 0 ) {
1014 ops.push( {
1015 type: 'replace',
1016 remove: [],
1017 insert: metaItems
1018 } );
1019 return;
1020 }
1021
1022 // Start at the current end of the transaction
1023 position = { opIndex: ops.length - 1, itemIndex: ops[ ops.length - 1 ].length };
1024
1025 let op;
1026 // Walk backwards over the linear data as it will be after the transaction is
1027 // applied, tracking depth, and disregarding tags deeper than the depth at offset.
1028 // - If we hit a structural open tag with restricted childNodeTypes (like list) then
1029 // move position to just before the tag, and keep walking
1030 // - If we hit a structural open tag with unrestricted childNodeTypes, or the document
1031 // start, then position is fine: insert metaItems there and return
1032 findPositionLoop:
1033 for ( let i = ops.length - 1; i >= 0; i-- ) {
1034 op = ops[ i ];
1035 let items;
1036 if ( op.type === 'replace' ) {
1037 items = op.insert;
1038 offset -= op.remove.length;
1039 } else if ( op.type === 'retain' ) {
1040 items = doc.getData( new ve.Range( offset - op.length, offset ) );
1041 offset -= op.length;
1042 } else {
1043 // attribute/annotate: do nothing
1044 continue;
1045 }
1046 for ( let j = items.length - 1; j >= 0; j-- ) {
1047 const type = items[ j ].type;
1048 if ( !type || typeof type !== 'string' ) {
1049 continue;
1050 }
1051 if ( type.charAt( 0 ) === '/' ) {
1052 // Close element, so going backwards we're getting deeper
1053 relDepth++;
1054 continue;
1055 }
1056 // Else open element
1057 relDepth--;
1058 if ( relDepth >= 0 ) {
1059 continue;
1060 // TODO: This could be a long walk. Do we want to infer stuff
1061 // from element types we see at relDepth 0? For instance, if
1062 // we see a structural node at the same depth as position, with
1063 // unrestricted parentNodeTypes, could we perhaps infer that
1064 // position is a legal place for metadata without walking the
1065 // whole 874 miles to the start of the document?
1066 //
1067 // This is not an immediate priority because for text
1068 // replacement during typing (the main performance-critical use
1069 // case) we only have to walk back to the start of the CBN,
1070 // which is unlikely to be far.
1071 }
1072 // We won't let relDepth go below -1 (see below), so this element is
1073 // the parent of position
1074 if (
1075 !ve.dm.nodeFactory.canNodeContainContent( type ) &&
1076 !ve.dm.nodeFactory.getChildNodeTypes( type )
1077 ) {
1078 // This is a legal parent for metadata
1079 break findPositionLoop;
1080 }
1081 // Else not a legal parent for metadata: move position up and continue
1082 position = { opIndex: i, itemIndex: j };
1083 relDepth = 0;
1084 }
1085 }
1086 op = ops[ position.opIndex ];
1087 if ( op.type === 'replace' ) {
1088 ve.batchSplice( op.insert, position.itemIndex, 0, metaItems );
1089 return;
1090 }
1091 // Else it's a retain op (it cannot be attribute/annotate because we skip those above)
1092 if ( position.itemIndex > 0 ) {
1093 ops.splice( position.opIndex, 0, {
1094 type: 'retain',
1095 length: position.itemIndex
1096 } );
1097 position.opIndex++;
1098 }
1099 ops.splice( position.opIndex, 0, {
1100 type: 'replace',
1101 remove: [],
1102 insert: metaItems
1103 } );
1104 op.length -= position.itemIndex;
1105 if ( op.length === 0 ) {
1106 ops.splice( position.opIndex + 1, 1 );
1107 }
1108 // TODO: normalize resulting consecutive replace ops?
1109 };