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