Skip to content

Commit

Permalink
Version Chooser: Integrate most recent changes from pydata-sphinx-theme
Browse files Browse the repository at this point in the history
> 1. don't return false, use event.prevent_default() instead
> 2. the fetch().then().catch() pattern you've copied here doesn't actually work as
>    advertised. See the updated logic, which includes an if (head.ok) conditional to
>    distinguish between "successful fetch of desired head (2xx response)" versus
>    "successful fetch of the 404 page (4xx response)". The catch clause is still needed to
>    handle genuine errors (like the fetch being blocked by CORS policy).

Thank you, @drammock.
  • Loading branch information
amotl committed Sep 6, 2023
1 parent 9aebecb commit d4ba6ef
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
3 changes: 2 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ CHANGES
Unreleased
----------

- Add version chooser JavaScript helpers derived from ``pydata-sphinx-theme``
- Add version chooser JavaScript helpers derived from ``pydata-sphinx-theme``.
Thanks, @drammock.


2023/09/01 0.29.5
Expand Down
27 changes: 14 additions & 13 deletions src/crate/theme/rtd/crate/version_chooser.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,24 @@
// BSD 3-Clause License; Copyright (c) 2018, pandas; All rights reserved.
// See `version-switcher.html` and `pydata-sphinx-theme.js`.

function checkPageExistsAndRedirect(event) {
async function checkPageExistsAndRedirect(event) {
// Make sure not to follow the original link.
event.preventDefault();
const currentFilePath = `{{ pagename }}.html`,
tryUrl = event.target.getAttribute("href");
tryUrl = event.currentTarget.getAttribute("href");
let otherDocsHomepage = tryUrl.replace(currentFilePath, "");

fetch(tryUrl, { method: "HEAD" })
.then(() => {
location.href = tryUrl;
}) // if the page exists, go there
.catch((error) => {
try {
let head = await fetch(tryUrl, { method: "HEAD" });
if (head.ok) {
location.href = tryUrl; // the page exists, go there
} else {
location.href = otherDocsHomepage;
});

// Cancel browser's native event handling.
// Prevent the browser from following the href of the clicked node,
// which is fine because this function takes care of redirecting.
return false;
}
} catch (err) {
// something went wrong, probably CORS restriction, fallback to other docs homepage
location.href = otherDocsHomepage;
}
}

function versionChooserAppendItem(slug, url) {
Expand Down

0 comments on commit d4ba6ef

Please sign in to comment.