Debian Codegraph @

skins/Vector/resources/skins.vector.js/stickyHeader.js

raw symbols SCIP
1 /**
2 * Functions and variables to implement sticky header.
3 */
4 const
5 initSearchToggle = require( './searchToggle.js' ),
6 updateWatchIcon = require( './watchstar.js' ).updateWatchIcon,
7 STICKY_HEADER_ID = 'vector-sticky-header',
8 STICKY_HEADER_APPENDED_ID = '-sticky-header',
9 STICKY_HEADER_APPENDED_PARAM = [ 'wvprov', 'sticky-header' ],
10 STICKY_HEADER_VISIBLE_CLASS = 'vector-sticky-header-visible',
11 STICKY_HEADER_USER_MENU_CONTAINER_SELECTOR = '.vector-sticky-header-icon-end .vector-user-links',
12 FIRST_HEADING_ID = 'firstHeading',
13 USER_LINKS_DROPDOWN_ID = 'vector-user-links-dropdown',
14 ULS_STICKY_CLASS = 'uls-dialog-sticky',
15 ULS_HIDE_CLASS = 'uls-dialog-sticky-hide',
16 SEARCH_TOGGLE_SELECTOR = '.vector-sticky-header-search-toggle',
17 STICKY_HEADER_EXPERIMENT_NAME = 'vector.sticky_header';
18
19 /**
20 * Copies attribute from an element to another.
21 *
22 * @param {Element} from
23 * @param {Element} to
24 * @param {string} attribute
25 */
26 function copyAttribute( from, to, attribute ) {
27 const fromAttr = from.getAttribute( attribute );
28 if ( fromAttr ) {
29 to.setAttribute( attribute, fromAttr );
30 }
31 }
32
33 /**
34 * Show the sticky header.
35 */
36 function show() {
37 document.body.classList.add( STICKY_HEADER_VISIBLE_CLASS );
38 document.body.classList.remove( ULS_HIDE_CLASS );
39 }
40
41 /**
42 * Hide the sticky header.
43 */
44 function hide() {
45 document.body.classList.remove( STICKY_HEADER_VISIBLE_CLASS );
46 document.body.classList.add( ULS_HIDE_CLASS );
47
48 // Dismiss dropdown menus and search if active
49 const stickyHeader = /** @type {HTMLElement} */ ( document.getElementById( STICKY_HEADER_ID ) );
50 if ( stickyHeader && stickyHeader.contains( document.activeElement ) ) {
51 document.body.click();
52 }
53 }
54
55 /**
56 * Copies attribute from an element to another.
57 *
58 * @param {Element} from
59 * @param {Element} to
60 */
61 function copyButtonAttributes( from, to ) {
62 copyAttribute( from, to, 'href' );
63 copyAttribute( from, to, 'title' );
64 // Copy button labels
65 if ( to.lastElementChild && from.lastElementChild ) {
66 to.lastElementChild.textContent = from.lastElementChild.textContent || '';
67 }
68 }
69
70 /**
71 * Suffixes an attribute with a value that indicates it
72 * relates to the sticky header to support click tracking instrumentation.
73 *
74 * @param {Element} node
75 * @param {string} attribute
76 */
77 function suffixStickyAttribute( node, attribute ) {
78 const value = node.getAttribute( attribute );
79 if ( value ) {
80 node.setAttribute( attribute, value + STICKY_HEADER_APPENDED_ID );
81 }
82 }
83
84 /**
85 * Suffixes the href attribute of a node with a value that indicates it
86 * relates to the sticky header to support tracking instrumentation.
87 *
88 * Distinct from suffixStickyAttribute as it's intended to support followed
89 * links recording their origin.
90 *
91 * @param {HTMLAnchorElement} node
92 */
93 function suffixStickyHref( node ) {
94 const url = new URL( node.href );
95 if ( url && !url.searchParams.has( STICKY_HEADER_APPENDED_PARAM[ 0 ] ) ) {
96 url.searchParams.append(
97 STICKY_HEADER_APPENDED_PARAM[ 0 ], STICKY_HEADER_APPENDED_PARAM[ 1 ]
98 );
99 node.href = url.toString();
100 }
101 }
102
103 /**
104 * Undoes the effect of suffixStickyHref
105 *
106 * @param {HTMLAnchorElement} node
107 */
108 function unsuffixStickyHref( node ) {
109 const url = new URL( node.href );
110 url.searchParams.delete( STICKY_HEADER_APPENDED_PARAM[ 0 ] );
111 node.href = url.toString();
112 }
113
114 /**
115 * Makes a node trackable by our click tracking instrumentation.
116 *
117 * @param {Element} node
118 */
119 function makeNodeTrackable( node ) {
120 suffixStickyAttribute( node, 'id' );
121 suffixStickyAttribute( node, 'data-event-name' );
122 }
123
124 /**
125 * @param {Element} node
126 */
127 function removeNode( node ) {
128 if ( node.parentNode ) {
129 node.parentNode.removeChild( node );
130 }
131 }
132
133 /**
134 * Ensures a sticky header button has the correct attributes
135 *
136 * @param {Element} watchLink
137 * @param {boolean} isWatched The page is watched
138 */
139 function updateStickyWatchlink( watchLink, isWatched ) {
140 watchLink.setAttribute( 'data-event-name', isWatched ? 'watch-sticky-header' : 'unwatch-sticky-header' );
141 }
142
143 /**
144 * @param {NodeList} nodes
145 * @param {string} className
146 */
147 function removeClassFromNodes( nodes, className ) {
148 Array.prototype.forEach.call( nodes, ( node ) => {
149 node.classList.remove( className );
150 } );
151 }
152
153 /**
154 * @param {NodeList} nodes
155 */
156 function removeNodes( nodes ) {
157 Array.prototype.forEach.call( nodes, ( node ) => {
158 node.parentNode.removeChild( node );
159 } );
160 }
161
162 /**
163 * Callback for watchsar
164 *
165 * @param {JQuery} $link Watchstar link
166 * @param {boolean} isWatched The page is watched
167 */
168 function watchstarCallback( $link, isWatched ) {
169 updateStickyWatchlink( /** @type {HTMLAnchorElement} */( $link[ 0 ] ), isWatched );
170 }
171
172 /**
173 * Makes sticky header icons functional for modern Vector.
174 *
175 * @param {Element} header
176 * @param {Element|null} history
177 * @param {Element|null} talk
178 * @param {Element|null} subject
179 * @param {Element|null} watch
180 */
181 function prepareIcons( header, history, talk, subject, watch ) {
182 const historySticky = header.querySelector( '#ca-history-sticky-header' ),
183 talkSticky = header.querySelector( '#ca-talk-sticky-header' ),
184 subjectSticky = header.querySelector( '#ca-subject-sticky-header' ),
185 watchSticky = header.querySelector( '#ca-watchstar-sticky-header' );
186
187 if ( !historySticky || !talkSticky || !subjectSticky || !watchSticky ) {
188 throw new Error( 'Sticky header has unexpected HTML' );
189 }
190
191 if ( history ) {
192 copyButtonAttributes( history, historySticky );
193 } else {
194 removeNode( historySticky );
195 }
196
197 if ( talk ) {
198 copyButtonAttributes( talk, talkSticky );
199 } else {
200 removeNode( talkSticky );
201 }
202
203 if ( subject ) {
204 copyButtonAttributes( subject, subjectSticky );
205 } else {
206 removeNode( subjectSticky );
207 }
208
209 if ( watch && watch.parentNode instanceof Element ) {
210 const watchContainer = watch.parentNode;
211 const isTemporaryWatch = watchContainer.classList.contains( 'mw-watchlink-temp' );
212 const isWatched = isTemporaryWatch || watchContainer.getAttribute( 'id' ) === 'ca-unwatch';
213 const watchIcon = /** @type {HTMLElement} */ ( watchSticky.querySelector( '.vector-icon' ) );
214
215 // Initialize sticky watchlink
216 copyButtonAttributes( watch, watchSticky );
217 updateWatchIcon( watchIcon, isWatched, isTemporaryWatch ? '' : 'infinity' );
218 updateStickyWatchlink( watchSticky, isWatched );
219
220 const watchLib = require( /** @type {string} */( 'mediawiki.page.watch.ajax' ) );
221 // jQuery required as parameter for external API:
222 // eslint-disable-next-line no-jquery/no-jquery-constructor
223 watchLib.watchstar( $( watchSticky ), mw.config.get( 'wgRelevantPageName' ), watchstarCallback );
224 } else {
225 removeNode( watchSticky );
226 }
227 }
228
229 /**
230 * Render sticky header edit or protected page icons for modern Vector.
231 *
232 * @param {Element} header
233 * @param {Element|null} primaryEdit
234 * @param {boolean} isProtected
235 * @param {Element|null} secondaryEdit
236 * @param {Element|null} addSection
237 * @param {Function} disableStickyHeader function to call to disable the sticky
238 * header.
239 */
240 function prepareEditIcons(
241 header,
242 primaryEdit,
243 isProtected,
244 secondaryEdit,
245 addSection,
246 disableStickyHeader
247 ) {
248 /**
249 * @param {string} selector
250 * @return {HTMLAnchorElement|null}
251 */
252 const getAnchorElement = ( selector ) => header.querySelector( selector );
253 const
254 primaryEditSticky = getAnchorElement(
255 '#ca-ve-edit-sticky-header'
256 ),
257 protectedSticky = getAnchorElement(
258 '#ca-viewsource-sticky-header'
259 ),
260 wikitextSticky = getAnchorElement(
261 '#ca-edit-sticky-header'
262 ),
263 addSectionSticky = getAnchorElement(
264 '#ca-addsection-sticky-header'
265 );
266
267 if ( addSectionSticky ) {
268 if ( addSection ) {
269 copyButtonAttributes( addSection, addSectionSticky );
270 suffixStickyHref( addSectionSticky );
271 } else {
272 removeNode( addSectionSticky );
273 }
274 }
275
276 // If no primary edit icon is present the feature is disabled.
277 if ( !primaryEditSticky || !wikitextSticky || !protectedSticky ) {
278 return;
279 }
280
281 if ( !primaryEdit ) {
282 removeNode( protectedSticky );
283 removeNode( wikitextSticky );
284 removeNode( primaryEditSticky );
285 return;
286 } else if ( isProtected ) {
287 removeNode( wikitextSticky );
288 removeNode( primaryEditSticky );
289 copyButtonAttributes( primaryEdit, protectedSticky );
290 suffixStickyHref( protectedSticky );
291 } else {
292 removeNode( protectedSticky );
293 copyButtonAttributes( primaryEdit, primaryEditSticky );
294 suffixStickyHref( primaryEditSticky );
295
296 primaryEditSticky.addEventListener( 'click', ( ev ) => {
297 const target = ev.target;
298 // T336639:
299 // eslint-disable-next-line no-jquery/no-jquery-constructor
300 const $ve = $( primaryEdit );
301 if ( target && $ve.length ) {
302 const link = /** @type {HTMLAnchorElement} */( $ve[ 0 ] );
303 // eslint-disable-next-line no-jquery/no-other-utils
304 const event = $.Event( 'click' );
305 suffixStickyHref( link );
306 // eslint-disable-next-line no-jquery/no-trigger
307 $ve.trigger( event );
308 unsuffixStickyHref( link );
309 // The link has been progressively enhanced.
310 if ( event.isDefaultPrevented() ) {
311 disableStickyHeader();
312 ev.preventDefault();
313 }
314 }
315 } );
316 if ( secondaryEdit ) {
317 copyButtonAttributes( secondaryEdit, wikitextSticky );
318 suffixStickyHref( wikitextSticky );
319 wikitextSticky.addEventListener( 'click', ( ev ) => {
320 const target = ev.target;
321 if ( target ) {
322 // T336639:
323 // eslint-disable-next-line no-jquery/no-jquery-constructor
324 const $edit = $( secondaryEdit );
325 if ( $edit.length ) {
326 const link = /** @type {HTMLAnchorElement} */( $edit[ 0 ] );
327 // eslint-disable-next-line no-jquery/no-other-utils
328 const event = $.Event( 'click' );
329 suffixStickyHref( link );
330 // eslint-disable-next-line no-jquery/no-trigger
331 $edit.trigger( event );
332 unsuffixStickyHref( link );
333 // The link has been progressively enhanced.
334 if ( event.isDefaultPrevented() ) {
335 disableStickyHeader();
336 ev.preventDefault();
337 }
338 }
339 }
340 } );
341 } else {
342 removeNode( wikitextSticky );
343 }
344 }
345 }
346
347 /**
348 * Check if element is in viewport.
349 *
350 * @param {Element} element
351 * @return {boolean}
352 */
353 function isInViewport( element ) {
354 const rect = element.getBoundingClientRect();
355 return (
356 rect.top >= 0 &&
357 rect.left >= 0 &&
358 rect.bottom <= ( window.innerHeight || document.documentElement.clientHeight ) &&
359 rect.right <= ( window.innerWidth || document.documentElement.clientWidth )
360 );
361 }
362
363 /**
364 * Add hooks for sticky header when Visual Editor is used.
365 *
366 * @param {Element} stickyIntersection intersection element
367 * @param {IntersectionObserver} observer
368 */
369 function addVisualEditorHooks( stickyIntersection, observer ) {
370 // When Visual Editor is activated, hide the sticky header.
371 mw.hook( 've.activationStart' ).add( () => {
372 hide();
373 observer.unobserve( stickyIntersection );
374 } );
375
376 // When Visual Editor is deactivated (by clicking "Read" tab at top of page), show sticky header
377 // by re-triggering the observer.
378 mw.hook( 've.deactivationComplete' ).add( () => {
379 // Wait for the next repaint or we might calculate that
380 // sticky header should not be visible (T299114)
381 requestAnimationFrame( () => {
382 observer.observe( stickyIntersection );
383 } );
384 } );
385
386 // After saving edits, re-apply the sticky header if the target is not in the viewport.
387 mw.hook( 'postEdit.afterRemoval' ).add( () => {
388 if ( !isInViewport( stickyIntersection ) ) {
389 show();
390 observer.observe( stickyIntersection );
391 }
392 } );
393 }
394
395 /**
396 * Clones the existing user menu (excluding items added by gadgets) and adds to the sticky header
397 * ensuring it is not focusable and that elements are no longer collapsible (since the sticky header
398 * itself collapses at low resolutions) and updates click tracking event names. Also wires up the
399 * logout link so it works in a single click.
400 *
401 * @param {Element} userLinksDropdown
402 * @return {Element} cloned userLinksDropdown
403 */
404 function prepareUserLinksDropdown( userLinksDropdown ) {
405 const
406 // Type declaration needed because of https://github.com/Microsoft/TypeScript/issues/3734#issuecomment-118934518
407 userLinksDropdownClone = /** @type {Element} */( userLinksDropdown.cloneNode( true ) ),
408 userLinksDropdownStickyElementsWithIds = userLinksDropdownClone.querySelectorAll( '[ id ], [ data-event-name ]' );
409 // Update all ids of the cloned user menu to make them unique.
410 makeNodeTrackable( userLinksDropdownClone );
411 userLinksDropdownStickyElementsWithIds.forEach( makeNodeTrackable );
412 // Remove portlet links added by gadgets using mw.util.addPortletLink, T291426
413 removeNodes( userLinksDropdownClone.querySelectorAll( '.mw-list-item-js' ) );
414 removeClassFromNodes(
415 userLinksDropdownClone.querySelectorAll( '.user-links-collapsible-item' ),
416 'user-links-collapsible-item'
417 );
418 // Prevents user menu from being focusable, T290201
419 const userLinksDropdownCheckbox = userLinksDropdownClone.querySelector( 'input' );
420 if ( userLinksDropdownCheckbox ) {
421 userLinksDropdownCheckbox.setAttribute( 'tabindex', '-1' );
422 }
423
424 // Make the logout go through the API (T324638)
425 const logoutLink = /** @type {HTMLAnchorElement} */( userLinksDropdownClone.querySelector( '#pt-logout-sticky-header a' ) );
426 if ( logoutLink ) {
427 logoutLink.addEventListener( 'click', ( ev ) => {
428 ev.preventDefault();
429 mw.hook( 'skin.logout' ).fire( logoutLink.href );
430 } );
431 }
432 return userLinksDropdownClone;
433 }
434
435 /**
436 * Makes sticky header functional for modern Vector.
437 *
438 * @param {Element} header
439 * @param {Element} userLinksDropdown
440 * @param {IntersectionObserver} stickyObserver
441 * @param {Element} stickyIntersection
442 */
443 function makeStickyHeaderFunctional(
444 header,
445 userLinksDropdown,
446 stickyObserver,
447 stickyIntersection
448 ) {
449 const userLinksDropdownStickyContainer = document.querySelector(
450 STICKY_HEADER_USER_MENU_CONTAINER_SELECTOR
451 );
452
453 // Clone the updated user menu to the sticky header.
454 if ( userLinksDropdownStickyContainer ) {
455 const clonedUserLinksDropdown = prepareUserLinksDropdown( userLinksDropdown );
456 userLinksDropdownStickyContainer.appendChild( clonedUserLinksDropdown );
457 }
458
459 let namespaceName = mw.config.get( 'wgCanonicalNamespace' );
460 const namespaceNumber = mw.config.get( 'wgNamespaceNumber' );
461 if ( namespaceNumber >= 0 && namespaceNumber % 2 === 1 ) {
462 // Remove '_talk' to get subject namespace
463 namespaceName = namespaceName.slice( 0, -5 );
464 }
465 // Title::getNamespaceKey()
466 let namespaceKey = namespaceName.toLowerCase() || 'main';
467 if ( namespaceKey === 'file' ) {
468 namespaceKey = 'image';
469 }
470 const namespaceTabId = 'ca-nstab-' + namespaceKey;
471
472 prepareIcons( header,
473 document.querySelector( '#ca-history a' ),
474 document.querySelector( '#ca-talk:not( .selected ) a' ),
475 document.querySelector( '#' + namespaceTabId + ':not( .selected ) a' ),
476 document.querySelector( '#ca-watch a, #ca-unwatch a' )
477 );
478
479 const veEdit = document.querySelector( '#ca-ve-edit a' );
480 const ceEdit = document.querySelector( '#ca-edit a' );
481 const protectedEdit = document.querySelector( '#ca-viewsource a' );
482 const isProtected = !!protectedEdit;
483 // For sticky header edit A/B test, conditionally remove the edit icon by setting null.
484 // Otherwise, use either protected, ve, or source edit (in that order).
485 const primaryEdit = protectedEdit || veEdit || ceEdit;
486 const secondaryEdit = veEdit ? ceEdit : null;
487 const disableStickyHeader = () => {
488 document.body.classList.remove( STICKY_HEADER_VISIBLE_CLASS );
489 stickyObserver.unobserve( stickyIntersection );
490 };
491 // When VectorPromoteAddTopic is set, #ca-addsection is the link itself
492 const addSection = document.querySelector( '#ca-addsection a' ) || document.querySelector( 'a#ca-addsection' );
493
494 prepareEditIcons(
495 header,
496 primaryEdit,
497 isProtected,
498 secondaryEdit,
499 addSection,
500 disableStickyHeader
501 );
502
503 stickyObserver.observe( stickyIntersection );
504 }
505
506 /**
507 * @param {Element} header
508 */
509 function setupSearchIfNeeded( header ) {
510 const
511 searchToggle = header.querySelector( SEARCH_TOGGLE_SELECTOR );
512
513 if ( !document.body.classList.contains( 'skin-vector-search-vue' ) ) {
514 return;
515 }
516
517 if ( searchToggle ) {
518 initSearchToggle( searchToggle );
519 }
520 }
521
522 /**
523 * Determines if sticky header should be visible for a given namespace.
524 *
525 * @param {number} namespaceNumber
526 * @return {boolean}
527 */
528 function isAllowedNamespace( namespaceNumber ) {
529 // Corresponds to Main, User, Wikipedia, Template, Help, Category, Portal, Module.
530 const allowedNamespaceNumbers = [ 0, 2, 4, 10, 12, 14, 100, 828 ];
531 // Also allow on all talk namespaces (compare NamespaceInfo::isTalk()).
532 const isAllowedTalk = namespaceNumber > 0 && namespaceNumber % 2 !== 0;
533 return isAllowedTalk || allowedNamespaceNumbers.indexOf( namespaceNumber ) > -1;
534 }
535
536 /**
537 * Determines if sticky header should be visible for a given action.
538 *
539 * @param {string} action
540 * @return {boolean}
541 */
542 function isAllowedAction( action ) {
543 const disallowedActions = [ 'history', 'edit' ],
544 hasDiffId = mw.config.get( 'wgDiffOldId' );
545 return disallowedActions.indexOf( action ) < 0 && !hasDiffId;
546 }
547
548 /**
549 * @typedef {Object} StickyHeaderProps
550 * @property {Element} header
551 * @property {Element} userLinksDropdown
552 * @property {IntersectionObserver} observer
553 * @property {Element} stickyIntersection
554 */
555
556 /**
557 * @param {StickyHeaderProps} props
558 */
559 function initStickyHeader( props ) {
560 makeStickyHeaderFunctional(
561 props.header,
562 props.userLinksDropdown,
563 props.observer,
564 props.stickyIntersection
565 );
566
567 setupSearchIfNeeded( props.header );
568 addVisualEditorHooks( props.stickyIntersection, props.observer );
569
570 // Make sure ULS outside sticky header disables the sticky header behaviour.
571 mw.hook( 'mw.uls.compact_language_links.open' ).add( ( $trigger ) => {
572 const trigger = $trigger[ 0 ];
573 if ( trigger.id !== 'p-lang-btn-sticky-header' ) {
574 const bodyClassList = document.body.classList;
575 bodyClassList.remove( ULS_HIDE_CLASS );
576 bodyClassList.remove( ULS_STICKY_CLASS );
577 }
578 } );
579
580 // Make sure ULS dialog is sticky.
581 const langBtn = props.header.querySelector( '#p-lang-btn-sticky-header' );
582 if ( langBtn ) {
583 langBtn.addEventListener( 'click', () => {
584 const bodyClassList = document.body.classList;
585 bodyClassList.remove( ULS_HIDE_CLASS );
586 bodyClassList.add( ULS_STICKY_CLASS );
587 } );
588 }
589 }
590
591 module.exports = {
592 show,
593 hide,
594 prepareUserLinksDropdown,
595 isAllowedNamespace,
596 isAllowedAction,
597 initStickyHeader,
598 STICKY_HEADER_ID,
599 FIRST_HEADING_ID,
600 USER_LINKS_DROPDOWN_ID,
601 STICKY_HEADER_EXPERIMENT_NAME
602 };