Debian Codegraph @

skins/Vector/resources/skins.vector.js/tableOfContents.js

raw symbols SCIP
1 /** @module TableOfContents */
2
3 /**
4 * TableOfContents Mustache templates
5 */
6 const templateTocContents = require( /** @type {string} */ ( './templates/TableOfContents__list.mustache' ) );
7 const templateTocLine = require( /** @type {string} */ ( './templates/TableOfContents__line.mustache' ) );
8 /**
9 * TableOfContents Config object for filling mustache templates
10 */
11 const tableOfContentsConfig = require( /** @type {string} */ ( './tableOfContentsConfig.json' ) );
12 const deferUntilFrame = require( './deferUntilFrame.js' );
13
14 const SECTION_ID_PREFIX = 'toc-';
15 const SECTION_CLASS = 'vector-toc-list-item';
16 const ACTIVE_SECTION_CLASS = 'vector-toc-list-item-active';
17 const EXPANDED_SECTION_CLASS = 'vector-toc-list-item-expanded';
18 const TOP_SECTION_CLASS = 'vector-toc-level-1';
19 const ACTIVE_TOP_SECTION_CLASS = 'vector-toc-level-1-active';
20 const LINK_CLASS = 'vector-toc-link';
21 const TOGGLE_CLASS = 'vector-toc-toggle';
22 const TOC_CONTENTS_ID = 'mw-panel-toc-list';
23
24 /**
25 * Fired when the user clicks a toc link. Note that this callback takes
26 * precedence over the onHashChange callback. The onHashChange callback will not
27 * be called when the user clicks a toc link.
28 *
29 * @callback onHeadingClick
30 * @param {string} id The id of the clicked list item.
31 */
32
33 /**
34 * Fired when the page's hash fragment has changed. Note that if the user clicks
35 * a link inside the TOC, the `onHeadingClick` callback will fire instead of the
36 * `onHashChange` callback to avoid redundant behavior.
37 *
38 * @callback onHashChange
39 * @param {string} id The id of the list item that corresponds to the hash change event.
40 */
41
42 /**
43 * @callback onToggleClick
44 * @param {string} id The id of the list item corresponding to the arrow.
45 */
46
47 /**
48 * @callback onTogglePinned
49 */
50
51 /**
52 * @callback tableOfContents
53 * @param {TableOfContentsProps} props
54 * @return {TableOfContents}
55 */
56
57 /**
58 * @typedef {Object} TableOfContentsProps
59 * @property {HTMLElement} container The container element for the table of contents.
60 * @property {onHeadingClick} onHeadingClick Called when an arrow is clicked.
61 * @property {onHashChange} onHashChange Called when a hash change event
62 * matches the id of a LINK_CLASS anchor element.
63 * @property {onToggleClick} [onToggleClick] Called when an arrow is clicked.
64 * @property {onTogglePinned} onTogglePinned Called when pinned toggle buttons are clicked.
65 */
66
67 /**
68 * @typedef {Object} Section
69 * @property {number} toclevel
70 * @property {string} anchor
71 * @property {string} line
72 * @property {string} number
73 * @property {string} index
74 * @property {number} byteoffset
75 * @property {string} fromtitle
76 * @property {boolean} is-parent-section
77 * @property {boolean} is-top-level-section
78 * @property {Section[]} array-sections
79 * @property {string} level
80 */
81
82 /**
83 * @typedef {Object} SectionsListData
84 * @property {Section[]} array-sections
85 * @property {boolean} vector-is-collapse-sections-enabled
86 * @property {string} msg-vector-toc-beginning
87 */
88
89 /**
90 * @typedef {Object} ArraySectionsData
91 * @property {number} number-section-count
92 * @property {Section[]} array-sections
93 */
94
95 /**
96 * Initializes the sidebar's Table of Contents.
97 *
98 * @param {TableOfContentsProps} props
99 * @return {TableOfContents}
100 */
101 module.exports = function tableOfContents( props ) {
102 let /** @type {HTMLElement | undefined} */ activeTopSection;
103 let /** @type {HTMLElement | undefined} */ activeSubSection;
104 let /** @type {Array<HTMLElement>} */ expandedSections;
105
106 /**
107 * @typedef {Object} activeSectionIds
108 * @property {string|undefined} parent - The active top level section ID
109 * @property {string|undefined} child - The active subsection ID
110 */
111
112 /**
113 * Get the ids of the active sections.
114 *
115 * @return {activeSectionIds}
116 */
117 function getActiveSectionIds() {
118 return {
119 parent: ( activeTopSection ) ? activeTopSection.id : undefined,
120 child: ( activeSubSection ) ? activeSubSection.id : undefined
121 };
122 }
123
124 /**
125 * Does the user prefer reduced motion?
126 *
127 * @return {boolean}
128 */
129 const prefersReducedMotion = () => window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
130
131 /**
132 * Sets an `ACTIVE_SECTION_CLASS` on the element with an id that matches `id`.
133 * Sets an `ACTIVE_TOP_SECTION_CLASS` on the top level heading (e.g. element with the
134 * `TOP_SECTION_CLASS`).
135 * If the element is a top level heading, the element will have both classes.
136 *
137 * @param {string} id The id of the element to be activated in the Table of Contents.
138 */
139 function activateSection( id ) {
140 const selectedTocSection = document.getElementById( id );
141 const {
142 parent: previousActiveTopId,
143 child: previousActiveSubSectionId
144 } = getActiveSectionIds();
145
146 if (
147 !selectedTocSection ||
148 ( previousActiveTopId === id ) ||
149 ( previousActiveSubSectionId === id )
150 ) {
151 return;
152 }
153
154 // Assign the active top and sub sections, apply classes
155 activeTopSection = /** @type {HTMLElement|undefined} */ ( selectedTocSection.closest( `.${ TOP_SECTION_CLASS }` ) );
156 if ( activeTopSection ) {
157 // T328089 Sometimes activeTopSection is null
158 activeTopSection.classList.add( ACTIVE_TOP_SECTION_CLASS );
159 }
160 activeSubSection = selectedTocSection;
161 activeSubSection.classList.add( ACTIVE_SECTION_CLASS );
162 }
163
164 /**
165 * Removes the `ACTIVE_SECTION_CLASS` from all ToC sections.
166 *
167 */
168 function deactivateSections() {
169 if ( activeSubSection ) {
170 activeSubSection.classList.remove( ACTIVE_SECTION_CLASS );
171 activeSubSection = undefined;
172 }
173 if ( activeTopSection ) {
174 activeTopSection.classList.remove( ACTIVE_TOP_SECTION_CLASS );
175 activeTopSection = undefined;
176 }
177 }
178
179 /**
180 * Scroll active section into view if necessary
181 *
182 * @param {string} id The id of the element to be scrolled to in the Table of Contents.
183 */
184 function scrollToActiveSection( id ) {
185 const section = document.getElementById( id );
186 if ( !section ) {
187 return;
188 }
189
190 // Get currently visible active link
191 let link = /** @type {HTMLElement|null} */( section.firstElementChild );
192 if ( link && !link.offsetParent ) {
193 // If active link is a hidden subsection, use active parent link
194 const { parent: activeTopId } = getActiveSectionIds();
195 const parentSection = document.getElementById( activeTopId || '' );
196 if ( parentSection ) {
197 link = /** @type {HTMLElement|null} */( parentSection.firstElementChild );
198 } else {
199 link = null;
200 }
201 }
202
203 const isContainerScrollable = props.container.scrollHeight > props.container.clientHeight;
204 if ( link && isContainerScrollable ) {
205 const containerRect = props.container.getBoundingClientRect();
206 const linkRect = link.getBoundingClientRect();
207
208 // Pixels above or below the TOC where we start scrolling the active section into view
209 const hiddenThreshold = 100;
210 const midpoint = ( containerRect.bottom - containerRect.top ) / 2;
211 const linkHiddenTopValue = containerRect.top - linkRect.top;
212 // Because the bottom of the TOC can extend below the viewport,
213 // min() is used to find the value where the active section first becomes hidden
214 const linkHiddenBottomValue = linkRect.bottom -
215 Math.min( containerRect.bottom, window.innerHeight );
216
217 // Respect 'prefers-reduced-motion' user preference
218 const scrollBehavior = prefersReducedMotion() ? 'smooth' : undefined;
219
220 // Manually increment and decrement TOC scroll rather than using scrollToView
221 // in order to account for threshold
222 if ( linkHiddenTopValue + hiddenThreshold > 0 ) {
223 props.container.scrollTo( {
224 top: props.container.scrollTop - linkHiddenTopValue - midpoint,
225 behavior: scrollBehavior
226 } );
227 }
228 if ( linkHiddenBottomValue + hiddenThreshold > 0 ) {
229 props.container.scrollTo( {
230 top: props.container.scrollTop + linkHiddenBottomValue + midpoint,
231 behavior: scrollBehavior
232 } );
233 }
234 }
235 }
236
237 /**
238 * Adds the `EXPANDED_SECTION_CLASS` CSS class name
239 * to a top level heading in the ToC.
240 *
241 * @param {string} id
242 */
243 function expandSection( id ) {
244 const tocSection = document.getElementById( id );
245
246 if ( !tocSection ) {
247 return;
248 }
249
250 const topSection = /** @type {HTMLElement} */ ( tocSection.closest( `.${ TOP_SECTION_CLASS }` ) );
251 const toggle = topSection.querySelector( `.${ TOGGLE_CLASS }` );
252
253 if ( topSection && toggle && expandedSections.indexOf( topSection ) < 0 ) {
254 toggle.setAttribute( 'aria-expanded', 'true' );
255 topSection.classList.add( EXPANDED_SECTION_CLASS );
256 expandedSections.push( topSection );
257 }
258 }
259
260 /**
261 * Get the IDs of expanded sections.
262 *
263 * @return {Array<string>}
264 */
265 function getExpandedSectionIds() {
266 return expandedSections.map( ( s ) => s.id );
267 }
268
269 /**
270 * @param {string} id
271 */
272 function changeActiveSection( id ) {
273
274 const { parent: activeParentId, child: activeChildId } = getActiveSectionIds();
275
276 if ( id === activeParentId && id === activeChildId ) {
277 return;
278 } else {
279 deactivateSections();
280 activateSection( id );
281 scrollToActiveSection( id );
282 }
283 }
284
285 /**
286 * @param {string} id
287 * @return {boolean}
288 */
289 function isTopLevelSection( id ) {
290 const section = document.getElementById( id );
291 return !!section && section.classList.contains( TOP_SECTION_CLASS );
292 }
293
294 /**
295 * Removes all `EXPANDED_SECTION_CLASS` CSS class names
296 * from the top level sections in the ToC.
297 *
298 * @param {Array<string>} [selectedIds]
299 */
300 function collapseSections( selectedIds ) {
301 const sectionIdsToCollapse = selectedIds || getExpandedSectionIds();
302 expandedSections = expandedSections.filter( ( section ) => {
303 const isSelected = sectionIdsToCollapse.indexOf( section.id ) > -1;
304 const toggle = isSelected ? section.getElementsByClassName( TOGGLE_CLASS ) : undefined;
305 if ( isSelected && toggle && toggle.length > 0 ) {
306 toggle[ 0 ].setAttribute( 'aria-expanded', 'false' );
307 section.classList.remove( EXPANDED_SECTION_CLASS );
308 return false;
309 }
310 return true;
311 } );
312 }
313
314 /**
315 * @param {string} id
316 */
317 function toggleExpandSection( id ) {
318 const expandedSectionIds = getExpandedSectionIds();
319 const indexOfExpandedSectionId = expandedSectionIds.indexOf( id );
320 if ( isTopLevelSection( id ) ) {
321 if ( indexOfExpandedSectionId >= 0 ) {
322 collapseSections( [ id ] );
323 } else {
324 expandSection( id );
325 }
326 }
327 }
328
329 /**
330 * Set aria-expanded attribute for all toggle buttons.
331 */
332 function initializeExpandedStatus() {
333 const parentSections = props.container.querySelectorAll( `.${ TOP_SECTION_CLASS }` );
334 parentSections.forEach( ( section ) => {
335 const expanded = section.classList.contains( EXPANDED_SECTION_CLASS );
336 const toggle = section.querySelector( `.${ TOGGLE_CLASS }` );
337 if ( toggle ) {
338 toggle.setAttribute( 'aria-expanded', expanded.toString() );
339 }
340 } );
341 }
342
343 /**
344 * Event handler for hash change event.
345 */
346 function handleHashChange() {
347 const hash = location.hash.slice( 1 );
348 const listItem = mw.util.getTargetFromFragment( `${ SECTION_ID_PREFIX }${ hash }` );
349
350 if ( !listItem ) {
351 return;
352 }
353
354 expandSection( listItem.id );
355 changeActiveSection( listItem.id );
356
357 props.onHashChange( listItem.id );
358 }
359
360 /**
361 * Bind event listener for hash change events that match the hash of
362 * LINK_CLASS.
363 *
364 * Note that if the user clicks a link inside the TOC, the onHeadingClick
365 * callback will fire instead of the onHashChange callback, since it takes
366 * precedence.
367 */
368 function bindHashChangeListener() {
369 window.addEventListener( 'hashchange', handleHashChange );
370 }
371
372 /**
373 * Unbinds event listener for hash change events.
374 */
375 function unbindHashChangeListener() {
376 window.removeEventListener( 'hashchange', handleHashChange );
377 }
378
379 /**
380 * Bind event listener for clicking on show/hide Table of Contents links.
381 */
382 function bindPinnedToggleListeners() {
383 const toggleButtons = document.querySelectorAll( '.vector-toc-pinnable-header button' );
384 toggleButtons.forEach( ( btn ) => {
385 btn.addEventListener( 'click', () => {
386 props.onTogglePinned();
387 } );
388 } );
389 }
390
391 /**
392 * Bind event listeners for clicking on section headings and toggle buttons.
393 */
394 function bindSubsectionToggleListeners() {
395 props.container.addEventListener( 'click', ( e ) => {
396 if (
397 !( e.target instanceof HTMLElement )
398 ) {
399 return;
400 }
401
402 const tocSection =
403 /** @type {HTMLElement | null} */ ( e.target.closest( `.${ SECTION_CLASS }` ) );
404
405 if ( tocSection && tocSection.id ) {
406 // In case section link contains HTML,
407 // test if click occurs on any child elements.
408 if ( e.target.closest( `.${ LINK_CLASS }` ) ) {
409 // Temporarily unbind the hash change listener to avoid redundant
410 // behavior caused by firing both the onHeadingClick callback and the
411 // onHashChange callback. Instead, only fire the onHeadingClick
412 // callback.
413 unbindHashChangeListener();
414
415 expandSection( tocSection.id );
416 changeActiveSection( tocSection.id );
417 props.onHeadingClick( tocSection.id );
418
419 deferUntilFrame( () => {
420 bindHashChangeListener();
421 }, 3 );
422 }
423 // Toggle button does not contain child elements,
424 // so classList check will suffice.
425 if ( e.target.closest( `.${ TOGGLE_CLASS }` ) ) {
426 toggleExpandSection( tocSection.id );
427 if ( props.onToggleClick ) {
428 props.onToggleClick( tocSection.id );
429 }
430 }
431 }
432
433 } );
434 }
435
436 /**
437 * Binds event listeners and sets the default state of the component.
438 */
439 function initialize() {
440 // Sync component state to the default rendered state of the table of contents.
441 expandedSections = Array.from(
442 props.container.querySelectorAll( `.${ EXPANDED_SECTION_CLASS }` )
443 );
444
445 // Initialize toggle buttons aria-expanded attribute.
446 initializeExpandedStatus();
447
448 // Bind event listeners.
449 bindSubsectionToggleListeners();
450 bindPinnedToggleListeners();
451 bindHashChangeListener();
452 }
453
454 /**
455 * Reexpands all sections that were expanded before the table of contents was reloaded.
456 * Edited Sections are not reexpanded, as the ID of the edited section is changed after reload.
457 */
458 function reExpandSections() {
459 initializeExpandedStatus();
460 const expandedSectionIds = getExpandedSectionIds();
461 for ( const id of expandedSectionIds ) {
462 expandSection( id );
463 }
464 }
465
466 /**
467 * Updates button styling for the TOC toggle button when scrolled below the page title
468 *
469 * @param {boolean} scrollBelow
470 */
471 function updateTocToggleStyles( scrollBelow ) {
472 const TOC_TITLEBAR_TOGGLE_ID = 'vector-page-titlebar-toc-label';
473 const QUIET_BUTTON_CLASS = 'cdx-button--weight-quiet';
474 const tocToggle = document.getElementById( TOC_TITLEBAR_TOGGLE_ID );
475 if ( tocToggle ) {
476 if ( scrollBelow ) {
477 tocToggle.classList.remove( QUIET_BUTTON_CLASS );
478 } else {
479 tocToggle.classList.add( QUIET_BUTTON_CLASS );
480 }
481 }
482 }
483
484 /**
485 * Reloads the table of contents from saved data
486 *
487 * @param {Section[]} sections
488 * @return {Promise<any>}
489 */
490 function reloadTableOfContents( sections ) {
491 if ( sections.length < 1 ) {
492 reloadPartialHTML( TOC_CONTENTS_ID, '' );
493 return Promise.resolve( [] );
494 }
495 const load = () => mw.loader.using( 'mediawiki.template.mustache' ).then( () => {
496 const { parent: activeParentId, child: activeChildId } = getActiveSectionIds();
497 reloadPartialHTML( TOC_CONTENTS_ID, getTableOfContentsHTML( sections ) );
498 // Reexpand sections that were expanded before the table of contents was reloaded.
499 reExpandSections();
500 // reActivate the active sections
501 deactivateSections();
502 if ( activeParentId ) {
503 activateSection( activeParentId );
504 }
505 if ( activeChildId ) {
506 activateSection( activeChildId );
507 }
508 } );
509 return new Promise( ( resolve ) => {
510 load().then( () => {
511 resolve( sections );
512 } );
513 } );
514 }
515
516 /**
517 * Replaces the contents of the given element with the given HTML
518 *
519 * @param {string} elementId
520 * @param {string} html
521 */
522 function reloadPartialHTML( elementId, html ) {
523 const htmlElement = document.getElementById( elementId );
524 if ( htmlElement && html ) {
525 htmlElement.innerHTML = html;
526 }
527 }
528
529 /**
530 * Generates the HTML for the table of contents.
531 *
532 * @param {Section[]} sections
533 * @return {string}
534 */
535 function getTableOfContentsHTML( sections ) {
536 return getTableOfContentsListHtml( getTableOfContentsData( sections ) );
537 }
538
539 /**
540 * Generates the table of contents List HTML from the templates
541 *
542 * @param {Object} data
543 * @return {string}
544 */
545 function getTableOfContentsListHtml( data ) {
546 const mustacheCompiler = mw.template.getCompiler( 'mustache' );
547 const compiledTemplateTocContents = mustacheCompiler.compile( templateTocContents );
548
549 // Identifier 'TableOfContents__line' is not in camel case
550 // (template name is 'TableOfContents__line')
551 const partials = {
552 // eslint-disable-next-line camelcase
553 TableOfContents__line: mustacheCompiler.compile( templateTocLine )
554 };
555
556 return compiledTemplateTocContents.render( data, partials ).html();
557 }
558
559 /**
560 * @param {Section[]} sections
561 * @return {SectionsListData}
562 */
563 function getTableOfContentsData( sections ) {
564 const tableOfContentsLevel1Sections = getTableOfContentsSectionsData( sections, 1 );
565 return {
566 'msg-vector-toc-beginning': mw.message( 'vector-toc-beginning' ).text(),
567 'array-sections': tableOfContentsLevel1Sections,
568 'vector-is-collapse-sections-enabled': tableOfContentsLevel1Sections.length > 3 && sections.length >= tableOfContentsConfig.VectorTableOfContentsCollapseAtCount
569 };
570 }
571
572 /**
573 * Prepares the data for rendering the table of contents,
574 * nesting child sections within their parent sections.
575 * This should yield the same result as the php function
576 * VectorComponentTableOfContents::getTemplateData(),
577 * please make sure to keep them in sync.
578 *
579 * @param {Section[]} sections
580 * @param {number} toclevel
581 * @return {Section[]}
582 */
583 function getTableOfContentsSectionsData( sections, toclevel = 1 ) {
584 const data = [];
585 for ( let i = 0; i < sections.length; i++ ) {
586 const section = sections[ i ];
587 if ( section.toclevel === toclevel ) {
588 const childSections = getTableOfContentsSectionsData(
589 sections.slice( i + 1 ),
590 toclevel + 1
591 );
592 section[ 'array-sections' ] = childSections;
593 section[ 'is-top-level-section' ] = toclevel === 1;
594 section[ 'is-parent-section' ] = Object.keys( childSections ).length > 0;
595 data.push( section );
596 }
597 // Child section belongs to a higher parent.
598 if ( section.toclevel < toclevel ) {
599 return data;
600 }
601 }
602
603 return data;
604 }
605
606 /**
607 * Cleans up the hash change event listener to prevent memory leaks. This
608 * should be called when the table of contents is permanently no longer
609 * needed.
610 *
611 * @ignore
612 */
613 function unmount() {
614 unbindHashChangeListener();
615 }
616
617 initialize();
618
619 /**
620 * @typedef {Object} TableOfContents
621 * @property {reloadTableOfContents} reloadTableOfContents
622 * @property {changeActiveSection} changeActiveSection
623 * @property {expandSection} expandSection
624 * @property {toggleExpandSection} toggleExpandSection
625 * @property {updateTocToggleStyles} updateTocToggleStyles
626 * @property {unmount} unmount
627 * @property {string} ACTIVE_SECTION_CLASS
628 * @property {string} ACTIVE_TOP_SECTION_CLASS
629 * @property {string} EXPANDED_SECTION_CLASS
630 * @property {string} LINK_CLASS
631 * @property {string} TOGGLE_CLASS
632 */
633 return {
634 reloadTableOfContents,
635 expandSection,
636 changeActiveSection,
637 toggleExpandSection,
638 updateTocToggleStyles,
639 unmount,
640 ACTIVE_SECTION_CLASS,
641 ACTIVE_TOP_SECTION_CLASS,
642 EXPANDED_SECTION_CLASS,
643 LINK_CLASS,
644 TOGGLE_CLASS
645 };
646 };