mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
fix: transcluded content gets ids unique on the page and links to them; heading transclusions hold only their own footnotes
This commit is contained in:
4 files changed
+266
-2
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Transcluded content no longer duplicates ids. Headings and footnotes inside a transclusion get ids unique on the page, and the links inside it go to them, so the host's footnotes and a `[[#Heading]]` link inside a transclusion jump to the right place. A same-page link whose target isn't in the transcluded section links to the transcluded page. A heading transclusion (`![[note#Heading]]`) holds only the footnotes it references instead of the page's whole footnotes section.
|
||||
@@ -15,6 +15,7 @@ import { i18n } from "../i18n"
|
||||
import { styleText } from "util"
|
||||
import { resolveFrame } from "./frames"
|
||||
import type { PageTreeTransforms, TreeTransform } from "../plugins/types"
|
||||
import { createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
import type { BuildCtx } from "../util/ctx"
|
||||
|
||||
interface RenderComponents {
|
||||
@@ -146,6 +147,9 @@ export function renderTranscludes(
|
||||
componentData: QuartzComponentProps,
|
||||
visited: Set<FullSlug>,
|
||||
) {
|
||||
// a prefix per transclusion, unique on the page, for the ids inside it
|
||||
const scopeFor = createIdScopes()
|
||||
|
||||
// Walk the tree manually instead of using visit() so we can track the
|
||||
// ancestor chain for cycle detection. visit() runs the callback before
|
||||
// descending into replaced children, so a Set-based guard there falsely
|
||||
@@ -265,8 +269,8 @@ export function renderTranscludes(
|
||||
}
|
||||
|
||||
el.children = [
|
||||
...(page.htmlAst.children.slice(startIdx, endIdx) as ElementContent[]).map((c) =>
|
||||
normalizeHastElement(c as Element, slug, transcludeTarget),
|
||||
...sliceWithFootnotes(page.htmlAst.children as ElementContent[], startIdx, endIdx).map(
|
||||
(c) => normalizeHastElement(c as Element, slug, transcludeTarget),
|
||||
),
|
||||
{
|
||||
type: "element",
|
||||
@@ -318,6 +322,8 @@ export function renderTranscludes(
|
||||
// Recurse into the replaced children to resolve nested transclusions,
|
||||
// then remove from visited so sibling embeds of the same target work.
|
||||
walk(el)
|
||||
// its ids (headings, footnotes) are unique on the page, and links inside it go to them
|
||||
scopeTranscludedIds(el, scopeFor(transcludeTarget), inner.properties?.href as string)
|
||||
visited.delete(transcludeTarget)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import type { Element, ElementContent } from "hast"
|
||||
import { createIdScopes, scopeTranscludedIds, sliceWithFootnotes } from "./transcludeScope"
|
||||
|
||||
const h = (
|
||||
tagName: string,
|
||||
properties: Element["properties"] = {},
|
||||
children: ElementContent[] = [],
|
||||
): Element => ({ type: "element", tagName, properties, children })
|
||||
const text = (value: string): ElementContent => ({ type: "text", value })
|
||||
|
||||
describe("createIdScopes", () => {
|
||||
test("a prefix per transclusion, unique on the page", () => {
|
||||
const scope = createIdScopes()
|
||||
assert.strictEqual(scope("notes/Source"), "source--")
|
||||
assert.strictEqual(scope("notes/source"), "source-2--")
|
||||
assert.strictEqual(scope("other"), "other--")
|
||||
})
|
||||
})
|
||||
|
||||
describe("scopeTranscludedIds", () => {
|
||||
test("prefixes ids and the references to them inside the transclusion", () => {
|
||||
const el = h("div", { className: ["transclude"] }, [
|
||||
h("h2", { id: "details" }, [text("Details")]),
|
||||
h("p", {}, [
|
||||
h("a", { href: "#details" }, [text("jump")]),
|
||||
h("sup", {}, [
|
||||
h(
|
||||
"a",
|
||||
{
|
||||
href: "#user-content-fn-1",
|
||||
id: "user-content-fnref-1",
|
||||
dataFootnoteRef: "",
|
||||
ariaDescribedBy: ["footnote-label"],
|
||||
},
|
||||
[text("1")],
|
||||
),
|
||||
]),
|
||||
]),
|
||||
h("section", { dataFootnotes: "" }, [
|
||||
h("h2", { id: "footnote-label" }, [text("Footnotes")]),
|
||||
h("ol", {}, [
|
||||
h("li", { id: "user-content-fn-1" }, [
|
||||
h("a", { href: "#user-content-fnref-1" }, [text("↩")]),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
scopeTranscludedIds(el, "source--", "./source")
|
||||
const [heading, para, section] = el.children as Element[]
|
||||
assert.strictEqual(heading!.properties.id, "source--details")
|
||||
const [jump, sup] = para!.children as Element[]
|
||||
assert.strictEqual(jump!.properties.href, "#source--details")
|
||||
const ref = (sup!.children[0] as Element).properties
|
||||
assert.strictEqual(ref.href, "#source--user-content-fn-1")
|
||||
assert.strictEqual(ref.id, "source--user-content-fnref-1")
|
||||
assert.deepStrictEqual(ref.ariaDescribedBy, ["source--footnote-label"])
|
||||
const li = (section!.children[1] as Element).children[0] as Element
|
||||
assert.strictEqual(li.properties.id, "source--user-content-fn-1")
|
||||
assert.strictEqual((li.children[0] as Element).properties.href, "#source--user-content-fnref-1")
|
||||
})
|
||||
|
||||
test("a same-page link whose target isn't in the transclusion goes to the transcluded page", () => {
|
||||
const el = h("div", {}, [h("a", { href: "#elsewhere" }, [text("x")])])
|
||||
scopeTranscludedIds(el, "source--", "./source#overview")
|
||||
assert.strictEqual((el.children[0] as Element).properties.href, "./source#elsewhere")
|
||||
})
|
||||
|
||||
test("leaves inline svg and math alone, and other links", () => {
|
||||
const el = h("div", {}, [
|
||||
h("svg", {}, [h("linearGradient", { id: "grad" }), h("rect", { fill: "url(#grad)" })]),
|
||||
h("a", { href: "./other#x" }, [text("x")]),
|
||||
])
|
||||
scopeTranscludedIds(el, "source--", "./source")
|
||||
const svg = el.children[0] as Element
|
||||
assert.strictEqual((svg.children[0] as Element).properties.id, "grad")
|
||||
assert.strictEqual((el.children[1] as Element).properties.href, "./other#x")
|
||||
})
|
||||
})
|
||||
|
||||
describe("sliceWithFootnotes", () => {
|
||||
const page: ElementContent[] = [
|
||||
h("h2", { id: "a" }, [text("A")]),
|
||||
h("p", {}, [h("a", { href: "#user-content-fn-2", dataFootnoteRef: "" }, [text("2")])]),
|
||||
h("h2", { id: "b" }, [text("B")]),
|
||||
h("p", {}, [h("a", { href: "#user-content-fn-1", dataFootnoteRef: "" }, [text("1")])]),
|
||||
h("section", { dataFootnotes: "", className: ["footnotes"] }, [
|
||||
h("ol", {}, [h("li", { id: "user-content-fn-1" }), h("li", { id: "user-content-fn-2" })]),
|
||||
]),
|
||||
]
|
||||
const footnoteIds = (nodes: ElementContent[]) =>
|
||||
nodes
|
||||
.filter((n): n is Element => n.type === "element" && n.tagName === "section")
|
||||
.flatMap((s) =>
|
||||
((s.children[0] as Element).children as Element[]).map((li) => li.properties.id),
|
||||
)
|
||||
|
||||
test("the last section gets only its own footnotes, not the whole footnotes section", () => {
|
||||
assert.deepStrictEqual(footnoteIds(sliceWithFootnotes(page, 2, undefined)), [
|
||||
"user-content-fn-1",
|
||||
])
|
||||
})
|
||||
|
||||
test("an earlier section gets its footnotes too", () => {
|
||||
const slice = sliceWithFootnotes(page, 0, 2)
|
||||
assert.strictEqual(slice.length, 3)
|
||||
assert.deepStrictEqual(footnoteIds(slice), ["user-content-fn-2"])
|
||||
})
|
||||
|
||||
test("a section without footnote references gets no footnotes section", () => {
|
||||
const plain = [h("h2", { id: "c" }), h("p"), page[4]!]
|
||||
assert.deepStrictEqual(footnoteIds(sliceWithFootnotes(plain, 0, undefined)), [])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import type { Element, ElementContent, Root } from "hast"
|
||||
|
||||
/**
|
||||
* Transcluded content is a copy of another page's HTML, ids included: two transclusions (or a
|
||||
* transclusion and its host) share heading ids and footnote ids (`user-content-fn-1`), so a
|
||||
* footnote reference or a `[[#Heading]]` link jumps to whichever element comes first on the page.
|
||||
* Obsidian resolves each embed on its own.
|
||||
*
|
||||
* {@link scopeTranscludedIds} gives the ids inside one transclusion a prefix, unique on the page,
|
||||
* and rewrites the references inside it to match. The host's ids stay as they are. A same-page
|
||||
* link (`#id`) whose target isn't in the transclusion (a heading slice that doesn't hold it) links
|
||||
* to the id on the transcluded page instead.
|
||||
*/
|
||||
|
||||
/** Space-separated id references (hast property names). */
|
||||
const ID_LIST_PROPERTIES = [
|
||||
"ariaDescribedBy",
|
||||
"ariaLabelledBy",
|
||||
"ariaControls",
|
||||
"ariaOwns",
|
||||
"ariaDetails",
|
||||
"ariaFlowTo",
|
||||
"htmlFor",
|
||||
"headers",
|
||||
] as const
|
||||
|
||||
/** Subtrees whose ids are referenced from inside them in ways we don't rewrite (`url(#id)`). */
|
||||
const OPAQUE = new Set(["svg", "math"])
|
||||
|
||||
function forEachElement(node: Element | Root, fn: (el: Element) => void) {
|
||||
for (const child of node.children) {
|
||||
if (child.type !== "element") continue
|
||||
fn(child)
|
||||
if (!OPAQUE.has(child.tagName)) forEachElement(child, fn)
|
||||
}
|
||||
}
|
||||
|
||||
/** Per page render: a prefix for each transclusion, unique on the page. */
|
||||
export function createIdScopes(): (target: string) => string {
|
||||
const used = new Map<string, number>()
|
||||
return (target) => {
|
||||
const base =
|
||||
(target.split("/").pop() ?? target)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "") || "transclude"
|
||||
const count = (used.get(base) ?? 0) + 1
|
||||
used.set(base, count)
|
||||
return count === 1 ? `${base}--` : `${base}-${count}--`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefixes the ids inside the transclusion `el` with `prefix` and rewrites references to them
|
||||
* inside it. `sourceHref` is the link to the transcluded page (relative to the host), for
|
||||
* same-page links whose target isn't in the transclusion.
|
||||
*/
|
||||
export function scopeTranscludedIds(el: Element, prefix: string, sourceHref?: string) {
|
||||
const ids = new Set<string>()
|
||||
forEachElement(el, (node) => {
|
||||
const id = node.properties?.id
|
||||
if (typeof id === "string" && id) ids.add(id)
|
||||
})
|
||||
|
||||
const pageHref = typeof sourceHref === "string" ? sourceHref.split("#")[0] : undefined
|
||||
const scoped = (id: string) => (ids.has(id) ? `${prefix}${id}` : id)
|
||||
|
||||
forEachElement(el, (node) => {
|
||||
const props = node.properties
|
||||
if (!props) return
|
||||
if (typeof props.id === "string" && ids.has(props.id)) props.id = `${prefix}${props.id}`
|
||||
|
||||
const href = props.href
|
||||
if (typeof href === "string" && href.startsWith("#") && href.length > 1) {
|
||||
let target = href.slice(1)
|
||||
try {
|
||||
target = decodeURIComponent(target)
|
||||
} catch {
|
||||
// keep as written
|
||||
}
|
||||
if (ids.has(target)) props.href = `#${prefix}${target}`
|
||||
else if (pageHref) props.href = `${pageHref}${href}`
|
||||
}
|
||||
|
||||
const record = props as Record<string, unknown>
|
||||
for (const name of ID_LIST_PROPERTIES) {
|
||||
const value = record[name]
|
||||
if (Array.isArray(value)) record[name] = value.map((token) => scoped(String(token)))
|
||||
else if (typeof value === "string") record[name] = value.split(/\s+/).map(scoped).join(" ")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function isFootnotesSection(node: ElementContent): node is Element {
|
||||
if (node.type !== "element" || node.tagName !== "section") return false
|
||||
const props = node.properties ?? {}
|
||||
const classes = (props.className ?? []) as string[]
|
||||
return props.dataFootnotes !== undefined || classes.includes("footnotes")
|
||||
}
|
||||
|
||||
/**
|
||||
* A heading transclusion: the slice of the page from the heading to the next one of the same or
|
||||
* a higher level. The page's footnotes section is not part of the section; the footnotes the
|
||||
* slice references are added after it (in a copy of the section holding only those).
|
||||
*/
|
||||
export function sliceWithFootnotes(
|
||||
pageChildren: ElementContent[],
|
||||
start: number,
|
||||
end: number | undefined,
|
||||
): ElementContent[] {
|
||||
const slice = pageChildren.slice(start, end).filter((node): boolean => !isFootnotesSection(node))
|
||||
const section = pageChildren.find(isFootnotesSection)
|
||||
if (!section) return slice
|
||||
|
||||
const referenced = new Set<string>()
|
||||
const collect = (node: Element | Root) =>
|
||||
forEachElement(node, (child) => {
|
||||
const href = child.properties?.href
|
||||
if (child.properties?.dataFootnoteRef !== undefined && typeof href === "string")
|
||||
referenced.add(href.replace(/^#/, ""))
|
||||
})
|
||||
for (const node of slice) if (node.type === "element") collect(node as Element)
|
||||
if (referenced.size === 0) return slice
|
||||
|
||||
const copy = structuredClone(section) as Element
|
||||
const keep = (list: Element) => {
|
||||
list.children = list.children.filter(
|
||||
(item) =>
|
||||
item.type !== "element" ||
|
||||
item.tagName !== "li" ||
|
||||
referenced.has(String(item.properties?.id ?? "")),
|
||||
)
|
||||
}
|
||||
forEachElement(copy, (node) => {
|
||||
if (node.tagName === "ol") keep(node)
|
||||
})
|
||||
return [...slice, copy]
|
||||
}
|
||||
Reference in new issue
Block a user