mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
feat: page types may generate virtual pages asynchronously (#2575)
This commit is contained in:
5 files changed
+133
-59
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": minor
|
||||
---
|
||||
|
||||
A page type's `generate` can be async: it may return a promise of its virtual pages, which Quartz awaits in full and incremental builds. Page types that create pages from other files (like `.mdx`) can now run content through the site's transformers or bundle with esbuild; previously a promise crashed the build with "virtualPages is not iterable" (#2575).
|
||||
@@ -391,7 +391,7 @@ export interface QuartzPageTypePluginInstance {
|
||||
- `priority`: Controls matching order when multiple page types could match a slug. Higher priority page types are checked first. Default: `0`.
|
||||
- `fileExtensions`: Array of file extensions this page type handles (e.g. `[".canvas"]`, `[".base"]`). Content files (`.md`) are handled by the default content page type.
|
||||
- `match`: A function that determines whether a given slug/file should be rendered by this page type.
|
||||
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices).
|
||||
- `generate`: An optional function that produces virtual pages (pages not backed by files on disk, such as folder listings or tag indices). It receives `{ content, cfg, ctx }` and returns the pages, or (Quartz 5.1+) a promise of them, so it can do async work such as running content through the site's transformers or bundling with esbuild. Page types generate one after another, in priority order. A plugin with an async `generate` should declare `"quartzVersion": ">=5.1.0"`, since older versions don't wait for it.
|
||||
- `layout`: The layout configuration key (e.g. `"content"`, `"folder"`, `"tag"`). This determines which `byPageType` entry in `quartz.config.yaml` provides the layout overrides for this page type.
|
||||
- `frame`: The [[layout#Page Frames|page frame]] to use for this page type. Controls the overall HTML structure (e.g. `"default"`, `"full-width"`, `"minimal"`, or a custom frame provided by your plugin). If not set, defaults to `"default"`. Can be overridden per-page-type via `layout.byPageType.<name>.template` in `quartz.config.yaml`.
|
||||
- `body`: The Quartz component constructor that renders the page body content.
|
||||
|
||||
@@ -5,6 +5,7 @@ import os from "os"
|
||||
import path from "path"
|
||||
import {
|
||||
collectComponents,
|
||||
generateVirtualPages,
|
||||
pageOutputPath,
|
||||
removeStalePageOutput,
|
||||
resolveLayout,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
import { QuartzPageTypePluginInstance } from "../types"
|
||||
import { QuartzComponent } from "../../components/types"
|
||||
import { FilePath, FullSlug } from "../../util/path"
|
||||
import { BuildCtx } from "../../util/ctx"
|
||||
|
||||
const StubA: QuartzComponent = (() => null) as unknown as QuartzComponent
|
||||
const StubB: QuartzComponent = (() => null) as unknown as QuartzComponent
|
||||
@@ -211,3 +213,67 @@ describe("incremental page deletion", () => {
|
||||
assert.strictEqual(await fs.promises.readFile(outputPath, "utf8"), "current")
|
||||
})
|
||||
})
|
||||
|
||||
describe("generateVirtualPages", () => {
|
||||
const makeCtx = () => ({ cfg: { configuration: {} }, virtualPages: [] }) as unknown as BuildCtx
|
||||
const page = (slug: string) => ({ slug: slug as FullSlug, title: slug, data: {} })
|
||||
|
||||
test("accepts sync and async generate, in page type order (#2575)", async () => {
|
||||
const ctx = makeCtx()
|
||||
const entries = await generateVirtualPages(
|
||||
[
|
||||
makePageType({ name: "sync", generate: () => [page("tags/a")] }),
|
||||
makePageType({
|
||||
name: "async",
|
||||
generate: async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 5))
|
||||
return [page("mdx/b")]
|
||||
},
|
||||
}),
|
||||
makePageType({ name: "none" }),
|
||||
],
|
||||
[],
|
||||
ctx,
|
||||
{ head: StubHead },
|
||||
{},
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
entries.map((e) => e.vpSlug),
|
||||
["tags/a", "mdx/b"],
|
||||
)
|
||||
assert.strictEqual(entries[1].vfile.data.slug, "mdx/b")
|
||||
assert.strictEqual(ctx.virtualPages.length, 2)
|
||||
})
|
||||
|
||||
test("keeps the 404 page out of ctx.virtualPages", async () => {
|
||||
const ctx = makeCtx()
|
||||
const entries = await generateVirtualPages(
|
||||
[makePageType({ generate: async () => [page("404")] })],
|
||||
[],
|
||||
ctx,
|
||||
{ head: StubHead },
|
||||
{},
|
||||
)
|
||||
assert.strictEqual(entries.length, 1)
|
||||
assert.strictEqual(ctx.virtualPages.length, 0)
|
||||
})
|
||||
|
||||
test("a failing async generate rejects instead of being skipped", async () => {
|
||||
await assert.rejects(
|
||||
generateVirtualPages(
|
||||
[
|
||||
makePageType({
|
||||
generate: async () => {
|
||||
throw new Error("boom")
|
||||
},
|
||||
}),
|
||||
],
|
||||
[],
|
||||
makeCtx(),
|
||||
{ head: StubHead },
|
||||
{},
|
||||
),
|
||||
/boom/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -138,18 +138,57 @@ export async function removeStalePageOutput(
|
||||
return outputPath
|
||||
}
|
||||
|
||||
export type VirtualEntry = {
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}
|
||||
|
||||
/**
|
||||
* Run every page type's `generate` and turn the virtual pages it returns into processed
|
||||
* content. `generate` may be async (Quartz 5.1+), e.g. to run the transformer chain or
|
||||
* esbuild; page types run one after another in priority order, as before. Virtual pages
|
||||
* (except the 404 page) are added to `ctx.virtualPages`.
|
||||
*/
|
||||
export async function generateVirtualPages(
|
||||
pageTypes: QuartzPageTypePluginInstance[],
|
||||
content: ProcessedContent[],
|
||||
ctx: BuildCtx,
|
||||
defaults: Partial<FullPageLayout>,
|
||||
byPageType: Record<string, Partial<FullPageLayout>>,
|
||||
): Promise<VirtualEntry[]> {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const virtualEntries: VirtualEntry[] = []
|
||||
for (const pt of pageTypes) {
|
||||
if (!pt.generate) continue
|
||||
const virtualPages = await pt.generate({ content, cfg, ctx })
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
for (const vp of virtualPages) {
|
||||
const vpSlug = vp.slug as FullSlug
|
||||
const vpRelativePath = (vpSlug + ".md") as FilePath
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug: vpSlug,
|
||||
relativePath: vpRelativePath,
|
||||
frontmatter: { title: vp.title, tags: [] },
|
||||
...vp.data,
|
||||
})
|
||||
if (vpSlug !== "404") {
|
||||
ctx.virtualPages.push([tree, vfile])
|
||||
}
|
||||
virtualEntries.push({ tree, vfile, layout, vpSlug })
|
||||
}
|
||||
}
|
||||
return virtualEntries
|
||||
}
|
||||
|
||||
/**
|
||||
* Render each virtual page's Body component to HTML and parse it to a hast tree,
|
||||
* populating both the ProcessedContent tree and vfile.data.htmlAst so that
|
||||
* transclusion (e.g. ![[file.canvas]]) can inline the virtual page's content.
|
||||
*/
|
||||
function populateVirtualPageHtmlAst(
|
||||
virtualEntries: Array<{
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}>,
|
||||
virtualEntries: VirtualEntry[],
|
||||
ctx: BuildCtx,
|
||||
allFiles: ProcessedContent[1]["data"][],
|
||||
resources: StaticResources,
|
||||
@@ -203,31 +242,13 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
|
||||
|
||||
// Phase 1: Generate all virtual pages first so their data is available in allFiles
|
||||
// for transclude resolution in renderPage (e.g. ![[file.canvas]], ![[file.base]])
|
||||
const virtualEntries: Array<{
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}> = []
|
||||
for (const pt of pageTypes) {
|
||||
if (!pt.generate) continue
|
||||
const virtualPages = pt.generate({ content, cfg, ctx })
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
for (const vp of virtualPages) {
|
||||
const vpSlug = vp.slug as FullSlug
|
||||
const vpRelativePath = (vpSlug + ".md") as FilePath
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug: vpSlug,
|
||||
relativePath: vpRelativePath,
|
||||
frontmatter: { title: vp.title, tags: [] },
|
||||
...vp.data,
|
||||
})
|
||||
if (vpSlug !== "404") {
|
||||
ctx.virtualPages.push([tree, vfile])
|
||||
}
|
||||
virtualEntries.push({ tree, vfile, layout, vpSlug })
|
||||
}
|
||||
}
|
||||
const virtualEntries = await generateVirtualPages(
|
||||
pageTypes,
|
||||
content,
|
||||
ctx,
|
||||
defaults,
|
||||
byPageType,
|
||||
)
|
||||
|
||||
// Merge virtual page data into allFiles before populating htmlAst so that
|
||||
// Body components rendered during populateVirtualPageHtmlAst can resolve
|
||||
@@ -305,31 +326,13 @@ export const PageTypeDispatcher: QuartzEmitterPlugin<Partial<DispatcherOptions>>
|
||||
}
|
||||
|
||||
// Phase 1: Generate all virtual pages first so their data is available in allFiles
|
||||
const virtualEntries: Array<{
|
||||
tree: ProcessedContent[0]
|
||||
vfile: ProcessedContent[1]
|
||||
layout: FullPageLayout
|
||||
vpSlug: FullSlug
|
||||
}> = []
|
||||
for (const pt of pageTypes) {
|
||||
if (!pt.generate) continue
|
||||
const virtualPages = pt.generate({ content, cfg, ctx })
|
||||
const layout = resolveLayout(pt, defaults, byPageType)
|
||||
for (const vp of virtualPages) {
|
||||
const vpSlug = vp.slug as FullSlug
|
||||
const vpRelativePath = (vpSlug + ".md") as FilePath
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug: vpSlug,
|
||||
relativePath: vpRelativePath,
|
||||
frontmatter: { title: vp.title, tags: [] },
|
||||
...vp.data,
|
||||
})
|
||||
if (vpSlug !== "404") {
|
||||
ctx.virtualPages.push([tree, vfile])
|
||||
}
|
||||
virtualEntries.push({ tree, vfile, layout, vpSlug })
|
||||
}
|
||||
}
|
||||
const virtualEntries = await generateVirtualPages(
|
||||
pageTypes,
|
||||
content,
|
||||
ctx,
|
||||
defaults,
|
||||
byPageType,
|
||||
)
|
||||
|
||||
const allFilesWithVirtual = [...allFiles, ...virtualEntries.map((ve) => ve.vfile.data)]
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ export type PageGenerator = (args: {
|
||||
cfg: GlobalConfiguration
|
||||
ctx: BuildCtx
|
||||
[key: string]: unknown
|
||||
}) => VirtualPage[]
|
||||
}) => VirtualPage[] | Promise<VirtualPage[]>
|
||||
|
||||
/** A function that mutates a HAST tree at render time, when allFiles is available. */
|
||||
export type TreeTransform = (
|
||||
@@ -163,7 +163,7 @@ export interface PageTypePluginEntry {
|
||||
priority?: number
|
||||
fileExtensions?: string[]
|
||||
match: (...args: never[]) => boolean
|
||||
generate?: (...args: never[]) => VirtualPage[]
|
||||
generate?: (...args: never[]) => VirtualPage[] | Promise<VirtualPage[]>
|
||||
layout: string
|
||||
/** Optional page frame name (e.g. "default", "full-width", "minimal"). Defaults to "default". */
|
||||
frame?: string
|
||||
|
||||
Reference in new issue
Block a user