Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Fragment class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel surface fragment.
9 *
10 * @class
11 *
12 * @constructor
13 * @param {ve.dm.Surface} surface Target surface
14 * @param {ve.dm.Selection} [selection] Selection within target document, current selection used by default
15 * @param {boolean} [noAutoSelect] Don't update the surface's selection when making changes
16 * @param {boolean} [excludeInsertions] Exclude inserted content at the boundaries when updating range
17 */
18 ve.dm.SurfaceFragment = function VeDmSurfaceFragment( surface, selection, noAutoSelect, excludeInsertions ) {
19 // Short-circuit for missing-surface null fragment
20 if ( !surface ) {
21 return this;
22 }
23
24 // Properties
25 this.document = surface.getDocument();
26 this.noAutoSelect = !!noAutoSelect;
27 this.excludeInsertions = !!excludeInsertions;
28 this.surface = surface;
29 this.selection = selection || surface.getSelection();
30 this.leafNodes = null;
31 this.pending = [];
32
33 // Initialization
34 this.historyPointer = this.document.getCompleteHistoryLength();
35 };
36
37 /* Inheritance */
38
39 OO.initClass( ve.dm.SurfaceFragment );
40
41 /* Methods */
42
43 /**
44 * Get list of selected nodes and annotations.
45 *
46 * @param {boolean} [all] Include nodes and annotations which only cover some of the fragment
47 * @return {ve.dm.Model[]} Selected models
48 */
49 ve.dm.SurfaceFragment.prototype.getSelectedModels = function ( all ) {
50 // Handle null selection
51 if ( this.isNull() ) {
52 return [];
53 }
54
55 const annotations = this.getAnnotations( all );
56
57 // Filter out nodes with collapsed ranges
58 let nodes;
59 if ( all ) {
60 nodes = this.getCoveredNodes();
61 for ( let i = 0, len = nodes.length; i < len; i++ ) {
62 if ( nodes[ i ].range && nodes[ i ].range.isCollapsed() ) {
63 nodes.splice( i, 1 );
64 len--;
65 i--;
66 } else {
67 nodes[ i ] = nodes[ i ].node;
68 }
69 }
70 } else {
71 nodes = [];
72 const selectedNode = this.getSelectedNode();
73 if ( selectedNode ) {
74 nodes.push( selectedNode );
75 }
76 }
77
78 return nodes.concat( !annotations.isEmpty() ? annotations.get() : [] );
79 };
80
81 /**
82 * Update selection based on un-applied transactions in the surface, or specified selection.
83 *
84 * @param {ve.dm.Selection} [selection] Optional selection to set
85 * @return {ve.dm.SurfaceFragment}
86 * @chainable
87 */
88 ve.dm.SurfaceFragment.prototype.update = function ( selection ) {
89 // Handle null selection
90 if ( this.isNull() ) {
91 return this;
92 }
93
94 if ( selection && !selection.equals( this.selection ) ) {
95 this.selection = selection;
96 this.leafNodes = null;
97 this.historyPointer = this.document.getCompleteHistoryLength();
98 } else if ( this.historyPointer < this.document.getCompleteHistoryLength() ) {
99 // Small optimisation: check history pointer is in the past
100 const txs = this.document.getCompleteHistorySince( this.historyPointer );
101 this.selection = this.selection.translateByTransactions( txs, this.excludeInsertions );
102 this.leafNodes = null;
103 this.historyPointer += txs.length;
104 }
105 return this;
106 };
107
108 /**
109 * Process a set of transactions on the surface, and update the selection if the fragment
110 * is auto-selecting.
111 *
112 * @param {ve.dm.Transaction|ve.dm.Transaction[]} txs Transaction(s) to process
113 * @param {ve.dm.Selection} [selection] Selection to set, if different from translated selection, required if the
114 * fragment is null
115 * @throws {Error} If fragment is null and selection is omitted
116 */
117 ve.dm.SurfaceFragment.prototype.change = function ( txs, selection ) {
118 if ( !selection && this.isNull() ) {
119 throw new Error( 'Cannot change null fragment without selection' );
120 }
121
122 if ( !Array.isArray( txs ) ) {
123 txs = [ txs ];
124 }
125 this.surface.change(
126 txs,
127 !this.noAutoSelect && ( selection || this.getSelection().translateByTransactions( txs, this.excludeInsertions ) )
128 );
129 if ( selection ) {
130 // Overwrite the selection
131 this.update( selection );
132 }
133 };
134
135 /**
136 * Get the surface the fragment is a part of.
137 *
138 * @return {ve.dm.Surface|null} Surface of fragment
139 */
140 ve.dm.SurfaceFragment.prototype.getSurface = function () {
141 return this.surface;
142 };
143
144 /**
145 * Get the document of the surface the fragment is a part of.
146 *
147 * @return {ve.dm.Document|null} Document of surface of fragment
148 */
149 ve.dm.SurfaceFragment.prototype.getDocument = function () {
150 return this.document;
151 };
152
153 /**
154 * Get the selection of the fragment within the surface.
155 *
156 * This method also calls update to make sure the selection returned is current.
157 *
158 * @return {ve.dm.Selection} The selection
159 */
160 ve.dm.SurfaceFragment.prototype.getSelection = function () {
161 this.update();
162 return this.selection;
163 };
164
165 /**
166 * Check if the fragment is null.
167 *
168 * @return {boolean} Fragment is a null fragment
169 */
170 ve.dm.SurfaceFragment.prototype.isNull = function () {
171 return this.selection.isNull();
172 };
173
174 /**
175 * Check if the surface's selection will be updated automatically when changes are made.
176 *
177 * @return {boolean} Will automatically update surface selection
178 */
179 ve.dm.SurfaceFragment.prototype.willAutoSelect = function () {
180 return !this.noAutoSelect;
181 };
182
183 /**
184 * Change whether to automatically update the surface selection when making changes.
185 *
186 * @param {boolean} [autoSelect=true] Automatically update surface selection
187 * @return {ve.dm.SurfaceFragment}
188 * @chainable
189 */
190 ve.dm.SurfaceFragment.prototype.setAutoSelect = function ( autoSelect ) {
191 this.noAutoSelect = !autoSelect;
192 return this;
193 };
194
195 /**
196 * Get a clone of this SurfaceFragment, optionally with a different selection.
197 *
198 * @param {ve.dm.Selection} [selection] If set, use this selection rather than the old fragment's selection
199 * @return {ve.dm.SurfaceFragment} Clone of this fragment
200 */
201 ve.dm.SurfaceFragment.prototype.clone = function ( selection ) {
202 return new this.constructor(
203 this.surface,
204 selection || this.getSelection(),
205 this.noAutoSelect,
206 this.excludeInsertions
207 );
208 };
209
210 /**
211 * Check whether updates to this fragment's selection will exclude content inserted at the boundaries.
212 *
213 * @return {boolean} Selection updates will exclude insertions
214 */
215 ve.dm.SurfaceFragment.prototype.willExcludeInsertions = function () {
216 return this.excludeInsertions;
217 };
218
219 /**
220 * Tell this fragment whether it should exclude insertions. If this option is enabled, updates to
221 * this fragment's selection in response to transactions will not include content inserted at the
222 * boundaries of the selection; if it is disabled, insertions will be included.
223 *
224 * @param {boolean} excludeInsertions Whether to exclude insertions
225 * @return {ve.dm.SurfaceFragment}
226 * @chainable
227 */
228 ve.dm.SurfaceFragment.prototype.setExcludeInsertions = function ( excludeInsertions ) {
229 excludeInsertions = !!excludeInsertions;
230 if ( this.excludeInsertions !== excludeInsertions ) {
231 // Process any deferred updates with the old value
232 this.update();
233 // Set the new value
234 this.excludeInsertions = excludeInsertions;
235 }
236 return this;
237 };
238
239 /**
240 * Get a new fragment with an adjusted position
241 *
242 * @param {number} [start] Adjustment for start position
243 * @param {number} [end] Adjustment for end position
244 * @return {ve.dm.SurfaceFragment} Adjusted fragment
245 */
246 ve.dm.SurfaceFragment.prototype.adjustLinearSelection = function ( start, end ) {
247 if ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
248 return this.clone();
249 }
250 const oldRange = this.getSelection().getRange();
251 const newRange = oldRange && new ve.Range( oldRange.start + ( start || 0 ), oldRange.end + ( end || 0 ) );
252 return this.clone( new ve.dm.LinearSelection( newRange ) );
253 };
254
255 /**
256 * Get a new fragment with a truncated length.
257 *
258 * @param {number} limit Maximum length of new range (negative for left-side truncation)
259 * @return {ve.dm.SurfaceFragment} Truncated fragment
260 */
261 ve.dm.SurfaceFragment.prototype.truncateLinearSelection = function ( limit ) {
262 if ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
263 return this.clone();
264 }
265 const range = this.getSelection().getRange();
266 return this.clone( new ve.dm.LinearSelection( range.truncate( limit ) ) );
267 };
268
269 /**
270 * Get a new fragment with a zero-length selection at the start offset.
271 *
272 * @return {ve.dm.SurfaceFragment} Collapsed fragment
273 */
274 ve.dm.SurfaceFragment.prototype.collapseToStart = function () {
275 return this.clone( this.getSelection().collapseToStart() );
276 };
277
278 /**
279 * Get a new fragment with a zero-length selection at the end offset.
280 *
281 * @return {ve.dm.SurfaceFragment} Collapsed fragment
282 */
283 ve.dm.SurfaceFragment.prototype.collapseToEnd = function () {
284 return this.clone( this.getSelection().collapseToEnd() );
285 };
286
287 /**
288 * Get a new fragment with a range that no longer includes leading and trailing whitespace.
289 *
290 * @return {ve.dm.SurfaceFragment} Trimmed fragment
291 */
292 ve.dm.SurfaceFragment.prototype.trimLinearSelection = function () {
293 if ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
294 return this.clone();
295 }
296 const oldRange = this.getSelection().getRange();
297 let newRange;
298
299 if ( this.getText().trim().length === 0 ) {
300 // oldRange is only whitespace
301 newRange = new ve.Range( oldRange.start );
302 } else {
303 newRange = this.document.data.trimOuterSpaceFromRange( oldRange );
304 }
305
306 return this.clone( new ve.dm.LinearSelection( newRange ) );
307 };
308
309 /**
310 * Get a new fragment that covers an expanded range of the document.
311 *
312 * @param {string} [scope='parent'] Method of expansion:
313 * - `word`: Expands to cover the nearest word by looking for word breaks (see UnicodeJS.wordbreak)
314 * - `annotation`: Expands to cover a given annotation type (ve.dm.Annotation) within the current range
315 * - `root`: Expands to cover the entire document
316 * - `siblings`: Expands to cover all sibling nodes
317 * - `closest`: Expands to cover the closest common ancestor node of a give type (ve.dm.Node)
318 * - `parent`: Expands to cover the closest common parent node
319 * @param {ve.dm.Annotation|ve.dm.Node} [type] Parameter to use with scope method if needed
320 * @return {ve.dm.SurfaceFragment} Expanded fragment
321 */
322 ve.dm.SurfaceFragment.prototype.expandLinearSelection = function ( scope, type ) {
323 if ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
324 return this.clone();
325 }
326
327 const oldRange = this.getSelection().getRange();
328 let newRange;
329 let nodes, node, parent;
330
331 switch ( scope || 'parent' ) {
332 case 'word':
333 if ( !oldRange.isCollapsed() ) {
334 newRange = ve.Range.static.newCoveringRange( [
335 this.document.data.getWordRange( oldRange.start ),
336 this.document.data.getWordRange( oldRange.end )
337 ], oldRange.isBackwards() );
338 } else {
339 // Optimisation for zero-length ranges
340 newRange = this.document.data.getWordRange( oldRange.start );
341 }
342 break;
343 case 'annotation':
344 newRange = this.document.data.getAnnotatedRangeFromSelection( oldRange, type );
345 // Adjust selection if it does not contain the annotated range
346 if ( oldRange.start > newRange.start || oldRange.end < newRange.end ) {
347 // Maintain range direction
348 if ( oldRange.from > oldRange.to ) {
349 newRange = newRange.flip();
350 }
351 } else {
352 // Otherwise just keep the range as is
353 newRange = oldRange;
354 }
355 break;
356 case 'root':
357 newRange = this.getDocument().getDocumentRange();
358 break;
359 case 'siblings':
360 // Grow range to cover all siblings
361 nodes = this.document.selectNodes( oldRange, 'siblings' );
362 if ( nodes.length === 1 ) {
363 newRange = nodes[ 0 ].node.getOuterRange();
364 } else {
365 newRange = new ve.Range(
366 nodes[ 0 ].node.getOuterRange().start,
367 nodes[ nodes.length - 1 ].node.getOuterRange().end
368 );
369 }
370 break;
371 case 'closest':
372 // Grow range to cover closest common ancestor node of given type
373 nodes = this.document.selectNodes( oldRange, 'siblings' );
374 // If the range covered the entire node check that node
375 if ( nodes[ 0 ].nodeRange.equalsSelection( oldRange ) && nodes[ 0 ].node instanceof type ) {
376 newRange = nodes[ 0 ].nodeOuterRange;
377 break;
378 }
379 parent = nodes[ 0 ].node.getParent();
380 while ( parent && !( parent instanceof type ) ) {
381 node = parent;
382 parent = parent.getParent();
383 }
384 if ( parent ) {
385 newRange = parent.getOuterRange();
386 }
387 break;
388 case 'parent':
389 // Grow range to cover the closest common parent node
390 node = this.document.selectNodes( oldRange, 'siblings' )[ 0 ].node;
391 parent = node.getParent();
392 if ( parent ) {
393 newRange = parent.getOuterRange();
394 }
395 break;
396 default:
397 throw new Error( 'Invalid scope argument: ' + scope );
398 }
399 return this.clone(
400 newRange ?
401 new ve.dm.LinearSelection( newRange ) :
402 new ve.dm.NullSelection()
403 );
404 };
405
406 /**
407 * Get data for the fragment.
408 *
409 * @param {boolean} [deep] Get a deep copy of the data
410 * @return {Array} Fragment data
411 */
412 ve.dm.SurfaceFragment.prototype.getData = function ( deep ) {
413 const range = this.getSelection().getCoveringRange();
414 if ( !range ) {
415 return [];
416 }
417 return this.document.getData( range, deep );
418 };
419
420 /**
421 * Get plain text for the fragment.
422 *
423 * @param {boolean} [maintainIndices] Maintain data offset to string index alignment by replacing elements with line breaks
424 * @return {string} Fragment text
425 */
426 ve.dm.SurfaceFragment.prototype.getText = function ( maintainIndices ) {
427 const range = this.getSelection().getCoveringRange();
428 if ( !range ) {
429 return '';
430 }
431 return this.document.data.getText( maintainIndices, range );
432 };
433
434 /**
435 * Whether the fragment contains only text, allowing annotations
436 *
437 * @method
438 * @return {boolean} Whether there's only text
439 */
440 ve.dm.SurfaceFragment.prototype.containsOnlyText = function () {
441 const range = this.getSelection().getCoveringRange();
442 if ( !range ) {
443 return true;
444 }
445 return this.document.data.isPlainText( range, false, false, false, true );
446 };
447
448 /**
449 * Get annotations in fragment.
450 *
451 * By default, this will only get annotations that completely cover the fragment. Use the {all}
452 * argument to get all annotations that occur within the fragment.
453 *
454 * @param {boolean} [all] Get annotations which only cover some of the fragment
455 * @return {ve.dm.AnnotationSet} All annotation objects range is covered by
456 */
457 ve.dm.SurfaceFragment.prototype.getAnnotations = function ( all ) {
458 const selection = this.getSelection();
459
460 if ( selection.isCollapsed() ) {
461 return this.surface.getInsertionAnnotations();
462 } else {
463 let annotations = null;
464 const ranges = selection.getRanges( this.getDocument() );
465 for ( let i = 0, l = ranges.length; i < l; i++ ) {
466 const rangeAnnotations = this.getDocument().data.getAnnotationsFromRange( ranges[ i ], all, true );
467 if ( !rangeAnnotations ) {
468 continue;
469 }
470 if ( !annotations ) {
471 annotations = rangeAnnotations;
472 } else if ( all ) {
473 annotations.addSet( rangeAnnotations );
474 } else {
475 const matchingAnnotations = rangeAnnotations.getComparableAnnotationsFromSet( annotations );
476 if ( matchingAnnotations.isEmpty() ) {
477 // Nothing matched so our intersection is empty
478 annotations = matchingAnnotations;
479 break;
480 } else {
481 // Match in the other direction, to keep all distinct compatible annotations (e.g. both b and strong)
482 annotations = annotations.getComparableAnnotationsFromSet( rangeAnnotations );
483 annotations.addSet( matchingAnnotations );
484 }
485 }
486 }
487 return annotations || new ve.dm.AnnotationSet( this.getDocument().getStore() );
488 }
489 };
490
491 /**
492 * Check if the fragment has any annotations
493 *
494 * Quicker than doing !fragment.getAnnotations( true ).isEmpty() as
495 * it stops at the first sight of an annotation.
496 *
497 * @return {boolean} The fragment contains at least one annotation
498 */
499 ve.dm.SurfaceFragment.prototype.hasAnnotations = function () {
500 const ranges = this.getSelection().getRanges( this.getDocument() );
501
502 for ( let i = 0, l = ranges.length; i < l; i++ ) {
503 if ( this.getDocument().data.hasAnnotationsInRange( ranges[ i ] ) ) {
504 return true;
505 }
506 }
507 return false;
508 };
509
510 /**
511 * Get all leaf nodes covered by the fragment.
512 *
513 * @see {@link ve.Document#selectNodes} for more information about the return value.
514 *
515 * @return {Array} List of nodes and related information
516 */
517 ve.dm.SurfaceFragment.prototype.getLeafNodes = function () {
518 const range = this.getSelection().getCoveringRange();
519 if ( !range ) {
520 return [];
521 }
522
523 // Update in case the cache needs invalidating
524 this.update();
525 // Cache leafNodes because it's expensive to compute
526 if ( !this.leafNodes ) {
527 this.leafNodes = this.document.selectNodes( range, 'leaves' );
528 }
529 return this.leafNodes;
530 };
531
532 /**
533 * Get all leaf nodes excluding nodes where the selection is empty.
534 *
535 * @return {ve.dm.Node[]} List of nodes and related information
536 */
537 ve.dm.SurfaceFragment.prototype.getSelectedLeafNodes = function () {
538 const selectedLeafNodes = [],
539 leafNodes = this.getLeafNodes();
540 for ( let i = 0, len = leafNodes.length; i < len; i++ ) {
541 if ( len === 1 || !leafNodes[ i ].range || !leafNodes[ i ].range.isCollapsed() ) {
542 selectedLeafNodes.push( leafNodes[ i ].node );
543 }
544 }
545 return selectedLeafNodes;
546 };
547
548 /**
549 * Get the node selected by a range, i.e. the range matches the node's range exactly.
550 *
551 * Note that this method operates on the fragment's range, not the document's current selection.
552 * This fragment does not need to be selected for this method to work.
553 *
554 * @return {ve.dm.Node|null} The node selected by the range, or null if a node is not selected
555 */
556 ve.dm.SurfaceFragment.prototype.getSelectedNode = function () {
557 const surface = this.getSurface();
558
559 // Ensure the fragment is up to date
560 this.update();
561 return this.selection.equals( surface.getSelection() ) ?
562 // If the selection is equal to the surface's use the cached node
563 surface.getSelectedNode() :
564 surface.getSelectedNodeFromSelection( this.selection );
565 };
566
567 /**
568 * Get nodes covered by the fragment.
569 *
570 * Does not descend into nodes that are entirely covered by the range. The result is
571 * similar to that of {ve.dm.SurfaceFragment.prototype.getLeafNodes} except that if a node is
572 * entirely covered, its children aren't returned separately.
573 *
574 * @see {@link ve.Document#selectNodes} for more information about the return value.
575 *
576 * @return {Array} List of nodes and related information
577 */
578 ve.dm.SurfaceFragment.prototype.getCoveredNodes = function () {
579 const range = this.getSelection().getCoveringRange();
580 if ( !range ) {
581 return [];
582 }
583 return this.document.selectNodes( range, 'covered' );
584 };
585
586 /**
587 * Get nodes covered by the fragment.
588 *
589 * Includes adjacent siblings covered by the range, descending if the range is in a single node.
590 *
591 * @see {@link ve.Document#selectNodes} for more information about the return value.
592 *
593 * @return {Array} List of nodes and related information
594 */
595 ve.dm.SurfaceFragment.prototype.getSiblingNodes = function () {
596 const range = this.getSelection().getCoveringRange();
597 if ( !range ) {
598 return [];
599 }
600 return this.document.selectNodes( range, 'siblings' );
601 };
602
603 /**
604 * Check if the nodes at the current fragment have an ancestor with matching type and attribute values.
605 *
606 * @param {string} type Node type to match
607 * @param {Object} [attributes] Node attributes to match
608 * @param {boolean} [matchFirstAncestorOfType] Require the match to be the first of its type, e.g. if type is 'list',
609 * only match the first 'list' ancestor, then check if the attributes match.
610 * @return {boolean} Nodes have a matching ancestor
611 */
612 ve.dm.SurfaceFragment.prototype.hasMatchingAncestor = function ( type, attributes, matchFirstAncestorOfType ) {
613 const selection = this.getSelection();
614
615 let all;
616 if ( selection instanceof ve.dm.LinearSelection ) {
617 const nodes = this.getSelectedLeafNodes();
618 all = !!nodes.length;
619 for ( let i = 0, len = nodes.length; i < len; i++ ) {
620 if ( matchFirstAncestorOfType ) {
621 const node = nodes[ i ].findMatchingAncestor( type );
622 if ( !( node && node.compareAttributes( attributes ) ) ) {
623 all = false;
624 break;
625 }
626 } else {
627 if ( !nodes[ i ].hasMatchingAncestor( type, attributes ) ) {
628 all = false;
629 break;
630 }
631 }
632 }
633 } else if ( selection instanceof ve.dm.TableSelection ) {
634 const cells = selection.getMatrixCells( this.getDocument() );
635 all = true;
636 for ( let j = cells.length - 1; j >= 0; j-- ) {
637 if ( !cells[ j ].node.matches( type, attributes ) ) {
638 all = false;
639 break;
640 }
641 }
642 }
643
644 return all;
645 };
646
647 /**
648 * Clear a fragment's pending list
649 */
650 ve.dm.SurfaceFragment.prototype.clearPending = function () {
651 this.pending = [];
652 };
653
654 /**
655 * Push a promise to the fragment's pending list
656 *
657 * @param {jQuery.Promise} promise
658 */
659 ve.dm.SurfaceFragment.prototype.pushPending = function ( promise ) {
660 this.pending.push( promise );
661 };
662
663 /**
664 * Get a promise that resolves when the pending list is complete
665 *
666 * @return {jQuery.Promise}
667 */
668 ve.dm.SurfaceFragment.prototype.getPending = function () {
669 return ve.promiseAll( this.pending );
670 };
671
672 /**
673 * Apply the fragment's range to the surface as a selection.
674 *
675 * @return {ve.dm.SurfaceFragment}
676 * @chainable
677 */
678 ve.dm.SurfaceFragment.prototype.select = function () {
679 this.surface.setSelection( this.getSelection() );
680 return this;
681 };
682
683 /**
684 * Change one or more attributes on covered nodes.
685 *
686 * @param {Object} attr List of attributes to change, use undefined to remove an attribute
687 * @param {string} [type] Node type to restrict changes to
688 * @return {ve.dm.SurfaceFragment}
689 * @chainable
690 */
691 ve.dm.SurfaceFragment.prototype.changeAttributes = function ( attr, type ) {
692 const txs = [],
693 covered = this.getCoveredNodes();
694
695 for ( let i = 0, len = covered.length; i < len; i++ ) {
696 const result = covered[ i ];
697 if (
698 // Non-wrapped nodes have no attributes
699 !result.node.isWrapped() ||
700 // Filtering by node type
701 ( type && result.node.getType() !== type ) ||
702 // Ignore zero-length results
703 ( result.range && result.range.isCollapsed() )
704 ) {
705 continue;
706 }
707 txs.push(
708 ve.dm.TransactionBuilder.static.newFromAttributeChanges(
709 this.document, result.nodeOuterRange.start, attr
710 )
711 );
712 }
713 if ( txs.length ) {
714 this.change( txs );
715 }
716 return this;
717 };
718
719 /**
720 * Apply an annotation to content in the fragment.
721 *
722 * To avoid problems identified in T35108, use the {ve.dm.SurfaceFragment.trimLinearSelection} method.
723 *
724 * TODO: Optionally take an annotation set instead of name and data arguments and set/clear multiple
725 * annotations in a single transaction.
726 *
727 * @param {string} method Mode of annotation, either 'set' or 'clear'
728 * @param {string|ve.dm.Annotation|ve.dm.AnnotationSet} nameOrAnnotations Annotation name, for example: 'textStyle/bold',
729 * Annotation object or AnnotationSet
730 * @param {Object} [data] Additional annotation data (not used if annotation object is given)
731 * @return {ve.dm.SurfaceFragment}
732 * @chainable
733 */
734 ve.dm.SurfaceFragment.prototype.annotateContent = function ( method, nameOrAnnotations, data ) {
735 const ranges = this.getSelection().getRanges( this.getDocument() ),
736 txs = [];
737
738 let annotations = new ve.dm.AnnotationSet( this.getDocument().getStore() );
739 if ( nameOrAnnotations instanceof ve.dm.AnnotationSet ) {
740 annotations = nameOrAnnotations;
741 } else if ( nameOrAnnotations instanceof ve.dm.Annotation ) {
742 annotations.push( nameOrAnnotations );
743 } else {
744 const annotation = ve.dm.annotationFactory.create( nameOrAnnotations, data );
745 if ( method === 'set' ) {
746 annotations.push( annotation );
747 } else if ( method === 'clear' ) {
748 for ( let i = 0, ilen = ranges.length; i < ilen; i++ ) {
749 annotations.addSet(
750 this.document.data.getAnnotationsFromRange( ranges[ i ], true ).getAnnotationsByName( annotation.name )
751 );
752 }
753 }
754 }
755 for ( let i = 0, ilen = ranges.length; i < ilen; i++ ) {
756 const range = ranges[ i ];
757 if ( !range.isCollapsed() ) {
758 // Apply to selection
759 for ( let j = 0, jlen = annotations.getLength(); j < jlen; j++ ) {
760 const tx = ve.dm.TransactionBuilder.static.newFromAnnotation( this.document, range, method, annotations.get( j ) );
761 txs.push( tx );
762 }
763 } else {
764 // Apply annotation to stack
765 if ( method === 'set' ) {
766 this.surface.addInsertionAnnotations( annotations );
767 } else if ( method === 'clear' ) {
768 this.surface.removeInsertionAnnotations( annotations );
769 }
770 }
771 }
772 this.change( txs );
773
774 return this;
775 };
776
777 /**
778 * Remove content in the fragment and insert content before it.
779 *
780 * This will move the fragment's range to cover the inserted content. Note that this may be
781 * different from what a normal range translation would do: the insertion might occur
782 * at a different offset if that is needed to make the document balanced.
783 *
784 * If the content is a plain text string containing linebreaks, each line will be wrapped
785 * in a paragraph.
786 *
787 * @param {string|Array} content Content to insert, can be either a string or array of data
788 * @param {boolean|ve.dm.AnnotationSet} [annotateOrSet] Content should be automatically annotated to match surrounding content,
789 * or an AnnotationSet from the current offset (calculated from the view)
790 * @return {ve.dm.SurfaceFragment}
791 * @chainable
792 */
793 ve.dm.SurfaceFragment.prototype.insertContent = function ( content, annotateOrSet ) {
794 const range = this.getSelection().getCoveringRange(),
795 doc = this.getDocument();
796
797 if ( !range ) {
798 return this;
799 }
800
801 let annotations, annotate;
802 if ( annotateOrSet instanceof ve.dm.AnnotationSet ) {
803 annotations = annotateOrSet;
804 annotate = true;
805 } else {
806 annotate = annotateOrSet;
807 }
808
809 if ( !range.isCollapsed() ) {
810 if ( annotate ) {
811 // If we're replacing content, use the annotations selected
812 // instead of continuing from the left
813 annotations = this.getAnnotations();
814 }
815 this.removeContent();
816 }
817
818 const offset = range.start;
819 // Auto-convert content to array of plain text characters
820 if ( typeof content === 'string' ) {
821 const lines = content.split( /[\r\n]+/ );
822
823 if ( lines.length > 1 ) {
824 content = [];
825 for ( let i = 0, l = lines.length; i < l; i++ ) {
826 if ( lines[ i ].length ) {
827 content.push( { type: 'paragraph' } );
828 ve.batchPush( content, lines[ i ].split( '' ) );
829 content.push( { type: '/paragraph' } );
830 }
831 }
832 } else {
833 content = content.split( '' );
834 }
835 }
836 if ( content.length ) {
837 if ( annotate && !annotations ) {
838 // TODO T126021: Don't reach into properties of document
839 // FIXME T126022: the logic we actually need for annotating inserted content
840 // correctly is much more complicated
841 annotations = doc.data
842 .getAnnotationsFromOffset( offset === 0 ? 0 : offset - 1 );
843 }
844 if ( annotations && annotations.getLength() > 0 ) {
845 // Add the annotations to the content, passing the
846 // replaceComparable argument which will remove any comparable
847 // annotations from content so that they can be replaced with
848 // those in annotations. This has the effect of not double-
849 // wrapping any annotations which are identical apart from their
850 // original DOM element so we don't generate markup like
851 // <b>f<b>o</b>o</b> when pasting.
852 ve.dm.Document.static.addAnnotationsToData( content, annotations, true, doc.store );
853 }
854 const tx = ve.dm.TransactionBuilder.static.newFromInsertion( doc, offset, content );
855 // Set the range to cover the inserted content; the offset translation will be wrong
856 // if newFromInsertion() decided to move the insertion point
857 const newRange = tx.getModifiedRange( doc );
858 this.change( tx, newRange ? new ve.dm.LinearSelection( newRange ) : new ve.dm.NullSelection() );
859 }
860
861 return this;
862 };
863
864 /**
865 * Insert HTML in the fragment.
866 *
867 * This will move the fragment's range to cover the inserted content. Note that this may be
868 * different from what a normal range translation would do: the insertion might occur
869 * at a different offset if that is needed to make the document balanced.
870 *
871 * @param {string} html HTML to insert
872 * @param {Object} [importRules] The import rules for the target surface, if importing
873 * @return {ve.dm.SurfaceFragment}
874 * @chainable
875 */
876 ve.dm.SurfaceFragment.prototype.insertHtml = function ( html, importRules ) {
877 this.insertDocument( this.getDocument().newFromHtml( html, importRules ) );
878 return this;
879 };
880
881 /**
882 * Insert a ve.dm.Document in the fragment.
883 *
884 * This will move the fragment's range to cover the inserted content. Note that this may be
885 * different from what a normal range translation would do: the insertion might occur
886 * at a different offset if that is needed to make the document balanced.
887 *
888 * @param {ve.dm.Document} newDoc Document to insert
889 * @param {ve.Range} [newDocRange] Range from the new document to insert (defaults to entire document)
890 * @param {boolean|ve.dm.AnnotationSet} [annotateOrSet] Content should be automatically annotated to match surrounding content,
891 * or an AnnotationSet from the current offset (calculated from the view)
892 * @return {ve.dm.SurfaceFragment}
893 * @chainable
894 */
895 ve.dm.SurfaceFragment.prototype.insertDocument = function ( newDoc, newDocRange, annotateOrSet ) {
896 const range = this.getSelection().getCoveringRange(),
897 doc = this.getDocument();
898
899 if ( !range ) {
900 return this;
901 }
902
903 let annotations, annotate;
904 if ( annotateOrSet instanceof ve.dm.AnnotationSet ) {
905 annotations = annotateOrSet;
906 annotate = true;
907 } else {
908 annotate = annotateOrSet;
909 }
910
911 if ( !range.isCollapsed() ) {
912 if ( annotate ) {
913 // If we're replacing content, use the annotations selected
914 // instead of continuing from the left
915 annotations = this.getAnnotations();
916 }
917 this.removeContent();
918 }
919
920 const offset = range.start;
921 if ( annotate && !annotations ) {
922 // TODO T126021: Don't reach into properties of document
923 annotations = doc.data
924 .getAnnotationsFromOffset( offset === 0 ? 0 : offset - 1 );
925 }
926
927 let annotatedDoc;
928 if ( !annotations || annotations.getLength() === 0 ) {
929 annotatedDoc = newDoc;
930 } else {
931 // Build shallow-cloned annotatedData array, copying on write as we go
932 // FIXME T126022: the logic we actually need for annotating inserted content
933 // correctly is much more complicated
934 const annotatedData = newDoc.data.slice();
935 ve.dm.Document.static.addAnnotationsToData( annotatedData, annotations, true, newDoc.store, true );
936 annotatedDoc = newDoc.cloneWithData( annotatedData );
937 }
938 const tx = ve.dm.TransactionBuilder.static.newFromDocumentInsertion( doc, offset, annotatedDoc, newDocRange );
939 if ( !tx.isNoOp() ) {
940 // Set the range to cover the inserted content; the offset translation will be wrong
941 // if newFromInsertion() decided to move the insertion point
942 const newRange = tx.getModifiedRange( doc );
943 this.change( tx, newRange ? new ve.dm.LinearSelection( newRange ) : new ve.dm.NullSelection() );
944 }
945 return this;
946 };
947
948 /**
949 * Remove content in the fragment.
950 *
951 * @return {ve.dm.SurfaceFragment}
952 * @chainable
953 */
954 ve.dm.SurfaceFragment.prototype.removeContent = function () {
955 const range = this.getSelection().getCoveringRange();
956 if ( !range ) {
957 return this;
958 }
959
960 if ( !range.isCollapsed() ) {
961 this.change( ve.dm.TransactionBuilder.static.newFromRemoval( this.document, range ) );
962 }
963
964 return this;
965 };
966
967 /**
968 * Delete content and correct selection
969 *
970 * @param {number} [directionAfterDelete=-1] Direction to move after delete: 1 or -1 or 0
971 * @return {ve.dm.SurfaceFragment}
972 * @chainable
973 */
974 ve.dm.SurfaceFragment.prototype.delete = function ( directionAfterDelete ) {
975 const rangeToRemove = this.getSelection().getCoveringRange();
976
977 if ( !rangeToRemove || rangeToRemove.isCollapsed() ) {
978 return this;
979 }
980
981 // Try to build a removal transaction. At the moment the transaction processor is only
982 // capable of merging nodes of the same type and at the same depth level, so some or all
983 // of rangeToRemove may be left untouched (and in some cases tx may not remove anything
984 // at all).
985 let tx = ve.dm.TransactionBuilder.static.newFromRemoval( this.document, rangeToRemove );
986 this.change( tx );
987 let rangeAfterRemove = tx.translateRange( rangeToRemove );
988
989 let endNode;
990 if (
991 !rangeAfterRemove.isCollapsed() &&
992 ( endNode = this.document.getBranchNodeFromOffset( rangeAfterRemove.end, false ) ) &&
993 // If endNode is within our rangeAfterRemove, then we shouldn't delete it
994 endNode.getRange().start >= rangeAfterRemove.end
995 ) {
996 // If after processing removal transaction range is not collapsed it means that
997 // not everything got merged nicely, so we process further to deal with
998 // remaining content.
999
1000 let startNode = this.document.getBranchNodeFromOffset( rangeAfterRemove.start, false );
1001 if ( startNode.getRange().isCollapsed() ) {
1002 // If startNode has no content then just delete that node instead of
1003 // moving content from endNode to startNode. This prevents content being
1004 // inserted into empty structure, e.g. and empty heading will be deleted
1005 // rather than "converting" the paragraph beneath to a heading.
1006 while ( true ) {
1007 tx = ve.dm.TransactionBuilder.static.newFromRemoval( this.document, startNode.getOuterRange() );
1008 startNode = startNode.getParent();
1009 this.change( tx );
1010
1011 // If the removal resulted in the parent node being empty (e.g.
1012 // when startNode was a paragraph inside a list item), loop to
1013 // delete the parent node. Else break.
1014 if ( !( startNode && startNode.children.length === 0 && (
1015 startNode.hasSlugAtOffset( startNode.getRange().start ) ||
1016 // These would be uneditable when empty, so remove
1017 startNode instanceof ve.dm.DefinitionListNode ||
1018 startNode instanceof ve.dm.ListNode
1019 ) && startNode.canHaveChildrenNotContent() ) ) {
1020 break;
1021 }
1022 // Only fix up the range if we're going to loop (if we're not, the
1023 // range collapse using getNearestContentOffset below will already
1024 // do the fix up).
1025 rangeAfterRemove = tx.translateRange( rangeAfterRemove );
1026 }
1027 } else {
1028 // If startNode has content then take remaining content from endNode and
1029 // append it into startNode. Then remove endNode (and recursively any
1030 // ancestor that the removal causes to be empty).
1031 const endNodeData = this.document.getData( endNode.getRange() );
1032 let nodeToDelete = endNode;
1033 nodeToDelete.traverseUpstream( ( node ) => {
1034 const parent = node.getParent();
1035 if ( parent.children.length === 1 ) {
1036 nodeToDelete = parent;
1037 return true;
1038 } else {
1039 return false;
1040 }
1041 } );
1042 tx = ve.dm.TransactionBuilder.static.newFromRemoval(
1043 this.document,
1044 nodeToDelete.getOuterRange()
1045 );
1046 if ( !tx.isNoOp() ) {
1047 // Move contents of endNode into startNode, and delete nodeToDelete
1048 this.change( tx );
1049 this.change( ve.dm.TransactionBuilder.static.newFromInsertion(
1050 this.document,
1051 rangeAfterRemove.start,
1052 endNodeData
1053 ) );
1054 }
1055 }
1056 }
1057
1058 // Use a collapsed range at a content offset beside rangeAfterRemove.start
1059 const nearestOffset = this.document.data.getNearestContentOffset(
1060 rangeAfterRemove.start,
1061 // If undefined (e.g. cut), default to backwards movement
1062 directionAfterDelete || -1
1063 );
1064 if ( nearestOffset > -1 ) {
1065 rangeAfterRemove = new ve.Range( nearestOffset );
1066 } else {
1067 // There isn't a valid content offset. This probably means that we're
1068 // in a strange document which consists entirely of aliens, with no
1069 // text entered. This is unusual, but not impossible. As such, just
1070 // collapse the selection and accept that it won't really be
1071 // meaningful in most cases.
1072 rangeAfterRemove = new ve.Range( rangeAfterRemove.start );
1073 }
1074
1075 this.change( [], new ve.dm.LinearSelection( rangeAfterRemove ) );
1076
1077 return this;
1078 };
1079
1080 /**
1081 * Convert each content branch in the fragment from one type to another.
1082 *
1083 * @param {string} type Element type to convert to
1084 * @param {Object} [attr] Initial attributes for new element
1085 * @param {Object} [internal] Internal attributes for new element
1086 * @return {ve.dm.SurfaceFragment}
1087 * @chainable
1088 */
1089 ve.dm.SurfaceFragment.prototype.convertNodes = function ( type, attr, internal ) {
1090 const range = this.getSelection().getCoveringRange();
1091 if ( !range ) {
1092 return this;
1093 }
1094
1095 this.change( ve.dm.TransactionBuilder.static.newFromContentBranchConversion(
1096 this.document, range, type, attr, internal
1097 ) );
1098
1099 return this;
1100 };
1101
1102 /**
1103 * Wrap each node in the fragment with one or more elements.
1104 *
1105 * A wrapper object is a linear model element; a plain object containing a type property and an
1106 * optional attributes property.
1107 *
1108 * Example:
1109 * // fragment is a selection of: <p>a</p><p>b</p>
1110 * fragment.wrapNodes(
1111 * [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
1112 * )
1113 * // fragment is now a selection of: <ul><li><p>a</p></li></ul><ul><li><p>b</p></li></ul>
1114 *
1115 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
1116 * @param {string} wrapper.type Node type of wrapper
1117 * @param {Object} [wrapper.attributes] Attributes of wrapper
1118 * @return {ve.dm.SurfaceFragment}
1119 * @chainable
1120 */
1121 ve.dm.SurfaceFragment.prototype.wrapNodes = function ( wrapper ) {
1122 const range = this.getSelection().getCoveringRange();
1123 if ( !range ) {
1124 return this;
1125 }
1126
1127 if ( !Array.isArray( wrapper ) ) {
1128 wrapper = [ wrapper ];
1129 }
1130 this.change(
1131 ve.dm.TransactionBuilder.static.newFromWrap( this.document, range, [], [], [], wrapper )
1132 );
1133
1134 return this;
1135 };
1136
1137 /**
1138 * Unwrap nodes in the fragment out of one or more elements.
1139 *
1140 * Example:
1141 * // fragment is a selection of: <ul>「<li><p>a</p></li><li><p>b</p></li>」</ul>
1142 * fragment.unwrapNodes( 1, 1 )
1143 * // fragment is now a selection of: 「<p>a</p><p>b</p>」
1144 *
1145 * @param {number} outerDepth Number of nodes outside the selection to unwrap
1146 * @param {number} innerDepth Number of nodes inside the selection to unwrap
1147 * @return {ve.dm.SurfaceFragment}
1148 * @chainable
1149 */
1150 ve.dm.SurfaceFragment.prototype.unwrapNodes = function ( outerDepth, innerDepth ) {
1151 const range = this.getSelection().getCoveringRange();
1152
1153 if ( !range ) {
1154 return this;
1155 }
1156
1157 if ( range.getLength() < innerDepth * 2 ) {
1158 throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
1159 }
1160
1161 let i;
1162 const innerUnwrapper = [];
1163 const outerUnwrapper = [];
1164 for ( i = 0; i < innerDepth; i++ ) {
1165 innerUnwrapper.push( this.document.data.getData( range.start + i ) );
1166 }
1167 for ( i = outerDepth; i > 0; i-- ) {
1168 outerUnwrapper.push( this.document.data.getData( range.start - i ) );
1169 }
1170
1171 this.change( ve.dm.TransactionBuilder.static.newFromWrap(
1172 this.document, range, outerUnwrapper, [], innerUnwrapper, []
1173 ) );
1174
1175 return this;
1176 };
1177
1178 /**
1179 * Change the wrapping of each node in the fragment from one type to another.
1180 *
1181 * A wrapper object is a linear model element; a plain object containing a type property and an
1182 * optional attributes property.
1183 *
1184 * Example:
1185 * // fragment is a selection of: <dl><dt><p>a</p></dt></dl><dl><dt><p>b</p></dt></dl>
1186 * fragment.rewrapNodes(
1187 * 2,
1188 * [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
1189 * )
1190 * // fragment is now a selection of: <ul><li><p>a</p></li></ul><ul><li><p>b</p></li></ul>
1191 *
1192 * @param {number} depth Number of nodes to unwrap
1193 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
1194 * @param {string} wrapper.type Node type of wrapper
1195 * @param {Object} [wrapper.attributes] Attributes of wrapper
1196 * @return {ve.dm.SurfaceFragment}
1197 * @chainable
1198 */
1199 ve.dm.SurfaceFragment.prototype.rewrapNodes = function ( depth, wrapper ) {
1200 const range = this.getSelection().getCoveringRange();
1201
1202 if ( !range ) {
1203 return this;
1204 }
1205
1206 if ( !Array.isArray( wrapper ) ) {
1207 wrapper = [ wrapper ];
1208 }
1209
1210 if ( range.getLength() < depth * 2 ) {
1211 throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
1212 }
1213
1214 const unwrapper = [];
1215 for ( let i = 0; i < depth; i++ ) {
1216 unwrapper.push( this.document.data.getData( range.start + i ) );
1217 }
1218
1219 this.change(
1220 ve.dm.TransactionBuilder.static.newFromWrap( this.document, range, [], [], unwrapper, wrapper )
1221 );
1222
1223 return this;
1224 };
1225
1226 /**
1227 * Wrap nodes in the fragment with one or more elements.
1228 *
1229 * A wrapper object is a linear model element; a plain object containing a type property and an
1230 * optional attributes property.
1231 *
1232 * Example:
1233 * // fragment is a selection of: <p>a</p><p>b</p>
1234 * fragment.wrapAllNodes(
1235 * { type: 'list', attributes: { style: 'bullet' } },
1236 * { type: 'listItem' }
1237 * )
1238 * // fragment is now a selection of: <ul><li><p>a</p></li><li><p>b</p></li></ul>
1239 *
1240 * Example:
1241 * // fragment is a selection of: <p>a</p><p>b</p>
1242 * fragment.wrapAllNodes(
1243 * [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
1244 * )
1245 * // fragment is now a selection of: <ul><li><p>a</p><p>b</p></li></ul>
1246 *
1247 * @param {Object|Object[]} wrapOuter Opening element(s) to wrap around the range
1248 * @param {Object|Object[]} wrapEach Opening element(s) to wrap around each top-level element in the range
1249 * @return {ve.dm.SurfaceFragment}
1250 * @chainable
1251 */
1252 ve.dm.SurfaceFragment.prototype.wrapAllNodes = function ( wrapOuter, wrapEach ) {
1253 const range = this.getSelection().getCoveringRange();
1254 if ( !range ) {
1255 return this;
1256 }
1257
1258 if ( !Array.isArray( wrapOuter ) ) {
1259 wrapOuter = [ wrapOuter ];
1260 }
1261
1262 wrapEach = wrapEach || [];
1263
1264 if ( !Array.isArray( wrapEach ) ) {
1265 wrapEach = [ wrapEach ];
1266 }
1267
1268 this.change(
1269 ve.dm.TransactionBuilder.static.newFromWrap( this.document, range, [], wrapOuter, [], wrapEach )
1270 );
1271
1272 return this;
1273 };
1274
1275 /**
1276 * Change the wrapping of nodes in the fragment from one type to another.
1277 *
1278 * A wrapper object is a linear model element; a plain object containing a type property and an
1279 * optional attributes property.
1280 *
1281 * Example:
1282 * // fragment is a selection of: <h1><p>a</p><p>b</p></h1>
1283 * fragment.rewrapAllNodes( 1, { type: 'heading', attributes: { level: 2 } } );
1284 * // fragment is now a selection of: <h2><p>a</p><p>b</p></h2>
1285 *
1286 * @param {number} depth Number of nodes to unwrap
1287 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
1288 * @param {string} wrapper.type Node type of wrapper
1289 * @param {Object} [wrapper.attributes] Attributes of wrapper
1290 * @return {ve.dm.SurfaceFragment}
1291 * @chainable
1292 */
1293 ve.dm.SurfaceFragment.prototype.rewrapAllNodes = function ( depth, wrapper ) {
1294 const range = this.getSelection().getCoveringRange(),
1295 unwrapper = [];
1296
1297 if ( !range ) {
1298 return this;
1299 }
1300
1301 // TODO: preserve direction
1302 const innerRange = new ve.Range(
1303 range.start + depth,
1304 range.end - depth
1305 );
1306
1307 if ( !Array.isArray( wrapper ) ) {
1308 wrapper = [ wrapper ];
1309 }
1310
1311 if ( range.getLength() < depth * 2 ) {
1312 throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
1313 }
1314
1315 for ( let i = 0; i < depth; i++ ) {
1316 unwrapper.push( this.document.data.getData( range.start + i ) );
1317 }
1318
1319 this.change(
1320 ve.dm.TransactionBuilder.static.newFromWrap( this.document, innerRange, unwrapper, wrapper, [], [] )
1321 );
1322
1323 return this;
1324 };
1325
1326 /**
1327 * Isolates the nodes in a fragment then unwraps them.
1328 *
1329 * The node selection is expanded to siblings. These are isolated such that they are the
1330 * sole children of the nearest parent element which can 'type' can exist in.
1331 *
1332 * The new isolated selection is then safely unwrapped.
1333 *
1334 * @param {string} isolateForType Node type to isolate for
1335 * @return {ve.dm.SurfaceFragment}
1336 * @chainable
1337 */
1338 ve.dm.SurfaceFragment.prototype.isolateAndUnwrap = function ( isolateForType ) {
1339 const insertions = [],
1340 factory = ve.dm.nodeFactory,
1341 startSplitNodes = [],
1342 endSplitNodes = [];
1343 let startOffset, endOffset,
1344 outerDepth = 0,
1345 startSplitRequired = false,
1346 endSplitRequired = false;
1347
1348 function createSplits( splitNodes, insertBefore ) {
1349 const data = [];
1350
1351 let adjustment = 0;
1352 for ( let i = 0, length = splitNodes.length; i < length; i++ ) {
1353 data.unshift( { type: '/' + splitNodes[ i ].type } );
1354 data.push( splitNodes[ i ].getClonedElement() );
1355
1356 if ( insertBefore ) {
1357 adjustment += 2;
1358 }
1359 }
1360
1361 // Queue up transaction data
1362 insertions.push( {
1363 offset: insertBefore ? startOffset : endOffset,
1364 data: data
1365 } );
1366
1367 startOffset += adjustment;
1368 endOffset += adjustment;
1369 }
1370
1371 if ( !( this.selection instanceof ve.dm.LinearSelection ) ) {
1372 return this;
1373 }
1374
1375 const allowedParents = factory.getSuggestedParentNodeTypes( isolateForType );
1376 const nodes = this.getSiblingNodes();
1377
1378 // Find start split point, if required
1379 let startSplitNode = nodes[ 0 ].node;
1380 startOffset = startSplitNode.getOuterRange().start;
1381 if ( allowedParents !== null ) {
1382 while ( allowedParents.indexOf( startSplitNode.getParent().type ) === -1 ) {
1383 if ( startSplitNode.getParent().indexOf( startSplitNode ) > 0 ) {
1384 startSplitRequired = true;
1385 }
1386 startSplitNode = startSplitNode.getParent();
1387 if ( startSplitRequired ) {
1388 startSplitNodes.unshift( startSplitNode );
1389 } else {
1390 startOffset = startSplitNode.getOuterRange().start;
1391 }
1392 outerDepth++;
1393 }
1394 }
1395
1396 // Find end split point, if required
1397 let endSplitNode = nodes[ nodes.length - 1 ].node;
1398 endOffset = endSplitNode.getOuterRange().end;
1399 if ( allowedParents !== null ) {
1400 while ( allowedParents.indexOf( endSplitNode.getParent().type ) === -1 ) {
1401 if ( endSplitNode.getParent().indexOf( endSplitNode ) < endSplitNode.getParent().getChildren().length - 1 ) {
1402 endSplitRequired = true;
1403 }
1404 endSplitNode = endSplitNode.getParent();
1405 if ( endSplitRequired ) {
1406 endSplitNodes.unshift( endSplitNode );
1407 } else {
1408 endOffset = endSplitNode.getOuterRange().end;
1409 }
1410 }
1411 }
1412
1413 // We have to exclude insertions while doing splits, because we want the range to be
1414 // exactly what we're isolating, we don't want it to grow to include the separators
1415 // we're inserting (which would happen if one of them is immediately adjacent to the range)
1416 const oldExclude = this.willExcludeInsertions();
1417 this.setExcludeInsertions( true );
1418
1419 if ( startSplitRequired ) {
1420 createSplits( startSplitNodes, true );
1421 }
1422
1423 if ( endSplitRequired ) {
1424 createSplits( endSplitNodes, false );
1425 }
1426
1427 insertions.forEach( ( insertion ) => {
1428 this.change(
1429 ve.dm.TransactionBuilder.static.newFromInsertion( this.getDocument(), insertion.offset, insertion.data )
1430 );
1431 } );
1432
1433 this.setExcludeInsertions( oldExclude );
1434
1435 this.unwrapNodes( outerDepth, 0 );
1436
1437 return this;
1438 };
1439
1440 /**
1441 * Insert new metadata into the document. This builds and processes a transaction that inserts
1442 * metadata into the document.
1443 *
1444 * Pass a plain object rather than a MetaItem into this function unless you know what you're doing.
1445 *
1446 * @param {Object|ve.dm.MetaItem} meta Metadata element (or MetaItem) to insert
1447 * @param {number} offset Document offset to insert at; must be a valid offset for metadata;
1448 * defaults to document end
1449 */
1450 ve.dm.SurfaceFragment.prototype.insertMeta = function ( meta, offset ) {
1451 if ( arguments[ 2 ] !== undefined ) {
1452 throw new Error( 'Old "index" argument is no longer supported' );
1453 }
1454 if ( meta instanceof ve.dm.MetaItem ) {
1455 meta = meta.getElement();
1456 }
1457 const closeMeta = { type: '/' + meta.type };
1458 const doc = this.getDocument();
1459 if ( offset === undefined ) {
1460 offset = doc.getDocumentRange().end;
1461 }
1462 const tx = ve.dm.TransactionBuilder.static.newFromInsertion( doc, offset, [ meta, closeMeta ] );
1463 this.surface.change( tx );
1464 };
1465
1466 /**
1467 * Remove a meta item from the document. This builds and processes a transaction that removes the
1468 * associated metadata from the document.
1469 *
1470 * @param {ve.dm.MetaItem} item Item to remove
1471 */
1472 ve.dm.SurfaceFragment.prototype.removeMeta = function ( item ) {
1473 const tx = ve.dm.TransactionBuilder.static.newFromRemoval(
1474 this.getDocument(),
1475 item.getOuterRange(),
1476 true
1477 );
1478 this.surface.change( tx );
1479 };
1480
1481 /**
1482 * Replace a MetaItem with another in-place.
1483 *
1484 * Pass a plain object rather than a MetaItem into this function unless you know what you're doing.
1485 *
1486 * @param {ve.dm.MetaItem} oldItem Old item to replace
1487 * @param {Object|ve.dm.MetaItem} meta Metadata element (or MetaItem) to insert
1488 */
1489 ve.dm.SurfaceFragment.prototype.replaceMeta = function ( oldItem, meta ) {
1490 if ( meta instanceof ve.dm.MetaItem ) {
1491 meta = meta.getElement();
1492 }
1493 const closeMeta = { type: '/' + meta.type };
1494 const tx = ve.dm.TransactionBuilder.static.newFromReplacement(
1495 this.getDocument(),
1496 oldItem.getOuterRange(),
1497 [ meta, closeMeta ],
1498 true
1499 );
1500 this.surface.change( tx );
1501 };