Debian Codegraph @

extensions/DiscussionTools/modules/utils.js

raw symbols SCIP
1 'use strict';
2 /* global $:off */
3
4 /**
5 * @constant
6 */
7 const NEW_TOPIC_COMMENT_ID = 'new|' + mw.config.get( 'wgRelevantPageName' );
8
9 /**
10 * @param {Node} node
11 * @return {boolean} Node is a block element
12 */
13 function isBlockElement( node ) {
14 return node instanceof HTMLElement && ve.isBlockElement( node );
15 }
16
17 const solTransparentLinkRegexp = /(?:^|\s)mw:PageProp\/(?:Category|redirect|Language)(?=$|\s)/;
18
19 /**
20 * @param {Node} node
21 * @return {boolean} Node is considered a rendering-transparent node in Parsoid
22 */
23 function isRenderingTransparentNode( node ) {
24 const nextSibling = node.nextSibling;
25 return (
26 node.nodeType === Node.COMMENT_NODE ||
27 node.nodeType === Node.ELEMENT_NODE && (
28 node.tagName.toLowerCase() === 'meta' ||
29 (
30 node.tagName.toLowerCase() === 'link' &&
31 solTransparentLinkRegexp.test( node.getAttribute( 'rel' ) || '' )
32 ) ||
33 // Empty inline templates, e.g. tracking templates
34 (
35 node.tagName.toLowerCase() === 'span' &&
36 ( node.getAttribute( 'typeof' ) || '' ).split( ' ' ).indexOf( 'mw:Transclusion' ) !== -1 &&
37 !htmlTrim( node.innerHTML ) &&
38 (
39 !nextSibling || nextSibling.nodeType !== Node.ELEMENT_NODE ||
40 // Maybe we should be checking all of the about-grouped nodes to see if they're empty,
41 // but that's prooobably not needed in practice, and it leads to a quadratic worst case.
42 nextSibling.getAttribute( 'about' ) !== node.getAttribute( 'about' )
43 )
44 )
45 )
46 );
47 }
48
49 /**
50 * @param {Node} node
51 * @return {boolean} Node was added to the page by DiscussionTools
52 */
53 function isOurGeneratedNode( node ) {
54 return node.nodeType === Node.ELEMENT_NODE && (
55 node.classList.contains( 'ext-discussiontools-init-replylink-buttons' ) ||
56 node.hasAttribute( 'data-mw-comment-start' ) ||
57 node.hasAttribute( 'data-mw-comment-end' )
58 );
59 }
60
61 // Elements which can't have element children (but some may have text content).
62 const noElementChildrenElementTypes = [
63 // https://html.spec.whatwg.org/multipage/syntax.html#elements-2
64 // Void elements
65 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
66 'link', 'meta', 'param', 'source', 'track', 'wbr',
67 // Raw text elements
68 'script', 'style',
69 // Escapable raw text elements
70 'textarea', 'title',
71 // Foreign elements
72 'math', 'svg',
73 // Treated like text when scripting is enabled in the parser
74 // https://html.spec.whatwg.org/#the-noscript-element
75 'noscript',
76 // Replaced elements (that aren't already included above)
77 // https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements
78 // They might allow element children, but they aren't rendered on the page.
79 'audio', 'canvas', 'iframe', 'object', 'video'
80 ];
81
82 /**
83 * @param {Node} node
84 * @return {boolean} If true, node can't have element children. If false, it's complicated.
85 */
86 function cantHaveElementChildren( node ) {
87 return (
88 node.nodeType === Node.COMMENT_NODE ||
89 node.nodeType === Node.ELEMENT_NODE && (
90 noElementChildrenElementTypes.indexOf( node.tagName.toLowerCase() ) !== -1 ||
91 // Thumbnail wrappers generated by MediaTransformOutput::linkWrap (T301427),
92 // for compatibility with TimedMediaHandler.
93 // There is no better way to detect them, and we can't insert markers here,
94 // because the media DOM CSS depends on specific tag names and their order :(
95 // TODO See if we can remove this condition when wgParserEnableLegacyMediaDOM=false
96 // is enabled everywhere.
97 (
98 [ 'a', 'span' ].indexOf( node.tagName.toLowerCase() ) !== -1 &&
99 node.firstChild &&
100 cantHaveElementChildren( node.firstChild )
101 ) ||
102 // Do not insert anything inside figures when using wgParserEnableLegacyMediaDOM=false,
103 // because their CSS can't handle it (T320285).
104 node.tagName.toLowerCase() === 'figure'
105 )
106 );
107 }
108
109 /**
110 * Check whether the node is a comment separator (instead of a part of the comment).
111 *
112 * @param {Node} node
113 * @return {boolean}
114 */
115 function isCommentSeparator( node ) {
116 if ( node.nodeType !== Node.ELEMENT_NODE ) {
117 return false;
118 }
119
120 const tagName = node.tagName.toLowerCase();
121 if ( tagName === 'br' || tagName === 'hr' ) {
122 return true;
123 }
124
125 // TemplateStyles followed by any of the others
126 if ( node.nextSibling &&
127 ( tagName === 'link' || tagName === 'style' ) &&
128 isCommentSeparator( node.nextSibling )
129 ) {
130 return true;
131 }
132
133 const classList = node.classList;
134 if (
135 // Anything marked as not containing comments
136 classList.contains( 'mw-notalk' ) ||
137 // {{outdent}} templates
138 classList.contains( 'outdent-template' ) ||
139 // {{tracked}} templates (T313097)
140 classList.contains( 'mw-trackedTemplate' )
141 ) {
142 return true;
143 }
144
145 // Wikitext definition list term markup (`;`) when used as a fake heading (T265964)
146 if ( tagName === 'dl' &&
147 node.childNodes.length === 1 &&
148 node.firstChild.nodeType === Node.ELEMENT_NODE &&
149 node.firstChild.nodeName.toLowerCase() === 'dt'
150 ) {
151 return true;
152 }
153
154 return false;
155 }
156
157 /**
158 * Check whether the node is a comment content. It's a little vague what this means…
159 *
160 * @param {Node} node Node, should be a leaf node (a node with no children)
161 * @return {boolean}
162 */
163 function isCommentContent( node ) {
164 return (
165 ( node.nodeType === Node.TEXT_NODE && htmlTrim( node.textContent ) !== '' ) ||
166 ( cantHaveElementChildren( node ) )
167 );
168 }
169
170 /**
171 * Get the index of a node in its parentNode's childNode list
172 *
173 * @param {Node} child
174 * @return {number} Index in parentNode's childNode list
175 */
176 function childIndexOf( child ) {
177 let i = 0;
178 while ( ( child = child.previousSibling ) ) {
179 i++;
180 }
181 return i;
182 }
183
184 /**
185 * Find closest ancestor element using one of the given tag names.
186 *
187 * @param {Node} node
188 * @param {string[]} tagNames
189 * @return {HTMLElement|null}
190 */
191 function closestElement( node, tagNames ) {
192 do {
193 if (
194 node.nodeType === Node.ELEMENT_NODE &&
195 tagNames.indexOf( node.tagName.toLowerCase() ) !== -1
196 ) {
197 return node;
198 }
199 node = node.parentNode;
200 } while ( node );
201 return null;
202 }
203
204 /**
205 * Find the transclusion node which rendered the current node, if it exists.
206 *
207 * 1. Find the closest ancestor with an 'about' attribute
208 * 2. Find the main node of the about-group (first sibling with the same 'about' attribute)
209 * 3. If this is an mw:Transclusion node, return it; otherwise, go to step 1
210 *
211 * @param {Node} node
212 * @return {HTMLElement|null} Transclusion node, null if not found
213 */
214 function getTranscludedFromElement( node ) {
215 while ( node ) {
216 // 1.
217 if (
218 node.nodeType === Node.ELEMENT_NODE &&
219 node.getAttribute( 'about' ) &&
220 /^#mwt\d+$/.test( node.getAttribute( 'about' ) )
221 ) {
222 const about = node.getAttribute( 'about' );
223
224 // 2.
225 while (
226 node.previousSibling &&
227 node.previousSibling.nodeType === Node.ELEMENT_NODE &&
228 node.previousSibling.getAttribute( 'about' ) === about
229 ) {
230 node = node.previousSibling;
231 }
232
233 // 3.
234 if (
235 node.getAttribute( 'typeof' ) &&
236 node.getAttribute( 'typeof' ).split( ' ' ).indexOf( 'mw:Transclusion' ) !== -1
237 ) {
238 break;
239 }
240 }
241
242 node = node.parentNode;
243 }
244 return node;
245 }
246
247 /**
248 * Given a heading node, return the node on which the ID attribute is set.
249 *
250 * @param {HTMLElement} heading Heading node (`<h1>`-`<h6>`)
251 * @return {HTMLElement}
252 */
253 function getHeadlineNode( heading ) {
254 // This code assumes that $wgFragmentMode is [ 'html5', 'legacy' ] or [ 'html5' ]
255 let headline = heading;
256
257 if ( headline.hasAttribute( 'data-mw-comment-start' ) ) {
258 // JS only: Support output from the PHP CommentFormatter
259 headline = headline.parentNode;
260 }
261
262 if ( !headline.getAttribute( 'id' ) ) {
263 // JS only: Support output after HandleSectionLinks OutputTransform has been applied
264 headline = headline.querySelector( '.mw-headline' );
265 if ( !headline ) {
266 headline = heading;
267 }
268 }
269
270 return headline;
271 }
272
273 /**
274 * Trim ASCII whitespace, as defined in the HTML spec.
275 *
276 * @param {string} str
277 * @return {string}
278 */
279 function htmlTrim( str ) {
280 // https://infra.spec.whatwg.org/#ascii-whitespace
281 return str.replace( /^[\t\n\f\r ]+/, '' ).replace( /[\t\n\f\r ]+$/, '' );
282 }
283
284 /**
285 * Get the indent level of the node, relative to rootNode.
286 *
287 * The indent level is the number of lists inside of which it is nested.
288 *
289 * @private
290 * @param {Node} node
291 * @param {Element} rootNode
292 * @return {number}
293 */
294 function getIndentLevel( node, rootNode ) {
295 let indent = 0;
296 while ( node ) {
297 if ( node === rootNode ) {
298 break;
299 }
300 const tagName = node instanceof HTMLElement ? node.tagName.toLowerCase() : null;
301 if ( tagName === 'li' || tagName === 'dd' ) {
302 indent++;
303 }
304 node = node.parentNode;
305 }
306 return indent;
307 }
308
309 /**
310 * Get an array of sibling nodes that contain parts of the given range.
311 *
312 * @param {Range} range
313 * @return {Node[]}
314 */
315 function getCoveredSiblings( range ) {
316 const ancestor = range.commonAncestorContainer;
317
318 const siblings = ancestor.childNodes;
319 let start = 0;
320 let end = siblings.length - 1;
321
322 // Find first of the siblings that contains the item
323 if ( ancestor === range.startContainer ) {
324 start = range.startOffset;
325 } else {
326 while ( !siblings[ start ].contains( range.startContainer ) ) {
327 start++;
328 }
329 }
330
331 // Find last of the siblings that contains the item
332 if ( ancestor === range.endContainer ) {
333 end = range.endOffset - 1;
334 } else {
335 while ( !siblings[ end ].contains( range.endContainer ) ) {
336 end--;
337 }
338 }
339
340 return Array.prototype.slice.call( siblings, start, end + 1 );
341 }
342
343 /**
344 * Get the nodes (if any) that contain the given thread item, and nothing else.
345 *
346 * @param {ThreadItem} item Thread item
347 * @param {Node} [excludedAncestorNode] Node that shouldn't be included in the result, even if it
348 * contains the item and nothing else. This is intended to avoid traversing outside of a node
349 * which is a container for all the thread items.
350 * @return {Node[]|null}
351 */
352 function getFullyCoveredSiblings( item, excludedAncestorNode ) {
353 let siblings = getCoveredSiblings( item.getRange() );
354
355 function makeRange( sibs ) {
356 const range = sibs[ 0 ].ownerDocument.createRange();
357 range.setStartBefore( sibs[ 0 ] );
358 range.setEndAfter( sibs[ sibs.length - 1 ] );
359 return range;
360 }
361
362 const matches = compareRanges( makeRange( siblings ), item.getRange() ) === 'equal';
363
364 if ( matches ) {
365 // If these are all of the children (or the only child), go up one more level
366 let parent;
367 while (
368 ( parent = siblings[ 0 ].parentNode ) &&
369 parent !== excludedAncestorNode &&
370 compareRanges( makeRange( [ parent ] ), item.getRange() ) === 'equal'
371 ) {
372 siblings = [ parent ];
373 }
374 return siblings;
375 }
376 return null;
377 }
378
379 /**
380 * Get a MediaWiki page title from a URL.
381 *
382 * @private
383 * @param {string} url Absolute URL
384 * @return {string|null} Page title, or null if this isn't a link to a page
385 */
386 function getTitleFromUrl( url ) {
387 if ( !url ) {
388 return null;
389 }
390 const parsedUrl = new URL( url );
391 if ( parsedUrl.searchParams.get( 'title' ) ) {
392 return parsedUrl.searchParams.get( 'title' );
393 }
394
395 // wgArticlePath is site config so is trusted
396 const articlePathRegexp = new RegExp(
397 mw.util.escapeRegExp( mw.config.get( 'wgArticlePath' ) )
398 .replace( '\\$1', '(.*)' )
399 );
400 let match;
401 if ( ( match = parsedUrl.pathname.match( articlePathRegexp ) ) ) {
402 return decodeURIComponent( match[ 1 ] );
403 }
404
405 return null;
406 }
407
408 /**
409 * Traverse the document in depth-first order, calling the callback whenever entering and leaving
410 * a node. The walk starts before the given node and ends when callback returns a truthy value, or
411 * after reaching the end of the document.
412 *
413 * You might also think about this as processing XML token stream linearly (rather than XML
414 * nodes), as if we were parsing the document.
415 *
416 * @param {Node} node Node to start at
417 * @param {Function} callback Function accepting two arguments: `event` ('enter' or 'leave') and
418 * `node` (DOMNode)
419 * @return {any} Final return value of the callback
420 */
421 function linearWalk( node, callback ) {
422 let
423 result = null,
424 withinNode = node.parentNode,
425 beforeNode = node;
426
427 while ( beforeNode || withinNode ) {
428 if ( beforeNode ) {
429 result = callback( 'enter', beforeNode );
430 withinNode = beforeNode;
431 beforeNode = beforeNode.firstChild;
432 } else {
433 result = callback( 'leave', withinNode );
434 beforeNode = withinNode.nextSibling;
435 withinNode = withinNode.parentNode;
436 }
437
438 if ( result ) {
439 return result;
440 }
441 }
442 return result;
443 }
444
445 /**
446 * Like #linearWalk, but it goes backwards.
447 *
448 * @inheritdoc #linearWalk
449 */
450 function linearWalkBackwards( node, callback ) {
451 let
452 result = null,
453 withinNode = node.parentNode,
454 beforeNode = node;
455
456 while ( beforeNode || withinNode ) {
457 if ( beforeNode ) {
458 result = callback( 'enter', beforeNode );
459 withinNode = beforeNode;
460 beforeNode = beforeNode.lastChild;
461 } else {
462 result = callback( 'leave', withinNode );
463 beforeNode = withinNode.previousSibling;
464 withinNode = withinNode.parentNode;
465 }
466
467 if ( result ) {
468 return result;
469 }
470 }
471 return result;
472 }
473
474 /**
475 * @param {Range} range
476 * @return {Node}
477 */
478 function getRangeFirstNode( range ) {
479 return range.startContainer.childNodes.length ?
480 range.startContainer.childNodes[ range.startOffset ] :
481 range.startContainer;
482 }
483
484 /**
485 * @param {Range} range
486 * @return {Node}
487 */
488 function getRangeLastNode( range ) {
489 return range.endContainer.childNodes.length ?
490 range.endContainer.childNodes[ range.endOffset - 1 ] :
491 range.endContainer;
492 }
493
494 /**
495 * Check whether two ranges overlap, and how.
496 *
497 * Includes a hack to check for "almost equal" ranges (whose start/end boundaries only differ by
498 * "uninteresting" nodes that we ignore when detecting comments), and treat them as equal.
499 *
500 * Illustration of return values:
501 * [ equal ]
502 * |[ contained ]|
503 * [ | contains | ]
504 * [overlap|start] |
505 * | [overlap|end]
506 * [before] | |
507 * | | [after]
508 *
509 * @param {Range} a
510 * @param {Range} b
511 * @return {string} One of:
512 * - 'equal': Ranges A and B are equal
513 * - 'contains': Range A contains range B
514 * - 'contained': Range A is contained within range B
515 * - 'after': Range A is before range B
516 * - 'before': Range A is after range B
517 * - 'overlapstart': Start of range A overlaps range B
518 * - 'overlapend': End of range A overlaps range B
519 */
520 function compareRanges( a, b ) {
521 // Compare the positions of: start of A to start of B, start of A to end of B, and so on.
522 // Watch out, the constant names are the opposite of what they should be.
523 let startToStart = a.compareBoundaryPoints( Range.START_TO_START, b );
524 const startToEnd = a.compareBoundaryPoints( Range.END_TO_START, b );
525 const endToStart = a.compareBoundaryPoints( Range.START_TO_END, b );
526 let endToEnd = a.compareBoundaryPoints( Range.END_TO_END, b );
527
528 // Check for almost equal ranges (boundary points only differing by uninteresting nodes)
529 if (
530 ( startToStart < 0 && compareRangesAlmostEqualBoundaries( a, b, 'start' ) ) ||
531 ( startToStart > 0 && compareRangesAlmostEqualBoundaries( b, a, 'start' ) )
532 ) {
533 startToStart = 0;
534 }
535 if (
536 ( endToEnd < 0 && compareRangesAlmostEqualBoundaries( a, b, 'end' ) ) ||
537 ( endToEnd > 0 && compareRangesAlmostEqualBoundaries( b, a, 'end' ) )
538 ) {
539 endToEnd = 0;
540 }
541
542 if ( startToStart === 0 && endToEnd === 0 ) {
543 return 'equal';
544 }
545 if ( startToStart <= 0 && endToEnd >= 0 ) {
546 return 'contains';
547 }
548 if ( startToStart >= 0 && endToEnd <= 0 ) {
549 return 'contained';
550 }
551 if ( startToEnd >= 0 ) {
552 return 'after';
553 }
554 if ( endToStart <= 0 ) {
555 return 'before';
556 }
557 if ( startToStart > 0 && startToEnd < 0 && endToEnd >= 0 ) {
558 return 'overlapstart';
559 }
560 if ( endToEnd < 0 && endToStart > 0 && startToStart <= 0 ) {
561 return 'overlapend';
562 }
563
564 throw new Error( 'Unreachable' );
565 }
566
567 /**
568 * Check if the given boundary points of ranges A and B are almost equal (only differing by
569 * uninteresting nodes).
570 *
571 * Boundary of A must be before the boundary of B in the tree.
572 *
573 * @param {Range} a
574 * @param {Range} b
575 * @param {string} boundary 'start' or 'end'
576 * @return {boolean}
577 */
578 function compareRangesAlmostEqualBoundaries( a, b, boundary ) {
579 // This code is awful, but several attempts to rewrite it made it even worse.
580 // You're welcome to give it a try.
581
582 const from = boundary === 'end' ? getRangeLastNode( a ) : getRangeFirstNode( a );
583 const to = boundary === 'end' ? getRangeLastNode( b ) : getRangeFirstNode( b );
584
585 let skipNode = null;
586 if ( boundary === 'end' ) {
587 skipNode = from;
588 }
589
590 let foundContent = false;
591 linearWalk(
592 from,
593 ( event, n ) => {
594 if ( n === to && event === ( boundary === 'end' ? 'leave' : 'enter' ) ) {
595 return true;
596 }
597 if ( skipNode ) {
598 if ( n === skipNode && event === 'leave' ) {
599 skipNode = null;
600 }
601 return;
602 }
603
604 if ( event === 'enter' ) {
605 if (
606 isCommentSeparator( n ) ||
607 isRenderingTransparentNode( n ) ||
608 isOurGeneratedNode( n )
609 ) {
610 skipNode = n;
611
612 } else if (
613 isCommentContent( n )
614 ) {
615 foundContent = true;
616 return true;
617 }
618 }
619 }
620 );
621
622 return !foundContent;
623 }
624
625 /**
626 * Get the ID for a new topics subscription from a page title
627 *
628 * @param {mw.Title} title Page title
629 * @return {string} ID for a new topics subscription
630 */
631 function getNewTopicsSubscriptionId( title ) {
632 return 'p-topics-' + title.getNamespaceId() + ':' + title.getMain();
633 }
634
635 /**
636 * Check whether a jQuery event represents a plain left click, without any modifiers
637 *
638 * @param {jQuery.Event} e
639 * @return {boolean} Whether it was an unmodified left click
640 */
641 function isUnmodifiedLeftClick( e ) {
642 return e.which === OO.ui.MouseButtons.LEFT && !( e.shiftKey || e.altKey || e.ctrlKey || e.metaKey );
643 }
644
645 module.exports = {
646 NEW_TOPIC_COMMENT_ID: NEW_TOPIC_COMMENT_ID,
647 isBlockElement: isBlockElement,
648 isRenderingTransparentNode: isRenderingTransparentNode,
649 isCommentSeparator: isCommentSeparator,
650 isCommentContent: isCommentContent,
651 cantHaveElementChildren: cantHaveElementChildren,
652 childIndexOf: childIndexOf,
653 closestElement: closestElement,
654 getIndentLevel: getIndentLevel,
655 getCoveredSiblings: getCoveredSiblings,
656 getFullyCoveredSiblings: getFullyCoveredSiblings,
657 getTranscludedFromElement: getTranscludedFromElement,
658 getHeadlineNode: getHeadlineNode,
659 htmlTrim: htmlTrim,
660 getTitleFromUrl: getTitleFromUrl,
661 linearWalk: linearWalk,
662 linearWalkBackwards: linearWalkBackwards,
663 compareRanges: compareRanges,
664 getNewTopicsSubscriptionId: getNewTopicsSubscriptionId,
665 isUnmodifiedLeftClick: isUnmodifiedLeftClick
666 };