Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel Document class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * DataModel document.
9 *
10 * WARNING: The data parameter is passed by reference. Do not modify a data array after passing
11 * it to this constructor, and do not construct multiple Documents with the same data array. If you
12 * need to do these things, make a deep copy (ve.copy) of the data array and operate on the
13 * copy.
14 *
15 * @class
16 * @extends ve.Document
17 * @constructor
18 * @param {Array|ve.dm.ElementLinearData} data Raw linear model data or ElementLinearData
19 * @param {HTMLDocument} [htmlDocument] HTML document the data was converted from, if any.
20 * If omitted, a new document will be created. If data is an HTMLDocument, this parameter is
21 * ignored.
22 * @param {ve.dm.Document} [parentDocument] Document to use as root for created nodes, used when cloning
23 * @param {ve.dm.InternalList} [internalList] Internal list to clone; passed when creating a document slice
24 * @param {Array.<string|undefined>} [innerWhitespace] Inner whitespace to clone; passed when creating a document slice
25 * @param {string} [lang] Language code
26 * @param {string} [dir='ltr'] Directionality (ltr/rtl)
27 * @param {ve.dm.Document} [originalDocument] Original document form which this was cloned.
28 * @param {boolean} [sourceMode] Document is in source mode
29 * @param {Object} [persistentStorage] Persistent storage object
30 */
31 ve.dm.Document = function VeDmDocument( data, htmlDocument, parentDocument, internalList, innerWhitespace, lang, dir, originalDocument, sourceMode, persistentStorage ) {
32 // Parent constructor
33 ve.dm.Document.super.call( this, new ve.dm.DocumentNode() );
34
35 // Initialization
36 const doc = parentDocument || this;
37 const root = this.documentNode;
38
39 this.lang = lang || 'en';
40 this.dir = dir || 'ltr';
41
42 this.sourceMode = !!sourceMode;
43
44 this.documentNode.setRoot( root );
45 // ve.Document already called setDocument(), but it could be that doc !== this
46 // so call it again
47 this.documentNode.setDocument( doc );
48 this.internalList = internalList ? internalList.clone( this ) : new ve.dm.InternalList( this );
49 this.innerWhitespace = innerWhitespace ? ve.copy( innerWhitespace ) : new Array( 2 );
50 this.metaList = new ve.dm.MetaList( this );
51
52 // Properties
53 this.parentDocument = parentDocument || null;
54 this.originalDocument = originalDocument || null;
55 this.nodesByType = {};
56 this.origInternalListLength = null;
57 this.readOnly = false;
58 this.attachedRoot = this.documentNode;
59
60 // Sparse array
61 this.branchNodeFromOffsetCache = [];
62
63 if ( data instanceof ve.dm.ElementLinearData ) {
64 this.data = data;
65 } else if ( data instanceof ve.dm.FlatLinearData ) {
66 this.data = new ve.dm.ElementLinearData( data.getStore(), data.getData() );
67 } else {
68 this.data = new ve.dm.ElementLinearData(
69 new ve.dm.HashValueStore(),
70 Array.isArray( data ) ? data : []
71 );
72 }
73 this.store = this.data.getStore();
74 this.completeHistory = new ve.dm.Change();
75 // Use the store by reference inside the completeHistory
76 this.completeHistory.store = this.store;
77 if ( this.store.getLength() > 0 ) {
78 // Push an identity transaction and the initial store
79 this.completeHistory.transactions.push( new ve.dm.Transaction( [ {
80 type: 'retain',
81 length: this.data.data.length
82 } ] ) );
83 this.completeHistory.storeLengthAtTransaction.push( this.store.getLength() );
84 }
85 this.htmlDocument = htmlDocument || ve.createDocumentFromHtml( '' );
86 this.persistentStorage = persistentStorage || {};
87 };
88
89 /* Inheritance */
90
91 OO.inheritClass( ve.dm.Document, ve.Document );
92
93 /* Events */
94
95 /**
96 * Emitted when a transaction is about to be committed.
97 *
98 * @event ve.dm.Document#precommit
99 * @param {ve.dm.Transaction} tx Transaction that is about to be committed
100 */
101
102 /**
103 * Emitted when a transaction has been committed.
104 *
105 * @event ve.dm.Document#transact
106 * @param {ve.dm.Transaction} tx Transaction that was just processed
107 */
108
109 /**
110 * A value in persistent storage has changed
111 *
112 * @event ve.dm.Document#storage
113 */
114
115 /* Static methods */
116
117 /**
118 * Apply annotations to content data.
119 *
120 * This method modifies data in place.
121 *
122 * @static
123 * @param {ve.dm.ElementLinearData|Array} data Data to apply annotations to
124 * @param {ve.dm.AnnotationSet} annotationSet Annotations to apply
125 * @param {boolean} [replaceComparable] Whether to remove annotations from the data which are comparable to those in annotationSet
126 * @param {ve.dm.HashValueStore} [store] Store associated with the data; only needs to be provided if that data is associated with a different store than annotationSet
127 * @param {boolean} [prepend] Whether to prepend annotationSet to the existing annotations
128 */
129 ve.dm.Document.static.addAnnotationsToData = function ( data, annotationSet, replaceComparable, store, prepend ) {
130 const offset = prepend ? 0 : undefined;
131
132 let ignoreChildrenDepth = 0;
133 if ( annotationSet.isEmpty() ) {
134 // Nothing to do
135 return;
136 }
137 if ( store ) {
138 store.merge( annotationSet.getStore() );
139 } else {
140 store = annotationSet.getStore();
141 }
142 if ( !( data instanceof ve.dm.ElementLinearData ) ) {
143 data = new ve.dm.ElementLinearData( store, data );
144 }
145
146 // Apply annotations to data
147 for ( let i = 0, length = data.getLength(); i < length; i++ ) {
148 if ( data.isElementData( i ) && ve.dm.nodeFactory.shouldIgnoreChildren( data.getType( i ) ) ) {
149 ignoreChildrenDepth += data.isOpenElementData( i ) ? 1 : -1;
150 }
151 if ( ignoreChildrenDepth ) {
152 continue;
153 }
154 const allowedAnnotations = annotationSet.filter( ( ann ) => data.canTakeAnnotationAtOffset( i, ann, true ) );
155 const existingAnnotations = data.getAnnotationsFromOffset( i, true );
156 let newAnnotationSet;
157 if ( !existingAnnotations.isEmpty() ) {
158 newAnnotationSet = existingAnnotations;
159 if ( replaceComparable ) {
160 newAnnotationSet = newAnnotationSet.withoutComparableSet( allowedAnnotations );
161 }
162 newAnnotationSet.addSet( allowedAnnotations, offset );
163 } else {
164 newAnnotationSet = allowedAnnotations;
165 }
166 data.setAnnotationsAtOffset( i, newAnnotationSet );
167 }
168 };
169
170 /**
171 * Provide a new, empty Document.
172 *
173 * @param {string} [paragraphType='empty'] Paragraph type: 'empty', 'wrapper' or null for a regular paragraph
174 * @return {ve.dm.Document}
175 */
176 ve.dm.Document.static.newBlankDocument = function ( paragraphType ) {
177 const paragraph = { type: 'paragraph' };
178
179 paragraphType = paragraphType === undefined ? 'empty' : paragraphType;
180
181 if ( paragraphType ) {
182 ve.setProp( paragraph, 'internal', 'generated', paragraphType );
183 }
184
185 return new ve.dm.Document( [
186 paragraph,
187 { type: '/paragraph' },
188 { type: 'internalList' },
189 { type: '/internalList' }
190 ] );
191 };
192
193 /* Methods */
194
195 /**
196 * @inheritdoc
197 */
198 ve.dm.Document.prototype.getDocumentNode = function () {
199 if ( !this.documentNode.length && !this.documentNode.getDocument().buildingNodeTree ) {
200 this.buildNodeTree();
201 }
202 return this.documentNode;
203 };
204
205 /**
206 * Set the attached root node
207 *
208 * @param {ve.dm.BranchNode} attachedRoot Attached root
209 */
210 ve.dm.Document.prototype.setAttachedRoot = function ( attachedRoot ) {
211 this.attachedRoot = attachedRoot;
212 };
213
214 /**
215 * Get the attached root node
216 *
217 * @return {ve.dm.BranchNode} Attached root
218 */
219 ve.dm.Document.prototype.getAttachedRoot = function () {
220 return this.attachedRoot;
221 };
222
223 /**
224 * Get a range that spans the entire document (excluding the internal list)
225 *
226 * @return {ve.Range} Document range
227 */
228 ve.dm.Document.prototype.getDocumentRange = function () {
229 return new ve.Range( 0, this.getInternalList().getListNode().getOuterRange().start );
230 };
231
232 /**
233 * Get a range that spans the attached root (excluding the internal list)
234 *
235 * @return {ve.Range} Attached root's range
236 */
237 ve.dm.Document.prototype.getAttachedRootRange = function () {
238 return this.attachedRoot === this.documentNode ? this.getDocumentRange() : this.attachedRoot.getRange();
239 };
240
241 /**
242 * Build the node tree.
243 */
244 ve.dm.Document.prototype.buildNodeTree = function () {
245 let textLength = 0,
246 inTextNode = false;
247
248 // Build a tree of nodes and nodes that will be added to them after a full scan is complete,
249 // then from the bottom up add nodes to their potential parents. This avoids massive length
250 // updates being broadcast upstream constantly while building is underway.
251 let currentStack = [];
252 let parentStack = [ this.documentNode ];
253 // Stack of stacks
254 const nodeStack = [ parentStack, currentStack ];
255 let currentNode = this.documentNode;
256 const doc = this.documentNode.getDocument();
257
258 for ( let i = 0, len = this.data.getLength(); i < len; i++ ) {
259 if ( !this.data.isElementData( i ) ) {
260 // Text node opening
261 if ( !inTextNode ) {
262 // Create a lengthless text node
263 const node = new ve.dm.TextNode();
264 // Put the node on the current inner stack
265 currentStack.push( node );
266 currentNode = node;
267 // Set a flag saying we're inside a text node
268 inTextNode = true;
269 }
270 // Track the length
271 textLength++;
272 } else {
273 // Text node closing
274 if ( inTextNode ) {
275 // Finish the text node by setting the length
276 currentNode.setLength( textLength );
277 // Put the state variables back as they were
278 currentNode = parentStack[ parentStack.length - 1 ];
279 inTextNode = false;
280 textLength = 0;
281 }
282 // Element open/close
283 if ( this.data.isOpenElementData( i ) ) {
284 // Branch or leaf node opening
285 // Create a childless node
286 const node = ve.dm.nodeFactory.createFromElement( this.data.getData( i ) );
287 // Put the childless node on the current inner stack
288 currentStack.push( node );
289 if ( ve.dm.nodeFactory.canNodeHaveChildren( node.getType() ) ) {
290 // Create a new inner stack for this node
291 parentStack = currentStack;
292 currentStack = [];
293 nodeStack.push( currentStack );
294 currentNode = node;
295 } else {
296 // Assert that the next element is a closing element for this node,
297 // and skip over it.
298 if (
299 !this.data.isCloseElementData( i + 1 ) ||
300 this.data.getType( i + 1 ) !== this.data.getType( i )
301 ) {
302 throw new Error( 'Opening element for node that cannot have children must be followed by closing element' );
303 }
304 i++;
305 }
306 } else {
307 // Branch or leaf node closing
308 if ( this.data.getType( i ) !== currentNode.getType() ) {
309 throw new Error( 'Expected closing for ' + currentNode.getType() +
310 ' but got closing for ' + this.data.getType( i ) );
311 }
312 // Pop this node's inner stack from the outer stack. It'll have all of the
313 // node's child nodes fully constructed
314 const children = nodeStack.pop();
315 currentStack = parentStack;
316 parentStack = nodeStack[ nodeStack.length - 2 ];
317 if ( !parentStack ) {
318 // This can only happen if we got unbalanced data
319 throw new Error( 'Unbalanced input passed to document' );
320 }
321 // Attach the children to the node
322 ve.batchSplice( currentNode, 0, 0, children );
323 currentNode = parentStack[ parentStack.length - 1 ];
324 }
325 }
326 }
327
328 if ( inTextNode ) {
329 // Text node ended by end-of-input rather than by an element
330 currentNode.setLength( textLength );
331 // Don't bother updating currentNode et al, we don't use them below
332 }
333
334 // State variable that allows nodes to know that they are being
335 // appended in order. Used by ve.dm.InternalList.
336 doc.buildingNodeTree = true;
337
338 // The end state is nodeStack = [ [this.documentNode], [ array, of, its, children ] ]
339 // so attach all nodes in currentStack to the root node
340 if ( nodeStack.length > 2 ) {
341 // A node was opened but never closed
342 throw new Error( 'Unbalanced input passed to document' );
343 }
344 ve.batchSplice( this.documentNode, 0, 0, currentStack );
345 this.updateNodesByType( [ this.documentNode ], [ this.documentNode ] );
346
347 doc.buildingNodeTree = false;
348 };
349
350 /**
351 * Get the length of the document. This is also the highest valid offset in the document.
352 *
353 * @return {number} Length of the document
354 */
355 ve.dm.Document.prototype.getLength = function () {
356 return this.data.getLength();
357 };
358
359 /**
360 * Get the meta list.
361 *
362 * @return {ve.dm.MetaList} Meta list of the surface
363 */
364 ve.dm.Document.prototype.getMetaList = function () {
365 // Ensure the DM tree has been built
366 this.getDocumentNode();
367 return this.metaList;
368 };
369
370 /**
371 * Set the read-only state of the document
372 *
373 * Actual locking of the model is done by the surface, but
374 * we pass through this flag so we can do some optimizations
375 * in read-only mode, such as caching node offsets.
376 *
377 * TODO: It might just be easier for Documents to know which
378 * Surface they belong to, although we should make sure that
379 * this doesn't violate the direction of data flow.
380 *
381 * @param {boolean} readOnly Mark document as read-only
382 */
383 ve.dm.Document.prototype.setReadOnly = function ( readOnly ) {
384 this.readOnly = !!readOnly;
385 if ( !this.readOnly ) {
386 // Clear offset cache when leaving read-only mode
387 this.getDocumentNode().traverse( ( node ) => {
388 node.offset = null;
389 } );
390 }
391 };
392
393 /**
394 * Check if the document is read-only
395 *
396 * @return {boolean}
397 */
398 ve.dm.Document.prototype.isReadOnly = function () {
399 return this.readOnly;
400 };
401
402 /**
403 * Apply a transaction's effects on the content data.
404 *
405 * @param {ve.dm.Transaction} transaction Transaction to apply
406 * @param {boolean} isStaging Transaction is being applied in staging mode
407 * @fires ve.dm.Document#precommit
408 * @fires ve.dm.Document#transact
409 * @throws {Error} Cannot commit a transaction that has already been committed
410 */
411 ve.dm.Document.prototype.commit = function ( transaction, isStaging ) {
412 if ( transaction.hasBeenApplied() ) {
413 throw new Error( 'Cannot commit a transaction that has already been committed' );
414 }
415 this.emit( 'precommit', transaction );
416 this.branchNodeFromOffsetCache = [];
417 new ve.dm.TransactionProcessor( this, transaction, isStaging ).process();
418 this.completeHistory.pushTransaction( transaction, this.store.getLength() );
419 this.emit( 'transact', transaction );
420 };
421
422 /**
423 * Get a slice or copy of the document data.
424 *
425 * @param {ve.Range} [range] Range of data to get, all data will be given by default
426 * @param {boolean} [deep=false] Whether to return a deep copy (WARNING! This may be very slow)
427 * @return {Array} Slice or copy of document data
428 */
429 ve.dm.Document.prototype.getData = function ( range, deep ) {
430 return this.data.getDataSlice( range, deep );
431 };
432
433 /**
434 * Get a copy of the document metadata.
435 *
436 * This is just a sparse shallow copy of the document data, with meta-item open tags only (i.e.
437 * with blanks in place of non-meta-items and meta-item close tags).
438 *
439 * @param {ve.Range} [range] Range of metadata to get, all metadata will be given by default
440 * @return {ve.dm.MetaItem[]} Sparse array of ve.dm.MetaItems.
441 */
442 ve.dm.Document.prototype.getMetadata = function ( range ) {
443 if ( arguments.length > 1 ) {
444 throw new Error( 'Argument "deep" is no longer supported' );
445 }
446 const documentNode = this.getDocumentNode();
447 if ( !range ) {
448 range = new ve.Range( 0, documentNode.length );
449 }
450 const data = [];
451 documentNode.traverse( ( node ) => {
452 let offset;
453 if ( node instanceof ve.dm.MetaItem ) {
454 offset = node.getOffset();
455 if ( range.start <= offset && offset < range.end ) {
456 data[ offset - range.start ] = node;
457 }
458 }
459 } );
460 data.length = range.end - range.start;
461 return data;
462 };
463
464 /**
465 * Get the HTMLDocument associated with this document.
466 *
467 * @return {HTMLDocument} Associated document
468 */
469 ve.dm.Document.prototype.getHtmlDocument = function () {
470 return this.htmlDocument;
471 };
472
473 /**
474 * Get the document model form which this document was cloned.
475 *
476 * @return {ve.dm.Document|null} Original document
477 */
478 ve.dm.Document.prototype.getOriginalDocument = function () {
479 return this.originalDocument;
480 };
481
482 /**
483 * Get the document's hash-value store
484 *
485 * @return {ve.dm.HashValueStore} The document's hash-value store
486 */
487 ve.dm.Document.prototype.getStore = function () {
488 return this.store;
489 };
490
491 /**
492 * Get the document's internal list
493 *
494 * @return {ve.dm.InternalList} The document's internal list
495 */
496 ve.dm.Document.prototype.getInternalList = function () {
497 return this.internalList;
498 };
499
500 /**
501 * Get the document's inner whitespace
502 *
503 * @return {Array.<string|undefined>} The document's inner whitespace
504 */
505 ve.dm.Document.prototype.getInnerWhitespace = function () {
506 return this.innerWhitespace;
507 };
508
509 /**
510 * Clone a sub-document from a shallow copy of this document.
511 *
512 * The new document's elements, internal list and store will only contain references to data within the slice.
513 *
514 * @param {ve.dm.Selection} selection Selection to create sub-document from
515 * @return {ve.dm.DocumentSlice} New document
516 */
517 ve.dm.Document.prototype.shallowCloneFromSelection = function ( selection ) {
518 if ( selection instanceof ve.dm.LinearSelection ) {
519 return this.shallowCloneFromRange( selection.getRange() );
520 } else if ( selection instanceof ve.dm.TableSelection ) {
521 const data = [];
522 const ranges = selection.getTableSliceRanges( this );
523 for ( let i = 0, l = ranges.length; i < l; i++ ) {
524 ve.batchPush( data, this.data.slice( ranges[ i ].start, ranges[ i ].end ) );
525 }
526 const linearData = new ve.dm.ElementLinearData( this.getStore(), data );
527
528 const tableRange = new ve.Range( 0, data.length );
529
530 // Copy over the internal list
531 ve.batchSplice(
532 linearData.data, linearData.getLength(), 0,
533 this.getData( this.getInternalList().getListNode().getOuterRange(), true )
534 );
535
536 // The internalList is rebuilt by the document constructor
537 return new ve.dm.TableSlice(
538 linearData, this.getHtmlDocument(), undefined, this.getInternalList(), tableRange, this
539 );
540 } else {
541 return this.shallowCloneFromRange( new ve.Range( 0 ) );
542 }
543 };
544
545 /**
546 * Clone a sub-document from a shallow copy of this document.
547 *
548 * The new document's elements, internal list and store will only contain references to data within the slice.
549 *
550 * @param {ve.Range} [range] Range of data to slice; defaults to whole document
551 * @return {ve.dm.DocumentSlice} New document
552 */
553 ve.dm.Document.prototype.shallowCloneFromRange = function ( range ) {
554 const balanceOpenings = [],
555 balanceClosings = [],
556 contextOpenings = [],
557 contextClosings = [];
558
559 let linearData, originalRange, balancedRange;
560 if ( !range ) {
561 // Default to the whole document
562 linearData = this.data.sliceObject();
563 originalRange = balancedRange = this.getDocumentRange();
564 } else {
565 const selection = this.selectNodes( range, 'siblings' );
566 const first = selection[ 0 ];
567 const last = selection[ selection.length - 1 ];
568 let firstNode = first.node;
569 let lastNode = last.node;
570
571 // Use first/lastNode if they are non-content branch nodes, otherwise use getBranchNodeFromOffset.
572 let startNode = !firstNode.hasChildren() && !firstNode.isContent() ? firstNode : this.getBranchNodeFromOffset( range.start );
573 let endNode = !lastNode.hasChildren() && !lastNode.isContent() ? lastNode : this.getBranchNodeFromOffset( range.end );
574
575 // Fix up selection to remove empty items in unwrapped nodes
576 // TODO: fix this is selectNodes
577 while ( selection[ 0 ] && selection[ 0 ].range && selection[ 0 ].range.isCollapsed() && !selection[ 0 ].node.isWrapped() ) {
578 selection.shift();
579 }
580
581 let i = selection.length - 1;
582 while ( selection[ i ] && selection[ i ].range && selection[ i ].range.isCollapsed() && !selection[ i ].node.isWrapped() ) {
583 selection.pop();
584 i--;
585 }
586
587 let balancedNodes;
588 if ( selection.length === 0 || range.isCollapsed() ) {
589 // Nothing selected
590 linearData = new ve.dm.ElementLinearData( this.getStore(), [
591 { type: 'paragraph', internal: { generated: 'empty' } },
592 { type: '/paragraph' }
593 ] );
594 originalRange = balancedRange = new ve.Range( 1 );
595 } else if ( startNode === endNode ) {
596 // Nothing to balance
597 balancedNodes = selection;
598 } else {
599 // Selection is not balanced
600 while ( !firstNode.isWrapped() ) {
601 firstNode = firstNode.getParent();
602 }
603 while ( !lastNode.isWrapped() ) {
604 lastNode = lastNode.getParent();
605 }
606
607 if ( first.range ) {
608 while ( true ) {
609 while ( !startNode.isWrapped() ) {
610 startNode = startNode.getParent();
611 }
612 balanceOpenings.push( startNode.getClonedElement() );
613 if ( startNode === firstNode ) {
614 break;
615 }
616 startNode = startNode.getParent();
617 }
618 }
619
620 if ( last !== first && last.range ) {
621 while ( true ) {
622 while ( !endNode.isWrapped() ) {
623 endNode = endNode.getParent();
624 }
625 balanceClosings.push( { type: '/' + endNode.getType() } );
626 if ( endNode === lastNode ) {
627 break;
628 }
629 endNode = endNode.getParent();
630 }
631 }
632
633 balancedNodes = this.selectNodes(
634 new ve.Range( firstNode.getOuterRange().start, lastNode.getOuterRange().end ),
635 'covered'
636 );
637 }
638
639 // eslint-disable-next-line no-inner-declarations
640 function nodeNeedsContext( node ) {
641 return node.getParentNodeTypes() !== null || node.isContent();
642 }
643
644 if ( !balancedRange ) {
645 // Check if any of the balanced siblings need more context for insertion anywhere
646 let needsContext = false;
647 for ( i = balancedNodes.length - 1; i >= 0; i-- ) {
648 if ( nodeNeedsContext( balancedNodes[ i ].node ) ) {
649 needsContext = true;
650 break;
651 }
652 }
653
654 if ( needsContext ) {
655 startNode = balancedNodes[ 0 ].node;
656 // Keep wrapping until the outer node can be inserted anywhere
657 while ( startNode.getParent() && nodeNeedsContext( startNode ) ) {
658 const isContent = startNode.isContent();
659 startNode = startNode.getParent();
660 const contextElement = startNode.getClonedElement();
661 if ( isContent ) {
662 ve.setProp( contextElement, 'internal', 'generated', 'wrapper' );
663 }
664 contextOpenings.push( contextElement );
665 contextClosings.push( { type: '/' + contextElement.type } );
666 }
667 }
668
669 // Final data:
670 // contextOpenings + balanceOpenings + data slice + balanceClosings + contextClosings
671 linearData = new ve.dm.ElementLinearData(
672 this.getStore(),
673 [].concat(
674 contextOpenings.reverse(),
675 balanceOpenings.reverse(),
676 this.data.slice( range.start, range.end ),
677 balanceClosings,
678 contextClosings
679 )
680 );
681 originalRange = new ve.Range(
682 contextOpenings.length + balanceOpenings.length,
683 contextOpenings.length + balanceOpenings.length + range.getLength()
684 );
685 balancedRange = new ve.Range(
686 contextOpenings.length,
687 contextOpenings.length + balanceOpenings.length + range.getLength() + balanceClosings.length
688 );
689 }
690
691 // Shallow copy over the internal list
692 ve.batchSplice(
693 linearData.data, linearData.getLength(), 0,
694 this.getData( this.getInternalList().getListNode().getOuterRange() )
695 );
696 }
697
698 // The internalList is rebuilt by the document constructor
699 const slice = new ve.dm.DocumentSlice(
700 linearData, this.getHtmlDocument(), undefined, this.getInternalList(), originalRange, balancedRange, this
701 );
702 return slice;
703 };
704
705 /**
706 * Clone a sub-document from a range in this document. The new document's elements, store and internal list
707 * will be clones of the ones in this document.
708 *
709 * @param {ve.Range} [range] Range of data to clone, clones the whole document if ommitted.
710 * @param {boolean} [detachedCopy] The copy is not intended to be merged into the original
711 * @param {string} [mode] Mode for getting data, see #getFullData
712 * @return {ve.dm.Document} New document
713 */
714 ve.dm.Document.prototype.cloneFromRange = function ( range, detachedCopy, mode ) {
715 const listRange = this.getInternalList().getListNode().getOuterRange();
716 const data = ve.copy( this.getFullData( range, mode || 'roundTrip' ) );
717 if ( range && ( range.start > listRange.start || range.end < listRange.end ) ) {
718 // The range does not include the entire internal list, so add it
719 ve.batchPush( data, this.getFullData( listRange ) );
720 }
721 return this.cloneWithData( data, true, detachedCopy );
722 };
723
724 /**
725 * Create a sub-document associated with this document like #cloneFromRange, but without cloning
726 * any data from a range in this document: instead, use the specified data.
727 *
728 * @param {Array|ve.dm.ElementLinearData} data Raw linear model data or ElementLinearData
729 * @param {boolean} [copyInternalList] Copy the internal list
730 * @param {boolean} [detachedCopy] The copy is not intended to be merged into the original
731 * @return {ve.dm.Document} New document
732 */
733 ve.dm.Document.prototype.cloneWithData = function ( data, copyInternalList, detachedCopy ) {
734 if ( Array.isArray( data ) ) {
735 data = new ve.dm.ElementLinearData( this.getStore().slice(), data );
736 }
737
738 const newDoc = new this.constructor(
739 data,
740 // htmlDocument
741 this.getHtmlDocument(),
742 // parentDocument
743 undefined,
744 // internalList
745 copyInternalList ? this.getInternalList() : undefined,
746 // innerWhitespace
747 undefined,
748 // lang+dir
749 this.getLang(), this.getDir(),
750 // originalDocument
751 this,
752 // sourceMode
753 this.sourceMode,
754 // persistentStorage
755 this.getStorage()
756 );
757 if ( copyInternalList && !detachedCopy ) {
758 // Record the length of the internal list at the time the slice was created so we can
759 // reconcile additions properly
760 newDoc.origInternalListLength = this.internalList.getItemNodeCount();
761 }
762 return newDoc;
763 };
764
765 /**
766 * Get document data, possibly with inline MetaItem load offsets restored, possibly without metadata
767 *
768 * @param {ve.Range} [range] Range to get full data for. If omitted, all data will be returned
769 * @param {string} [mode] If 'roundTrip', restore load offsets of inlined meta items from unchanged
770 * branches. If 'noMetadata', don't include metadata items.
771 * @return {Array} Data, with load offset info removed (some items are referenced, others copied)
772 */
773 ve.dm.Document.prototype.getFullData = function ( range, mode ) {
774 const insertedMetaItems = [],
775 insertions = {},
776 iLen = range ? range.end : this.data.getLength(),
777 result = [];
778
779 function stripMetaLoadInfo( element ) {
780 if ( !element || !element.internal ) {
781 return element;
782 }
783 element = ve.copy( element );
784 delete element.internal.changesSinceLoad;
785 delete element.internal.metaItems;
786 delete element.internal.loadMetaParentHash;
787 delete element.internal.loadMetaParentOffset;
788 if ( Object.keys( element.internal ).length === 0 ) {
789 delete element.internal;
790 }
791 return element;
792 }
793
794 for ( let i = range ? range.start : 0; i < iLen; i++ ) {
795 const item = this.data.getData( i );
796 if (
797 ve.dm.LinearData.static.isOpenElementData( item ) &&
798 ve.dm.nodeFactory.isMetaData( item.type ) &&
799 (
800 mode === 'noMetadata' ||
801 mode === 'roundTrip' && (
802 // Already inserted
803 insertedMetaItems.indexOf( item.originalDomElementsHash ) !== -1 ||
804 // Removable meta item that was not handled yet, which means that its entire branch node
805 // must have been removed, so it's out of place and should be removed too
806 ve.dm.nodeFactory.isRemovableMetaData( item.type ) && ve.getProp( item, 'internal', 'loadMetaParentOffset' )
807 )
808 )
809 ) {
810 // Skip this item and its matching close tag
811 i += 1;
812 continue;
813 }
814 let metaItem, metaItems, internal;
815 if (
816 mode === 'roundTrip' &&
817 ( internal = item.internal ) &&
818 ( metaItems = internal.metaItems )
819 ) {
820 if ( !internal.changesSinceLoad ) {
821 this.data.modifyData( i, ( dataItem ) => {
822 // Re-fetch unfrozen metaItems.
823 metaItems = dataItem.internal.metaItems;
824 // No changes, so restore meta item offsets
825 for ( let j = 0, jLen = metaItems.length; j < jLen; j++ ) {
826 metaItem = metaItems[ j ];
827 const offset = i + metaItem.internal.loadMetaParentOffset;
828 if ( !insertions[ offset ] ) {
829 insertions[ offset ] = [];
830 }
831
832 delete metaItem.internal.loadBranchNodeHash;
833 delete metaItem.internal.loadBranchNodeOffset;
834 if ( Object.keys( metaItem.internal ).length === 0 ) {
835 delete metaItem.internal;
836 }
837 insertions[ offset ].push( stripMetaLoadInfo( metaItem ) );
838 insertedMetaItems.push( metaItem.originalDomElementsHash );
839 }
840 } );
841 } else {
842 // Had changes, so remove removable meta items that are out of place now
843 for ( let j = 0, jLen = metaItems.length; j < jLen; j++ ) {
844 metaItem = metaItems[ j ];
845 if ( ve.dm.nodeFactory.isRemovableMetaData( metaItem.type ) ) {
846 insertedMetaItems.push( metaItem.originalDomElementsHash );
847 }
848 }
849 }
850 }
851 result.push( stripMetaLoadInfo( item ) );
852 if ( mode === 'roundTrip' && insertions[ i ] ) {
853 for ( let j = 0, jLen = insertions[ i ].length; j < jLen; j++ ) {
854 metaItem = insertions[ i ][ j ];
855 result.push( metaItem );
856 result.push( { type: '/' + metaItem.type } );
857 }
858 }
859 }
860 return result;
861 };
862
863 /**
864 * Get the nearest word boundary.
865 *
866 * @param {number} offset Offset to start from
867 * @param {number} [direction] Direction to prefer matching offset in, -1 for left and 1 for right
868 * @return {number} Nearest word boundary
869 */
870 ve.dm.Document.prototype.getSiblingWordBoundary = function ( offset, direction ) {
871 const dataString = new ve.dm.DataString( this.getData() );
872 return unicodeJS.wordbreak.moveBreakOffset( direction, dataString, offset, true );
873 };
874
875 /**
876 * Get the relative word or character boundary.
877 *
878 * @param {number} offset Offset to start from
879 * @param {number} direction Direction to prefer matching offset in, -1 for left and 1 for right
880 * @param {string} [unit] Unit [word|character]
881 * @return {number} Relative offset
882 */
883 ve.dm.Document.prototype.getRelativeOffset = function ( offset, direction, unit ) {
884 const data = this.data;
885 if ( unit === 'word' ) { // Word
886 // Method getSiblingWordBoundary does not "move/jump" over element data. If passed offset is
887 // an element data offset then the same offset is returned - and in such case this method
888 // fallback to the other path (character) which does "move/jump" over element data.
889 let newOffset = this.getSiblingWordBoundary( offset, direction );
890 if ( offset === newOffset ) {
891 newOffset = this.getRelativeOffset( offset, direction, 'character' );
892 }
893 return newOffset;
894 } else { // Character
895 // Check if we are adjacent to a focusable node
896 const adjacentDataOffset = offset + ( direction > 0 ? 0 : -1 );
897 if (
898 data.isElementData( adjacentDataOffset ) &&
899 ve.dm.nodeFactory.isNodeFocusable( data.getType( adjacentDataOffset ) )
900 ) {
901 // We are adjacent to a focusableNode, move inside it
902 return offset + direction;
903 }
904 const relativeContentOffset = data.getRelativeContentOffset( offset, direction );
905 let relativeStructuralOffset = data.getRelativeStructuralOffset( offset, direction, true );
906 let isFocusable;
907 // Check the structural offset is not in the wrong direction
908 if ( ( relativeStructuralOffset - offset < 0 ? -1 : 1 ) !== direction ) {
909 relativeStructuralOffset = offset;
910 } else {
911 isFocusable = ( relativeStructuralOffset - offset < 0 ? -1 : 1 ) === direction &&
912 data.isElementData( relativeStructuralOffset + direction ) &&
913 ve.dm.nodeFactory.isNodeFocusable( data.getType( relativeStructuralOffset + direction ) );
914 }
915 // Check if we've moved into a slug or a focusableNode
916 if ( isFocusable || this.hasSlugAtOffset( relativeStructuralOffset ) ) {
917 if ( isFocusable ) {
918 relativeStructuralOffset += direction;
919 }
920 // Check if the relative content offset is in the opposite direction we are trying to go
921 if (
922 relativeContentOffset === offset ||
923 ( relativeContentOffset - offset < 0 ? -1 : 1 ) !== direction
924 ) {
925 return relativeStructuralOffset;
926 }
927 // There's a slug nearby, go into it if it's closer
928 return direction > 0 ?
929 Math.min( relativeContentOffset, relativeStructuralOffset ) :
930 Math.max( relativeContentOffset, relativeStructuralOffset );
931 } else {
932 // Don't allow the offset to move in the wrong direction
933 return direction > 0 ?
934 Math.max( relativeContentOffset, offset ) :
935 Math.min( relativeContentOffset, offset );
936 }
937 }
938 };
939
940 /**
941 * Get the relative range.
942 *
943 * @param {ve.Range} range Input range
944 * @param {number} direction Direction to look in, +1 or -1
945 * @param {string} unit Unit [word|character]
946 * @param {boolean} expand Expanding range
947 * @param {ve.Range} [limit] Optional limiting range. If the relative range is not in this range
948 * the input range is returned instead.
949 * @return {ve.Range} Relative range
950 */
951 ve.dm.Document.prototype.getRelativeRange = function ( range, direction, unit, expand, limit ) {
952 let to = range.to;
953
954 // If you have a non-collapsed range and you move, collapse to the end
955 // in the direction you moved, provided you end up at a content or slug offset
956 if ( !range.isCollapsed() && !expand ) {
957 const newOffset = direction > 0 ? range.end : range.start;
958 if ( this.data.isContentOffset( newOffset ) || this.hasSlugAtOffset( newOffset ) ) {
959 return new ve.Range( newOffset );
960 } else {
961 to = newOffset;
962 }
963 }
964
965 const contentOrSlugOffset = this.getRelativeOffset( to, direction, unit );
966
967 const focusableNode = this.getNearestFocusableNode( to, direction, contentOrSlugOffset );
968 let newRange;
969 if ( focusableNode ) {
970 newRange = focusableNode.getOuterRange( direction === -1 );
971 } else {
972 newRange = new ve.Range( contentOrSlugOffset );
973 }
974 if ( limit && !limit.containsRange( newRange ) ) {
975 return range;
976 }
977 if ( expand ) {
978 return new ve.Range( range.from, newRange.to );
979 } else {
980 return newRange;
981 }
982 };
983
984 /**
985 * Get the nearest node matching a test.
986 *
987 * @param {Function} test Function to test whether a node matches, called with the nodeType
988 * @param {number} offset Offset to start looking at
989 * @param {number} direction Direction to look in, +1 or -1
990 * @param {number} limit Stop looking after reaching certain offset
991 * @return {ve.dm.Node|null} Nearest matching node, or null if not found
992 */
993 ve.dm.Document.prototype.getNearestNodeMatching = function ( test, offset, direction, limit ) {
994 // It is never an offset of the node, but just an offset for which getNodeFromOffset should
995 // return that node. Usually it would be node offset + 1 or offset of node closing tag.
996 let coveredOffset;
997 this.data.getRelativeOffset(
998 offset,
999 direction === 1 ? 0 : -1,
1000 function ( index, lim ) {
1001 // Our result must be between offset and limit
1002 if ( index >= Math.max( offset, lim ) || index < Math.min( offset, lim ) ) {
1003 return true;
1004 }
1005 if (
1006 this.isOpenElementData( index ) &&
1007 test( this.getType( index ) )
1008 ) {
1009 coveredOffset = index + 1;
1010 return true;
1011 }
1012 if (
1013 this.isCloseElementData( index ) &&
1014 test( this.getType( index ) )
1015 ) {
1016 coveredOffset = index;
1017 return true;
1018 }
1019 },
1020 limit
1021 );
1022 if ( coveredOffset ) {
1023 return this.getDocumentNode().getNodeFromOffset( coveredOffset );
1024 } else {
1025 return null;
1026 }
1027 };
1028
1029 /**
1030 * Get the nearest focusable node.
1031 *
1032 * @param {number} offset Offset to start looking at
1033 * @param {number} direction Direction to look in, +1 or -1
1034 * @param {number} limit Stop looking after reaching certain offset
1035 * @return {ve.dm.Node|null} Nearest focusable node, or null if not found
1036 */
1037 ve.dm.Document.prototype.getNearestFocusableNode = function ( offset, direction, limit ) {
1038 return this.getNearestNodeMatching( ( nodeType ) => ve.dm.nodeFactory.isNodeFocusable( nodeType ), offset, direction, limit );
1039 };
1040
1041 /**
1042 * Get the nearest offset that a cursor can be placed at.
1043 *
1044 * Note that an offset in the other direction can be returned if there are no valid offsets in the
1045 * preferred direction.
1046 *
1047 * @param {number} offset Offset to start looking at
1048 * @param {number} [direction=-1] Direction to check first, +1 or -1; if 0, find the closest offset
1049 * @return {number} Nearest offset a cursor can be placed at, or -1 if there are no valid offsets in
1050 * data
1051 */
1052 ve.dm.Document.prototype.getNearestCursorOffset = function ( offset, direction ) {
1053 if ( direction === 0 ) {
1054 const left = this.getNearestCursorOffset( offset, -1 );
1055 const right = this.getNearestCursorOffset( offset, 1 );
1056 // If only one of `left` and `right` is valid, return the valid one.
1057 // If neither is valid, this returns -1.
1058 if ( right === -1 ) {
1059 return left;
1060 } else if ( left === -1 ) {
1061 return right;
1062 }
1063 return offset - left < right - offset ? left : right;
1064 }
1065
1066 direction = direction > 0 ? 1 : -1;
1067 if (
1068 this.data.isContentOffset( offset ) ||
1069 this.hasSlugAtOffset( offset )
1070 ) {
1071 return offset;
1072 }
1073
1074 const contentOffset = this.data.getNearestContentOffset( offset, direction );
1075 const structuralOffset = this.data.getNearestStructuralOffset( offset, direction, true );
1076
1077 // If only one of `contentOffset` and `structuralOffset` is valid, return the valid one.
1078 // If neither is valid, this returns -1.
1079 if ( structuralOffset === -1 || !this.hasSlugAtOffset( structuralOffset ) ) {
1080 return contentOffset;
1081 } else if ( contentOffset === -1 ) {
1082 return structuralOffset;
1083 }
1084
1085 if ( direction === 1 ) {
1086 if ( contentOffset < offset ) {
1087 return structuralOffset;
1088 } else {
1089 return Math.min( contentOffset, structuralOffset );
1090 }
1091 } else {
1092 if ( contentOffset > offset ) {
1093 return structuralOffset;
1094 } else {
1095 return Math.max( contentOffset, structuralOffset );
1096 }
1097 }
1098 };
1099
1100 /**
1101 * @inheritdoc
1102 */
1103 ve.dm.Document.prototype.getBranchNodeFromOffset = function ( offset ) {
1104 if ( offset < 0 || offset > this.data.getLength() ) {
1105 throw new Error( 've.dm.Document.getBranchNodeFromOffset(): offset ' + offset + ' is out of bounds' );
1106 }
1107 if ( !this.branchNodeFromOffsetCache[ offset ] ) {
1108 this.branchNodeFromOffsetCache[ offset ] = ve.Document.prototype.getBranchNodeFromOffset.call( this, offset );
1109 }
1110 return this.branchNodeFromOffsetCache[ offset ];
1111 };
1112
1113 /**
1114 * Check if there is a slug at an offset.
1115 *
1116 * @param {number} offset Offset to check for a slug at
1117 * @return {boolean} There is a slug at the offset
1118 */
1119 ve.dm.Document.prototype.hasSlugAtOffset = function ( offset ) {
1120 let node;
1121 try {
1122 node = this.getBranchNodeFromOffset( offset );
1123 } catch ( e ) {
1124 // Offset was out of bounds
1125 }
1126 return node ? node.hasSlugAtOffset( offset ) : false;
1127 };
1128
1129 /**
1130 * Get the content data of a node.
1131 *
1132 * @param {ve.dm.Node} node Node to get content data for
1133 * @return {Array|null} List of content and elements inside node or null if node is not found
1134 */
1135 ve.dm.Document.prototype.getDataFromNode = function ( node ) {
1136 let offset = node.getOffset();
1137 if ( offset >= 0 ) {
1138 // FIXME T126023: If the node is wrapped in an element than we should increment
1139 // the offset by one so we only return the content inside the element.
1140 if ( node.isWrapped() ) {
1141 offset++;
1142 }
1143 return this.data.slice( offset, offset + node.getLength() );
1144 }
1145 return null;
1146 };
1147
1148 /**
1149 * Rebuild the entire node tree from linear model data.
1150 */
1151 ve.dm.Document.prototype.rebuildTree = function () {
1152 // attachedRootRange is an inner range for a non-document node,
1153 // so that we never rebuild above the attachedRoot node as that
1154 // would destroy that node, and invalidate all references to it (T293254).
1155 // When it is the full document it spans all nodes in the document,
1156 // excluding the interna list.
1157 const attachedRoot = this.getAttachedRoot();
1158 this.rebuildTreeNode( attachedRoot );
1159 };
1160
1161 /**
1162 * Rebuild the node tree from linear model data from a specicifc range.
1163 *
1164 * @param {ve.dm.BranchNode} rootNode Node to rebuild
1165 */
1166 ve.dm.Document.prototype.rebuildTreeNode = function ( rootNode ) {
1167 if ( !rootNode.length ) {
1168 this.buildNodeTree();
1169 }
1170 const range = rootNode.getRange();
1171 const data = this.data.sliceObject( range.start, range.end );
1172 // Build document fragment from data
1173 // Use plain ve.dm.Document, instead of whatever this.constructor is.
1174 const documentFragment = new ve.dm.Document( data, this.htmlDocument, this );
1175 // Get generated child nodes from the document fragment
1176 const addedNodes = documentFragment.getDocumentNode().getChildren();
1177 // Replace nodes in the model tree
1178 const removedNodes = ve.batchSplice( rootNode, 0, rootNode.getChildren().length, addedNodes );
1179
1180 this.updateNodesByType( addedNodes, removedNodes );
1181
1182 // Clear branch node cache
1183 this.branchNodeFromOffsetCache = [];
1184 };
1185
1186 /**
1187 * Update the nodes-by-type index
1188 *
1189 * @param {ve.dm.Node[]} addedNodes Added nodes
1190 * @param {ve.dm.Node[]} removedNodes Removed nodes
1191 */
1192 ve.dm.Document.prototype.updateNodesByType = function ( addedNodes, removedNodes ) {
1193 const remove = ( node ) => {
1194 const type = node.getType(),
1195 nodes = this.nodesByType[ type ] || [],
1196 index = nodes.indexOf( node );
1197
1198 if ( index !== -1 ) {
1199 nodes.splice( index, 1 );
1200 if ( !nodes.length ) {
1201 delete this.nodesByType[ type ];
1202 }
1203 }
1204 };
1205
1206 const add = ( node ) => {
1207 const type = node.getType(),
1208 nodes = this.nodesByType[ type ] = this.nodesByType[ type ] || [];
1209
1210 nodes.push( node );
1211 };
1212
1213 const traverse = ( nodes, action ) => {
1214 nodes.forEach( ( node ) => {
1215 if ( node.hasChildren() ) {
1216 node.traverse( action );
1217 }
1218 action( node );
1219 } );
1220 };
1221
1222 traverse( removedNodes, remove );
1223 traverse( addedNodes, add );
1224 };
1225
1226 /**
1227 * Get all nodes in the tree for a specific type
1228 *
1229 * If a string type is passed only nodes of that exact type will be returned,
1230 * if a node class is passed, all sub types will be matched.
1231 *
1232 * String type matching will be faster than class matching.
1233 *
1234 * @param {string|Function} type Node type name or node constructor
1235 * @param {boolean} sort Sort nodes by document order
1236 * @return {ve.dm.Node[]} Nodes of a specific type
1237 */
1238 ve.dm.Document.prototype.getNodesByType = function ( type, sort ) {
1239 if ( !this.documentNode.length && !this.documentNode.getDocument().buildingNodeTree ) {
1240 this.buildNodeTree();
1241 }
1242 let nodes;
1243 if ( type instanceof Function ) {
1244 nodes = [];
1245 for ( const t in this.nodesByType ) {
1246 const nodeType = ve.dm.nodeFactory.lookup( t );
1247 if ( nodeType === type || nodeType.prototype instanceof type ) {
1248 ve.batchPush( nodes, this.getNodesByType( t ) );
1249 }
1250 }
1251 } else {
1252 nodes = this.nodesByType[ type ] || [];
1253 }
1254
1255 if ( sort ) {
1256 nodes.sort( ( a, b ) => a.getOffset() - b.getOffset() );
1257 }
1258 return nodes;
1259 };
1260
1261 /**
1262 * @typedef FixedInsertion
1263 * @memberof ve.dm.Document
1264 * @property {Array} data Possibly modified copy of `data`
1265 * @property {number} offset Possibly modified offset
1266 * @property {number} remove Number of elements to remove after the modified `offset`
1267 * @property {number} [insertedDataOffset] Offset of intended insertion within fixed up data
1268 * @property {number} [insertedDataLength] Length of intended insertion within fixed up data
1269 */
1270
1271 /**
1272 * Fix up data so it can safely be inserted into the document data at an offset.
1273 *
1274 * TODO: this function needs more work but it seems to work, mostly
1275 *
1276 * @param {Array} data Snippet of linear model data to insert
1277 * @param {number} offset Offset in the linear model where the caller wants to insert data
1278 * @return {ve.dm.Document.FixedInsertion}
1279 */
1280 ve.dm.Document.prototype.fixupInsertion = function ( data, offset ) {
1281 const
1282 // Array where we build the return value
1283 newData = [],
1284
1285 // Inserting block element into an empty content branch will replace it.
1286 remove = 0,
1287
1288 // *** Stacks ***
1289 // Array of element openings (object). Openings in data are pushed onto this stack
1290 // when they are encountered and popped off when they are closed
1291 openingStack = [],
1292 // Array of node objects. Closings in data that close nodes that were
1293 // not opened in data (i.e. were already in the document) are pushed onto this stack
1294 // and popped off when balanced out by an opening in data
1295 closingStack = [];
1296
1297 // Track the position of the original data in the fixed up data for range adjustments
1298 let insertedDataOffset = 0,
1299 insertedDataLength = data.length,
1300
1301 // *** State persisting across iterations of the outer loop ***
1302 // The node (from the document) we're currently in. When in a node that was opened
1303 // in data, this is set to its first ancestor that is already in the document
1304 parentNode,
1305 // The type of the node we're currently in, even if that node was opened within data
1306 parentType,
1307 // Whether we are currently in a text node
1308 inTextNode,
1309 // Whether this is the first child of its parent
1310 // The test for last child isn't a loop so we don't need to cache it
1311 isFirstChild = null;
1312
1313 /**
1314 * Append a linear model element to newData and update the state.
1315 *
1316 * This function updates parentNode, parentType, openingStack and closingStack.
1317 *
1318 * @private
1319 * @param {Object|Array|string} element Linear model element
1320 * @param {number} index Index in data that the element came from (for error reporting only)
1321 */
1322 function writeElement( element, index ) {
1323 if ( element.type !== undefined ) {
1324 // Content, do nothing
1325 if ( element.type.charAt( 0 ) !== '/' ) {
1326 // Opening
1327 // Check if this opening balances an earlier closing of a node that was already in
1328 // the document. This is only the case if openingStack is empty (otherwise we still
1329 // have unclosed nodes from within data) and if this opening matches the top of
1330 // closingStack
1331 if ( openingStack.length === 0 && closingStack.length > 0 &&
1332 closingStack[ closingStack.length - 1 ].getType() === element.type
1333 ) {
1334 // The top of closingStack is now balanced out, so remove it
1335 // Also restore parentNode from closingStack. While this is technically not
1336 // entirely accurate (the current node is a new node that's a sibling of this
1337 // node), it's good enough for the purposes of this algorithm
1338 parentNode = closingStack.pop();
1339 } else {
1340 // This opens something new, put it on openingStack
1341 openingStack.push( element );
1342 }
1343 parentType = element.type;
1344 } else {
1345 let expectedType;
1346 // Closing
1347 // Make sure that this closing matches the currently opened node
1348 if ( openingStack.length > 0 ) {
1349 // The opening was on openingStack, so we're closing a node that was opened
1350 // within data. Don't track that on closingStack
1351 expectedType = openingStack.pop().type;
1352 } else {
1353 // openingStack is empty, so we're closing a node that was already in the
1354 // document. This means we have to reopen it later, so track this on
1355 // closingStack
1356 expectedType = parentNode.getType();
1357 closingStack.push( parentNode );
1358 parentNode = parentNode.getParent();
1359 if ( !parentNode ) {
1360 throw new Error( 'Inserted data is trying to close the root node ' +
1361 '(at index ' + index + ')' );
1362 }
1363 parentType = expectedType;
1364
1365 // Validate
1366 // FIXME this breaks certain input, should fix it up, not scream and die
1367 // For now we fall back to inserting balanced data, but then we miss out on
1368 // a lot of the nice content adoption abilities of just fixing up the data in
1369 // the context of the insertion point - an example of how this will fail is if
1370 // you try to insert "b</p></li></ul><p>c" into "<p>a[cursor]d</p>"
1371 if (
1372 element.type !== '/' + expectedType &&
1373 (
1374 // Only throw an error if the content can't be adopted from one content
1375 // branch to another
1376 !ve.dm.nodeFactory.canNodeContainContent( element.type.slice( 1 ) ) ||
1377 !ve.dm.nodeFactory.canNodeContainContent( expectedType )
1378 )
1379 ) {
1380 throw new Error( 'Cannot adopt content from ' + element.type +
1381 ' nodes into ' + expectedType + ' nodes (at index ' + index + ')' );
1382 }
1383 }
1384 }
1385 }
1386 newData.push( element );
1387 }
1388
1389 /**
1390 * Close the current element on the stack and arrange for its later reopening
1391 *
1392 * This function updates parentNode, parentType, closingStack, reopenElements, and closings.
1393 *
1394 * @private
1395 * @param {Array} closings Closing elements array to be appended to
1396 * @param {Array} reopenElements Opening elements array to be appended to
1397 * @param {string} type Current element type we're considering (for error reporting only)
1398 * @param {number} index Current index (for error reporting only)
1399 */
1400 function closeElement( closings, reopenElements, type, index ) {
1401 // Close the parent and try one level up
1402 closings.push( { type: '/' + parentType } );
1403 if ( openingStack.length > 0 ) {
1404 const element = openingStack.pop();
1405 parentType = element.type;
1406 reopenElements.push( ve.copy( element ) );
1407 // The opening was on openingStack, so we're closing a node that was opened
1408 // within data. Don't track that on closingStack
1409 } else {
1410 if ( !parentNode.getParent() ) {
1411 throw new Error( 'Cannot insert ' + type + ' even after closing ' +
1412 'all containing nodes (at index ' + index + ')' );
1413 }
1414 // openingStack is empty, so we're closing a node that was already in the
1415 // document. This means we have to reopen it later, so track this on
1416 // closingStack
1417 closingStack.push( parentNode );
1418 reopenElements.push( parentNode.getClonedElement() );
1419 parentNode = parentNode.getParent();
1420 parentType = parentNode.getType();
1421 }
1422 }
1423
1424 parentNode = this.getBranchNodeFromOffset( offset );
1425 parentType = parentNode.getType();
1426 inTextNode = false;
1427 isFirstChild = this.data.isOpenElementData( offset - 1 );
1428
1429 for ( let i = 0; i < data.length; i++ ) {
1430 if ( inTextNode && data[ i ].type !== undefined ) {
1431 parentType = openingStack.length > 0 ?
1432 openingStack[ openingStack.length - 1 ].type : parentNode.getType();
1433 }
1434 if ( data[ i ].type === undefined || data[ i ].type.charAt( 0 ) !== '/' ) {
1435 // The type of the node we're currently inserting. When the to-be-inserted node
1436 // is wrapped, this is set to the type of the outer wrapper.
1437 let childType = data[ i ].type || 'text';
1438 // Array of opening elements to insert (for wrapping the to-be-inserted element)
1439 const openings = [];
1440 // Array of closing elements to insert (for splitting nodes)
1441 const closings = [];
1442 // Array of opening elements matching the elements in closings (in the same order)
1443 const reopenElements = [];
1444 // Opening or content
1445 // Make sure that opening this element here does not violate the parent/children/content
1446 // rules. If it does, insert stuff to fix it
1447
1448 // If this node is content, check that the containing node can contain content.
1449 // If not, add a wrapper paragraph
1450 if ( ve.dm.nodeFactory.isNodeContent( childType ) &&
1451 !ve.dm.nodeFactory.canNodeContainContent( parentType )
1452 ) {
1453 childType = 'paragraph';
1454 const wrapper = ve.dm.nodeFactory.getDataElement( childType );
1455 ve.setProp( wrapper, 'internal', 'generated', 'wrapper' );
1456 openings.unshift( wrapper );
1457 }
1458
1459 // Check that this node is allowed to have the containing node as its parent. If not,
1460 // wrap it until it's fixed
1461 let parentsOK;
1462 do {
1463 const allowedParents = ve.dm.nodeFactory.getParentNodeTypes( childType );
1464 parentsOK = allowedParents === null ||
1465 allowedParents.indexOf( parentType ) !== -1;
1466 if ( !parentsOK ) {
1467 // We can't have this as the parent
1468 if ( allowedParents.length === 0 ) {
1469 throw new Error( 'Cannot insert ' + childType + ' because it ' +
1470 ' cannot have a parent (at index ' + i + ')' );
1471 }
1472 // Open an allowed node around this node
1473 childType = allowedParents[ 0 ];
1474 openings.unshift( ve.dm.nodeFactory.getDataElement( childType ) );
1475 }
1476 } while ( !parentsOK );
1477
1478 // Check that the node is allowed to have the containing node as
1479 // its parent. If not, close surrounding nodes until the node is
1480 // contained in an acceptable parent.
1481 const suggestedParents = ve.dm.nodeFactory.getSuggestedParentNodeTypes( childType );
1482 let suggestedParentsOK;
1483 do {
1484 suggestedParentsOK = suggestedParents === null ||
1485 suggestedParents.indexOf( parentType ) !== -1;
1486 if ( !suggestedParentsOK ) {
1487 closeElement( closings, reopenElements, childType, i );
1488 }
1489 } while ( !suggestedParentsOK );
1490
1491 // Check that the containing node can have this node as its child. If not, close nodes
1492 // until it's fixed
1493 let childrenOK;
1494 do {
1495 const allowedChildren = ve.dm.nodeFactory.getChildNodeTypes( parentType );
1496 childrenOK = allowedChildren === null ||
1497 allowedChildren.indexOf( childType ) !== -1;
1498 // Also check if we're trying to insert structure into a node that has to contain
1499 // content
1500 childrenOK = childrenOK && !(
1501 !ve.dm.nodeFactory.isNodeContent( childType ) &&
1502 ve.dm.nodeFactory.canNodeContainContent( parentType )
1503 );
1504 if ( !childrenOK ) {
1505 // We can't insert this into this parent
1506 if ( isFirstChild ) {
1507 // This element would be the first child of its parent, so
1508 // abandon this fix up and try again one offset to the left
1509 const insertion = this.fixupInsertion( data, offset - 1 );
1510 if ( this.data.isCloseElementData( offset ) && !ve.dm.nodeFactory.isNodeInternal( parentType ) ) {
1511 // This element would also be the last child, so that means parent is empty.
1512 // Remove it entirely. (Never remove the internal list though, ugh...)
1513 insertion.remove += 2;
1514 }
1515 return insertion;
1516 }
1517
1518 // Close the parent and try one level up
1519 closeElement( closings, reopenElements, childType, i );
1520 }
1521 } while ( !childrenOK );
1522
1523 for ( let j = 0; j < closings.length; j++ ) {
1524 // writeElement() would update openingStack/closingStack, but we've already done
1525 // that for closings
1526 if ( i === 0 ) {
1527 insertedDataOffset++;
1528 } else {
1529 insertedDataLength++;
1530 }
1531 newData.push( closings[ j ] );
1532 }
1533 for ( let j = 0; j < openings.length; j++ ) {
1534 if ( i === 0 ) {
1535 insertedDataOffset++;
1536 } else {
1537 insertedDataLength++;
1538 }
1539 writeElement( openings[ j ], i );
1540 }
1541 writeElement( data[ i ], i );
1542 if ( data[ i ].type === undefined ) {
1543 // Special treatment for text nodes
1544 inTextNode = true;
1545 if ( openings.length > 0 ) {
1546 // We wrapped the text node, update parentType
1547 parentType = childType;
1548 }
1549 // If we didn't wrap the text node, then the node we're inserting into can have
1550 // content, so we couldn't have closed anything
1551 } else {
1552 parentType = data[ i ].type;
1553 }
1554 } else {
1555 // Closing
1556 writeElement( data[ i ], i );
1557 parentType = openingStack.length > 0 ?
1558 openingStack[ openingStack.length - 1 ].type : parentNode.getType();
1559 }
1560 }
1561
1562 if ( closingStack.length > 0 && this.data.isCloseElementData( offset ) ) {
1563 // This element would be the last child of its parent, so
1564 // abandon this fix up and try again one offset to the right
1565 return this.fixupInsertion( data, offset + 1 );
1566 }
1567
1568 if ( inTextNode ) {
1569 parentType = openingStack.length > 0 ?
1570 openingStack[ openingStack.length - 1 ].type : parentNode.getType();
1571 }
1572
1573 // Close unclosed openings
1574 while ( openingStack.length > 0 ) {
1575 const popped = openingStack[ openingStack.length - 1 ];
1576 // writeElement() will perform the actual pop() that removes
1577 // popped from openingStack
1578 writeElement( { type: '/' + popped.type }, data.length );
1579 }
1580 // Re-open closed nodes
1581 while ( closingStack.length > 0 ) {
1582 const popped = closingStack[ closingStack.length - 1 ];
1583 // writeElement() will perform the actual pop() that removes
1584 // popped from closingStack
1585 writeElement( popped.getClonedElement(), data.length );
1586 }
1587
1588 return {
1589 offset: offset,
1590 data: newData,
1591 remove: remove,
1592 insertedDataOffset: insertedDataOffset !== 0 ? insertedDataOffset : undefined,
1593 insertedDataLength: insertedDataLength !== newData.length ? insertedDataLength : undefined
1594 };
1595 };
1596
1597 /**
1598 * Create a document given an HTML string or document.
1599 *
1600 * @param {string|HTMLDocument} html HTML string or document to insert
1601 * @param {Object} [importRules] The import rules with which to sanitize the HTML, if importing
1602 * @return {ve.dm.Document} New document
1603 */
1604 ve.dm.Document.prototype.newFromHtml = function ( html, importRules ) {
1605 const htmlDoc = typeof html === 'string' ? ve.createDocumentFromHtml( html ) : html,
1606 doc = ve.dm.converter.getModelFromDom( htmlDoc, {
1607 targetDoc: this.getHtmlDocument(),
1608 fromClipboard: !!importRules
1609 } ),
1610 data = doc.data;
1611
1612 if ( importRules ) {
1613 data.sanitize( importRules.external || {} );
1614 data.sanitize( importRules.all || {} );
1615 }
1616
1617 data.remapInternalListKeys( this.getInternalList() );
1618 // Initialize node tree
1619 // BUG T75569: This shouldn't be needed
1620 doc.buildNodeTree();
1621
1622 return doc;
1623 };
1624
1625 /**
1626 * Find a text string within the document
1627 *
1628 * @param {string|RegExp} query Text to find, string or regex with no flags
1629 * @param {Object} [options] Search options
1630 * @param {boolean} [options.searchRange] Range to search. Defaults to the attached root.
1631 * @param {boolean} [options.caseSensitiveString] Case sensitive search for a string query. Ignored by regexes (use 'i' flag).
1632 * @param {boolean} [options.diacriticInsensitiveString] Diacritic insensitive search for a string query. Ignored by regexes.
1633 * Only works in browsers which support the Internationalization API
1634 * @param {boolean} [options.noOverlaps] Avoid overlapping matches
1635 * @param {boolean} [options.wholeWord] Only match whole-word occurrences
1636 * @return {ve.Range[]} List of ranges where the string was found
1637 */
1638 ve.dm.Document.prototype.findText = function ( query, options ) {
1639 options = options || {};
1640
1641 const data = this.data,
1642 searchRange = options.searchRange || this.getAttachedRootRange();
1643 let ranges = [];
1644
1645 if ( query instanceof RegExp ) {
1646 // Avoid multi-line matching by only matching within content (text or content elements)
1647 data.forEachRunOfContent( searchRange, ( off, line ) => {
1648 query.lastIndex = 0;
1649 let match;
1650 while ( ( match = query.exec( line ) ) !== null ) {
1651 let matchText = match[ 0 ];
1652
1653 // Skip empty string matches (e.g. with .*)
1654 if ( matchText.length === 0 ) {
1655 // Set lastIndex to the next character to avoid an infinite
1656 // loop. Browsers differ in whether they do this for you
1657 // for empty matches; see
1658 // http://blog.stevenlevithan.com/archives/exec-bugs
1659 query.lastIndex = match.index + 1;
1660 continue;
1661 }
1662
1663 // Content elements' open/close data is replaced by the replacement character U+FFFC.
1664 // Ensure that matches of U+FFFC contain the entire element (opening and closing data).
1665 // The U+FFFC placeholder is only used for elements which "are content" (.static.isContent
1666 // is true), and such elements are guaranteed to not contain content, so this is safe.
1667 // Note, however, that this character is allowed to appear in normal text (eww),
1668 // so we consult the actual document data to make sure we actually matched an element.
1669
1670 // 1/2: If we matched opening U+FFFC at the end, extend the match forwards by 1.
1671 if (
1672 matchText[ matchText.length - 1 ] === '\uFFFC' &&
1673 data.isOpenElementData( off + match.index + matchText.length - 1 ) &&
1674 data.isCloseElementData( off + match.index + matchText.length )
1675 ) {
1676 matchText += '\uFFFC';
1677 query.lastIndex += 1;
1678 }
1679
1680 // 2/2: If we matched closing U+FFFC at the beginning, skip the match.
1681 // (We do not extend the match backwards to avoid overlapping matches.)
1682 if (
1683 matchText[ 0 ] === '\uFFFC' &&
1684 data.isOpenElementData( off + match.index - 1 ) &&
1685 data.isCloseElementData( off + match.index )
1686 ) {
1687 // Continue matching at the next character, rather than the end of this match.
1688 query.lastIndex = match.index + 1;
1689 continue;
1690 }
1691
1692 ranges.push( new ve.Range(
1693 off + match.index,
1694 off + match.index + matchText.length
1695 ) );
1696 if ( !options.noOverlaps ) {
1697 query.lastIndex = match.index + 1;
1698 }
1699 }
1700 } );
1701 } else {
1702 const qLen = query.length;
1703 let sensitivity;
1704 if ( options.diacriticInsensitiveString ) {
1705 sensitivity = options.caseSensitiveString ? 'case' : 'base';
1706 } else {
1707 sensitivity = options.caseSensitiveString ? 'variant' : 'accent';
1708 }
1709 // Intl is only used browser clients
1710 const compare = new Intl.Collator( this.lang, { sensitivity: sensitivity } ).compare;
1711 // Iterate up to (and including) offset textLength - queryLength. Beyond that point
1712 // there is not enough room for the query to exist
1713 for ( let offset = searchRange.start, l = searchRange.end - qLen; offset <= l; offset++ ) {
1714 let j = 0;
1715 while ( compare( data.getCharacterData( offset + j ), query[ j ] ) === 0 ) {
1716 j++;
1717 if ( j === qLen ) {
1718 ranges.push( new ve.Range( offset, offset + qLen ) );
1719 offset += options.noOverlaps ? qLen - 1 : 0;
1720 break;
1721 }
1722 }
1723 }
1724 }
1725
1726 if ( options.wholeWord ) {
1727 const dataString = new ve.dm.DataString( this.getData() );
1728 ranges = ranges.filter( ( range ) => unicodeJS.wordbreak.isBreak( dataString, range.start ) &&
1729 unicodeJS.wordbreak.isBreak( dataString, range.end ) );
1730 }
1731
1732 return ranges;
1733 };
1734
1735 /**
1736 * Get the length of the complete history. This is also the current pointer.
1737 *
1738 * @return {number} Length of the complete history stack
1739 */
1740 ve.dm.Document.prototype.getCompleteHistoryLength = function () {
1741 return this.completeHistory.getLength();
1742 };
1743
1744 /**
1745 * Get all the transactions in the complete history since a specified pointer.
1746 *
1747 * @param {number} start Pointer from where to start the slice
1748 * @return {ve.dm.Transaction[]} Array of transaction objects
1749 */
1750 ve.dm.Document.prototype.getCompleteHistorySince = function ( start ) {
1751 return this.completeHistory.transactions.slice( start );
1752 };
1753
1754 /**
1755 * Single change containing most recent transactions in history stack
1756 *
1757 * @param {number} start Pointer from where to start slicing transactions
1758 * @return {ve.dm.Change} Single change containing transactions since pointer
1759 */
1760 ve.dm.Document.prototype.getChangeSince = function ( start ) {
1761 const change = this.completeHistory.mostRecent( start );
1762 // Remove any selections that might have been added by e.g. ve.dm.Change#addToHistory
1763 change.selections = {};
1764 return change;
1765 };
1766
1767 /**
1768 * Get the content language
1769 *
1770 * @return {string} Language code
1771 */
1772 ve.dm.Document.prototype.getLang = function () {
1773 return this.lang;
1774 };
1775
1776 /**
1777 * Get the content directionality
1778 *
1779 * @return {string} Directionality (ltr/rtl)
1780 */
1781 ve.dm.Document.prototype.getDir = function () {
1782 return this.dir;
1783 };
1784
1785 /**
1786 * Set a key/value pair in persistent static storage, or restore the whole store
1787 *
1788 * Storage is used for static variables related to document state,
1789 * such as InternalList's nextUniqueNumber.
1790 *
1791 * @param {string|Object} [keyOrStorage] Key, or storage object to restore
1792 * @param {any} [value] Serializable value, if key is set
1793 * @fires ve.dm.Document#storage
1794 */
1795 ve.dm.Document.prototype.setStorage = function ( keyOrStorage, value ) {
1796 if ( typeof keyOrStorage === 'string' ) {
1797 this.persistentStorage[ keyOrStorage ] = value;
1798 this.emit( 'storage' );
1799 } else {
1800 this.persistentStorage = keyOrStorage;
1801 }
1802 };
1803
1804 /**
1805 * Get a value from the persistent static storage, or the whole store
1806 *
1807 * @param {string} [key] Key
1808 * @return {any|Object} Value at key, or whole storage object if key not provided
1809 */
1810 ve.dm.Document.prototype.getStorage = function ( key ) {
1811 if ( key ) {
1812 return this.persistentStorage[ key ];
1813 } else {
1814 return this.persistentStorage;
1815 }
1816 };