From d61fb266c7f6b534236340d5359d0cbe14f55834 Mon Sep 17 00:00:00 2001
From: Emile Bangma <github@emilebangma.com>
Date: Sat, 05 Apr 2025 17:31:17 +0000
Subject: [PATCH] fix(popover): automatically position anchored links properly (#1897)
---
quartz/components/scripts/popover.inline.ts | 17 ++++++++++++-----
1 files changed, 12 insertions(+), 5 deletions(-)
diff --git a/quartz/components/scripts/popover.inline.ts b/quartz/components/scripts/popover.inline.ts
index 972d3c6..7d8aec3 100644
--- a/quartz/components/scripts/popover.inline.ts
+++ b/quartz/components/scripts/popover.inline.ts
@@ -1,9 +1,10 @@
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
import { normalizeRelativeURLs } from "../../util/path"
+import { fetchCanonical } from "./util"
const p = new DOMParser()
async function mouseEnterHandler(
- this: HTMLLinkElement,
+ this: HTMLAnchorElement,
{ clientX, clientY }: { clientX: number; clientY: number },
) {
const link = this
@@ -33,11 +34,11 @@
thisUrl.hash = ""
thisUrl.search = ""
const targetUrl = new URL(link.href)
- const hash = targetUrl.hash
+ const hash = decodeURIComponent(targetUrl.hash)
targetUrl.hash = ""
targetUrl.search = ""
- const response = await fetch(`${targetUrl}`).catch((err) => {
+ const response = await fetchCanonical(targetUrl).catch((err) => {
console.error(err)
})
@@ -81,6 +82,11 @@
const contents = await response.text()
const html = p.parseFromString(contents, "text/html")
normalizeRelativeURLs(html, targetUrl)
+ // prepend all IDs inside popovers to prevent duplicates
+ html.querySelectorAll("[id]").forEach((el) => {
+ const targetID = `popover-${el.id}`
+ el.id = targetID
+ })
const elts = [...html.getElementsByClassName("popover-hint")]
if (elts.length === 0) return
@@ -91,7 +97,8 @@
link.appendChild(popoverElement)
if (hash !== "") {
- const heading = popoverInner.querySelector(hash) as HTMLElement | null
+ const targetAnchor = hash.startsWith("#popover") ? hash : `#popover-${hash.slice(1)}`
+ const heading = popoverInner.querySelector(targetAnchor) as HTMLElement | null
if (heading) {
// leave ~12px of buffer when scrolling to a heading
popoverInner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
@@ -100,7 +107,7 @@
}
document.addEventListener("nav", () => {
- const links = [...document.getElementsByClassName("internal")] as HTMLLinkElement[]
+ const links = [...document.getElementsByClassName("internal")] as HTMLAnchorElement[]
for (const link of links) {
link.addEventListener("mouseenter", mouseEnterHandler)
window.addCleanup(() => link.removeEventListener("mouseenter", mouseEnterHandler))
--
Gitblit v1.10.0