feat: renderTransforms, render-time transforms of a page's content before and after transclusions and page types' treeTransforms

This commit is contained in:
saberzero1 committed 2026-11-21 01:05:36 +01:00
1 parent e2e248b9b8
commit 97059690a0
11 files changed
+203 -32

No files matched your search

+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).
+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`.
+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: [],
+36 -14
View File
@@ -14,7 +14,7 @@ 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 type { BuildCtx } from "../util/ctx"
interface RenderComponents {
@@ -325,26 +325,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
+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