Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor Document class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Generic document.
9 *
10 * @class
11 * @mixes OO.EventEmitter
12 *
13 * @constructor
14 * @param {ve.BranchNode} documentNode Document node
15 */
16 ve.Document = function VeDocument( documentNode ) {
17 // Mixin constructors
18 OO.EventEmitter.call( this );
19
20 // Properties
21 this.documentNode = documentNode;
22 this.documentNode.setDocument( this );
23 };
24
25 /* Inheritance */
26
27 OO.mixinClass( ve.Document, OO.EventEmitter );
28
29 /* Events */
30
31 /**
32 * A node has been attached with ve.Node#setDocument . Its descendants are guaranteed
33 * to be attached too (and the event is emitted for descendants first, and for siblings
34 * in their order in the children list)
35 *
36 * @event ve.Document#nodeAttached
37 * @param {ve.Node} node The node that has been attached
38 */
39
40 /**
41 * A node has been detached with ve.Node#setDocument . Its descendants are guaranteed
42 * to be detached too (and the event is emitted for descendants first, and for siblings
43 * in their order in the children list)
44 *
45 * @event ve.Document#nodeDetached
46 * @param {ve.Node} node The node that has been detached
47 */
48
49 /* Methods */
50
51 /**
52 * Get the root of the document's node tree.
53 *
54 * @return {ve.BranchNode} Root of node tree
55 */
56 ve.Document.prototype.getDocumentNode = function () {
57 return this.documentNode;
58 };
59
60 /**
61 * Get a node at an offset.
62 *
63 * @param {number} offset Offset to get node at
64 * @return {ve.Node|null} Node at offset
65 */
66 ve.Document.prototype.getBranchNodeFromOffset = function ( offset ) {
67 let node = this.getDocumentNode().getNodeFromOffset( offset );
68 if ( node && !node.hasChildren() ) {
69 node = node.getParent();
70 }
71 return node;
72 };
73
74 /**
75 * Gets a list of nodes and the ranges within them that a selection of the document covers.
76 *
77 * @param {ve.Range} range Range within document to select nodes
78 * @param {string} [mode='leaves'] Type of selection to perform:
79 *
80 * - `leaves`: Return all leaf nodes in the given range (descends all the way down)
81 * - `branches`': Return all branch nodes in the given range
82 * - `covered`: Do not descend into nodes that are entirely covered by the range. The result
83 * is similar to that of 'leaves' except that if a node is entirely covered, its
84 * children aren't returned separately.
85 * - `siblings`: Return a set of adjacent siblings covered by the range (descends as long as the
86 * range is in a single node)
87 * @return {Array} List of objects describing nodes in the selection and the ranges therein:
88 *
89 * - `node`: Reference to a ve.Node
90 * - `range`: ve.Range, missing if the entire node is covered
91 * - `index`: Index of the node in its parent, missing if node has no parent
92 * - `indexInNode`: If range is a zero-length range between two children of node,
93 * this is set to the index of the child following range (or to
94 * `node.children.length + 1` if range is between the last child and
95 * the end). If range is a zero-length range inside an empty non-content branch node, this is 0.
96 * Missing in all other cases.
97 * - `nodeRange`: Range covering the inside of the entire node, not including wrapper
98 * - `nodeOuterRange`: Range covering the entire node, including wrapper
99 * - `parentOuterRange`: Outer range of node's parent. Missing if there is no parent
100 * or if indexInNode is set.
101 *
102 * @throws {Error} Invalid mode
103 * @throws {Error} Invalid start offset
104 * @throws {Error} Invalid end offset
105 * @throws {Error} Failed to select any nodes
106 */
107 ve.Document.prototype.selectNodes = function ( range, mode ) {
108 const doc = this.getDocumentNode(),
109 start = range.start,
110 end = range.end,
111 stack = [ {
112 // Node we are currently stepping through
113 // Note each iteration visits a child of node, not node itself
114 node: doc,
115 // Index of the child in node we're visiting
116 index: 0,
117 // First offset inside node
118 startOffset: 0
119 } ];
120 let retval = [],
121 currentFrame = stack[ 0 ],
122 startFound = false;
123
124 mode = mode || 'leaves';
125 if ( mode !== 'leaves' && mode !== 'branches' && mode !== 'covered' && mode !== 'siblings' ) {
126 throw new Error( 'Invalid mode: ' + mode );
127 }
128
129 if ( start < 0 || start > doc.getLength() ) {
130 throw new Error( 'Invalid start offset: ' + start );
131 }
132 if ( end < 0 || end > doc.getLength() ) {
133 throw new Error( 'Invalid end offset: ' + end );
134 }
135
136 if ( !doc.children || doc.children.length === 0 ) {
137 // Document has no children. This is weird
138 const nodeRange = new ve.Range( 0, doc.getLength() );
139 return [ {
140 node: doc,
141 range: new ve.Range( start, end ),
142 index: 0,
143 nodeRange: nodeRange,
144 nodeOuterRange: nodeRange
145 } ];
146 }
147 let left = doc.children[ 0 ].isWrapped() ? 1 : 0;
148
149 do {
150 const node = currentFrame.node.children[ currentFrame.index ];
151 const prevNode = currentFrame.node.children[ currentFrame.index - 1 ];
152 let nextNode = currentFrame.node.children[ currentFrame.index + 1 ];
153 const right = left + node.getLength();
154 // Is the start inside node?
155 const startInside = start >= left && start <= right;
156 // Is the end inside node?
157 const endInside = end >= left && end <= right;
158 // Does the node have wrapping elements around it
159 let isWrapped = node.isWrapped();
160 // Is there an unwrapped node right before this node?
161 const isPrevUnwrapped = prevNode ? !prevNode.isWrapped() : false;
162 // Is there an unwrapped node right after this node?
163 const isNextUnwrapped = nextNode ? !nextNode.isWrapped() : false;
164 // Is this node an empty non-content branch node?
165 const isEmptyBranch = ( node.getLength() === 0 || node.shouldIgnoreChildren() ) &&
166 !node.isContent() && !node.canContainContent();
167 // Is the start between prevNode's closing and node or between the parent's opening and node?
168 const startBetween = ( isWrapped ? start === left - 1 : start === left ) && !isPrevUnwrapped;
169 // Is the end between node and nextNode's opening or between node and the parent's closing?
170 const endBetween = ( isWrapped ? end === right + 1 : end === right ) && !isNextUnwrapped;
171 let parentRange = new ve.Range(
172 currentFrame.startOffset,
173 currentFrame.startOffset + currentFrame.node.getLength()
174 );
175
176 let parentFrame;
177 if ( isWrapped && end === left - 1 && currentFrame.index === 0 ) {
178 // The selection ends here with an empty range at the beginning of the node
179 // TODO duplicated code
180 isWrapped = currentFrame.node.isWrapped();
181 retval.push( {
182 node: currentFrame.node,
183 indexInNode: 0,
184 range: new ve.Range( end, end ),
185 nodeRange: parentRange,
186 nodeOuterRange: new ve.Range(
187 parentRange.start - isWrapped, parentRange.end + isWrapped
188 )
189 } );
190 parentFrame = stack[ stack.length - 2 ];
191 if ( parentFrame ) {
192 retval[ retval.length - 1 ].index = parentFrame.index;
193 }
194 return retval;
195 }
196
197 if ( start === end && ( startBetween || endBetween ) && isWrapped ) {
198 // Empty range in the parent, outside of any child
199 isWrapped = currentFrame.node.isWrapped();
200 retval = [ {
201 node: currentFrame.node,
202 indexInNode: currentFrame.index + ( endBetween ? 1 : 0 ),
203 range: new ve.Range( start, end ),
204 nodeRange: parentRange,
205 nodeOuterRange: new ve.Range(
206 parentRange.start - isWrapped, parentRange.end + isWrapped
207 )
208 } ];
209 parentFrame = stack[ stack.length - 2 ];
210 if ( parentFrame ) {
211 retval[ 0 ].index = parentFrame.index;
212 }
213 return retval;
214 } else if ( startBetween ) {
215 // start is between the previous sibling and node
216 // so the selection covers all or part of node
217
218 // Descend if
219 // - we are in leaves mode, OR
220 // - we are in covered mode and the end is inside node OR
221 // - we are in branches mode and node is a branch (can have grandchildren)
222 // AND
223 // the node is non-empty and doesn't handle its own children
224 if ( ( mode === 'leaves' ||
225 ( mode === 'covered' && endInside ) ||
226 ( mode === 'branches' && node.canHaveChildrenNotContent() ) ) &&
227 node.children && node.children.length && !node.shouldIgnoreChildren()
228 ) {
229 // Descend into node
230 currentFrame = {
231 node: node,
232 index: 0,
233 startOffset: left
234 };
235 stack.push( currentFrame );
236 startFound = true;
237 // If the first child of node has an opening, skip over it
238 if ( node.children[ 0 ].isWrapped() ) {
239 left++;
240 }
241 continue;
242 } else if ( !endInside ) {
243 // All of node is covered
244 retval.push( {
245 node: node,
246 // No 'range' because the entire node is covered
247 index: currentFrame.index,
248 nodeRange: new ve.Range( left, right ),
249 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
250 parentOuterRange: new ve.Range(
251 parentRange.start - currentFrame.node.isWrapped(),
252 parentRange.end + currentFrame.node.isWrapped()
253 )
254 } );
255 startFound = true;
256 } else {
257 // Part of node is covered
258 return [ {
259 node: node,
260 range: new ve.Range( start, end ),
261 index: currentFrame.index,
262 nodeRange: new ve.Range( left, right ),
263 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
264 parentOuterRange: new ve.Range(
265 parentRange.start - currentFrame.node.isWrapped(),
266 parentRange.end + currentFrame.node.isWrapped()
267 )
268 } ];
269 }
270 } else if ( startInside && endInside ) {
271 if ( node.children && node.children.length &&
272 ( mode !== 'branches' || node.canHaveChildrenNotContent() ) ) {
273 // Descend into node
274 currentFrame = {
275 node: node,
276 index: 0,
277 startOffset: left
278 };
279 stack.push( currentFrame );
280 // If the first child of node has an opening, skip over it
281 if ( node.children[ 0 ].isWrapped() ) {
282 left++;
283 }
284 continue;
285 } else {
286 // node is a leaf node and the range is entirely inside it
287 retval = [ {
288 node: node,
289 range: new ve.Range( start, end ),
290 index: currentFrame.index,
291 nodeRange: new ve.Range( left, right ),
292 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
293 parentOuterRange: new ve.Range(
294 parentRange.start - currentFrame.node.isWrapped(),
295 parentRange.end + currentFrame.node.isWrapped()
296 )
297 } ];
298 if ( isEmptyBranch ) {
299 retval[ 0 ].indexInNode = 0;
300 }
301 return retval;
302 }
303 } else if ( startInside ) {
304 if ( ( mode === 'leaves' ||
305 mode === 'covered' ||
306 ( mode === 'branches' && node.canHaveChildrenNotContent() ) ) &&
307 node.children && node.children.length
308 ) {
309 // node is a branch node and the start is inside it
310 // Descend into it
311 currentFrame = {
312 node: node,
313 index: 0,
314 startOffset: left
315 };
316 stack.push( currentFrame );
317 // If the first child of node has an opening, skip over it
318 if ( node.children[ 0 ].isWrapped() ) {
319 left++;
320 }
321 continue;
322 } else {
323 // node is a leaf node and the start is inside it
324 // Add to retval and keep going
325 retval.push( {
326 node: node,
327 range: new ve.Range( start, right ),
328 index: currentFrame.index,
329 nodeRange: new ve.Range( left, right ),
330 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
331 parentOuterRange: new ve.Range(
332 parentRange.start - currentFrame.node.isWrapped(),
333 parentRange.end + currentFrame.node.isWrapped()
334 )
335 } );
336 startFound = true;
337 }
338 } else if ( endBetween ) {
339 // end is between node and the next sibling
340 // start is not inside node, so the selection covers
341 // all of node, then ends
342
343 if (
344 ( mode === 'leaves' || ( mode === 'branches' && node.canHaveChildrenNotContent() ) ) &&
345 node.children && node.children.length
346 ) {
347 // Descend into node
348 currentFrame = {
349 node: node,
350 index: 0,
351 startOffset: left
352 };
353 stack.push( currentFrame );
354 // If the first child of node has an opening, skip over it
355 if ( node.children[ 0 ].isWrapped() ) {
356 left++;
357 }
358 continue;
359 } else {
360 // All of node is covered
361 retval.push( {
362 node: node,
363 // No 'range' because the entire node is covered
364 index: currentFrame.index,
365 nodeRange: new ve.Range( left, right ),
366 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
367 parentOuterRange: new ve.Range(
368 parentRange.start - currentFrame.node.isWrapped(),
369 parentRange.end + currentFrame.node.isWrapped()
370 )
371 } );
372 return retval;
373 }
374 } else if ( endInside ) {
375 if ( ( mode === 'leaves' ||
376 mode === 'covered' ||
377 ( mode === 'branches' && node.canHaveChildrenNotContent() ) ) &&
378 node.children && node.children.length
379 ) {
380 // node is a branch node and the end is inside it
381 // Descend into it
382 currentFrame = {
383 node: node,
384 index: 0,
385 startOffset: left
386 };
387 stack.push( currentFrame );
388 // If the first child of node has an opening, skip over it
389 if ( node.children[ 0 ].isWrapped() ) {
390 left++;
391 }
392 continue;
393 } else {
394 // node is a leaf node and the end is inside it
395 // Add to retval and return
396 retval.push( {
397 node: node,
398 range: new ve.Range( left, end ),
399 index: currentFrame.index,
400 nodeRange: new ve.Range( left, right ),
401 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
402 parentOuterRange: new ve.Range(
403 parentRange.start - currentFrame.node.isWrapped(),
404 parentRange.end + currentFrame.node.isWrapped()
405 )
406 } );
407 return retval;
408 }
409 } else if ( startFound && end > right ) {
410 // Neither the start nor the end is inside node, but we found the start earlier,
411 // so node must be between the start and the end
412 // Add the entire node, so no range property
413
414 if (
415 ( mode === 'leaves' || ( mode === 'branches' && node.canHaveChildrenNotContent() ) ) &&
416 node.children && node.children.length
417 ) {
418 // Descend into node
419 currentFrame = {
420 node: node,
421 index: 0,
422 startOffset: left
423 };
424 stack.push( currentFrame );
425 // If the first child of node has an opening, skip over it
426 if ( node.children[ 0 ].isWrapped() ) {
427 left++;
428 }
429 continue;
430 } else {
431 // All of node is covered
432 retval.push( {
433 node: node,
434 // No 'range' because the entire node is covered
435 index: currentFrame.index,
436 nodeRange: new ve.Range( left, right ),
437 nodeOuterRange: new ve.Range( left - isWrapped, right + isWrapped ),
438 parentOuterRange: new ve.Range(
439 parentRange.start - currentFrame.node.isWrapped(),
440 parentRange.end + currentFrame.node.isWrapped()
441 )
442 } );
443 }
444 }
445
446 // Move to the next node
447 if ( nextNode ) {
448 // The next node exists
449 // Advance the index; the start of the next iteration will essentially
450 // do node = nextNode;
451 currentFrame.index++;
452 // Advance to the first offset inside nextNode
453 left = right +
454 // Skip over node's closing, if present
455 ( node.isWrapped() ? 1 : 0 ) +
456 // Skip over nextNode's opening, if present
457 ( nextNode.isWrapped() ? 1 : 0 );
458 } else {
459 // There is no next node, move up the stack until there is one
460 left = right +
461 // Skip over node's closing, if present
462 ( node.isWrapped() ? 1 : 0 );
463 while ( !nextNode ) {
464 // Check if the start is right past the end of this node, at the end of
465 // the parent
466 if ( node.isWrapped() && start === left ) {
467 // TODO duplicated code
468 parentRange = new ve.Range( currentFrame.startOffset,
469 currentFrame.startOffset + currentFrame.node.getLength()
470 );
471 isWrapped = currentFrame.node.isWrapped();
472 retval = [ {
473 node: currentFrame.node,
474 indexInNode: currentFrame.index + 1,
475 range: new ve.Range( left, left ),
476 nodeRange: parentRange,
477 nodeOuterRange: new ve.Range(
478 parentRange.start - isWrapped, parentRange.end + isWrapped
479 )
480 } ];
481 parentFrame = stack[ stack.length - 2 ];
482 if ( parentFrame ) {
483 retval[ 0 ].index = parentFrame.index;
484 }
485 }
486
487 // Move up the stack
488 stack.pop();
489 if ( stack.length === 0 ) {
490 // This shouldn't be possible
491 return retval;
492 }
493 currentFrame = stack[ stack.length - 1 ];
494 currentFrame.index++;
495 nextNode = currentFrame.node.children[ currentFrame.index ];
496 // Skip over the parent node's closing
497 // (this is present for sure, because the parent has children)
498 left++;
499 }
500
501 // Skip over nextNode's opening if present
502 if ( nextNode.isWrapped() ) {
503 left++;
504 }
505 }
506 } while ( end >= left - 1 );
507 if ( retval.length === 0 ) {
508 throw new Error( 'Failed to select any nodes' );
509 }
510 return retval;
511 };
512
513 /**
514 * Get groups of sibling nodes covered by the given range.
515 *
516 * @param {ve.Range} range
517 * @return {Array} Array of objects. Each object has the following keys:
518 *
519 * - nodes: Array of sibling nodes covered by a part of range
520 * - parent: Parent of all of these nodes
521 * - grandparent: parent's parent
522 */
523 ve.Document.prototype.getCoveredSiblingGroups = function ( range ) {
524 const leaves = this.selectNodes( range, 'leaves' ),
525 groups = [];
526 let lastEndOffset = 0;
527 for ( let i = 0; i < leaves.length; i++ ) {
528 if ( leaves[ i ].nodeOuterRange.end <= lastEndOffset ) {
529 // This range is contained within a range we've already processed
530 continue;
531 }
532 let node = leaves[ i ].node;
533 // Traverse up to a content branch from content elements
534 if ( node.isContent() ) {
535 node = node.getParent();
536 }
537 const parentNode = node.getParent();
538 if ( !parentNode ) {
539 break;
540 }
541 // Group this with its covered siblings
542 groups.push( {
543 parent: parentNode,
544 grandparent: parentNode.getParent(),
545 nodes: []
546 } );
547 // Seek forward to the last covered sibling
548 let siblingNode = node;
549 do {
550 // Add this to its sibling's group
551 groups[ groups.length - 1 ].nodes.push( siblingNode );
552 i++;
553 if ( leaves[ i ] === undefined ) {
554 break;
555 }
556 // Traverse up to a content branch from content elements
557 siblingNode = leaves[ i ].node;
558 if ( siblingNode.isContent() ) {
559 siblingNode = siblingNode.getParent();
560 }
561 } while ( siblingNode.getParent() === parentNode );
562 i--;
563 lastEndOffset = parentNode.getOuterRange().end;
564 }
565 return groups;
566 };
567
568 /**
569 * Test whether a range lies within a single leaf node.
570 *
571 * @param {ve.Range} range The range to test
572 * @return {boolean} Whether the range lies within a single node
573 */
574 ve.Document.prototype.rangeInsideOneLeafNode = function ( range ) {
575 const selected = this.selectNodes( range, 'leaves' );
576 return selected.length === 1 && selected[ 0 ].nodeRange.containsRange( range ) && selected[ 0 ].indexInNode === undefined;
577 };
578
579 /**
580 * Callback when a node is attached with ve.Node#setDocument
581 *
582 * The node and all its children are guaranteed to be attached
583 *
584 * @param {ve.Node} node The node attached
585 * @fires ve.Document#nodeAttached
586 */
587 ve.Document.prototype.nodeAttached = function ( node ) {
588 this.emit( 'nodeAttached', node );
589 };
590
591 /**
592 * Callback when a node is attached with ve.Node#setDocument
593 *
594 * The node and all its children are guaranteed to be attached
595 *
596 * @param {ve.Node} node The node detached
597 * @fires ve.Document#nodeDetached
598 */
599 ve.Document.prototype.nodeDetached = function ( node ) {
600 this.emit( 'nodeDetached', node );
601 };