Debian Codegraph @

skins/Vector/resources/skins.vector.js/setupIntersectionObservers.js

raw symbols SCIP
1 // Enable Vector features limited to ES6 browse
2 const
3 stickyHeader = require( './stickyHeader.js' ),
4 scrollObserver = require( './scrollObserver.js' ),
5 initExperiment = require( './AB.js' ),
6 initSectionObserver = require( './sectionObserver.js' ),
7 initTableOfContents = require( './tableOfContents.js' ),
8 pinnableElement = require( './pinnableElement.js' ),
9 popupNotification = require( './popupNotification.js' ),
10 features = require( './features.js' ),
11 deferUntilFrame = require( './deferUntilFrame.js' ),
12 ABTestConfig = require( /** @type {string} */ ( './activeABTest.json' ) ),
13 STICKY_HEADER_VISIBLE_CLASS = 'vector-sticky-header-visible',
14 TOC_ID = 'vector-toc',
15 BODY_CONTENT_ID = 'bodyContent',
16 // Support two variants of heading markup: (see T13555, T358452)
17 // (old) <h2> <span class="mw-headline" id="...">...</span> ... </h2>
18 // (new) <div class="mw-heading"> <h2 id="...">...</h2> ... </div>
19 // [more information: https://www.mediawiki.org/wiki/Heading_HTML_changes]
20 HEADING_TAGS = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
21 HEADING_SELECTOR = [ '.mw-heading', ...HEADING_TAGS.map( ( tag ) => `${ tag }:not([id])` ) ]
22 .map( ( sel ) => `.mw-parser-output ${ sel }` ).join( ', ' ),
23 HEADLINE_SELECTOR = [ '.mw-headline', ...HEADING_TAGS.map( ( tag ) => `${ tag }[id]` ) ]
24 .map( ( sel ) => `.mw-parser-output ${ sel }` ).join( ', ' ),
25 TOC_SECTION_ID_PREFIX = 'toc-',
26 PAGE_TITLE_INTERSECTION_CLASS = 'vector-below-page-title';
27
28 const belowDesktopMedia = window.matchMedia( '(max-width: 1119px)' );
29
30 /**
31 * @callback OnIntersection
32 * @param {HTMLElement} element The section that triggered the new intersection change.
33 */
34
35 /**
36 * @ignore
37 * @param {Function} changeActiveSection
38 * @return {OnIntersection}
39 */
40 const getHeadingIntersectionHandler = ( changeActiveSection ) =>
41 /**
42 * @param {HTMLElement} section
43 */
44 // eslint-disable-next-line implicit-arrow-linebreak
45 ( section ) => {
46 const headline = section.classList.contains( 'mw-body-content' ) ?
47 section :
48 section.querySelector( HEADLINE_SELECTOR );
49 if ( headline ) {
50 changeActiveSection( `${ TOC_SECTION_ID_PREFIX }${ headline.id }` );
51 }
52 };
53
54 /**
55 * Initialize sticky header AB tests and determine whether to show the sticky header
56 * based on which buckets the user is in.
57 *
58 * @typedef {Object} InitStickyHeaderABTests
59 * @property {boolean} showStickyHeader - Should the sticky header be shown
60 * @param {ABTestConfig} abConfig
61 * @param {boolean} isStickyHeaderFeatureAllowed and the user is logged in
62 * @param {function(ABTestConfig): initExperiment.WebABTest} getEnabledExperiment
63 * @return {InitStickyHeaderABTests}
64 */
65 function initStickyHeaderABTests( abConfig, isStickyHeaderFeatureAllowed, getEnabledExperiment ) {
66 let showStickyHeader = isStickyHeaderFeatureAllowed,
67 stickyHeaderExperiment;
68
69 // One of the sticky header AB tests is specified in the config
70 const abTestName = abConfig.name,
71 isStickyHeaderExperiment = abTestName === stickyHeader.STICKY_HEADER_EXPERIMENT_NAME;
72
73 // Determine if user is eligible for sticky header AB test
74 if (
75 isStickyHeaderFeatureAllowed && // The sticky header can be shown on the page
76 abConfig.enabled && // An AB test config is enabled
77 isStickyHeaderExperiment // The AB test is one of the sticky header experiments
78 ) {
79 // If eligible, initialize the AB test
80 stickyHeaderExperiment = getEnabledExperiment( abConfig );
81
82 // If running initial or edit AB test, show sticky header to treatment groups
83 // only. Unsampled and control buckets do not see sticky header.
84 if ( abTestName === stickyHeader.STICKY_HEADER_EXPERIMENT_NAME ) {
85 showStickyHeader = stickyHeaderExperiment.isInTreatmentBucket();
86 }
87 }
88
89 return {
90 showStickyHeader
91 };
92 }
93
94 /*
95 * Updates TOC's location in the DOM (in sidebar or sticky header)
96 * depending on if the TOC is collapsed and if the sticky header is visible
97 *
98 * @return {void}
99 */
100 const updateTocLocation = () => {
101 const isPinned = features.isEnabled( 'toc-pinned' );
102 const isStickyHeaderVisible = document.body.classList.contains( STICKY_HEADER_VISIBLE_CLASS );
103 const isBelowDesktop = belowDesktopMedia.matches;
104
105 const pinnedContainerId = 'vector-toc-pinned-container';
106 const stickyHeaderUnpinnedContainerId = 'vector-sticky-header-toc-unpinned-container';
107 const pageTitlebarUnpinnedContainerId = 'vector-page-titlebar-toc-unpinned-container';
108
109 let newContainerId = '';
110 if ( isPinned ) {
111 if ( isBelowDesktop ) {
112 // Automatically move the ToC into the page titlebar when pinned on smaller resolutions
113 newContainerId = pageTitlebarUnpinnedContainerId;
114 } else {
115 newContainerId = pinnedContainerId;
116 }
117 } else {
118 if ( isStickyHeaderVisible && !isBelowDesktop ) {
119 newContainerId = stickyHeaderUnpinnedContainerId;
120 } else {
121 newContainerId = pageTitlebarUnpinnedContainerId;
122 }
123 }
124
125 pinnableElement.movePinnableElement( TOC_ID, newContainerId );
126 };
127
128 /**
129 * Return the computed value of the `scroll-margin-top` CSS property of the document element
130 * which is also used for the scroll intersection threshold (T317661).
131 *
132 * @return {number} Value of scroll-margin-top OR 75 if falsy.
133 * 75 derived from @scroll-padding-top LESS variable
134 * https://gerrit.wikimedia.org/r/c/mediawiki/skins/Vector/+/894696/3/resources/common/variables.less ?
135 */
136 function getDocumentScrollPaddingTop() {
137 const defaultScrollPaddingTop = 75;
138 const documentStyles = getComputedStyle( document.documentElement );
139 const scrollPaddingTopString = documentStyles.getPropertyValue( 'scroll-padding-top' );
140 return ( parseInt( scrollPaddingTopString, 10 ) || defaultScrollPaddingTop );
141 }
142
143 /**
144 * @param {HTMLElement|null} tocElement
145 * @param {HTMLElement|null} bodyContent
146 * @param {initSectionObserver} initSectionObserverFn
147 * @return {tableOfContents|null}
148 */
149 const setupTableOfContents = ( tocElement, bodyContent, initSectionObserverFn ) => {
150 if ( !(
151 tocElement &&
152 bodyContent
153 ) ) {
154 return null;
155 }
156
157 const handleTocSectionChange = () => {
158 // eslint-disable-next-line no-use-before-define
159 sectionObserver.pause();
160
161 // T297614: We want the link that the user has clicked inside the TOC or the
162 // section that corresponds to the hashchange event to be "active" (e.g.
163 // bolded) regardless of whether the browser's scroll position corresponds
164 // to that section. Therefore, we need to temporarily ignore section
165 // observer until the browser has finished scrolling to the section (if
166 // needed).
167 //
168 // However, because the scroll event happens asynchronously after the user
169 // clicks on a link and may not even happen at all (e.g. the user has
170 // scrolled all the way to the bottom and clicks a section that is already
171 // in the viewport), determining when we should resume section observer is a
172 // bit tricky.
173 //
174 // Because a scroll event may not even be triggered after clicking the link,
175 // we instead allow the browser to perform a maximum number of repaints
176 // before resuming sectionObserver. Per T297614#7687656, Firefox 97.0 wasn't
177 // consistently activating the table of contents section that the user
178 // clicked even after waiting 2 frames. After further investigation, it
179 // sometimes waits up to 3 frames before painting the new scroll position so
180 // we have that as the limit.
181 deferUntilFrame( () => {
182 // eslint-disable-next-line no-use-before-define
183 sectionObserver.resume();
184 }, 3 );
185 };
186
187 const tableOfContents = initTableOfContents( {
188 container: tocElement,
189 onHeadingClick: handleTocSectionChange,
190 onHashChange: handleTocSectionChange,
191 onTogglePinned: () => {
192 updateTocLocation();
193 pinnableElement.setFocusAfterToggle( TOC_ID );
194 if ( !features.isEnabled( 'toc-pinned' ) ) {
195 const isStickyHeaderVisible = document.body.classList
196 .contains( STICKY_HEADER_VISIBLE_CLASS );
197 const containerSelector = !isStickyHeaderVisible ?
198 '.vector-page-titlebar .vector-toc-landmark' : '#vector-sticky-header .vector-toc-landmark';
199 const container = /** @type {HTMLElement} */(
200 document.querySelector( containerSelector )
201 );
202 if ( container ) {
203 const containerId = !isStickyHeaderVisible ? 'toc-page-titlebar' : 'toc-sticky-header';
204 popupNotification.add( container, mw.message( 'vector-toc-unpinned-popup' ).text(), containerId )
205 .then( ( popupWidget ) => {
206 if ( popupWidget ) {
207 popupNotification.show( popupWidget );
208 }
209 } );
210 }
211 }
212
213 }
214 } );
215 const elements = () => bodyContent.querySelectorAll( `${ HEADING_SELECTOR }, .mw-body-content` );
216
217 const sectionObserver = initSectionObserverFn( {
218 elements: elements(),
219 topMargin: getDocumentScrollPaddingTop(),
220 onIntersection: getHeadingIntersectionHandler( tableOfContents.changeActiveSection )
221 } );
222 const updateElements = () => {
223 sectionObserver.resume();
224 sectionObserver.setElements( elements() );
225 };
226 mw.hook( 've.activationStart' ).add( () => {
227 sectionObserver.pause();
228 } );
229 mw.hook( 'wikipage.tableOfContents' ).add( ( sections ) => {
230 tableOfContents.reloadTableOfContents( sections ).then( () => {
231 /**
232 * @stable for use in gadgets and extensions
233 * @since 1.40
234 */
235 mw.hook( 'wikipage.tableOfContents.vector' ).fire( sections );
236 updateElements();
237 } );
238 } );
239 mw.hook( 've.deactivationComplete' ).add( updateElements );
240
241 const setInitialActiveSection = () => {
242 const hash = location.hash.slice( 1 );
243 // If hash fragment is blank, determine the active section with section
244 // observer.
245 if ( hash === '' ) {
246 sectionObserver.calcIntersection();
247 return;
248 }
249
250 // T325086: If hash fragment is present and corresponds to a toc section,
251 // expand the section.
252 const hashSection = /** @type {HTMLElement|null} */ ( mw.util.getTargetFromFragment( `${ TOC_SECTION_ID_PREFIX }${ hash }` ) );
253 if ( hashSection ) {
254 tableOfContents.expandSection( hashSection.id );
255 }
256
257 // T325086: If hash fragment corresponds to a section AND the user is at
258 // bottom of page, activate the section. Otherwise, use section observer to
259 // calculate the active section.
260 //
261 // Note that even if a hash fragment is present, it's possible for the
262 // browser to scroll to a position that is different from the position of
263 // the section that corresponds to the hash fragment. This can happen when
264 // the browser remembers a prior scroll position after refreshing the page,
265 // for example.
266 if (
267 hashSection &&
268 Math.round( window.innerHeight + window.scrollY ) >= document.body.scrollHeight
269 ) {
270 tableOfContents.changeActiveSection( hashSection.id );
271 } else {
272 // Fallback to section observer's calculation for the active section.
273 sectionObserver.calcIntersection();
274 }
275 };
276
277 setInitialActiveSection();
278
279 return tableOfContents;
280 };
281
282 /**
283 * @return {void}
284 */
285 const main = () => {
286 const isIntersectionObserverSupported = 'IntersectionObserver' in window;
287
288 //
289 // Table of contents
290 //
291 const tocElement = document.getElementById( TOC_ID );
292 const bodyContent = document.getElementById( BODY_CONTENT_ID );
293
294 const isToCUpdatingAllowed = isIntersectionObserverSupported &&
295 window.requestAnimationFrame;
296 const tableOfContents = isToCUpdatingAllowed ?
297 setupTableOfContents( tocElement, bodyContent, initSectionObserver ) : null;
298
299 //
300 // Sticky header
301 //
302 const
303 stickyHeaderElement = document.getElementById( stickyHeader.STICKY_HEADER_ID ),
304 stickyIntersection = document.getElementById( stickyHeader.FIRST_HEADING_ID ),
305 userLinksDropdown = document.getElementById( stickyHeader.USER_LINKS_DROPDOWN_ID ),
306 allowedNamespace = stickyHeader.isAllowedNamespace( mw.config.get( 'wgNamespaceNumber' ) ),
307 allowedAction = stickyHeader.isAllowedAction( mw.config.get( 'wgAction' ) );
308
309 const isStickyHeaderAllowed =
310 !!stickyHeaderElement &&
311 !!stickyIntersection &&
312 !!userLinksDropdown &&
313 allowedNamespace &&
314 allowedAction &&
315 isIntersectionObserverSupported;
316
317 const { showStickyHeader } = initStickyHeaderABTests(
318 ABTestConfig,
319 isStickyHeaderAllowed && !mw.user.isAnon(),
320 ( config ) => initExperiment(
321 config,
322 String( mw.user.getId() )
323 )
324 );
325
326 // Set up intersection observer for page title
327 // Used to show/hide sticky header and add class used by collapsible TOC (T307900)
328 const observer = scrollObserver.initScrollObserver(
329 () => {
330 if ( isStickyHeaderAllowed && showStickyHeader ) {
331 stickyHeader.show();
332 updateTocLocation();
333 }
334 document.body.classList.add( PAGE_TITLE_INTERSECTION_CLASS );
335 if ( tableOfContents ) {
336 tableOfContents.updateTocToggleStyles( true );
337 }
338 scrollObserver.firePageTitleScrollHook( 'down' );
339 },
340 () => {
341 if ( isStickyHeaderAllowed && showStickyHeader ) {
342 stickyHeader.hide();
343 updateTocLocation();
344 }
345 document.body.classList.remove( PAGE_TITLE_INTERSECTION_CLASS );
346 if ( tableOfContents ) {
347 tableOfContents.updateTocToggleStyles( false );
348 }
349 scrollObserver.firePageTitleScrollHook( 'up' );
350 }
351 );
352
353 // Handle toc location when sticky header is hidden on lower viewports
354 belowDesktopMedia.onchange = () => {
355 updateTocLocation();
356 };
357
358 updateTocLocation();
359
360 if ( !showStickyHeader ) {
361 stickyHeader.hide();
362 }
363
364 if ( isStickyHeaderAllowed && showStickyHeader ) {
365 stickyHeader.initStickyHeader( {
366 header: stickyHeaderElement,
367 userLinksDropdown,
368 observer,
369 stickyIntersection
370 } );
371 } else if ( stickyIntersection ) {
372 observer.observe( stickyIntersection );
373 }
374 };
375
376 module.exports = {
377 main,
378 test: {
379 setupTableOfContents,
380 initStickyHeaderABTests,
381 getHeadingIntersectionHandler
382 }
383 };