From 64227c1c2796d7d47393293de41cbc665624494d Mon Sep 17 00:00:00 2001 From: Lanius Trolling Date: Tue, 27 Aug 2024 06:18:53 -0400 Subject: [PATCH] Fix Fetch+History loading with same-page fragment links --- src/jvmMain/resources/static/init.js | 33 +++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/jvmMain/resources/static/init.js b/src/jvmMain/resources/static/init.js index 766cc5a..b377ef2 100644 --- a/src/jvmMain/resources/static/init.js +++ b/src/jvmMain/resources/static/init.js @@ -100,7 +100,29 @@ } (async function () { - const newState = {"href": url.pathname, "index": history.state.index + 1}; + const prevUrl = new URL(window.location.href); + const newState = {"href": url.href, "index": history.state.index + 1}; + + if (stateMode === "pop" && history.state.href === "") { + window.scroll(0, history.state.scroll); + return; + } else if (stateMode !== "pop" && url.pathname === prevUrl.pathname && url.search === prevUrl.search) { + newState.href = ""; + + if (stateMode === "push") { + history.replaceState({...history.state, "scroll": window.scrollY}, ""); + history.pushState(newState, "", url); + } else if (stateMode === "replace") { + history.replaceState(newState, "", url); + } + + const scrollToElement = document.querySelector(url.hash); + if (scrollToElement != null) { + scrollToElement.scrollIntoView(true); + } + + return; + } if (stateMode === "push") { history.replaceState({...history.state, "scroll": window.scrollY}, ""); @@ -124,7 +146,6 @@ mode: "same-origin" }); - htmlResponse.headers.forEach(console.log); const redirectJson = htmlResponse.headers.get("X-Redirect-Json"); if (redirectJson != null && redirectJson.toLowerCase() === "true") { const redirectJsonBody = await htmlResponse.json(); @@ -133,7 +154,7 @@ } const redirectUrl = new URL(redirectJsonBody.target, window.location.origin) - if (!goToPage(redirectUrl, "replace")) { + if (!goToPage(redirectUrl, "push")) { window.location.href = redirectUrl.href; } @@ -169,7 +190,7 @@ return true; } - history.replaceState({"href": window.location.pathname, "index": 0}, ""); + history.replaceState({"href": window.location.href, "index": 0}, ""); let isWindowScrollTicking = false; window.addEventListener("scroll", () => { @@ -184,7 +205,7 @@ window.addEventListener("popstate", e => { e.preventDefault(); - const url = new URL(e.state.href, window.location.origin); + const url = new URL(e.state.href); if (!goToPage(url, "pop")) { window.location.href = url.href; } @@ -611,7 +632,7 @@ const anchors = dom.querySelectorAll("a"); for (const anchor of anchors) { - if (anchor.hasAttribute("data-csrf-token") || anchor.classList.contains("comment-edit-link") || anchor.classList.contains("copy-text")) { + if (!anchor.hasAttribute("href") || anchor.getAttribute("href") === "#" || anchor.hasAttribute("data-csrf-token")) { continue; } -- 2.25.1