From a33fcef5ca969370ab571b111a95ee211764b5b3 Mon Sep 17 00:00:00 2001 From: Stefan Bauer Date: Mon, 16 Nov 2026 09:32:54 +0100 Subject: [PATCH 1/3] feat(storefront): regions and the table of contents A layout declares regions on page.regions (x-pd-regions) and writes each as {{{page.regions.}}}, null when empty. A placed component goes into one by region="..." on its tag or its schema's x-pd-region, in the page's order; another layout's region is left out, an unknown one stops the page with a did-you-mean. names the filled regions. header, footer, nav and main stay the layout's own landmarks, and a region's content can't bring one. The table of contents is the skin's components/toc: toc: true or a layout's x-pd-toc places the derived one, places it in the markdown with derived or its own links, whose anchors must be headings of the page. --- packages/dev-server/src/markdown.ts | 39 +++- packages/dev-server/src/storefront/derived.ts | 9 +- .../src/storefront/frontmatter-contract.ts | 13 +- packages/dev-server/src/storefront/page.ts | 79 +++++-- packages/dev-server/src/storefront/placed.ts | 76 ++++++- packages/dev-server/src/storefront/regions.ts | 120 ++++++++++ packages/dev-server/src/storefront/toc.ts | 85 +++++++ .../dev-server/test/placed-schema.spec.ts | 4 +- .../dev-server/test/storefront-bench.spec.ts | 5 +- .../dev-server/test/storefront-build.spec.ts | 3 +- .../test/storefront-derived.spec.ts | 6 +- .../dev-server/test/storefront-page.spec.ts | 6 +- .../test/storefront-regions.spec.ts | 214 ++++++++++++++++++ packages/renderer/src/schema-extensions.ts | 10 +- .../renderer/test/schema-extensions.spec.ts | 8 +- storefront-bench/e2e/headings.spec.ts | 6 +- storefront-bench/e2e/playwright.config.ts | 4 +- storefront-bench/e2e/regions.spec.ts | 51 +++++ storefront-bench/e2e/workbench.spec.ts | 2 +- storefront-bench/pages/about.md | 5 + storefront-bench/pages/guides/setup.md | 7 + .../src/patterns/components/toc/toc.hbs | 7 + .../src/patterns/components/toc/toc.json | 7 + .../src/patterns/components/toc/toc.md | 7 + .../patterns/components/toc/toc.schema.json | 21 ++ .../src/patterns/layouts/doc/doc.hbs | 14 +- .../src/patterns/layouts/doc/doc.md | 2 +- .../src/patterns/layouts/doc/doc.schema.json | 6 + storefront-bench/src/styles/layouts/doc.scss | 27 +++ 29 files changed, 779 insertions(+), 64 deletions(-) create mode 100644 packages/dev-server/src/storefront/regions.ts create mode 100644 packages/dev-server/src/storefront/toc.ts create mode 100644 packages/dev-server/test/storefront-regions.spec.ts create mode 100644 storefront-bench/e2e/regions.spec.ts create mode 100644 storefront-bench/src/patterns/components/toc/toc.hbs create mode 100644 storefront-bench/src/patterns/components/toc/toc.json create mode 100644 storefront-bench/src/patterns/components/toc/toc.md create mode 100644 storefront-bench/src/patterns/components/toc/toc.schema.json create mode 100644 storefront-bench/src/styles/layouts/doc.scss diff --git a/packages/dev-server/src/markdown.ts b/packages/dev-server/src/markdown.ts index a9a768f..6cb17e4 100644 --- a/packages/dev-server/src/markdown.ts +++ b/packages/dev-server/src/markdown.ts @@ -29,6 +29,8 @@ import { codeBlock, createMarkdown, fenceLanguage, placeOf } from "./code-blocks import { escapeAttr, escapeHtml } from "./http-utils.js"; import { usePlacedTags, type PlacedBlock } from "./placed-tags.js"; import { placeBlock, type PlacementDeps } from "./storefront/placed.js"; +import { regionLandmarks, type RegionChoice } from "./storefront/regions.js"; +import type { TocAnchor } from "./storefront/toc.js"; import { readSchema, type PlacedProblem } from "./storefront/declared-values.js"; import type { PageHeading } from "./storefront/derived.js"; import { slug, Slugger } from "./storefront/slug.js"; @@ -61,7 +63,23 @@ export type DocEmbed = * the body in its file (a page's frontmatter), so problems point into the file; they are collected here, * with their positions, and every tag that has one renders as a marker instead of the component. */ -export interface DocPlacing { deps: PlacementDeps; lineOffset: number; problems: PlacedProblem[] } +export interface DocPlacing { + deps: PlacementDeps; lineOffset: number; problems: PlacedProblem[]; + /** The page's regions (regions.ts): where a component that names one goes. Without it every component is in the + * body. */ + regions?: DocRegions; +} + +/** The regions of the page being rendered: the choice for each placed component, and what each region holds. */ +export interface DocRegions { + choose(region: string, what: string): RegionChoice; + /** Each region's components' HTML, in the page's order. */ + filled: Map; + /** Set when the page places a . */ + toc: boolean; + /** The #anchors its s link to, to be checked against the page's final headings. */ + tocAnchors: TocAnchor[]; +} /** * A storefront page's images (frame mode only; the workbench's docs keep markdown's own ). Every image needs a @@ -224,9 +242,24 @@ export async function renderDoc( if (placing) { for (const [idx, tok] of tokens.entries()) { if (tok.type !== "pd_component") continue; - const r = await placeBlock(tok.meta as PlacedBlock, placing.deps); + const block = tok.meta as PlacedBlock; + const r = await placeBlock(block, placing.deps, { headings: embed.embed === "frame" ? embed.headings ?? [] : [] }); placing.problems.push(...r.problems); - if (r.html !== undefined && r.problems.length === 0) resolvedPlaced.set(idx, `${r.html}\n`); + if (r.toc && placing.regions) { placing.regions.toc = true; placing.regions.tocAnchors.push(...r.tocAnchors ?? []); } + if (r.html === undefined || r.problems.length) continue; + // A component that names a region goes there, or nowhere when the page's layout hasn't that region. + const choice = r.region !== undefined && placing.regions ? placing.regions.choose(r.region, r.regionFrom ?? "") : { to: "body" as const }; + if (choice.to === "body") { resolvedPlaced.set(idx, `${r.html}\n`); continue; } + resolvedPlaced.set(idx, ""); + if (choice.to === "problem") { placing.problems.push({ at: block.root!.at, message: choice.message }); continue; } + if (choice.to === "none") continue; + const brought = regionLandmarks(r.html); + if (brought.length) { + placing.problems.push({ at: block.root!.at, message: `${r.regionFrom ?? `<${block.root!.name}>`}: what it renders would bring ${brought.join(" and ")} ` + + `into the region "${choice.region}": the page's landmarks are the layout's` }); + continue; + } + placing.regions!.filled.set(choice.region, [...placing.regions!.filled.get(choice.region) ?? [], r.html]); } } diff --git a/packages/dev-server/src/storefront/derived.ts b/packages/dev-server/src/storefront/derived.ts index c857e5f..2bbfd13 100644 --- a/packages/dev-server/src/storefront/derived.ts +++ b/packages/dev-server/src/storefront/derived.ts @@ -43,13 +43,15 @@ export interface DerivedPage { terms: TermPage[] | null; /** A folder's index.md: its pages rendered through the view it names (views.ts), as HTML; null on any other page. */ listing: string | null; + /** The layout's regions (regions.ts), by name: each one's HTML, null when the page puts nothing there. */ + regions: Record; } /** A tag or category with a generated page, as its page and its index get it. */ export interface TermPage { key: string; label: string; description: string | null; route: string; count: number } /** A value with no keys of its own; an object with exactly these fields; a list of one shape. */ -export type Shape = "value" | { fields: Record } | { items: Shape }; +export type Shape = "value" | { fields: Record } | { items: Shape } | { map: Shape }; const LINK: Shape = { fields: { route: "value", title: "value" } }; /** A tag or a category (categories.ts). */ @@ -81,11 +83,12 @@ export const PAGE_SHAPE: { fields: Record } = { term: TERM_PAGE, terms: { items: TERM_PAGE }, listing: "value", + regions: { map: "value" }, }, }; /** The sub-keys of `page` Pattern Dump fills today. Each later step adds the keys it derives. */ -export const FILLED: readonly (keyof DerivedPage)[] = ["headings", "section", "breadcrumbs", "prev", "next", "created", "updated", "children", "date", "tags", "categories", "term", "terms", "listing"]; +export const FILLED: readonly (keyof DerivedPage)[] = ["headings", "section", "breadcrumbs", "prev", "next", "created", "updated", "children", "date", "tags", "categories", "term", "terms", "listing", "regions"]; /** Sub-keys Pattern Dump filled once and no longer does, with what to declare instead. */ export const RETIRED: Readonly> = { @@ -170,6 +173,8 @@ export function outsideShape(value: unknown, shape: Shape, path: string): string return value.flatMap((v, i) => outsideShape(v, item, `${path}[${i}]`)); } if (!isObject(value)) return []; + // Any key, each value of one shape (page.regions: the layout's own region names). + if (typeof shape === "object" && "map" in shape) return Object.entries(value).flatMap(([key, v]) => outsideShape(v, shape.map, `${path}.${key}`)); const fields = typeof shape === "object" && "fields" in shape ? shape.fields : {}; return Object.entries(value).flatMap(([key, v]) => Object.hasOwn(fields, key) ? outsideShape(v, fields[key]!, `${path}.${key}`) : [`${path}.${key}`]); diff --git a/packages/dev-server/src/storefront/frontmatter-contract.ts b/packages/dev-server/src/storefront/frontmatter-contract.ts index 5b51bdd..6fa1712 100644 --- a/packages/dev-server/src/storefront/frontmatter-contract.ts +++ b/packages/dev-server/src/storefront/frontmatter-contract.ts @@ -1,12 +1,12 @@ // A storefront page's frontmatter, checked against the layout it uses. // -// Thirteen keys belong to the build, not to a layout: `layout` (which layout; when absent, the `childLayout` of the +// Fourteen keys belong to the build, not to a layout: `layout` (which layout; when absent, the `childLayout` of the // nearest folder above the page whose index.md sets one, else `page`), `childLayout` (on a folder's index.md), `order` // (where in the nav), the page's search and link-preview keys — `redirectFrom` (old routes that forward // here), `index` (`false` keeps the page out of search engines and the sitemap) and `image` (its link-preview // image, a raster file in the assets; checked against the files in page-image.ts) — and its listing keys // (listing-keys.ts): `date`, `updated`, `tags`, `categories` (declared in storefront.categories), `draft`, and `sort` and `view` on a -// folder's index.md. A layout cannot declare any of the thirteen. Every other key must be declared by the chosen layout's schema — the +// folder's index.md, and `toc` (the table of contents, toc.ts). A layout cannot declare any of the fourteen. Every other key must be declared by the chosen layout's schema — the // `.schema.json` beside `layouts//.hbs` — and is coerced to the type the schema // declares. Nothing is inferred: a key the schema does not declare is an error, and a layout with no // schema declares nothing. Four more keys are filled by the storefront itself (`body`, the rendered @@ -26,7 +26,7 @@ import { categoryIndex, termIndex, TERM_WORDS, type CategoryIndex, type TermInde import { declaredQueries } from "./query.js"; /** Keys the build owns: they are read by the storefront, never passed to the layout. */ -export const RESERVED_KEYS = ["layout", "childLayout", "order", "redirectFrom", "index", "image", "date", "updated", "tags", "categories", "draft", "sort", "view"] as const; +export const RESERVED_KEYS = ["layout", "childLayout", "order", "redirectFrom", "index", "image", "date", "updated", "tags", "categories", "draft", "sort", "view", "toc"] as const; /** Keys the storefront fills for every page: a page cannot set them. */ export const ASSEMBLY_KEYS = ["body", "nav", "site", "page"] as const; @@ -44,6 +44,8 @@ export interface BuildKeys { redirectFrom?: string[]; /** false: noindex, and no sitemap entry. */ index?: boolean; + /** true: the table of contents in its region (toc.ts); false: none, whatever the layout says. */ + toc?: boolean; /** A /assets/… path. */ image?: string; /** The page's date, YYYY-MM-DD. */ @@ -77,6 +79,11 @@ function checkBuildKeys(values: Record, path: string, + `a route: each old route starts and ends with "/", such as "/old/page/", with no query or fragment`); } else if (list.length) out.redirectFrom = list as string[]; } + const toc = values["toc"]; + if (toc !== undefined) { + if (toc === "true" || toc === "false") out.toc = toc === "true"; + else at("toc", `toc must be true or false`); + } const index = values["index"]; if (index !== undefined) { if (index === "true" || index === "false") out.index = index === "true"; diff --git a/packages/dev-server/src/storefront/page.ts b/packages/dev-server/src/storefront/page.ts index fb1d802..a797df0 100644 --- a/packages/dev-server/src/storefront/page.ts +++ b/packages/dev-server/src/storefront/page.ts @@ -17,9 +17,12 @@ import { createHeightFitter, generationBehind, PD_ROUTES, type DiscoveryMap, typ import { frontmatterBody, frontmatterBodyOffset, readFrontmatterStrict } from "../frontmatter.js"; import { escapeAttr, escapeHtml } from "../http-utils.js"; import type { SearchRecord } from "./search.js"; +import { chooseRegion, layoutRegions, regionLandmarks, skinRegions } from "./regions.js"; +import { derivedToc, TOC_ID, tocAnchorProblems } from "./toc.js"; +import { placeTocItems, type PlacementDeps } from "./placed.js"; import { isHelperNameProblem, itemsWrittenAsText, readProseSlot, renderPlainTemplate } from "@pattern-dump/renderer"; import { basename } from "node:path"; -import { renderDoc, type ProseImages } from "../markdown.js"; +import { renderDoc, type DocRegions, type ProseImages } from "../markdown.js"; import { readSchema, type PlacedProblem } from "./declared-values.js"; import { ASSEMBLY_KEYS, checkPageFrontmatter, RESERVED_KEYS } from "./frontmatter-contract.js"; import { DEFAULT_LAYOUT, NOT_FOUND_FILE, type PageFile, type PageModel } from "./pages.js"; @@ -186,7 +189,8 @@ function exampleHeightCheck(): string { /** `base`: the path the site is published under, written as `` on every page of the site * ("/" at a host's root), so a skin's own script can build a URL under it; undefined for a page that is not the * site's (a page with problems). */ -function document(head: string, body: string, live: PageAssembly["live"], lang = "en", base?: string): string { +/** `regions`: the filled regions of a page whose layout declares regions (regions.ts), on as data-pd-regions. */ +function document(head: string, body: string, live: PageAssembly["live"], lang = "en", base?: string, regions?: readonly string[]): string { return ` @@ -195,7 +199,7 @@ function document(head: string, body: string, live: PageAssembly["live"], lang = ${base !== undefined ? ` ` : ""}${head} - + ${body} ${live ? liveScript(live.wsPort, live.generation) : ""} @@ -411,6 +415,13 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem const proseSlot = readProseSlot(layoutSchema); const imageLookup = a.images ? await a.images() : undefined; + // The layout's regions (regions.ts), the skin's, and whether the page shows the table of contents (toc.ts). + const regionDecl = layoutRegions(layoutSchema, checked.layoutId); + problems.push(...regionDecl.problems); + const skin = await skinRegions(a.discoveryMap); + const wantsToc = checked.build.toc ?? regionDecl.toc; + const tocAt = page.frontmatter.lines["toc"]; + const tocWhat = checked.build.toc === true ? `toc: true` : `${checked.layoutId} (page.regions, x-pd-toc)`; /** The page's markdown, rendered; its headings' anchors never take one of `takenIds`. */ /** The components the page's pd- tags placed (the last rendering of its body). */ const placedIds = new Set(); @@ -423,6 +434,16 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem placedIds.clear(); const placedProblems: PlacedProblem[] = []; const headings: PageHeading[] = []; + const regions: DocRegions = { + choose: (region, what) => chooseRegion(region, what, checked.layoutId, regionDecl.regions, skin), filled: new Map(), toc: false, tocAnchors: [], + }; + const deps: PlacementDeps = { + discoveryMap: a.discoveryMap, handleMap: a.handleMap, composition: a.composition, + // Each component rendered for a placement: the page loads its behaviour scripts (page-head.ts). + render: input => { placedIds.add(input.component.split("~")[0]!); return a.render(input); }, + schemaOf: async id => (await readSchema(a.discoveryMap.get(id)?.schemaPath)).schema, + shown: a.shown, + }; const body = await renderDoc( frontmatterBody(source), (id, variant) => a.render({ component: id, variant }).then(r => r.html), @@ -430,20 +451,29 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem { embed: "frame", workbenchUrl: a.workbenchUrl, problems: docProblems, headings, takenIds, ...(prose ? { prose } : {}), // Components placed with values (pd- tags): checked against their schemas, rendered into the page. - placed: { - lineOffset: frontmatterBodyOffset(source), - problems: placedProblems, - deps: { - discoveryMap: a.discoveryMap, handleMap: a.handleMap, composition: a.composition, - // Each component rendered for a placement: the page loads its behaviour scripts (page-head.ts). - render: input => { placedIds.add(input.component.split("~")[0]!); return a.render(input); }, - schemaOf: async id => (await readSchema(a.discoveryMap.get(id)?.schemaPath)).schema, - shown: a.shown, - }, - }, + placed: { lineOffset: frontmatterBodyOffset(source), problems: placedProblems, deps, regions }, }, ); - return { body, headings, docProblems, placedProblems, imageProblems: prose?.problems ?? [] }; + // The table of contents the page or its layout asks for, with the derived items, first in its region; none when the + // page places a itself, or has no heading for it. + const items = derivedToc(headings); + if (wantsToc && !isNotFound && !regions.toc && items.length) { + const at = { line: tocAt ?? 1, column: 1 }; + const r = await placeTocItems(items, at, tocWhat, deps); + placedProblems.push(...r.problems); + if (r.html !== undefined && !r.problems.length) { + const choice = r.region === undefined + ? { to: "problem" as const, message: `${tocWhat}: ${TOC_ID} names no region (x-pd-region at its schema's root), so the table of contents has no place on the page` } + : chooseRegion(r.region, r.regionFrom ?? tocWhat, checked.layoutId, regionDecl.regions, skin); + if (choice.to === "problem") placedProblems.push({ at, message: choice.message }); + else if (choice.to === "region") { + const brought = regionLandmarks(r.html); + if (brought.length) placedProblems.push({ at, message: `${TOC_ID}: what it renders would bring ${brought.join(" and ")} into the region "${choice.region}": the page's landmarks are the layout's` }); + else regions.filled.set(choice.region, [r.html, ...regions.filled.get(choice.region) ?? []]); + } + } + } + return { body, headings, docProblems, placedProblems, imageProblems: prose?.problems ?? [], regions }; }; const first = await renderBody(); problems.push(...first.docProblems.map(p => `${page.path}: ${p}`)); @@ -614,12 +644,16 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem ...(collections ? { collections: collections.collections } : {}), ...(site.categories ? { categories: model.categories.list } : {}), }; + /** The layout's regions as it gets them: each one's HTML, null when empty. */ + const regionsOf = (filled: ReadonlyMap): Record => + Object.fromEntries(regionDecl.regions.map(r => [r, filled.get(r)?.length ? filled.get(r)!.join("\n") : null])); + let currentRegions = first.regions.filled; const dataFor = (body: string, headings: PageHeading[]) => ({ ...withDeclaredAbsentAsNull(checked.values, layoutDeclared, ["body", "nav", "site", "page"]), body, nav: markCurrent(model.nav, route), site: siteData, - ...(pageDeclaration.declared ? { page: pageValue(pageDeclaration.declared, { headings, ...positionOf(route, model), ...dates, ...listing, ...queryValues } as Partial) } : {}), + ...(pageDeclaration.declared ? { page: pageValue(pageDeclaration.declared, { headings, ...positionOf(route, model), ...dates, ...listing, ...queryValues, regions: regionsOf(currentRegions) } as Partial) } : {}), }); // A template that fails to render (a helper it calls that is not registered, say) is a page problem // like any other, listed and escaped, never an unhandled 500. @@ -633,6 +667,8 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem const isFailed = (r: Awaited> | AssembledPage): r is AssembledPage => "status" in r; let rendered = await renderLayout(first.body, first.headings); let finalBody = first.body; + let finalHeadings = first.headings; + let finalRegions = first.regions; if (isFailed(rendered)) return rendered; // A layout field named like a registered helper can never be shown by its name: the page fails, as the // workbench shows the same SCHEMA_INVALID on the layout. @@ -647,6 +683,9 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem const colliding = collidingHeadings(first.headings, layoutIds); if (colliding.length) { const second = await renderBody(layoutIds); + currentRegions = second.regions.filled; + finalHeadings = second.headings; + finalRegions = second.regions; rendered = await renderLayout(second.body, second.headings); finalBody = second.body; if (isFailed(rendered)) return rendered; @@ -664,6 +703,11 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem } } + // A 's #anchors, against the page's headings as they finally are (a suffix can still come from the layout). + const finalRender = colliding.length ? finalRegions : first.regions; + const badAnchors = tocAnchorProblems(finalRender.tocAnchors, finalHeadings); + if (badAnchors.length) return fail(badAnchors.map(p => `${page.path}:${p.at.line}:${p.at.column}: ${p.message}`)); + const html = rendered.html; // The skin's head partial: the site's values, and body and nav as null so no sample of them can show. let headExtra = ""; @@ -776,7 +820,8 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem route, title, body: finalBody, section: collectionOf(route, model), tags: (entry?.tags ?? []).map(t => t.label), categories: (entry?.categories ?? []).map(c => c.label), teaser: entry?.description ?? null, lang: a.lang ?? "en", }; - return { status: isNotFound ? 404 : 200, html: document(head, `${html}\n${fitterScript()}${html.includes(`class="shiki-container"`) ? `\n${copyScript()}` : ""}`, a.live, a.lang, a.basePath ?? "/"), problems: [], notes, + return { status: isNotFound ? 404 : 200, html: document(head, `${html}\n${fitterScript()}${html.includes(`class="shiki-container"`) ? `\n${copyScript()}` : ""}`, a.live, a.lang, a.basePath ?? "/", + regionDecl.regions.length ? regionDecl.regions.filter(r => currentRegions.get(r)?.length) : undefined), problems: [], notes, ...(search ? { search } : {}) }; } diff --git a/packages/dev-server/src/storefront/placed.ts b/packages/dev-server/src/storefront/placed.ts index c6f8fe3..d7e9e8c 100644 --- a/packages/dev-server/src/storefront/placed.ts +++ b/packages/dev-server/src/storefront/placed.ts @@ -17,7 +17,10 @@ import { createMarkdown } from "../code-blocks.js"; import type { DiscoveryMap, Render } from "@pattern-dump/contracts"; import { checkSchemaExtensions, isHelperNameProblem, unescapedOutputs } from "@pattern-dump/renderer"; import type { CompositionRegistry } from "../composition.js"; -import { toPlaced, type PlacedBlock, type PlacedResolver } from "../placed-tags.js"; +import { toPlaced, type PlacedBlock, type PlacedResolver, type PlacedTag } from "../placed-tags.js"; +import type { PageHeading } from "./derived.js"; +import { defaultRegion } from "./regions.js"; +import { TOC_ID, TOC_TAG, tocItems, type TocAnchor, type TocItem } from "./toc.js"; import { checkPlaced, type ObjectSchema, type PlacedProblem, type PropertySchema } from "./declared-values.js"; import { includeTree } from "./sample-data.js"; @@ -153,18 +156,51 @@ async function schemaProblems(id: string, at: PlacedProblem["at"], deps: Placeme return problems; } -/** A claimed `pd-` block: its HTML, or every problem (nothing is rendered when there is one). */ -export async function placeBlock(block: PlacedBlock, deps: PlacementDeps): Promise<{ html?: string; problems: PlacedProblem[] }> { +/** A placed block, rendered: its HTML (none when it has a problem), the region it asks for, and what asks. */ +export interface PlacedResult { + html?: string; + problems: PlacedProblem[]; + /** The region its tag names (region="..."), else its component's default (x-pd-region); undefined for the body. */ + region?: string; + /** How messages name where the region came from: the tag, or the component's default. */ + regionFrom?: string; + /** A : the page's table of contents. */ + toc?: boolean; + /** A 's #anchors, checked once the page's headings are final. */ + tocAnchors?: TocAnchor[]; +} + +/** A claimed `pd-` block: its HTML, or every problem (nothing is rendered when there is one). `headings`: the page's, + * for a . */ +export async function placeBlock(block: PlacedBlock, deps: PlacementDeps, page: { headings?: readonly PageHeading[] } = {}): Promise { const problems = [...block.problems]; if (problems.length || !block.root) return { problems }; + // region="..." on the root tag is Pattern Dump's: where the component goes, never one of its values. + const regionAttr = block.root.attrs.find(a => a.name === "region"); + const root = { ...block.root, attrs: block.root.attrs.filter(a => a.name !== "region") }; + if (regionAttr && (regionAttr.value === null || regionAttr.value === "")) { + return { problems: [{ at: regionAttr.at, message: `<${block.root.name}>: region names a region of the layout, such as region="sidebar"` }] }; + } + const tagRegion = regionAttr?.value ?? undefined; + const fromTag = `<${block.root.name} region="${tagRegion}">`; + if (block.root.name === TOC_TAG) return placeToc(block.root, deps, page.headings ?? [], tagRegion, fromTag); const resolver: PlacedResolver = { idOf: handle => deps.handleMap.get(handle), handleOf: id => [...deps.handleMap].find(([, v]) => v === id)?.[0] ?? id, handles: () => [...deps.handleMap.keys()], schemaOf: deps.schemaOf, }; - const { id, values } = await toPlaced(block.root, resolver, problems); + const { id, values } = await toPlaced(root, resolver, problems); if (!id || !values) return { problems }; + const schema = await deps.schemaOf(id); + if (regionAttr && schema?.properties && Object.hasOwn(schema.properties, "region")) { + return { problems: [{ at: regionAttr.at, message: `<${block.root.name}>: region="..." is Pattern Dump's (the layout's region the component goes into), ` + + `and ${id} declares a property "region" as well: rename that property to place it in a region` }] }; + } + const own = defaultRegion(schema, id); + if (own.problem) return { problems: [{ at: block.root.at, message: own.problem }] }; + const region = tagRegion ?? own.region; + const regionFrom = tagRegion !== undefined ? fromTag : `<${block.root.name}> (${id}'s default region, x-pd-region)`; const broken = await schemaProblems(id, block.root.at, deps); if (broken.length) return { problems: [...problems, ...broken] }; const checked = await checkPlaced(id, values, `<${block.root.name}>`, { @@ -174,12 +210,40 @@ export async function placeBlock(block: PlacedBlock, deps: PlacementDeps): Promi markdown: text => contentMd.render(text, { pdCodeBlocks: { storefront: true } }), }); problems.push(...checked.problems, ...await unsafeOutputs(id, block.root.at, deps), ...await sampleDataProblems(id, block.root.at, deps)); - if (problems.length) return { problems }; + const where = region !== undefined ? { region, regionFrom } : {}; + if (problems.length) return { problems, ...where }; // A placement that fails to render (an image that can't be served as variants, a helper that isn't registered) // is a problem of the page at the tag, listed and escaped like any other, never an unhandled 500. try { - return { html: (await deps.render({ component: id, data: checked.value })).html, problems }; + return { html: (await deps.render({ component: id, data: checked.value })).html, problems, ...where }; } catch (e) { return { problems: [{ at: block.root.at, message: `<${block.root.name}>: ${e instanceof Error ? e.message : String(e)}` }] }; } } + +/** The table of contents (toc.ts), placed with `items`: from the tag's links, or derived from the page's headings. */ +export async function placeTocItems(items: TocItem[], at: PlacedProblem["at"], what: string, deps: PlacementDeps, tagRegion?: string, fromTag?: string): Promise { + if (!deps.discoveryMap.has(TOC_ID)) { + return { problems: [{ at, message: `${what} places the table of contents, which is the skin's ${TOC_ID}, and the skin has none: add it (it gets items: [{ text, href, level }])` }] }; + } + const schema = await deps.schemaOf(TOC_ID); + const problems: PlacedProblem[] = []; + if (!schema?.properties?.["items"]) problems.push({ at, message: `${TOC_ID}: its schema declares no "items", the list of { text, href, level } it shows` }); + const own = defaultRegion(schema, TOC_ID); + if (own.problem) problems.push({ at, message: own.problem }); + problems.push(...await unsafeOutputs(TOC_ID, at, deps), ...await sampleDataProblems(TOC_ID, at, deps)); + const region = tagRegion ?? own.region; + const where = region !== undefined ? { region, regionFrom: tagRegion !== undefined ? fromTag! : `${what} (${TOC_ID}'s default region, x-pd-region)` } : {}; + if (problems.length) return { problems, toc: true, ...where }; + try { + return { html: (await deps.render({ component: TOC_ID, data: { items } })).html, problems, toc: true, ...where }; + } catch (e) { + return { problems: [{ at, message: `${TOC_ID}: ${e instanceof Error ? e.message : String(e)}` }], toc: true }; + } +} + +async function placeToc(tag: PlacedTag, deps: PlacementDeps, headings: readonly PageHeading[], tagRegion: string | undefined, fromTag: string): Promise { + const read = tocItems(tag, headings); + if (read.problems.length) return { problems: read.problems, toc: true }; + return { ...await placeTocItems(read.items, tag.at, `<${TOC_TAG}>`, deps, tagRegion, fromTag), tocAnchors: read.anchors }; +} diff --git a/packages/dev-server/src/storefront/regions.ts b/packages/dev-server/src/storefront/regions.ts new file mode 100644 index 0000000..fc4a752 --- /dev/null +++ b/packages/dev-server/src/storefront/regions.ts @@ -0,0 +1,120 @@ +// Regions: named places in a layout, besides the body, that a page's placed components can go into. +// +// - A layout declares them on page.regions: `"regions": { "x-pd-regions": ["sidebar"], "x-pd-toc": true }`, and +// writes each as `{{{page.regions.sidebar}}}`: its HTML, or null when the page puts nothing there, so `{{#if}}` can +// leave the element out. `x-pd-toc` shows the table of contents on its pages (toc.ts) unless a page says +// `toc: false`. A page whose layout declares regions says which hold something on its : +// `data-pd-regions="sidebar"`, so a skin can switch its grid without :has(). +// - A component names its default region at its schema's root (`"x-pd-region": "sidebar"`); `region="sidebar"` on a +// placed root tag wins over it. In a region, components keep the page's order. +// - A region another layout of the skin has, and this one doesn't, is left out without a message: some layouts have +// a sidebar, some don't. A region no layout has is a typo, and the page fails with a "did you mean". +// - The landmarks outside the content are the layout's own: header, footer, nav and main can't be regions (RESERVED), +// and a region's content can't bring a main, banner or contentinfo of its own. + +import { suggest } from "@pattern-dump/config"; +import type { DiscoveryMap } from "@pattern-dump/contracts"; +import { readSchema } from "./declared-values.js"; + +/** The layout's own landmarks: never a region a page can fill. One list, to be opened up deliberately. */ +export const RESERVED_REGIONS: readonly string[] = ["header", "footer", "nav", "main"]; + +/** The page sub-key that holds a layout's regions. */ +export const REGIONS_KEY = "regions"; +const NAME = /^[a-z][a-z0-9-]*$/; + +type Obj = Record; +const isObject = (v: unknown): v is Obj => typeof v === "object" && v !== null && !Array.isArray(v); + +/** What a layout declares on page.regions. */ +export interface LayoutRegions { + /** Its regions, in its order; empty when it declares none. */ + regions: string[]; + /** Whether its pages show the table of contents by default (x-pd-toc). */ + toc: boolean; + problems: string[]; +} + +/** page.regions of a layout's schema (`schema`), read; `layoutId` names it in messages. */ +export function layoutRegions(schema: unknown, layoutId: string): LayoutRegions { + const page = isObject(schema) && isObject(schema["properties"]) ? (schema["properties"] as Obj)["page"] : undefined; + const declared = isObject(page) && isObject(page["properties"]) ? (page["properties"] as Obj)[REGIONS_KEY] : undefined; + if (declared === undefined) return { regions: [], toc: false, problems: [] }; + const at = `${layoutId} (page.${REGIONS_KEY})`; + if (!isObject(declared)) return { regions: [], toc: false, problems: [`${at}: declare the layout's regions as { "x-pd-regions": ["sidebar"] }`] }; + const problems: string[] = []; + const list = declared["x-pd-regions"]; + const regions: string[] = []; + if (!Array.isArray(list) || list.some(r => typeof r !== "string")) { + problems.push(`${at}: "x-pd-regions" is a list of region names, such as ["sidebar"]`); + } else { + for (const name of list as string[]) { + if (RESERVED_REGIONS.includes(name)) problems.push(`${at}: ${name} is reserved for the layout's own landmark: write it in the layout, and name the region otherwise`); + else if (!NAME.test(name)) problems.push(`${at}: "${name}" is not a region name: lowercase letters, digits and hyphens, starting with a letter`); + else if (regions.includes(name)) problems.push(`${at}: "${name}" is listed twice`); + else regions.push(name); + } + } + const toc = declared["x-pd-toc"]; + if (toc !== undefined && typeof toc !== "boolean") problems.push(`${at}: "x-pd-toc" is true or false`); + const other = Object.keys(declared).filter(k => k !== "x-pd-regions" && k !== "x-pd-toc" && k !== "description"); + if (other.length) problems.push(`${at}: ${other.map(k => `"${k}"`).join(", ")}: page.${REGIONS_KEY} declares only "x-pd-regions" and "x-pd-toc" (the regions' shape is Pattern Dump's)`); + return { regions, toc: toc === true, problems }; +} + +/** Every region a layout of the skin declares, with the layouts that have it. */ +export async function skinRegions(discoveryMap: DiscoveryMap): Promise> { + const out = new Map(); + for (const [id, entry] of [...discoveryMap].sort(([a], [b]) => a < b ? -1 : 1)) { + if (!/^layouts\/[^/~]+$/.test(id)) continue; + for (const r of layoutRegions((await readSchema(entry.schemaPath)).schema, id).regions) out.set(r, [...out.get(r) ?? [], id]); + } + return out; +} + +/** Where a placed component goes: the body, a region of the page's layout, or nowhere (another layout's region). */ +export type RegionChoice = { to: "body" } | { to: "region"; region: string } | { to: "none" } | { to: "problem"; message: string }; + +/** Where `name` (a tag's region, else the component's default; undefined for neither) puts a component on a page + * whose layout is `layoutId` with `regions`, in a skin whose layouts have `skin`. `what` names the tag or default. */ +export function chooseRegion(name: string | undefined, what: string, layoutId: string, regions: readonly string[], skin: ReadonlyMap): RegionChoice { + if (name === undefined) return { to: "body" }; + const offers = regions.length ? `${layoutId} offers ${regions.map(r => `"${r}"`).join(", ")}` : `${layoutId} has no regions`; + if (RESERVED_REGIONS.includes(name)) { + return { to: "problem", message: `${what}: the ${name} belongs to the layout, so no component goes into it (${offers})` }; + } + if (regions.includes(name)) return { to: "region", region: name }; + if (skin.has(name)) return { to: "none" }; + const known = [...skin.keys()].sort(); + const near = suggest(name, known); + return { to: "problem", message: `${what}: region "${name}" is no layout's region${near ? `: did you mean "${near}"?` : ""} ` + + `(${known.length ? `the skin's regions are ${known.map(r => `"${r}"`).join(", ")}` : "the skin's layouts declare none"})` }; +} + +/** The region names a component's schema gives as its default (`x-pd-region`), or a problem. */ +export function defaultRegion(schema: unknown, componentId: string): { region?: string; problem?: string } { + if (!isObject(schema) || schema["x-pd-region"] === undefined) return {}; + const r = schema["x-pd-region"]; + return typeof r === "string" ? { region: r } : { problem: `${componentId}: "x-pd-region" is a region's name, such as "sidebar"` }; +} + +const SECTIONING = new Set(["article", "aside", "nav", "section"]); +const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]); + +/** The landmarks `html` (a region's content) would bring to the page: a main, a banner or a contentinfo. */ +export function regionLandmarks(html: string): string[] { + const found: string[] = []; + const open: string[] = []; + for (const m of html.replace(//g, "").matchAll(/<(\/?)([a-zA-Z][\w-]*)([^>]*)>/g)) { + const [, close, rawName, attrs] = m; + const name = rawName!.toLowerCase(); + if (close) { const i = open.lastIndexOf(name); if (i >= 0) open.length = i; continue; } + const role = /\srole\s*=\s*["']?([a-z]+)/i.exec(attrs!)?.[1]?.toLowerCase(); + const scoped = open.some(t => SECTIONING.has(t)); + if (name === "main" || role === "main") found.push("a main landmark"); + else if (role === "banner" || (name === "header" && !scoped && role === undefined)) found.push("a banner (a
outside article, aside, nav and section)"); + else if (role === "contentinfo" || (name === "footer" && !scoped && role === undefined)) found.push("a contentinfo (a