From 134b6ed582d6ce9d8fb8f1e58d2bae89c07c2d5d Mon Sep 17 00:00:00 2001 From: Jacky Zhao Date: Sat, 11 Nov 2023 10:11:31 -0800 Subject: [PATCH] fix: anchors links shouldnt cause reload (closes #574) --- docs/features/callouts.md | 2 +- quartz/components/scripts/spa.inline.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/features/callouts.md b/docs/features/callouts.md index 63051ad..27de687 100644 --- a/docs/features/callouts.md +++ b/docs/features/callouts.md @@ -33,7 +33,7 @@ SeeĀ [documentation on supported types and syntax here](https://help.obsidian.md > [!question]+ Can callouts be nested? > -> > [!todo]- Yes!, they can. +> > [!todo]- Yes!, they can. And collapsed! > > > > > [!example] You can even use multiple layers of nesting. diff --git a/quartz/components/scripts/spa.inline.ts b/quartz/components/scripts/spa.inline.ts index 31ae14f..115bc96 100644 --- a/quartz/components/scripts/spa.inline.ts +++ b/quartz/components/scripts/spa.inline.ts @@ -18,6 +18,12 @@ const isLocalUrl = (href: string) => { return false } +const isSamePage = (url: URL): boolean => { + const sameOrigin = url.origin === window.location.origin + const samePath = url.pathname === window.location.pathname + return sameOrigin && samePath +} + const getOpts = ({ target }: Event): { url: URL; scroll?: boolean } | undefined => { if (!isElement(target)) return if (target.attributes.getNamedItem("target")?.value === "_blank") return @@ -93,8 +99,16 @@ function createRouter() { if (typeof window !== "undefined") { window.addEventListener("click", async (event) => { const { url } = getOpts(event) ?? {} + // dont hijack behaviour, just let browser act normally if (!url || event.ctrlKey || event.metaKey) return event.preventDefault() + + if (isSamePage(url) && url.hash) { + const el = document.getElementById(decodeURIComponent(url.hash.substring(1))) + el?.scrollIntoView() + return + } + try { navigate(url, false) } catch (e) {