Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable namespace.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Namespace for all VisualEditor ContentEditable classes, static methods and static properties.
9 *
10 * @namespace
11 */
12 ve.ce = {
13 // nodeFactory: Initialized in ve.ce.NodeFactory.js
14 };
15
16 /* Static Properties */
17
18 /**
19 * Data URI for minimal GIF image. This is the smallest technically-valid 1x1px transparent GIF it's possible to create.
20 */
21 ve.ce.minImgDataUri = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
22
23 /* Static Methods */
24
25 /**
26 * Gets the plain text of a DOM element (that is a node canContainContent === true)
27 *
28 * In the returned string only the contents of text nodes are included, and the contents of
29 * non-editable elements are excluded (but replaced with the appropriate number of snowman
30 * characters so the offsets match up with the linear model).
31 *
32 * @param {HTMLElement} element DOM element to get text of
33 * @return {string} Plain text of DOM element
34 */
35 ve.ce.getDomText = function ( element ) {
36 // Inspired by jQuery.text / Sizzle.getText
37 const nodeType = element.nodeType;
38 let text = '';
39
40 if (
41 nodeType === Node.ELEMENT_NODE ||
42 nodeType === Node.DOCUMENT_NODE ||
43 nodeType === Node.DOCUMENT_FRAGMENT_NODE
44 ) {
45 if ( element.classList.contains( 've-ce-branchNode-blockSlug' ) ) {
46 // Block slugs are not represented in the model at all, but they do
47 // contain a single nbsp/FEFF character in the DOM, so make sure
48 // that character isn't counted
49 return '';
50 } else if ( element.classList.contains( 've-ce-cursorHolder' ) ) {
51 // Cursor holders do not exist in the model
52 return '';
53 } else if ( element.classList.contains( 've-ce-leafNode' ) ) {
54 // For leaf nodes, don't return the content, but return
55 // the right number of placeholder characters so the offsets match up.
56 const viewNode = $( element ).data( 'view' );
57 // Only return snowmen for the first element in a sibling group: otherwise
58 // we'll double-count this node
59 if ( viewNode && element === viewNode.$element[ 0 ] ) {
60 // \u2603 is the snowman character: ☃
61 return new Array( viewNode.getOuterLength() + 1 ).join( '\u2603' );
62 }
63 // Second or subsequent sibling, don't double-count
64 return '';
65 } else {
66 // Traverse its children
67 for ( element = element.firstChild; element; element = element.nextSibling ) {
68 text += ve.ce.getDomText( element );
69 }
70 }
71 } else if ( nodeType === Node.TEXT_NODE ) {
72 return element.data;
73 }
74 return text;
75 };
76
77 /**
78 * Gets a hash of a DOM element's structure.
79 *
80 * In the returned string text nodes are represented as "#" and elements are represented as "<type>"
81 * and "</type>" where "type" is their element name. This effectively generates an HTML
82 * serialization without any attributes or text contents. This can be used to observe structural
83 * changes.
84 *
85 * @param {HTMLElement} element DOM element to get hash of
86 * @return {string} Hash of DOM element
87 */
88 ve.ce.getDomHash = function ( element ) {
89 const nodeType = element.nodeType,
90 nodeName = element.nodeName;
91 let hash = '';
92
93 if ( nodeType === Node.TEXT_NODE || nodeType === Node.CDATA_SECTION_NODE ) {
94 return '#';
95 } else if ( nodeType === Node.ELEMENT_NODE || nodeType === Node.DOCUMENT_NODE ) {
96 if ( !(
97 element.classList.contains( 've-ce-branchNode-blockSlug' ) ||
98 element.classList.contains( 've-ce-cursorHolder' ) ||
99 element.classList.contains( 've-ce-nail' )
100 ) ) {
101 hash += '<' + nodeName + '>';
102 // Traverse its children
103 for ( element = element.firstChild; element; element = element.nextSibling ) {
104 hash += ve.ce.getDomHash( element );
105 }
106 hash += '</' + nodeName + '>';
107 }
108 // Merge adjacent text node representations
109 hash = hash.replace( /##+/g, '#' );
110 }
111 return hash;
112 };
113
114 /**
115 * @typedef {Object} NodeAndOffset
116 * @memberof ve.ce
117 * @return {Node} node
118 * @return {number} offset
119 */
120 /**
121 * Get the first cursor offset immediately after a node.
122 *
123 * @param {Node} node DOM node
124 * @return {ve.ce.NodeAndOffset}
125 */
126 ve.ce.nextCursorOffset = function ( node ) {
127 let nextNode, offset;
128 if ( node.nextSibling !== null && node.nextSibling.nodeType === Node.TEXT_NODE ) {
129 nextNode = node.nextSibling;
130 offset = 0;
131 } else {
132 nextNode = node.parentNode;
133 offset = 1 + ve.parentIndex( node );
134 }
135 return { node: nextNode, offset: offset };
136 };
137
138 /**
139 * Get the first cursor offset immediately before a node.
140 *
141 * @param {Node} node DOM node
142 * @return {ve.ce.NodeAndOffset}
143 */
144 ve.ce.previousCursorOffset = function ( node ) {
145 let previousNode, offset;
146 if ( node.previousSibling !== null && node.previousSibling.nodeType === Node.TEXT_NODE ) {
147 previousNode = node.previousSibling;
148 offset = previousNode.data.length;
149 } else {
150 previousNode = node.parentNode;
151 offset = ve.parentIndex( node );
152 }
153 return { node: previousNode, offset: offset };
154 };
155
156 /**
157 * Gets the linear offset from a given DOM node and offset within it.
158 *
159 * @param {HTMLElement} domNode DOM node
160 * @param {number} domOffset DOM offset within the DOM node
161 * @return {number} Linear model offset
162 * @throws {Error} domOffset is out of bounds
163 * @throws {Error} domNode has no ancestor with a .data( 'view' )
164 * @throws {Error} domNode is not in document
165 */
166 ve.ce.getOffset = function ( domNode, domOffset ) {
167 if ( domNode.nodeType === Node.ELEMENT_NODE && domNode.classList.contains( 've-ce-unicorn' ) ) {
168 if ( domOffset !== 0 ) {
169 throw new Error( 'Non-zero offset in unicorn' );
170 }
171 return $( domNode ).data( 'modelOffset' );
172 }
173
174 /**
175 * Move to the previous "traversal node" in "traversal sequence".
176 *
177 * - A node is a "traversal node" if it is either a leaf node or a "view node"
178 * - A "view node" is one that has $( n ).data( 'view' ) instanceof ve.ce.Node
179 * - "Traversal sequence" is defined on every node (not just traversal nodes).
180 * It is like document order, except that each parent node appears
181 * in the sequence both immediately before and immediately after its child nodes.
182 *
183 * Important properties:
184 * - Non-traversal nodes don't have any width in DM (e.g. bold).
185 * - Certain traversal nodes also have no width (namely, those within an alienated node).
186 * - Both the start and end of a (non-alienated) parent traversal node has width
187 * (which is one reason why traversal sequence is important).
188 * - In VE-normalized HTML, a text node cannot be a sibling of a non-leaf view node
189 * (because all non-alienated text nodes are inside a ContentBranchNode).
190 * - Traversal-consecutive non-view nodes are either all alienated or all not alienated.
191 *
192 * @param {Node} n Node to traverse from
193 * @return {Node} Previous traversal node from n
194 * @throws {Error} domNode has no ancestor with a .data( 'view' )
195 */
196 function traverse( n ) {
197 while ( !n.previousSibling ) {
198 n = n.parentNode;
199 if ( !n ) {
200 throw new Error( 'domNode has no ancestor with a .data( \'view\' )' );
201 }
202 if ( $( n ).data( 'view' ) instanceof ve.ce.Node ) {
203 return n;
204 }
205 }
206 n = n.previousSibling;
207 if ( $( n ).data( 'view' ) instanceof ve.ce.Node ) {
208 return n;
209 }
210 while ( n.lastChild ) {
211 n = n.lastChild;
212 if ( $( n ).data( 'view' ) instanceof ve.ce.Node ) {
213 return n;
214 }
215 }
216 return n;
217 }
218
219 // Validate domOffset
220 let maxOffset;
221 if ( domNode.nodeType === Node.ELEMENT_NODE ) {
222 maxOffset = domNode.childNodes.length;
223 } else {
224 maxOffset = domNode.data.length;
225 }
226 if ( domOffset < 0 || domOffset > maxOffset ) {
227 throw new Error( 'domOffset is out of bounds' );
228 }
229
230 let lengthSum = 0;
231 let startNode, node, view;
232 // Figure out what node to start traversing at (startNode)
233 if ( domNode.nodeType === Node.ELEMENT_NODE ) {
234 if ( domNode.childNodes.length === 0 ) {
235 // domNode has no children, and the offset is inside of it
236 // If domNode is a view node, return the offset inside of it
237 // Otherwise, start traversing at domNode
238 startNode = domNode;
239 view = $( startNode ).data( 'view' );
240 if ( view instanceof ve.ce.Node ) {
241 return view.getOffset() + ( view.isWrapped() ? 1 : 0 );
242 }
243 node = startNode;
244 } else if ( domOffset === domNode.childNodes.length ) {
245 // Offset is at the end of domNode, after the last child. Set startNode to the
246 // very rightmost descendant node of domNode (i.e. the last child of the last child
247 // of the last child, etc.)
248 // However, if the last child or any of the last children we encounter on the way
249 // is a view node, return the offset after it. This will be the correct return value
250 // because non-traversal nodes don't have a DM width.
251 startNode = domNode.lastChild;
252
253 view = $( startNode ).data( 'view' );
254 if ( view instanceof ve.ce.Node ) {
255 return view.getOffset() + view.getOuterLength();
256 }
257 while ( startNode.lastChild ) {
258 startNode = startNode.lastChild;
259 view = $( startNode ).data( 'view' );
260 if ( view instanceof ve.ce.Node ) {
261 return view.getOffset() + view.getOuterLength();
262 }
263 }
264 node = startNode;
265 } else {
266 // Offset is right before childNodes[domOffset]. Set startNode to this node
267 // (i.e. the node right after the offset), then traverse back once.
268 startNode = domNode.childNodes[ domOffset ];
269 node = traverse( startNode );
270 }
271 } else {
272 // Text inside of a block slug doesn't count
273 if ( !(
274 domNode.parentNode.classList.contains( 've-ce-branchNode-blockSlug' ) ||
275 domNode.parentNode.classList.contains( 've-ce-cursorHolder' )
276 ) ) {
277 lengthSum += domOffset;
278 }
279 startNode = domNode;
280 node = traverse( startNode );
281 }
282
283 // Walk the traversal nodes in reverse traversal sequence, until we find a view node.
284 // Add the width of each text node we meet. (Non-text node non-view nodes can only be widthless).
285 // Later, if it transpires that we're inside an alienated node, then we will throw away all the
286 // text node lengths, because the alien's content has no DM width.
287 while ( true ) {
288 // First node that has a ve.ce.Node, stop
289 // Note that annotations have a .data( 'view' ) too, but that's a ve.ce.Annotation,
290 // not a ve.ce.Node
291 view = $( node ).data( 'view' );
292 if ( view instanceof ve.ce.Node ) {
293 break;
294 }
295
296 // Text inside of a block slug doesn't count
297 if (
298 node.nodeType === Node.TEXT_NODE &&
299 !node.parentNode.classList.contains( 've-ce-branchNode-blockSlug' ) &&
300 !node.parentNode.classList.contains( 've-ce-cursorHolder' )
301 ) {
302 lengthSum += node.data.length;
303 }
304 // else: non-text nodes that don't have a .data( 'view' ) don't exist in the DM
305 node = traverse( node );
306 }
307
308 let offset = view.getOffset();
309
310 if ( $.contains( node, startNode ) ) {
311 // node is an ancestor of startNode
312 if ( !view.getModel().isContent() ) {
313 // Add 1 to take the opening into account
314 offset += view.getModel().isWrapped() ? 1 : 0;
315 }
316 if ( view.getModel().canContainContent() ) {
317 offset += lengthSum;
318 }
319 // else: we're inside an alienated node: throw away all the text node lengths,
320 // because the alien's content has no DM width
321 } else if ( view.parent ) {
322 // node is not an ancestor of startNode
323 // startNode comes after node, so add node's length
324 offset += view.getOuterLength();
325 if ( view.isContent() ) {
326 // view is a leaf node inside of a CBN, so we started inside of a CBN
327 // (otherwise we would have hit the CBN when entering it), so the text we summed up
328 // needs to be counted.
329 offset += lengthSum;
330 }
331 } else {
332 throw new Error( 'Node is not in document' );
333 }
334
335 return offset;
336 };
337
338 /**
339 * Gets the linear offset of a given slug
340 *
341 * @param {HTMLElement} element Slug DOM element
342 * @return {number} Linear model offset
343 * @throws {Error}
344 */
345 ve.ce.getOffsetOfSlug = function ( element ) {
346 const $element = $( element );
347 let model;
348 if ( $element.index() === 0 ) {
349 model = $element.parent().data( 'view' ).getModel();
350 return model.getOffset() + ( model.isWrapped() ? 1 : 0 );
351 } else {
352 // Don't pick up DOM nodes not from the view tree e.g. cursor holders (T202103)
353 const $prev = $element.prevAll( '.ve-ce-leafNode,.ve-ce-branchNode' ).first();
354 if ( $prev.length ) {
355 model = $prev.data( 'view' ).getModel();
356 return model.getOffset() + model.getOuterLength();
357 }
358 throw new Error( 'Incorrect slug location' );
359 }
360 };
361
362 /**
363 * Test whether the DOM position lies straight after annotation boundaries
364 *
365 * "Straight after" means that in document order, there are annotation open/close tags
366 * immediately before the position, and there are none immediately after.
367 *
368 * This is important for cursors: the DM position is ambiguous with respect to annotation
369 * boundaries, and the browser does not fully distinguish this position from the preceding
370 * position immediately before the annotation boundaries (e.g. 'a|&lt;b&gt;c' and 'a&lt;b&gt;|c'),
371 * but the two positions behave differently for insertions (in this case, whether the text
372 * appears bolded or not).
373 *
374 * In Chromium, cursor focus normalizes to the earliest (in document order) of equivalent
375 * positions, at least in reasonably-styled non-BIDI text. But in Firefox, the user can
376 * cursor/click into either the earliest or the latest equivalent position: the cursor lands in
377 * the closest (in document order) to the click location (for mouse actions) or cursor start
378 * location (for cursoring).
379 *
380 * @param {Node} node Position node
381 * @param {number} offset Position offset
382 * @return {boolean} Whether this is the end-most of multiple cursor-equivalent positions
383 */
384 ve.ce.isAfterAnnotationBoundary = function ( node, offset ) {
385 if ( node.nodeType === Node.TEXT_NODE ) {
386 if ( offset > 0 ) {
387 return false;
388 }
389 offset = ve.parentIndex( node );
390 node = node.parentNode;
391 }
392 if ( offset === 0 ) {
393 return ve.dm.modelRegistry.isAnnotation( node );
394 }
395
396 const previousNode = node.childNodes[ offset - 1 ];
397 if ( previousNode.nodeType === Node.ELEMENT_NODE && (
398 previousNode.classList.contains( 've-ce-nail-post-close' ) ||
399 previousNode.classList.contains( 've-ce-nail-post-open' )
400 ) ) {
401 return true;
402 }
403 return ve.dm.modelRegistry.isAnnotation( previousNode );
404 };
405
406 /**
407 * Check if keyboard shortcut modifier key is pressed.
408 *
409 * @param {jQuery.Event} e Key press event
410 * @return {boolean} Modifier key is pressed
411 */
412 ve.ce.isShortcutKey = function ( e ) {
413 return !!( e.ctrlKey || e.metaKey );
414 };
415
416 /**
417 * Find the DM range of a DOM selection
418 *
419 * @param {Object} selection DOM-selection-like object
420 * @param {Node} selection.anchorNode
421 * @param {number} selection.anchorOffset
422 * @param {Node} selection.focusNode
423 * @param {number} selection.focusOffset
424 * @return {ve.Range|null} DM range, or null if nothing in the CE document is selected
425 */
426 ve.ce.veRangeFromSelection = function ( selection ) {
427 try {
428 return new ve.Range(
429 ve.ce.getOffset( selection.anchorNode, selection.anchorOffset ),
430 ve.ce.getOffset( selection.focusNode, selection.focusOffset )
431 );
432 } catch ( e ) {
433 return null;
434 }
435 };
436
437 /**
438 * Find the closest nailed annotation in which a node lies
439 *
440 * @param {Node|null} node The node to test
441 * @return {Node|null} The closest nailed annotation within which the node lies (possibly the node itself)
442 */
443 ve.ce.nailedAnnotationAt = function ( node ) {
444 if ( node && node.nodeType === Node.TEXT_NODE ) {
445 node = node.parentNode;
446 }
447 return $( node ).closest( '.ve-ce-nailedAnnotation' )[ 0 ];
448 };
449
450 /**
451 * Check whether a given DOM element is an inline annotation
452 *
453 * @param {Node} element The element
454 * @return {boolean} Whether the element is an inline annotation
455 */
456 ve.ce.isAnnotationElement = function ( element ) {
457 return !(
458 ve.isBlockElement( element ) ||
459 ve.isVoidElement( element ) ||
460 element.classList.contains( 've-ce-branchNode-slug' )
461 );
462 };