Debian Codegraph @

src/pydata_sphinx_theme/assets/scripts/pydata-sphinx-theme.js

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Define the custom behavior of the page
2 import { documentReady } from "./mixin";
3 import { compare, validate } from "compare-versions";
4
5 import "../styles/pydata-sphinx-theme.scss";
6
7 /*******************************************************************************
8 * Theme interaction
9 */
10
11 var prefersDark = window.matchMedia("(prefers-color-scheme: dark)");
12
13 /**
14 * set the the body theme to the one specified by the user browser
15 *
16 * @param {event} e
17 */
18 function autoTheme(e) {
19 document.documentElement.dataset.theme = prefersDark.matches
20 ? "dark"
21 : "light";
22 }
23
24 /**
25 * Set the theme using the specified mode.
26 * It can be one of ["auto", "dark", "light"]
27 *
28 * @param {str} mode
29 */
30 function setTheme(mode) {
31 if (mode !== "light" && mode !== "dark" && mode !== "auto") {
32 console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`);
33 mode = "auto";
34 }
35
36 // get the theme
37 var colorScheme = prefersDark.matches ? "dark" : "light";
38 document.documentElement.dataset.mode = mode;
39 var theme = mode == "auto" ? colorScheme : mode;
40 document.documentElement.dataset.theme = theme;
41 // TODO: remove this line after Bootstrap upgrade
42 // v5.3 has a colors mode: https://getbootstrap.com/docs/5.3/customize/color-modes/
43 document.querySelectorAll(".dropdown-menu").forEach((el) => {
44 if (theme === "dark") {
45 el.classList.add("dropdown-menu-dark");
46 } else {
47 el.classList.remove("dropdown-menu-dark");
48 }
49 });
50
51 // save mode and theme
52 localStorage.setItem("mode", mode);
53 localStorage.setItem("theme", theme);
54 console.log(`[PST]: Changed to ${mode} mode using the ${theme} theme.`);
55
56 // add a listener if set on auto
57 prefersDark.onchange = mode == "auto" ? autoTheme : "";
58 }
59
60 /**
61 * Change the theme option order so that clicking on the btn is always a change
62 * from "auto"
63 */
64 function cycleMode() {
65 const defaultMode = document.documentElement.dataset.defaultMode || "auto";
66 const currentMode = localStorage.getItem("mode") || defaultMode;
67
68 var loopArray = (arr, current) => {
69 var nextPosition = arr.indexOf(current) + 1;
70 if (nextPosition === arr.length) {
71 nextPosition = 0;
72 }
73 return arr[nextPosition];
74 };
75
76 // make sure the next theme after auto is always a change
77 var modeList = prefersDark.matches
78 ? ["auto", "light", "dark"]
79 : ["auto", "dark", "light"];
80 var newMode = loopArray(modeList, currentMode);
81 setTheme(newMode);
82 }
83
84 /**
85 * add the theme listener on the btns of the navbar
86 */
87 function addModeListener() {
88 // the theme was set a first time using the initial mini-script
89 // running setMode will ensure the use of the dark mode if auto is selected
90 setTheme(document.documentElement.dataset.mode);
91
92 // Attach event handlers for toggling themes colors
93 document.querySelectorAll(".theme-switch-button").forEach((el) => {
94 el.addEventListener("click", cycleMode);
95 });
96 }
97
98 /*******************************************************************************
99 * Scroll
100 */
101
102 /**
103 * Navigation sidebar scrolling to active page
104 */
105 function scrollToActive() {
106 // If the docs nav doesn't exist, do nothing (e.g., on search page)
107 if (!document.querySelector(".bd-docs-nav")) {
108 return;
109 }
110
111 var sidebar = document.querySelector("div.bd-sidebar");
112
113 // Remember the sidebar scroll position between page loads
114 // Inspired on source of revealjs.com
115 let storedScrollTop = parseInt(
116 sessionStorage.getItem("sidebar-scroll-top"),
117 10,
118 );
119
120 if (!isNaN(storedScrollTop)) {
121 // If we've got a saved scroll position, just use that
122 sidebar.scrollTop = storedScrollTop;
123 console.log("[PST]: Scrolled sidebar using stored browser position...");
124 } else {
125 // Otherwise, calculate a position to scroll to based on the lowest `active` link
126 var sidebarNav = document.querySelector(".bd-docs-nav");
127 var active_pages = sidebarNav.querySelectorAll(".active");
128 if (active_pages.length > 0) {
129 // Use the last active page as the offset since it's the page we're on
130 var latest_active = active_pages[active_pages.length - 1];
131 var offset =
132 latest_active.getBoundingClientRect().y -
133 sidebar.getBoundingClientRect().y;
134 // Only scroll the navbar if the active link is lower than 50% of the page
135 if (latest_active.getBoundingClientRect().y > window.innerHeight * 0.5) {
136 let buffer = 0.25; // Buffer so we have some space above the scrolled item
137 sidebar.scrollTop = offset - sidebar.clientHeight * buffer;
138 console.log("[PST]: Scrolled sidebar using last active link...");
139 }
140 }
141 }
142
143 // Store the sidebar scroll position
144 window.addEventListener("beforeunload", () => {
145 sessionStorage.setItem("sidebar-scroll-top", sidebar.scrollTop);
146 });
147 }
148
149 /*******************************************************************************
150 * Search
151 */
152
153 /**
154 * Find any search forms on the page and return their input element
155 */
156 var findSearchInput = () => {
157 let forms = document.querySelectorAll("form.bd-search");
158 if (!forms.length) {
159 // no search form found
160 return;
161 } else {
162 var form;
163 if (forms.length == 1) {
164 // there is exactly one search form (persistent or hidden)
165 form = forms[0];
166 } else {
167 // must be at least one persistent form, use the first persistent one
168 form = document.querySelector(
169 ":not(#pst-search-dialog) > form.bd-search",
170 );
171 }
172 return form.querySelector("input");
173 }
174 };
175
176 /**
177 * Activate the search field on the page.
178 * - If there is a search field already visible it will be activated.
179 * - If not, then a search field will pop up.
180 */
181 var toggleSearchField = () => {
182 // Find the search input to highlight
183 const input = findSearchInput();
184
185 // if the input field is the hidden one (the one associated with the
186 // search button) then toggle the button state (to show/hide the field)
187 const searchDialog = document.getElementById("pst-search-dialog");
188 if (!searchDialog) {
189 // Search dialog was disabled via disable_search theme option; nothing to do.
190 return;
191 }
192 const hiddenInput = searchDialog.querySelector("input");
193 if (input === hiddenInput) {
194 if (searchDialog.open) {
195 searchDialog.close();
196 } else {
197 // Note: browsers should focus the input field inside the modal dialog
198 // automatically when it is opened.
199 searchDialog.showModal();
200 }
201 } else {
202 // if the input field is not the hidden one, then toggle its focus state
203
204 if (document.activeElement === input) {
205 input.blur();
206 } else {
207 input.focus();
208 input.select();
209 input.scrollIntoView({ block: "center" });
210 }
211 }
212 };
213
214 /**
215 * Add an event listener for toggleSearchField() for Ctrl/Cmd + K
216 */
217 var addEventListenerForSearchKeyboard = () => {
218 window.addEventListener(
219 "keydown",
220 (event) => {
221 let input = findSearchInput();
222 // toggle on Ctrl+k or ⌘+k
223 if (
224 // Ignore if shift or alt are pressed
225 !event.shiftKey &&
226 !event.altKey &&
227 // On Mac use ⌘, all other OS use Ctrl
228 (useCommandKey
229 ? event.metaKey && !event.ctrlKey
230 : !event.metaKey && event.ctrlKey) &&
231 // Case-insensitive so the shortcut still works with caps lock
232 /^k$/i.test(event.key)
233 ) {
234 event.preventDefault();
235 toggleSearchField();
236 }
237 // also allow Escape key to hide (but not show) the dynamic search field
238 else if (document.activeElement === input && /Escape/i.test(event.key)) {
239 toggleSearchField();
240 resetSearchAsYouTypeResults();
241 }
242 },
243 true,
244 );
245 };
246
247 /**
248 * If the user is on a Mac, use command (⌘) instead of control (ctrl) key
249 *
250 * Note: `navigator.platform` is deprecated; however MDN still recommends using
251 * it for the one specific use case of detecting whether a keyboard shortcut
252 * should use control or command:
253 * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform#examples
254 */
255 var useCommandKey =
256 navigator.platform.indexOf("Mac") === 0 || navigator.platform === "iPhone";
257
258 /**
259 * Change the search hint to `meta key` if we are a Mac
260 */
261
262 var changeSearchShortcutKey = () => {
263 let shortcuts = document.querySelectorAll(".search-button__kbd-shortcut");
264 if (useCommandKey) {
265 shortcuts.forEach(
266 (f) => (f.querySelector("kbd.kbd-shortcut__modifier").innerText = "⌘"),
267 );
268 }
269 };
270
271 const closeDialogOnBackdropClick = ({
272 currentTarget: dialog,
273 clientX,
274 clientY,
275 }) => {
276 if (!dialog.open) {
277 return;
278 }
279
280 // Dialog.getBoundingClientRect() does not include ::backdrop. (This is the
281 // trick that allows us to determine if click was inside or outside of the
282 // dialog: click handler includes backdrop, getBoundingClientRect does not.)
283 const { left, right, top, bottom } = dialog.getBoundingClientRect();
284
285 // 0, 0 means top left
286 const clickWasOutsideDialog =
287 clientX < left || right < clientX || clientY < top || bottom < clientY;
288
289 if (clickWasOutsideDialog) {
290 dialog.close();
291 }
292 };
293
294 /**
295 * Activate callbacks for search button popup
296 */
297 var setupSearchButtons = () => {
298 changeSearchShortcutKey();
299 addEventListenerForSearchKeyboard();
300
301 // Add the search button trigger event callback
302 document.querySelectorAll(".search-button__button").forEach((btn) => {
303 btn.onclick = toggleSearchField;
304 });
305
306 // If user clicks outside the search modal dialog, then close it.
307 const searchDialog = document.getElementById("pst-search-dialog");
308 if (!searchDialog) {
309 // Search dialog was disabled via disable_search theme option; nothing to do.
310 return;
311 }
312 // Dialog click handler includes clicks on dialog ::backdrop.
313 searchDialog.addEventListener("click", closeDialogOnBackdropClick);
314 };
315
316 /*******************************************************************************
317 * Inline search results (search-as-you-type)
318 *
319 * Immediately displays search results under the search query textbox.
320 *
321 * The search is conducted by Sphinx's built-in search tools (searchtools.js).
322 * Usually searchtools.js is only available on /search.html but
323 * pydata-sphinx-theme (PST) has been modified to load searchtools.js on every
324 * page. After the user types something into PST's search query textbox,
325 * searchtools.js executes the search and populates the results into
326 * the #search-results container. searchtools.js expects the results container
327 * to have that exact ID.
328 */
329 var setupSearchAsYouType = () => {
330 if (!DOCUMENTATION_OPTIONS.search_as_you_type) {
331 return;
332 }
333
334 // Don't interfere with the default search UX on /search.html.
335 if (window.location.pathname.endsWith("/search.html")) {
336 return;
337 }
338
339 // Bail if the Search class is not available. Search-as-you-type is
340 // impossible without that class. layout.html should ensure that
341 // searchtools.js loads.
342 //
343 // Search class is defined in upstream Sphinx:
344 // https://github.com/sphinx-doc/sphinx/blob/6678e357048ea1767daaad68e7e0569786f3b458/sphinx/themes/basic/static/searchtools.js#L181
345 if (!Search) {
346 return;
347 }
348
349 // Destroy the previous search container and create a new one.
350 resetSearchAsYouTypeResults();
351 let timeoutId = null;
352 let lastQuery = "";
353 const searchInput = document.querySelector(
354 "#pst-search-dialog input[name=q]",
355 );
356
357 // Initiate searches whenever the user types stuff in the search modal textbox.
358 searchInput.addEventListener("keyup", () => {
359 const query = searchInput.value;
360
361 // Don't search when there's nothing in the query textbox.
362 if (query === "") {
363 lastQuery = "";
364 resetSearchAsYouTypeResults(); // Remove previous results.
365 return;
366 }
367
368 // Don't search if there is no detectable change between
369 // the last query and the current query. E.g. the user presses
370 // Tab to start navigating the search results.
371 if (query === lastQuery) {
372 return;
373 }
374
375 // The user has changed the search query. Delete the old results
376 // and start setting up the new container.
377 resetSearchAsYouTypeResults();
378
379 // Debounce so that the search only starts when the user stops typing.
380 const delay_ms = 300;
381 lastQuery = query;
382 if (timeoutId) {
383 window.clearTimeout(timeoutId);
384 }
385 timeoutId = window.setTimeout(() => {
386 Search.performSearch(query);
387 document.querySelector("#search-results").classList.remove("empty");
388 timeoutId = null;
389 }, delay_ms);
390 });
391 };
392
393 // Delete the old search results container (if it exists) and set up a new one.
394 //
395 // There is some complexity around ensuring that the search results links are
396 // correct because we're extending searchtools.js past its assumed usage.
397 // Sphinx assumes that searches are only executed from /search.html and
398 // therefore it assumes that all search results links should be relative to
399 // the root directory of the website. In our case the search can now execute
400 // from any page of the website so we must fix the relative URLs that
401 // searchtools.js generates.
402 var resetSearchAsYouTypeResults = () => {
403 if (!DOCUMENTATION_OPTIONS.search_as_you_type) {
404 return;
405 }
406 // If a search-as-you-type results container was previously added,
407 // remove it now.
408 let results = document.querySelector("#search-results");
409 if (results) {
410 results.remove();
411 }
412
413 // Create a new search-as-you-type results container.
414 results = document.createElement("section");
415 results.classList.add("empty");
416 // Remove the container element from the tab order. Individual search
417 // results are still focusable.
418 results.tabIndex = -1;
419 // When focus is on a search result, make sure that pressing Escape closes
420 // the search modal.
421 results.addEventListener("keydown", (event) => {
422 if (event.key === "Escape") {
423 event.preventDefault();
424 event.stopPropagation();
425 toggleSearchField();
426 resetSearchAsYouTypeResults();
427 }
428 });
429 // IMPORTANT: The search results container MUST have this exact ID.
430 // searchtools.js is hardcoded to populate into the node with this ID.
431 results.id = "search-results";
432 let modal = document.querySelector("#pst-search-dialog");
433 modal.appendChild(results);
434
435 // Get the relative path back to the root of the website.
436 const root =
437 "URL_ROOT" in DOCUMENTATION_OPTIONS
438 ? DOCUMENTATION_OPTIONS.URL_ROOT // Sphinx v6 and earlier
439 : document.documentElement.dataset.content_root; // Sphinx v7 and later
440
441 // As Sphinx populates the search results, this observer makes sure that
442 // each URL is correct (i.e. doesn't 404).
443 const linkObserver = new MutationObserver(() => {
444 const links = Array.from(
445 document.querySelectorAll("#search-results .search a"),
446 );
447 // Check every link every time because the timing of when new results are
448 // added is unpredictable and it's not an expensive operation.
449 links.forEach((link) => {
450 link.tabIndex = 0; // Use natural tab order for search results.
451 // Don't use the link.href getter because the browser computes the href
452 // as a full URL. We need the relative URL that Sphinx generates.
453 const href = link.getAttribute("href");
454 if (href.startsWith(root)) {
455 // No work needed. The root has already been prepended to the href.
456 return;
457 }
458 link.href = `${root}${href}`;
459 });
460 });
461
462 // The node that linkObserver watches doesn't exist until the user types
463 // something into the search textbox. This second observer (resultsObserver)
464 // just waits for #search-results to exist and then registers
465 // linkObserver on it.
466 let isObserved = false;
467 const resultsObserver = new MutationObserver(() => {
468 if (isObserved) {
469 return;
470 }
471 const container = document.querySelector("#search-results .search");
472 if (!container) {
473 return;
474 }
475 linkObserver.observe(container, { childList: true });
476 isObserved = true;
477 });
478 resultsObserver.observe(results, { childList: true });
479 };
480
481 /*******************************************************************************
482 * Version Switcher
483 * Note that this depends on two variables existing that are defined in
484 * and `html-page-context` hook:
485 *
486 * - DOCUMENTATION_OPTIONS.pagename
487 * - DOCUMENTATION_OPTIONS.theme_switcher_url
488 */
489
490 /**
491 * path component of URL
492 */
493 var getCurrentUrlPath = () => {
494 if (DOCUMENTATION_OPTIONS.BUILDER == "dirhtml") {
495 return DOCUMENTATION_OPTIONS.pagename.endsWith("index")
496 ? `${DOCUMENTATION_OPTIONS.pagename.substring(0, DOCUMENTATION_OPTIONS.pagename.length - "index".length)}`
497 : `${DOCUMENTATION_OPTIONS.pagename}/`;
498 }
499 return `${DOCUMENTATION_OPTIONS.pagename}.html`;
500 };
501
502 /**
503 * Allow user to dismiss the warning banner about the docs version being dev / old.
504 * We store the dismissal date and version, to give us flexibility about making the
505 * dismissal last for longer than one browser session, if we decide to do that.
506 *
507 * @param {event} event the event that trigger the check
508 */
509 async function DismissBannerAndStorePref(event) {
510 const banner = document.querySelector("#bd-header-version-warning");
511 banner.remove();
512 const version = DOCUMENTATION_OPTIONS.VERSION;
513 const now = new Date();
514 const banner_pref = JSON.parse(
515 localStorage.getItem("pst_banner_pref") || "{}",
516 );
517 console.debug(
518 `[PST] Dismissing the version warning banner on ${version} starting ${now}.`,
519 );
520 banner_pref[version] = now;
521 localStorage.setItem("pst_banner_pref", JSON.stringify(banner_pref));
522 }
523
524 /**
525 * Check if corresponding page path exists in other version of docs
526 * and, if so, go there instead of the homepage of the other docs version
527 *
528 * @param {event} event the event that trigger the check
529 */
530 async function checkPageExistsAndRedirect(event) {
531 // ensure we don't follow the initial link
532 event.preventDefault();
533 const currentFilePath = getCurrentUrlPath();
534 let tryUrl = event.currentTarget.getAttribute("href");
535 let otherDocsHomepage = tryUrl.replace(currentFilePath, "");
536 try {
537 let head = await fetch(tryUrl, { method: "HEAD" });
538 if (head.ok) {
539 location.href = tryUrl; // the page exists, go there
540 } else {
541 location.href = otherDocsHomepage;
542 }
543 } catch (err) {
544 // something went wrong, probably CORS restriction, fallback to other docs homepage
545 location.href = otherDocsHomepage;
546 }
547 }
548
549 /**
550 * Load and parse the version switcher JSON file from an absolute or relative URL.
551 *
552 * @param {string} url The URL to load version switcher entries from.
553 */
554 async function fetchVersionSwitcherJSON(url) {
555 const currentPath = getCurrentUrlPath();
556 // first check if it's a valid URL
557 try {
558 var result = new URL(url);
559 } catch (err) {
560 if (err instanceof TypeError) {
561 // Assume we got a relative path, and fix accordingly.
562 if (window.location.protocol == "file:") {
563 // Here instead of returning `null` we work out what the file path would be
564 // anyway (same code path as for served docs), as a convenience to folks who
565 // routinely disable CORS when they boot up their browser.
566 console.info(
567 "[PST] looks like you're viewing this site from a local filesystem, so " +
568 "the version switcher won't work unless you've disabled CORS. See " +
569 "https://pydata-sphinx-theme.readthedocs.io/en/stable/user_guide/version-dropdown.html",
570 );
571 }
572 const cutoff = window.location.href.indexOf(currentPath);
573 // cutoff == -1 can happen e.g. on the homepage of locally served docs, where you
574 // get something like http://127.0.0.1:8000/ (no trailing `index.html`)
575 const origin =
576 cutoff == -1
577 ? window.location.href
578 : window.location.href.substring(0, cutoff);
579 result = new URL(url, origin);
580 } else {
581 // something unexpected happened
582 throw err;
583 }
584 }
585 // load and return the JSON
586 const response = await fetch(result);
587 const data = await response.json();
588 return data;
589 }
590
591 // Populate the version switcher from the JSON data
592 function populateVersionSwitcher(data, versionSwitcherBtns) {
593 const currentFilePath = getCurrentUrlPath();
594 versionSwitcherBtns.forEach((btn) => {
595 // Set empty strings by default so that these attributes exist and can be used in CSS selectors
596 btn.dataset["activeVersionName"] = "";
597 btn.dataset["activeVersion"] = "";
598 });
599 // in case there are multiple entries with the same version string, this helps us
600 // decide which entry's `name` to put on the button itself. Without this, it would
601 // always be the *last* version-matching entry; now it will be either the
602 // version-matching entry that is also marked as `"preferred": true`, or if that
603 // doesn't exist: the *first* version-matching entry.
604 data = data.map((entry) => {
605 // does this entry match the version that we're currently building/viewing?
606 entry.match =
607 entry.version == DOCUMENTATION_OPTIONS.theme_switcher_version_match;
608 entry.preferred = entry.preferred || false;
609 // if no custom name specified (e.g., "latest"), use version string
610 if (!("name" in entry)) {
611 entry.name = entry.version;
612 }
613 return entry;
614 });
615 const hasMatchingPreferredEntry = data
616 .map((entry) => entry.preferred && entry.match)
617 .some(Boolean);
618 var foundMatch = false;
619 // create links to the corresponding page in the other docs versions
620 data.forEach((entry) => {
621 // create the node
622 const anchor = document.createElement("a");
623 anchor.setAttribute(
624 "class",
625 "dropdown-item list-group-item list-group-item-action py-1",
626 );
627 anchor.setAttribute("href", `${entry.url}${currentFilePath}`);
628 anchor.setAttribute("role", "option");
629 const span = document.createElement("span");
630 span.textContent = `${entry.name}`;
631 anchor.appendChild(span);
632 // Add dataset values for the version and name in case people want
633 // to apply CSS styling based on this information.
634 anchor.dataset["versionName"] = entry.name;
635 anchor.dataset["version"] = entry.version;
636 // replace dropdown button text with the preferred display name of the
637 // currently-viewed version, rather than using sphinx's {{ version }} variable.
638 // also highlight the dropdown entry for the currently-viewed version's entry
639 let matchesAndIsPreferred = hasMatchingPreferredEntry && entry.preferred;
640 let matchesAndIsFirst =
641 !hasMatchingPreferredEntry && !foundMatch && entry.match;
642 if (matchesAndIsPreferred || matchesAndIsFirst) {
643 anchor.classList.add("active");
644 versionSwitcherBtns.forEach((btn) => {
645 btn.innerText = entry.name;
646 btn.dataset["activeVersionName"] = entry.name;
647 btn.dataset["activeVersion"] = entry.version;
648 });
649 foundMatch = true;
650 }
651 // There may be multiple version-switcher elements, e.g. one
652 // in a slide-over panel displayed on smaller screens.
653 document.querySelectorAll(".version-switcher__menu").forEach((menu) => {
654 // we need to clone the node for each menu, but onclick attributes are not
655 // preserved by `.cloneNode()` so we add onclick here after cloning.
656 let node = anchor.cloneNode(true);
657 node.onclick = checkPageExistsAndRedirect;
658 // on click, AJAX calls will check if the linked page exists before
659 // trying to redirect, and if not, will redirect to the homepage
660 // for that version of the docs.
661 menu.append(node);
662 });
663 });
664 }
665
666 /*******************************************************************************
667 * Warning banner when viewing non-stable version of the docs.
668 */
669
670 /**
671 * Show a warning banner when viewing a non-stable version of the docs.
672 *
673 * adapted 2023-06 from https://mne.tools/versionwarning.js, which was
674 * originally adapted 2020-05 from https://scikit-learn.org/versionwarning.js
675 *
676 * @param {Array} data The version data used to populate the switcher menu.
677 */
678 function showVersionWarningBanner(data) {
679 var version = DOCUMENTATION_OPTIONS.VERSION;
680 // figure out what latest stable version is
681 var preferredEntries = data.filter((entry) => entry.preferred);
682 if (preferredEntries.length !== 1) {
683 const howMany = preferredEntries.length == 0 ? "No" : "Multiple";
684 console.log(
685 `[PST] ${howMany} versions marked "preferred" found in versions JSON, ignoring.`,
686 );
687 return;
688 }
689 const preferredVersion = preferredEntries[0].version;
690 const preferredURL = preferredEntries[0].url;
691 // if already on preferred version, nothing to do
692 const versionsAreComparable = validate(version) && validate(preferredVersion);
693 if (versionsAreComparable && compare(version, preferredVersion, "=")) {
694 console.log(
695 "[PST]: This is the preferred version of the docs, not showing the warning banner.",
696 );
697 return;
698 }
699 // check if banner has been dismissed recently
700 const dismiss_date_str = JSON.parse(
701 localStorage.getItem("pst_banner_pref") || "{}",
702 )[version];
703 if (dismiss_date_str != null) {
704 const dismiss_date = new Date(dismiss_date_str);
705 const now = new Date();
706 const milliseconds_in_a_day = 24 * 60 * 60 * 1000;
707 const days_passed = (now - dismiss_date) / milliseconds_in_a_day;
708 const timeout_in_days = 14;
709 if (days_passed < timeout_in_days) {
710 console.info(
711 `[PST] Suppressing version warning banner; was dismissed ${Math.floor(
712 days_passed,
713 )} day(s) ago`,
714 );
715 return;
716 }
717 }
718
719 // now construct the warning banner
720 const banner = document.querySelector("#bd-header-version-warning");
721 const middle = document.createElement("div");
722 const inner = document.createElement("div");
723 const bold = document.createElement("strong");
724 const button = document.createElement("a");
725 const close_btn = document.createElement("a");
726 // these classes exist since pydata-sphinx-theme v0.10.0
727 // the init class is used for animation
728 middle.classList = "bd-header-announcement__content ms-auto me-auto";
729 inner.classList = "sidebar-message";
730 button.classList =
731 "btn text-wrap font-weight-bold ms-3 my-1 align-baseline pst-button-link-to-stable-version";
732 button.href = `${preferredURL}${getCurrentUrlPath()}`;
733 button.innerText = "Switch to stable version";
734 button.onclick = checkPageExistsAndRedirect;
735 close_btn.classList = "ms-3 my-1 align-baseline";
736 const close_x = document.createElement("i");
737 close_btn.append(close_x);
738 close_x.classList = "fa-solid fa-xmark";
739 close_btn.onclick = DismissBannerAndStorePref;
740 // add the version-dependent text
741 inner.innerText = "This is documentation for ";
742 const isDev =
743 version.includes("dev") ||
744 version.includes("rc") ||
745 version.includes("pre");
746 const newerThanPreferred =
747 versionsAreComparable && compare(version, preferredVersion, ">");
748 if (isDev || newerThanPreferred) {
749 bold.innerText = "an unstable development version";
750 } else if (versionsAreComparable && compare(version, preferredVersion, "<")) {
751 bold.innerText = `an old version (${version})`;
752 } else if (!version) {
753 bold.innerText = "an unknown version"; // e.g., an empty string
754 } else {
755 bold.innerText = `version ${version}`;
756 }
757 banner.appendChild(middle);
758 banner.append(close_btn);
759 middle.appendChild(inner);
760 inner.appendChild(bold);
761 inner.appendChild(document.createTextNode("."));
762 inner.appendChild(button);
763 banner.classList.remove("d-none");
764 }
765
766 async function fetchAndUseVersions() {
767 // fetch the JSON version data (only once), then use it to populate the version
768 // switcher and maybe show the version warning bar
769 var versionSwitcherBtns = document.querySelectorAll(
770 ".version-switcher__button",
771 );
772 const hasSwitcherMenu = versionSwitcherBtns.length > 0;
773 const hasVersionsJSON = DOCUMENTATION_OPTIONS.hasOwnProperty(
774 "theme_switcher_json_url",
775 );
776 const wantsWarningBanner = DOCUMENTATION_OPTIONS.show_version_warning_banner;
777
778 if (hasVersionsJSON && (hasSwitcherMenu || wantsWarningBanner)) {
779 const data = await fetchVersionSwitcherJSON(
780 DOCUMENTATION_OPTIONS.theme_switcher_json_url,
781 );
782 // TODO: remove the `if(data)` once the `return null` is fixed within fetchVersionSwitcherJSON.
783 // We don't really want the switcher and warning bar to silently not work.
784 if (data) {
785 populateVersionSwitcher(data, versionSwitcherBtns);
786 if (wantsWarningBanner) {
787 showVersionWarningBanner(data);
788 }
789 }
790 }
791 }
792
793 /*******************************************************************************
794 * Sidebar modals (for mobile / narrow screens)
795 */
796 function setupMobileSidebarKeyboardHandlers() {
797 // These are the left and right sidebars for wider screens. We cut and paste
798 // the content from these widescreen sidebars into the mobile dialogs, when
799 // the user clicks the hamburger icon button
800 const primarySidebar = document.getElementById("pst-primary-sidebar");
801 const secondarySidebar = document.getElementById("pst-secondary-sidebar");
802
803 // These are the corresponding left/right <dialog> elements, which are empty
804 // until the user clicks the hamburger icon
805 const primaryDialog = document.getElementById("pst-primary-sidebar-modal");
806 const secondaryDialog = document.getElementById(
807 "pst-secondary-sidebar-modal",
808 );
809
810 // These are the hamburger-style buttons in the header nav bar. They only
811 // appear at narrow screen width.
812 const primaryToggle = document.querySelector(".primary-toggle");
813 const secondaryToggle = document.querySelector(".secondary-toggle");
814
815 // Cut nodes and classes from `from`, paste into/onto `to`
816 const cutAndPasteNodesAndClasses = (from, to) => {
817 Array.from(from.childNodes).forEach((node) => to.appendChild(node));
818 Array.from(from.classList).forEach((cls) => {
819 from.classList.remove(cls);
820 to.classList.add(cls);
821 });
822 };
823
824 // Hook up the ways to open and close the dialog
825 [
826 [primaryToggle, primaryDialog, primarySidebar],
827 [secondaryToggle, secondaryDialog, secondarySidebar],
828 ].forEach(([toggleButton, dialog, sidebar]) => {
829 if (!toggleButton || !dialog || !sidebar) {
830 return;
831 }
832
833 // Clicking the button can only open the sidebar, not close it.
834 // Clicking the button is also the *only* way to open the sidebar.
835 toggleButton.addEventListener("click", (event) => {
836 event.preventDefault();
837 event.stopPropagation();
838
839 // Save focus so we can restore it when the dialog closes
840 const previouslyFocused = document.activeElement;
841
842 // When we open the dialog, we cut and paste the nodes and classes from
843 // the widescreen sidebar into the dialog
844 cutAndPasteNodesAndClasses(sidebar, dialog);
845
846 dialog.showModal();
847
848 // Restore focus when dialog closes
849 dialog.addEventListener(
850 "close",
851 () => {
852 if (previouslyFocused && previouslyFocused.focus) {
853 previouslyFocused.focus();
854 }
855 },
856 { once: true },
857 );
858 });
859
860 // Listen for clicks on the backdrop in order to close the dialog
861 dialog.addEventListener("click", closeDialogOnBackdropClick);
862
863 // We have to manually attach the escape key because there's some code in
864 // Sphinx's Sphinx_highlight.js that prevents the default behavior of the
865 // escape key
866 dialog.addEventListener("keydown", (event) => {
867 if (event.key === "Escape") {
868 event.preventDefault();
869 event.stopPropagation();
870 dialog.close();
871 }
872 });
873
874 // When the dialog is closed, move the nodes (and classes) back to their
875 // original place
876 dialog.addEventListener("close", () => {
877 cutAndPasteNodesAndClasses(dialog, sidebar);
878 });
879 });
880 }
881
882 /**
883 * When the page loads, or the window resizes, or descendant nodes are added or
884 * removed from the main element, check all code blocks and Jupyter notebook
885 * outputs, and for each one that has scrollable overflow, set tabIndex = 0.
886 */
887 function addTabStopsToScrollableElements() {
888 const updateTabStops = () => {
889 document
890 .querySelectorAll(
891 [
892 // code blocks
893 "pre",
894 // NBSphinx notebook output
895 ".nboutput > .output_area",
896 // Myst-NB
897 ".cell_output > .output",
898 // ipywidgets
899 ".jp-RenderedHTMLCommon",
900 // [rST table nodes](https://www.docutils.org/docs/ref/doctree.html#table)
901 ".pst-scrollable-table-container",
902 ].join(", "),
903 )
904 .forEach((el) => {
905 el.tabIndex =
906 el.scrollWidth > el.clientWidth || el.scrollHeight > el.clientHeight
907 ? 0
908 : -1;
909 });
910 };
911 const debouncedUpdateTabStops = debounce(updateTabStops, 300);
912
913 // On window resize
914 window.addEventListener("resize", debouncedUpdateTabStops);
915
916 // The following MutationObserver is for ipywidgets, which take some time to
917 // finish loading and rendering on the page (so even after the "load" event is
918 // fired, they still have not finished rendering). Would be nice to replace
919 // the MutationObserver if there is a way to hook into the ipywidgets code to
920 // know when it is done.
921 const mainObserver = new MutationObserver(debouncedUpdateTabStops);
922
923 // On descendant nodes added/removed from main element
924 mainObserver.observe(document.getElementById("main-content"), {
925 subtree: true,
926 childList: true,
927 });
928
929 // On page load (when this function gets called)
930 updateTabStops();
931 }
932 function debounce(callback, wait) {
933 let timeoutId = null;
934 return (...args) => {
935 clearTimeout(timeoutId);
936 timeoutId = setTimeout(() => {
937 callback(...args);
938 }, wait);
939 };
940 }
941
942 /*******************************************************************************
943 * Announcement banner - fetch and load remote HTML
944 */
945 async function setupAnnouncementBanner() {
946 const banner = document.querySelector(".bd-header-announcement");
947
948 // check if banner has been dismissed recently
949 const dismiss_date_str = JSON.parse(
950 localStorage.getItem("pst_announcement_banner_pref") || "{}",
951 )["closed"];
952 if (dismiss_date_str != null) {
953 const dismiss_date = new Date(dismiss_date_str);
954 const now = new Date();
955 const milliseconds_in_a_day = 24 * 60 * 60 * 1000;
956 const days_passed = (now - dismiss_date) / milliseconds_in_a_day;
957 const timeout_in_days = 14;
958 if (days_passed < timeout_in_days) {
959 console.info(
960 `[PST] Suppressing announcement banner; was dismissed ${Math.floor(
961 days_passed,
962 )} day(s) ago`,
963 );
964 banner.remove();
965 return;
966 }
967 }
968
969 const { pstAnnouncementUrl } = banner ? banner.dataset : null;
970
971 if (!pstAnnouncementUrl) {
972 return;
973 }
974
975 try {
976 const response = await fetch(pstAnnouncementUrl);
977 if (!response.ok) {
978 throw new Error(
979 `[PST]: HTTP response status not ok: ${response.status} ${response.statusText}`,
980 );
981 }
982 let data = await response.text();
983 data = data.trim();
984 if (data.length === 0) {
985 console.log(`[PST]: Empty announcement at: ${pstAnnouncementUrl}`);
986 return;
987 }
988 banner.innerHTML = `<div class="bd-header-announcement__content">${data}</div>`;
989 banner.classList.remove("d-none");
990 } catch (_error) {
991 console.log(`[PST]: Failed to load announcement at: ${pstAnnouncementUrl}`);
992 console.error(_error);
993 }
994
995 // Add close button
996 console.debug("[PST] Adding close button to announcement banner");
997 const close_btn = document.createElement("a");
998 close_btn.classList = "ms-3 my-1 align-baseline";
999 const close_x = document.createElement("i");
1000 close_btn.append(close_x);
1001 close_x.classList = "fa-solid fa-xmark";
1002 close_btn.onclick = DismissAnnouncementBannerAndStorePref;
1003 banner.append(close_btn);
1004 }
1005
1006 async function DismissAnnouncementBannerAndStorePref(event) {
1007 const banner = document.querySelector(".bd-header-announcement");
1008 banner.remove();
1009 const now = new Date();
1010 const banner_pref = JSON.parse(
1011 localStorage.getItem("pst_announcement_banner_pref") || "{}",
1012 );
1013 console.debug(`[PST] Dismissing the announcement banner starting ${now}.`);
1014 banner_pref["closed"] = now.toISOString();
1015 localStorage.setItem(
1016 "pst_announcement_banner_pref",
1017 JSON.stringify(banner_pref),
1018 );
1019 }
1020
1021 /*******************************************************************************
1022 * Reveal (and animate) the banners (version warning, announcement) together
1023 */
1024 async function fetchRevealBannersTogether() {
1025 // Wait until finished fetching and loading banners
1026 await Promise.allSettled([fetchAndUseVersions(), setupAnnouncementBanner()]);
1027
1028 // The revealer element should have CSS rules that set height to 0, overflow
1029 // to hidden, and an animation transition on the height (unless the user has
1030 // turned off animations)
1031 const revealer = document.querySelector(".pst-async-banner-revealer");
1032 if (!revealer) {
1033 return;
1034 }
1035
1036 // Remove the d-none (display-none) class to calculate the children heights.
1037 revealer.classList.remove("d-none");
1038
1039 // Add together the heights of the element's children
1040 const height = Array.from(revealer.children).reduce(
1041 (height, el) => height + el.offsetHeight,
1042 0,
1043 );
1044
1045 // Use the calculated height to give the revealer a non-zero height (if
1046 // animations allowed, the height change will animate)
1047 revealer.style.setProperty("height", `${height}px`);
1048
1049 // Wait for a bit more than 300ms (the transition duration), then set height
1050 // to auto so the banner can resize if the window is resized.
1051 setTimeout(() => {
1052 revealer.style.setProperty("height", "auto");
1053 }, 320);
1054 }
1055
1056 /**
1057 * Add the machinery needed to highlight elements in the TOC when scrolling.
1058 *
1059 */
1060 function setupArticleTocSyncing() {
1061 // Right sidebar table of contents container
1062 const pageToc = document.querySelector("#pst-page-toc-nav");
1063
1064 // Not all pages have or include a table of contents. (For example, in the PST
1065 // docs, at the time of this writing: /user_guide/index.html.)
1066 if (!pageToc) {
1067 return;
1068 }
1069
1070 // The table of contents is a list of .toc-entry items each of which contains
1071 // a link and possibly a nested list representing one level deeper in the
1072 // table of contents.
1073 const tocEntries = Array.from(pageToc.querySelectorAll(".toc-entry"));
1074 const tocLinks = Array.from(pageToc.querySelectorAll("a"));
1075
1076 // If there are no links in the TOC, there's no syncing to be done.
1077 // (Currently, the template does not render the TOC container if there are no
1078 // TOC links, so this condition should never evaluate to true if the TOC
1079 // container is found on the page, but should the template change in the
1080 // future, this check will prevent a runtime error.)
1081 if (tocLinks.length === 0) {
1082 return;
1083 }
1084
1085 // Create a boolean variable that allows us to turn off the intersection
1086 // observer (and then later back on). When the website visitor clicks an
1087 // in-page link, we want that entry in the TOC to be highlighted/activated,
1088 // NOT whichever TOC link the intersection observer callback would otherwise
1089 // highlight.
1090 let disableObserver = false;
1091
1092 function temporarilyDisableObserver(time) {
1093 disableObserver = true;
1094 setTimeout(() => {
1095 disableObserver = false;
1096 }, time);
1097 }
1098
1099 /**
1100 * If the provided URL hash fragment (beginning with "#") matches an entry in
1101 * the page table of contents, highlight that entry and temporarily disable
1102 * the intersection observer while the page scrolls to the corresponding
1103 * heading.
1104 */
1105 function syncTocHash(hash) {
1106 if (hash.length > 1) {
1107 const matchingTocLink = tocLinks.find((tocLink) => tocLink.hash === hash);
1108 if (matchingTocLink) {
1109 // It's important to disable the intersection observer before
1110 // highlighting the TOC link and its corresponding article heading. This
1111 // is because the browser takes a little time to scroll to the article
1112 // heading, and while scrolling, it could trigger intersection events
1113 // that cause some other link in the table of contents to be
1114 // highlighted.
1115 temporarilyDisableObserver(1000);
1116 activate(matchingTocLink);
1117 }
1118 }
1119 }
1120
1121 // On page load...
1122 //
1123 // When the page loads, sync the page's table of contents.
1124 syncTocHash(window.location.hash);
1125
1126 // On navigation to another part of the page...
1127 //
1128 // When the user navigates to another part of the page, sync the page's table
1129 // of contents.
1130 window.addEventListener("hashchange", () => {
1131 // By the time this event is fired, window.location.hash has already been
1132 // updated with the new hash
1133 syncTocHash(window.location.hash);
1134 });
1135
1136 // On return to the same part of the page...
1137 //
1138 // The hashchange event will handle most cases where we need to sync the table
1139 // of contents with a hash link click. But there is one edge case it doesn't
1140 // handle, which is when the user clicks an internal page link whose hash is
1141 // already in the browser address bar. For example, the user loads the page at
1142 // #first-heading, scrolls to the bottom of the page, then clicks in the
1143 // sidebar table of contents to go back up to the first heading in the
1144 // article. In this case the "hashchange" event will not fire. Nonetheless, we
1145 // want to guarantee that the TOC entry for the first heading gets
1146 // highlighted. Note we cannot rely exclusively on the "click" event for all
1147 // internal page navigations because it will not fire in the edge case where
1148 // the user modifies the hash directly in the browser address bar.
1149 window.addEventListener("click", (event) => {
1150 const link = event.target.closest("a");
1151 if (
1152 link &&
1153 link.hash === window.location.hash &&
1154 link.origin === window.location.origin
1155 ) {
1156 syncTocHash(link.hash);
1157 }
1158 });
1159
1160 /**
1161 * Activate an element and its chain of ancestor TOC entries; deactivate
1162 * everything else in the TOC. Together with the theme CSS, this unfolds
1163 * the TOC out to the given entry and highlights that entry.
1164 *
1165 * @param {HTMLElement} tocLink The TOC entry to be highlighted
1166 */
1167 function activate(tocLink) {
1168 tocLinks.forEach((el) => {
1169 if (el === tocLink) {
1170 el.classList.add("active");
1171 el.setAttribute("aria-current", "true");
1172 } else {
1173 el.classList.remove("active");
1174 el.removeAttribute("aria-current");
1175 }
1176 });
1177 tocEntries.forEach((el) => {
1178 if (el.contains(tocLink)) {
1179 el.classList.add("active");
1180 } else {
1181 el.classList.remove("active");
1182 }
1183 });
1184 }
1185
1186 /**
1187 * Get the heading in the article associated with the link in the table of contents
1188 *
1189 * @param {HTMLElement} tocLink TOC DOM element to use to grab an article heading
1190 *
1191 * @returns The article heading that the TOC element links to
1192 */
1193 function getHeading(tocLink) {
1194 const href = tocLink.getAttribute("href");
1195 if (!href.startsWith("#")) {
1196 return;
1197 }
1198 const id = href.substring(1);
1199 // There are cases where href="#" (for example, the first one at /examples/kitchen-sink/structure.html)
1200 if (!id) {
1201 return;
1202 }
1203 // Use getElementById() because querySelector() requires escaping the id string
1204 const target = document.getElementById(id);
1205 // Often the target is a section but we want to track section's heading
1206 const heading = target.querySelector(":is(h1,h2,h3,h4,h5,h6)");
1207 // Fallback to the target if there is no heading (for example, links on the
1208 // PST docs page /examples/kitchen-sink/api.html target <dt> elements)
1209 return heading || target;
1210 }
1211
1212 // Map heading elements to their associated TOC links
1213 const headingsToTocLinks = new Map();
1214 tocLinks.forEach((tocLink) => {
1215 const heading = getHeading(tocLink);
1216 if (heading) {
1217 headingsToTocLinks.set(heading, tocLink);
1218 }
1219 });
1220
1221 let observer;
1222
1223 function connectIntersectionObserver() {
1224 if (observer) {
1225 observer.disconnect();
1226 }
1227
1228 const header = document.querySelector("#pst-header");
1229 const headerHeight = header.getBoundingClientRect().height;
1230
1231 // Intersection observer options
1232 const options = {
1233 root: null,
1234 rootMargin: `-${headerHeight}px 0px -70% 0px`, // Use -70% for the bottom margin so that intersection events happen in only the top third of the viewport
1235 threshold: 0, // Trigger as soon as the heading goes into (or out of) the top 30% of the viewport
1236 };
1237
1238 /**
1239 *
1240 * @param {IntersectionObserverEntry[]} entries Objects containing threshold-crossing
1241 * event information
1242 *
1243 */
1244 function callback(entries) {
1245 if (disableObserver) {
1246 return;
1247 }
1248 const entry = entries.filter((entry) => entry.isIntersecting).pop();
1249 if (!entry) {
1250 return;
1251 }
1252 const heading = entry.target;
1253 const tocLink = headingsToTocLinks.get(heading);
1254 activate(tocLink);
1255 }
1256
1257 observer = new IntersectionObserver(callback, options);
1258 Array.from(headingsToTocLinks.keys()).forEach((heading) => {
1259 observer.observe(heading);
1260 });
1261 }
1262
1263 // If the user resizes the window, the header height may change and the
1264 // intersection observer's root margin will need to be recalculated
1265 window.addEventListener("resize", debounce(connectIntersectionObserver, 300));
1266 connectIntersectionObserver();
1267 }
1268
1269 /*******************************************************************************
1270 * Set up expand/collapse button for primary sidebar
1271 */
1272 function setupCollapseSidebarButton() {
1273 const button = document.getElementById("pst-collapse-sidebar-button");
1274 const sidebar = document.getElementById("pst-primary-sidebar");
1275
1276 // If this page rendered without the button or sidebar, then there's nothing to do.
1277 if (!button || !sidebar) {
1278 return;
1279 }
1280
1281 const sidebarSections = Array.from(sidebar.children);
1282
1283 const expandTooltip = new bootstrap.Tooltip(button, {
1284 title: button.querySelector(".pst-expand-sidebar-label").textContent,
1285
1286 // In manual testing, relying on Bootstrap to handle "hover" and "focus" was buggy.
1287 trigger: "manual",
1288
1289 placement: "left",
1290 fallbackPlacements: ["right"],
1291
1292 // Offsetting the tooltip a bit more than the default [0, 0] solves an issue
1293 // where the appearance of the tooltip triggers a mouseleave event which in
1294 // turn triggers the call to hide the tooltip. So in certain areas around
1295 // the button, it would appear to the user that tooltip flashes in and then
1296 // back out.
1297 offset: [0, 12],
1298 });
1299
1300 const showTooltip = () => {
1301 // Only show the "expand sidebar" tooltip when the sidebar is not expanded
1302 if (button.getAttribute("aria-expanded") === "false") {
1303 expandTooltip.show();
1304 }
1305 };
1306 const hideTooltip = () => {
1307 expandTooltip.hide();
1308 };
1309
1310 function squeezeSidebar(prefersReducedMotion, done) {
1311 // Before squeezing the sidebar, freeze the widths of its subsections.
1312 // Otherwise, the subsections will also narrow and cause the text in the
1313 // sidebar to reflow and wrap, which we don't want. This is necessary
1314 // because we do not remove the sidebar contents from the layout (with
1315 // `display: none`). Rather, we hide the contents from both sighted users
1316 // and screen readers (with `visibility: hidden`). This provides better
1317 // stability to the overall layout.
1318 sidebarSections.forEach(
1319 (el) => (el.style.width = el.getBoundingClientRect().width + "px"),
1320 );
1321
1322 const afterSqueeze = () => {
1323 // After squeezing the sidebar, set aria-expanded to false
1324 button.setAttribute("aria-expanded", "false"); // "false" is in quotes because HTML attributes are strings
1325
1326 button.dataset.busy = false;
1327 };
1328
1329 if (prefersReducedMotion) {
1330 sidebar.classList.add("pst-squeeze");
1331 afterSqueeze();
1332 } else {
1333 sidebar.addEventListener("transitionend", function onTransitionEnd() {
1334 afterSqueeze();
1335 sidebar.removeEventListener("transitionend", onTransitionEnd);
1336 });
1337 sidebar.classList.add("pst-squeeze");
1338 }
1339 }
1340
1341 function expandSidebar(prefersReducedMotion, done) {
1342 hideTooltip();
1343
1344 const afterExpand = () => {
1345 // After expanding the sidebar (which may be delayed by a CSS transition),
1346 // unfreeze the widths of the subsections that were frozen when the sidebar
1347 // was squeezed.
1348 sidebarSections.forEach((el) => (el.style.width = null));
1349
1350 // After expanding the sidebar, set aria-expanded to "true" - in quotes
1351 // because HTML attributes are strings.
1352 button.setAttribute("aria-expanded", "true");
1353
1354 button.dataset.busy = false;
1355 };
1356
1357 if (prefersReducedMotion) {
1358 sidebar.classList.remove("pst-squeeze");
1359 afterExpand();
1360 } else {
1361 sidebar.addEventListener("transitionend", function onTransitionEnd() {
1362 afterExpand();
1363 sidebar.removeEventListener("transitionend", onTransitionEnd);
1364 });
1365 sidebar.classList.remove("pst-squeeze");
1366 }
1367 }
1368
1369 button.addEventListener("click", () => {
1370 if (button.dataset.busy === "true") {
1371 return;
1372 }
1373 button.dataset.busy = "true";
1374
1375 const prefersReducedMotion = window.matchMedia(
1376 "(prefers-reduced-motion)", // must be in parentheses
1377 ).matches;
1378
1379 if (button.getAttribute("aria-expanded") === "true") {
1380 squeezeSidebar(prefersReducedMotion);
1381 } else {
1382 expandSidebar(prefersReducedMotion);
1383 }
1384 });
1385
1386 button.addEventListener("focus", showTooltip);
1387 button.addEventListener("mouseenter", showTooltip);
1388 button.addEventListener("mouseleave", hideTooltip);
1389 button.addEventListener("blur", hideTooltip);
1390 }
1391
1392 /*******************************************************************************
1393 * Call functions after document loading.
1394 */
1395
1396 // This one first to kick off the network request for the version warning
1397 // and announcement banner data as early as possible.
1398 documentReady(fetchRevealBannersTogether);
1399
1400 documentReady(addModeListener);
1401 documentReady(scrollToActive);
1402 documentReady(setupSearchButtons);
1403 documentReady(setupSearchAsYouType);
1404 documentReady(setupMobileSidebarKeyboardHandlers);
1405 documentReady(setupArticleTocSyncing);
1406 documentReady(() => {
1407 try {
1408 setupCollapseSidebarButton();
1409 } catch (err) {
1410 // This exact error message is used in pytest tests
1411 console.log("[PST] Error setting up collapse sidebar button");
1412 console.error(err);
1413 }
1414 });
1415
1416 // Determining whether an element has scrollable content depends on stylesheets,
1417 // so we're checking for the "load" event rather than "DOMContentLoaded"
1418 if (document.readyState === "complete") {
1419 addTabStopsToScrollableElements();
1420 } else {
1421 window.addEventListener("load", addTabStopsToScrollableElements);
1422 }