Compare commits

..
Author SHA1 Message Date
saberzero1 6f872d4302 chore: lockfile for alias-redirects 1.0.4 and note-properties 1.1.5 (#2641, #2635) 2026-11-21 17:05:45 +01:00
saberzero1 8578f2fdb2 chore: changeset for the permalink and pretty-link fixes 2026-11-21 16:27:29 +01:00
saberzero1 5b863b0752 fix(links): prettyLinks shortens wikilinks to notes whose name has a space or a non-ASCII letter (#2643)
Link text was compared with the percent-encoded href, so these links were classed alias.
Patch proposed in the issue by TraceKotae.
2026-11-21 16:27:29 +01:00
saberzero1 d092a3179b fix: worker threads get every plain-data field of the build context (workerCtx), with a test for permalinks (#2644) 2026-11-21 16:27:29 +01:00
saberzero1 dacfeba928 Merge #2642: ignore permalinks with . or .. segments 2026-11-21 16:23:44 +01:00
saberzero1 5fafbf37b7 Merge #2644: permalinks in the worker-thread context 2026-11-21 16:23:44 +01:00
Emile Bangma 2e4ef40bc0 Merge pull request #2652 from jackyzha0/dev-mode/bases-page-1.5.1
chore: lockfile for bases-page 1.5.1
2026-11-21 03:17:23 +01:00
saberzero1 99685cf741 chore: lockfile for bases-page 1.5.1 (bases in transcluded notes, link settings) 2026-11-21 02:54:23 +01:00
Emile Bangma b58a7f20fe Merge pull request #2651 from jackyzha0/dev-mode/transclusion-ids
fix: unique ids in transcluded content; heading transclusions hold only their own footnotes
2026-11-21 02:45:32 +01:00
saberzero1 49d05638f2 fix: transcluded content gets ids unique on the page and links to them; heading transclusions hold only their own footnotes 2026-11-21 02:32:00 +01:00
Emile Bangma d7d6c7b17f Merge pull request #2650 from jackyzha0/dev-mode/encrypted-pages-1.3
chore: lockfile for encrypted-pages 1.3.0 and types 1.5.0
2026-11-21 01:37:13 +01:00
saberzero1 db2ce262b7 chore: lockfile for encrypted-pages 1.3.0 and types 1.5.0 (render-time encryption) 2026-11-21 01:22:19 +01:00
Emile Bangma 29a5bdf4b9 Merge pull request #2649 from jackyzha0/dev-mode/render-transforms
feat: renderTransforms, render-time transforms around transclusions and treeTransforms
2026-11-21 01:13:54 +01:00
saberzero1 97059690a0 feat: renderTransforms, render-time transforms of a page's content before and after transclusions and page types' treeTransforms 2026-11-21 01:05:36 +01:00
Emile Bangma e2e248b9b8 Merge pull request #2648 from jackyzha0/dev-mode/bases-page-1.5
chore: lockfile for bases-page 1.5.0
2026-11-21 00:15:36 +01:00
yavidor f690faad9e Added permalinks to worker context 2026-11-19 14:08:29 +02:00
goranai 546703340e fix: ignore permalinks with . or .. segments so pages stay in the output folder
Fixes #2641
2026-11-16 10:11:16 +08:00
25 changed files with 610 additions and 60 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Bases inside a transcluded note render that note's own base, and links in bases follow `configuration.links` (external-link icon, new tab, lazy images, popovers) (bases-page 1.5.1).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Permalinks work on large sites: sites of 192 or more files are parsed in worker threads, which didn't receive the permalinks, so a note with a `permalink` was published at its file path (#2644). A permalink with `.` or `..` segments is ignored with a warning instead of writing pages outside the output folder (#2641). With `prettyLinks`, a wikilink to a note whose name has a space or a non-ASCII letter reads as the note's name without its folder, as other links do (#2643).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": patch
---
Updates `@quartz-community/alias-redirects` to 1.0.4 (aliases that point outside the site are skipped, #2641) and `@quartz-community/note-properties` to 1.1.5 (links in properties to missing pages get the `broken` class with `disableBrokenWikilinks`, #2635).
+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
Transformers can declare `renderTransforms`: transforms of a page's content when it is rendered, `before` transclusions are inlined and page types' `treeTransforms` run (bases are filled in), and `after` them, on the finished content. encrypted-pages uses them to encrypt a note's finished content, so bases and transclusions in encrypted notes show when unlocked (quartz-community/encrypted-pages#2).
+5
View File
@@ -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.
+1 -1
View File
@@ -41,7 +41,7 @@ This question is best answered by tracing what happens when a user (you!) runs `
2. The `PageTypeDispatcher` emitter renders the HTML pages (`quartz/plugins/pageTypes/dispatcher.ts`):
1. Each page type's `generate` runs, one after another in priority order, and returns virtual pages (folder and tag pages, `.base` and `.canvas` pages, …). They are collected in `ctx.virtualPages`. Pages that stand for a file (page types with `fileExtensions`) first go through the site's filters, with `file.data.referencedBy` set to the pages that link to them.
2. The bodies of the virtual pages are rendered (so they can be embedded), and the transformers' `virtualPageHtmlPlugins` run on those of file-backed pages.
3. Every content page is rendered by the first page type (highest priority) whose `match` accepts it, and every virtual page by the page type that generated it. Rendering transforms the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime, applies the page types' `treeTransforms`, assembles the page [[layout]] and [[layout#Page Frames|frame]], and renders the JSX to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) (statically: `useState`, `useEffect` and other interactive bits don't run). The bulk of this logic can be found in `quartz/components/renderPage.tsx`.
3. Every content page is rendered by the first page type (highest priority) whose `match` accepts it, and every virtual page by the page type that generated it. Rendering transforms the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime, applies the transformers' `renderTransforms` (`before`), inlines transclusions, applies the page types' `treeTransforms` and the transformers' `renderTransforms` (`after`), assembles the page [[layout]] and [[layout#Page Frames|frame]], and renders the JSX to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) (statically: `useState`, `useEffect` and other interactive bits don't run). The bulk of this logic can be found in `quartz/components/renderPage.tsx`.
3. The content index is built once from the published and virtual pages (`ctx.contentIndex`), then all other emitters run in parallel over the same content (virtual pages included). The built-in content index emitter writes `static/contentIndex.json`, the sitemap and the RSS feed; plugin emitters write their own files.
7. If the `--serve` flag was detected, we also set up another file watcher to detect content changes (only `.md` files). We keep a content map that tracks the parsed AST and plugin data for each slug and update this on file changes. Newly added or modified paths are rebuilt and added to the content map. Then, all the filters and emitters are run over the resulting content map. This file watcher is debounced with a threshold of 250ms. On success, we send a client refresh signal using the passed in callback function.
+2
View File
@@ -107,6 +107,7 @@ export type QuartzTransformerPluginInstance = {
markdownPlugins?: (ctx: BuildCtx) => PluggableList
htmlPlugins?: (ctx: BuildCtx) => PluggableList
virtualPageHtmlPlugins?: (ctx: BuildCtx, content: ProcessedContent[]) => PluggableList
renderTransforms?: (ctx: BuildCtx) => { before?: TreeTransform[]; after?: TreeTransform[] }
externalResources?: (ctx: BuildCtx) => Partial<StaticResources> | undefined
extendContentIndex?: ContentIndexExtension // any plugin type, see below
}
@@ -118,6 +119,7 @@ All transformer plugins must define at least a `name` field to register the plug
- `markdownPlugins` defines a list of [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md). `remark` is a tool that transforms Markdown to Markdown in a structured way.
- `htmlPlugins` defines a list of [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md). Similar to how `remark` works, `rehype` is a tool that transforms HTML to HTML in a structured way.
- `virtualPageHtmlPlugins` (Quartz 5.1+) defines rehype plugins for the pages that page types render from files (`.base`, `.canvas`, Excalidraw drawings). Those pages are rendered when emitting and never pass through `htmlPlugins`, so a plugin that should also act on them (e.g. encryption) registers its rehype plugin here too. They run on the page's rendered body, with the page's vfile (`file.data.frontmatter`, `file.data.referencedBy`), after the filters published the page; the page then shows the resulting tree. `content` is the published content.
- `renderTransforms` (Quartz 5.2+) defines transforms of a page's content tree when the page is rendered, when other pages' content and `allFiles` are available. Each is a function `(root, slug, componentData) => void` that changes `root`, a copy of the page's tree. `before` transforms run before transclusions are inlined and page types' `treeTransforms` run (bases are filled in, for example); `after` transforms run on the finished content. [encrypted-pages](https://github.com/quartz-community/encrypted-pages) uses both: `before` puts its page's content back, `after` encrypts the finished content, transclusions and bases included. Something that only needs the finished content, such as rewriting all links in it, needs only `after`.
- `externalResources` defines any external resources the plugin may need to load on the client-side for it to work properly.
Transformers run in plugin order (see [[plugin manifest#defaultOrder]]); the built-in frontmatter parsing runs at order 0 and the built-in link processing, which sets `file.data.links`, at 60.
+1 -1
View File
@@ -42,7 +42,7 @@ and says whether to update Quartz (`npx quartz upgrade`) or the plugin. If an in
### For plugin authors
- Set `quartzVersion` to the **oldest Quartz version your plugin works with**. Raise it when you start using a newer API — for example a plugin that relies on [[built-in processing]] (core-parsed frontmatter, `ctx.contentIndex`, `extendContentIndex`), an async page type `generate`, `virtualPageHtmlPlugins`, `assets` or `window.quartzStaticUrl` needs `">=5.1.0"`. The [plugin template](https://github.com/quartz-community/plugin-template) starts with `">=5.0.0"`.
- Set `quartzVersion` to the **oldest Quartz version your plugin works with**. Raise it when you start using a newer API — for example a plugin that relies on [[built-in processing]] (core-parsed frontmatter, `ctx.contentIndex`, `extendContentIndex`), an async page type `generate`, `virtualPageHtmlPlugins`, `assets` or `window.quartzStaticUrl` needs `">=5.1.0"`; one that relies on `renderTransforms` needs `">=5.2.0"` (or treats the hook as optional, as Quartz 5.1 never calls it). The [plugin template](https://github.com/quartz-community/plugin-template) starts with `">=5.0.0"`.
- Prefer a lower bound (`>=5.1.0`) over a caret range: minor Quartz releases don't break plugins, so `^5` would only add an upper bound you'd have to bump at every major release. Add an upper bound when you know a major version breaks you.
- Raising `quartzVersion` is a breaking change for users on older Quartz versions: release it as a new major (or at least minor) version of your plugin and say so in its changelog.
- Pre-releases count: Quartz `5.2.0-beta.1` satisfies `>=5.1.0`.
+15 -15
View File
@@ -2359,9 +2359,9 @@
}
},
"node_modules/@quartz-community/alias-redirects": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@quartz-community/alias-redirects/-/alias-redirects-1.0.3.tgz",
"integrity": "sha512-kA3MiAneoHlC09uQJxF1ex1GktkUf9Rm53b0ybeJrtNEcteRoqBCELHB+pf6hUj9i/k2Epx0J8RyTSe/zwTg2A==",
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@quartz-community/alias-redirects/-/alias-redirects-1.0.4.tgz",
"integrity": "sha512-DGlkfTtpG8TBI8zyibUq5XCK00gqEyG+nK8YfhNgnvIgUUKtO5Cdx5HSpI+K2a8bb0uT0zpeAUy/uwUp30EmLQ==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2425,9 +2425,9 @@
}
},
"node_modules/@quartz-community/bases-page": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.0.tgz",
"integrity": "sha512-fesgMUzNk0/IVrBPBrqW5pzLvvfhXwL2Gxu/5Q7S/pGHqJTsDH5VXUU0f0oFsbZI3FKlOefz+RYm/Knvo1Yrbg==",
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@quartz-community/bases-page/-/bases-page-1.5.1.tgz",
"integrity": "sha512-rdZZlrUM8Lj15mQf0EB8oYfFmwVH4N4Br68bI3tZLyfwwErfpJbRtc7sGHxxH+e9H+15dS8N0g+INcyNWRp9ag==",
"license": "MIT",
"dependencies": {
"@lucide/icons": "^1.70.0",
@@ -2677,9 +2677,9 @@
}
},
"node_modules/@quartz-community/encrypted-pages": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@quartz-community/encrypted-pages/-/encrypted-pages-1.2.0.tgz",
"integrity": "sha512-AlqVloG4yVyoV+XE4645Xoc0x35WLAAQ0QkeNLMbQKw4bGSxYQhFwwWojdwIifvULWezlUZFhYZciQe6+QmBug==",
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@quartz-community/encrypted-pages/-/encrypted-pages-1.3.0.tgz",
"integrity": "sha512-V04420LqG90y+LsZ7e9cOhRdHg/uVKKq0trWxjACnBQaHD9pAw/ODBh2FuXvjvj8ZuzzelRD6sIVeS9vq2isLg==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -2897,9 +2897,9 @@
}
},
"node_modules/@quartz-community/note-properties": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.1.4.tgz",
"integrity": "sha512-MTj7D4+CzmuYzZ8UwF8T5uzFf+JHoA2NzRCniuhug4h6KVxf3IRePqn5uVupjm/0Uzz2oeB7UX8Nr0hH0SNAdg==",
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@quartz-community/note-properties/-/note-properties-1.1.5.tgz",
"integrity": "sha512-C8sKIhjaD479SozfzmU/r6IMG7Jc279qPTTxpCuJthrTBW7oYcSn/iEieplhojIXbUo7GTWY23g0iL/jUfuL/g==",
"license": "MIT",
"dependencies": {
"@quartz-community/types": "^1.0.0",
@@ -3271,9 +3271,9 @@
}
},
"node_modules/@quartz-community/types": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@quartz-community/types/-/types-1.4.0.tgz",
"integrity": "sha512-e2Hh9/9D1bckbJnsLIRjSE0HhA7FOxhzTZbtbbNmHkOo2ozETBXJxbT7TU76FzTn6kHP/6o3yuTStHve8Tyj2g==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@quartz-community/types/-/types-1.5.0.tgz",
"integrity": "sha512-gOP+EgjEy687/pHtJenLdPHomstlDQ8mUsP3a62CDyMLH02uPaxw0zmZLLzOx9+VE47TOlMc05cUsIxq5f7U5A==",
"license": "MIT",
"dependencies": {
"unified": "^11.0.5",
+58 -1
View File
@@ -1,6 +1,7 @@
import test, { describe } from "node:test"
import { toHtml } from "hast-util-to-html"
import assert from "node:assert"
import { renderTranscludes, pageResources } from "./renderPage"
import { renderTranscludes, pageResources, transformPageContent } from "./renderPage"
import { Root, Element } from "hast"
import { FullSlug } from "../util/path"
import { GlobalConfiguration } from "../cfg"
@@ -308,6 +309,62 @@ describe("renderTranscludes", () => {
})
})
describe("transformPageContent (render-time transforms)", () => {
const text = (root: Root) => toHtml(root)
const target: Root = {
type: "root",
children: [
{
type: "element",
tagName: "p",
properties: {},
children: [{ type: "text", value: "Target content" }],
},
],
}
test("runs before, then transclusions, then treeTransforms, then after, on a copy", () => {
const page: Root = { type: "root", children: [makeTranscludeBlockquote("target")] }
const data = makeComponentData([makePageData("target", target)]) as QuartzComponentProps
data.tree = page
const seen: string[] = []
const root = transformPageContent(cfg, "current" as FullSlug, data, {
before: [(r) => seen.push(`before:${text(r).includes("Target content")}`)],
treeTransforms: [(r) => seen.push(`tree:${text(r).includes("Target content")}`)],
after: [
(r) => {
seen.push(`after:${text(r).includes("Target content")}`)
r.children = [{ type: "text", value: "replaced" }]
},
],
})
assert.deepStrictEqual(seen, ["before:false", "tree:true", "after:true"])
assert.strictEqual(text(root), "replaced")
// the page's own tree is untouched
assert.ok(text(page).includes("transclude"))
})
test("a before transform can swap in content that then gets transclusions inlined", () => {
const data = makeComponentData([makePageData("target", target)]) as QuartzComponentProps
data.tree = { type: "root", children: [{ type: "text", value: "placeholder" }] } as Root
const root = transformPageContent(cfg, "current" as FullSlug, data, {
before: [(r) => (r.children = [makeTranscludeBlockquote("target")])],
treeTransforms: [],
after: [],
})
assert.ok(text(root).includes("Target content"))
})
test("a plain list is the page types' treeTransforms", () => {
const data = makeComponentData([]) as QuartzComponentProps
data.tree = { type: "root", children: [] } as Root
const root = transformPageContent(cfg, "current" as FullSlug, data, [
(r) => r.children.push({ type: "text", value: "x" }),
])
assert.strictEqual(text(root), "x")
})
})
describe("pageResources", () => {
const emptyResources: StaticResources = {
css: [],
+44 -16
View File
@@ -14,7 +14,8 @@ import { GlobalConfiguration, SidebarModes } from "../cfg"
import { i18n } from "../i18n"
import { styleText } from "util"
import { resolveFrame } from "./frames"
import type { TreeTransform } from "../plugins/types"
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)
}
}
@@ -325,26 +331,48 @@ export function renderTranscludes(
walk(root)
}
/**
* A page's content as it is rendered: a copy of its tree with the transformers' `before`
* transforms applied, transclusions inlined, then the page types' `treeTransforms` and the
* transformers' `after` transforms applied.
*/
export function transformPageContent(
cfg: GlobalConfiguration,
slug: FullSlug,
componentData: QuartzComponentProps,
transforms?: TreeTransform[] | PageTreeTransforms,
): Root {
const { before, treeTransforms, after } = Array.isArray(transforms)
? { before: [], treeTransforms: transforms, after: [] }
: (transforms ?? { before: [], treeTransforms: [], after: [] })
// make a deep copy of the tree so we don't remove the transclusion references
// for the file cached in contentMap in build.ts
const root = clone(componentData.tree) as Root
// transformers' render-time transforms that need the content before it is filled in
for (const transform of before) transform(root, slug, componentData)
const visited = new Set<FullSlug>([slug])
renderTranscludes(root, cfg, slug, componentData, visited)
// Run plugin-provided tree transforms (e.g. resolving inline bases codeblocks)
for (const transform of treeTransforms) transform(root, slug, componentData)
// transformers' render-time transforms of the finished content (e.g. encrypting it)
for (const transform of after) transform(root, slug, componentData)
return root
}
export function renderPage(
cfg: GlobalConfiguration,
slug: FullSlug,
componentData: QuartzComponentProps,
components: RenderComponents,
pageResources: StaticResources,
treeTransforms?: TreeTransform[],
transforms?: TreeTransform[] | PageTreeTransforms,
): string {
// make a deep copy of the tree so we don't remove the transclusion references
// for the file cached in contentMap in build.ts
const root = clone(componentData.tree) as Root
const visited = new Set<FullSlug>([slug])
renderTranscludes(root, cfg, slug, componentData, visited)
// Run plugin-provided tree transforms (e.g. resolving inline bases codeblocks)
if (treeTransforms) {
for (const transform of treeTransforms) {
transform(root, slug, componentData)
}
}
const root = transformPageContent(cfg, slug, componentData, transforms)
// set componentData.tree to the edited html that has transclusions rendered
componentData.tree = root
+115
View File
@@ -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)), [])
})
})
+138
View File
@@ -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]
}
+21
View File
@@ -408,6 +408,27 @@ describe("links built-in", () => {
)
})
test("pretty links shorten a link whose text is its percent-decoded href (#2643)", () => {
const { els } = run(
[
a("Folder/Name%20With%20Space", "Folder/Name With Space"),
a("Ordner/%C3%9Cbersicht", "Ordner/Übersicht"),
a("Folder/Name%20With%20Space", "own text"),
],
"page",
{ prettyLinks: true },
)
const links = els.filter((e) => e.tagName === "a")
assert.deepStrictEqual(
links.map((e) => (e.children[0] as Text).value),
["Name With Space", "Übersicht", "own text"],
)
assert.deepStrictEqual(
links.map((e) => (e.properties.className as string[]).includes("alias")),
[false, false, true],
)
})
test("disableBrokenWikilinks adds a broken class to missing targets", () => {
const { els } = run([a("missing")], "page", { disableBrokenWikilinks: true }, ["page"])
assert.ok((els[0].properties.className as string[]).includes("broken"))
+12 -2
View File
@@ -50,6 +50,14 @@ const isAbsolute = isAbsoluteUrl as (url: string, options?: { httpOnly?: boolean
// As in Obsidian: a URL with a scheme (`x:y`, but not `../x:y`), or a link whose path is not valid
// percent-encoding (`%zz`, `a%E2.md`), which names no file
const isExternalUrl = (url: string) => isAbsolute(url, { httpOnly: false }) || !linkPathDecodes(url)
// An href percent-decoded, to compare with link text; left as it is when it does not decode
const decodedHref = (href: string) => {
try {
return decodeURI(href)
} catch {
return href
}
}
const EXTERNAL_ICON_PATH =
"M320 0H288V64h32 82.7L201.4 265.4 178.7 288 224 333.3l22.6-22.6L448 109.3V192v32h64V192 32 0H480 320zM32 32H0V64 480v32H32 456h32V480 352 320H424v32 96H64V96h96 32V32H160 32z"
@@ -131,12 +139,14 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
})
}
// link text differs from the href → it's an alias ("[[note|text]]")
// link text differs from the href → it's an alias ("[[note|text]]"). The href is
// percent-encoded by now ("a%20b" for "a b"), so it is compared decoded too (#2643)
const firstChild = node.children[0]
if (
node.children.length === 1 &&
firstChild?.type === "text" &&
firstChild.value !== dest
firstChild.value !== dest &&
firstChild.value !== decodedHref(dest)
) {
classes.push("alias")
}
+8 -2
View File
@@ -845,7 +845,11 @@ function validateCategory(
return "shouldPublish" in instance
case "transformer":
return (
"textTransform" in instance || "markdownPlugins" in instance || "htmlPlugins" in instance
"textTransform" in instance ||
"markdownPlugins" in instance ||
"htmlPlugins" in instance ||
"virtualPageHtmlPlugins" in instance ||
"renderTransforms" in instance
)
}
}
@@ -929,7 +933,9 @@ export function detectCategoryFromModule(module: unknown): ProcessingCategory |
if (
"textTransform" in instance ||
"markdownPlugins" in instance ||
"htmlPlugins" in instance
"htmlPlugins" in instance ||
"virtualPageHtmlPlugins" in instance ||
"renderTransforms" in instance
)
return "transformer"
}
+7 -3
View File
@@ -62,9 +62,13 @@ function detectPluginType(
const hasPageTypeProps = ["match", "body", "layout"].every((key) => key in mod)
const hasTransformerProps = ["textTransform", "markdownPlugins", "htmlPlugins"].some(
(key) => key in mod && (typeof mod[key] === "function" || mod[key] === undefined),
)
const hasTransformerProps = [
"textTransform",
"markdownPlugins",
"htmlPlugins",
"virtualPageHtmlPlugins",
"renderTransforms",
].some((key) => key in mod && (typeof mod[key] === "function" || mod[key] === undefined))
const hasFilterProps = ["shouldPublish"].some(
(key) => key in mod && typeof mod[key] === "function",
@@ -5,6 +5,7 @@ import os from "os"
import path from "path"
import {
collectComponents,
collectTreeTransforms,
folderTrie,
generateVirtualPages,
pageOutputPath,
@@ -133,6 +134,33 @@ describe("resolveLayout frame resolution", () => {
})
})
describe("collectTreeTransforms", () => {
test("transformers' renderTransforms wrap the page types' treeTransforms, in plugin order", () => {
const t = (name: string) => Object.assign(() => {}, { tname: name })
const ctx = {
cfg: {
plugins: {
transformers: [
{
name: "a",
renderTransforms: () => ({ before: [t("a-before")], after: [t("a-after")] }),
},
{ name: "b", htmlPlugins: () => [] },
{ name: "c", renderTransforms: () => ({ after: [t("c-after")] }) },
],
},
},
} as unknown as BuildCtx
const result = collectTreeTransforms(ctx, [
makePageType({ treeTransforms: () => [t("page") as never] }),
])
const names = (list: unknown[]) => list.map((f) => (f as { tname: string }).tname)
assert.deepStrictEqual(names(result.before), ["a-before"])
assert.deepStrictEqual(names(result.treeTransforms), ["page"])
assert.deepStrictEqual(names(result.after), ["a-after", "c-after"])
})
})
describe("collectComponents", () => {
test("collects all unique components across page types", () => {
const pageTypes = [makePageType(), makePageType({ layout: "landing" })]
+31 -10
View File
@@ -1,4 +1,9 @@
import { QuartzEmitterPlugin, QuartzPageTypePluginInstance, TreeTransform } from "../types"
import {
PageTreeTransforms,
QuartzEmitterPlugin,
QuartzPageTypePluginInstance,
TreeTransform,
} from "../types"
import { QuartzComponent, QuartzComponentProps } from "../../components/types"
import { pageResources, renderPage } from "../../components/renderPage"
import { FullPageLayout } from "../../cfg"
@@ -86,6 +91,26 @@ interface DispatcherOptions {
byPageType: Record<string, Partial<FullPageLayout>>
}
/**
* @internal Exported for testing only.
*
* The render-time transforms of every page: the transformers' `renderTransforms` (`before` and
* `after`, in plugin order) around the page types' `treeTransforms`.
*/
export function collectTreeTransforms(
ctx: BuildCtx,
pageTypes: { treeTransforms?: (ctx: BuildCtx) => TreeTransform[] }[],
): PageTreeTransforms {
const render = (ctx.cfg.plugins?.transformers ?? []).flatMap((transformer) =>
transformer.renderTransforms ? [transformer.renderTransforms(ctx)] : [],
)
return {
before: render.flatMap((transforms) => transforms.before ?? []),
treeTransforms: pageTypes.flatMap((pt) => pt.treeTransforms?.(ctx) ?? []),
after: render.flatMap((transforms) => transforms.after ?? []),
}
}
async function emitPage(
ctx: BuildCtx,
slug: FullSlug,
@@ -94,7 +119,7 @@ async function emitPage(
allFiles: ProcessedContent[1]["data"][],
layout: FullPageLayout,
resources: StaticResources,
treeTransforms?: TreeTransform[],
treeTransforms?: PageTreeTransforms,
) {
const cfg = ctx.cfg.configuration
// For the 404 page, use an absolute base path so assets resolve correctly
@@ -369,10 +394,8 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
const cfg = ctx.cfg.configuration
const allFiles = content.map((c) => c[1].data)
// Collect tree transforms from all page type plugins
const treeTransforms: TreeTransform[] = pageTypes.flatMap(
(pt) => pt.treeTransforms?.(ctx) ?? [],
)
// Collect render-time transforms: transformers' renderTransforms and page types' treeTransforms
const treeTransforms = collectTreeTransforms(ctx, pageTypes)
// Ensure trie is available for components that need folder hierarchy (e.g. FolderContent)
ctx.trie ??= trieFromAllFiles(allFiles)
@@ -448,10 +471,8 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
const cfg = ctx.cfg.configuration
const allFiles = content.map((c) => c[1].data)
// Collect tree transforms from all page type plugins
const treeTransforms: TreeTransform[] = pageTypes.flatMap(
(pt) => pt.treeTransforms?.(ctx) ?? [],
)
// Collect render-time transforms: transformers' renderTransforms and page types' treeTransforms
const treeTransforms = collectTreeTransforms(ctx, pageTypes)
// Rebuild trie on partial emit to reflect file changes
ctx.trie = trieFromAllFiles(allFiles)
+26
View File
@@ -69,9 +69,35 @@ export type QuartzTransformerPluginInstance = PluginHooks & {
* shows the resulting tree. `content` is the published content. Quartz 5.1+.
*/
virtualPageHtmlPlugins?: (ctx: BuildCtx, content: ProcessedContent[]) => PluggableList
/**
* Transforms of a page's content tree when the page is rendered, when the content of other
* pages (and allFiles) is available. `before` runs before transclusions are inlined and page
* types' `treeTransforms` run (e.g. bases are filled in), `after` runs on the finished content.
* E.g. encrypted-pages swaps its page's content in `before` and encrypts the finished content in
* `after`. Each transform gets the page's own tree (a copy), slug and component data.
* Quartz 5.2+.
*/
renderTransforms?: (ctx: BuildCtx) => RenderTransforms
externalResources?: ExternalResourcesFn
}
/** A transformer's render-time transforms (see `renderTransforms`). */
export interface RenderTransforms {
before?: TreeTransform[]
after?: TreeTransform[]
}
/**
* The transforms renderPage runs on a page's content, in order: the transformers' `before`, then
* (after transclusions are inlined) the page types' `treeTransforms`, then the transformers'
* `after`.
*/
export interface PageTreeTransforms {
before: TreeTransform[]
treeTransforms: TreeTransform[]
after: TreeTransform[]
}
export type QuartzFilterPlugin<Options extends OptionType = undefined> = (
opts?: Options,
) => QuartzFilterPluginInstance
+2 -9
View File
@@ -13,7 +13,7 @@ import path from "path"
import workerpool, { Promise as WorkerPromise } from "workerpool"
import { QuartzLogger } from "../util/log"
import { trace } from "../util/trace"
import { BuildCtx, WorkerSerializableBuildCtx } from "../util/ctx"
import { BuildCtx, workerCtx } from "../util/ctx"
import { styleText } from "util"
import {
attributeError,
@@ -206,14 +206,7 @@ export async function parseMarkdown(ctx: BuildCtx, fps: FilePath[]): Promise<Pro
maxWorkers: concurrency,
workerType: "thread",
})
const serializableCtx: WorkerSerializableBuildCtx = {
buildId: ctx.buildId,
argv: ctx.argv,
allSlugs: ctx.allSlugs,
allFiles: ctx.allFiles,
incremental: ctx.incremental,
virtualPages: [],
}
const serializableCtx = workerCtx(ctx)
try {
const textToMarkdownPromises: WorkerPromise<MarkdownContent[]>[] = []
+29
View File
@@ -0,0 +1,29 @@
import { describe, test } from "node:test"
import assert from "node:assert"
import { BuildCtx, workerCtx } from "./ctx"
import { FullSlug, FilePath } from "./path"
describe("workerCtx", () => {
const ctx = {
buildId: "b",
argv: { directory: "content" },
cfg: { configuration: {} },
allSlugs: ["index", "elsewhere/moved"] as FullSlug[],
allFiles: ["index.md", "Moved.md"] as FilePath[],
permalinks: { "Moved.md": "elsewhere/moved" as FullSlug },
incremental: false,
virtualPages: [],
trie: {},
} as unknown as BuildCtx
test("carries permalinks to worker threads (#2644)", () => {
assert.deepStrictEqual(workerCtx(ctx).permalinks, { "Moved.md": "elsewhere/moved" })
})
test("holds plain data only, and survives structured cloning", () => {
const worker = workerCtx(ctx)
assert.ok(!("cfg" in worker) && !("trie" in worker))
assert.deepStrictEqual(structuredClone(worker), worker)
assert.deepStrictEqual(worker.virtualPages, [])
})
})
+23
View File
@@ -86,3 +86,26 @@ export function trieFromAllFiles(allFiles: QuartzPluginData[]): FileTrieNode<Bui
}
export type WorkerSerializableBuildCtx = Omit<BuildCtx, "cfg" | "trie">
/** The plain-data fields of {@link BuildCtx} that worker threads need, each one required. */
type WorkerCtxFields = {
[K in "buildId" | "argv" | "allSlugs" | "allFiles" | "permalinks" | "incremental"]-?: BuildCtx[K]
}
/**
* The build context passed to worker threads (structured-cloned): every plain-data field the
* parse needs. Listing each field as required means a new one can't be forgotten here: worker
* threads run for sites of 192 or more files, so a missing field (permalinks, #2644) only broke
* large sites.
*/
export function workerCtx(ctx: BuildCtx): WorkerSerializableBuildCtx {
const fields: WorkerCtxFields = {
buildId: ctx.buildId,
argv: ctx.argv,
allSlugs: ctx.allSlugs,
allFiles: ctx.allFiles,
permalinks: ctx.permalinks ?? {},
incremental: ctx.incremental,
}
return { ...fields, virtualPages: [] }
}
+19
View File
@@ -19,6 +19,25 @@ describe("permalinks (Obsidian Publish semantics)", () => {
assert.strictEqual(normalizePermalink(2024), "2024")
})
test("collectPermalinks ignores permalinks with a . or .. segment", () => {
const fm: Record<string, unknown> = {
"a.md": "../escaped",
"b.md": "x/../../escaped",
"c.md": "./c",
"d.md": "/../../d/",
"e.md": "..\\..\\e",
"f.md": "fine..name/ok",
}
const warnings: string[] = []
const permalinks = collectPermalinks({
files: Object.keys(fm),
permalinkOf: (f) => fm[f],
warn: (m) => warnings.push(m),
})
assert.deepStrictEqual(permalinks, { "f.md": "fine..name/ok" })
assert.strictEqual(warnings.length, 5)
})
test("collectPermalinks maps files to their permalink; the address can't be taken twice", () => {
const fm: Record<string, unknown> = {
"folder/note.md": "page",
+5
View File
@@ -46,6 +46,11 @@ export function collectPermalinks({
for (const file of files) {
const slug = normalizePermalink(permalinkOf(file))
if (!slug) continue
if (slug.split("/").some((segment) => segment === "." || segment === "..")) {
// a "." or ".." segment would be written outside the output directory (../x.html)
warn(`${file}: permalink "${slug}" contains a "." or ".." segment and is ignored.`)
continue
}
const own = slugifyFilePath(file as FilePath)
if (slug === own) continue // the note's own path: nothing to do
const owner = pathSlugs.get(slug) ?? taken.get(slug)