From d4ba6ef702f19eaab579237d1926f6c624890b16 Mon Sep 17 00:00:00 2001 From: Andreas Motl Date: Tue, 5 Sep 2023 18:18:34 +0200 Subject: [PATCH] Version Chooser: Integrate most recent changes from pydata-sphinx-theme > 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. --- CHANGES.rst | 3 ++- .../theme/rtd/crate/version_chooser.html | 27 ++++++++++--------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 286a1d2f0..52ff55668 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -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 diff --git a/src/crate/theme/rtd/crate/version_chooser.html b/src/crate/theme/rtd/crate/version_chooser.html index a1ef1a113..cd4ba5510 100644 --- a/src/crate/theme/rtd/crate/version_chooser.html +++ b/src/crate/theme/rtd/crate/version_chooser.html @@ -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) {