diff --git a/CHANGELOG.md b/CHANGELOG.md index abb0d47..defa44e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,9 +19,25 @@ clock), with every page under a folder whose `index.md` is dated so. A site with such a page builds without it now. `pd dev` shows it, and the report names it: `scheduled: 1 held back (articles/launch.md until 2026-12-01)`. - `updated` and `categories` are now keys the build owns: a layout's schema that declares either must rename it. +- `childLayout` and `view` are keys the build owns too, so the same holds for them. ### Added +- `childLayout:` on a folder's `index.md`: the layout of the pages under it that name none. The nearest folder that + sets one wins, and a page's own `layout:` wins over it. A `childLayout` that names no layout fails the `index.md` + and each page that takes it, and every problem about a page's layout names where the layout came from. The + workbench lists a layout's pages in its Relationships tab, each with where its layout came from, and `/api/pages` + gives `layoutFrom`. +- A listing's card: `x-pd-card` names the component each page of a listing is shown as (on a layout's + `page.children`, or a view's `entries`). Every page in the listing is checked against the card's schema: a field + the card requires that a page doesn't have fails the listing, naming the page. A card declares only fields a + listing's page has, and its sample data may set only those. +- Listing views: `view: grid` on a folder's `index.md` shows its listing through `views/grid`, a component in the + skin's style guide (Pattern Dump has none of its own). The layout writes `{{{page.listing}}}`; the view gets the + pages as `entries`, and names its card, so each view's required fields are checked on their own. A view that + doesn't exist, a listing that names none and a view on a page with no listing are problems. +- The website starter (`pd init --storefront`) ships four plain views with their cards: `list`, `grid`, `featured` + and `compact`. Its articles listing uses `view: list`. - `updated:` on a storefront page, its last real change: `page.updated`, JSON-LD `dateModified`, `article:modified_time` on an article, and the sitemap's `lastmod`. Checked: a real date, not before `date`. - Categories, independent of folders: `storefront.categories` declares them (key, label, optional description, and diff --git a/apps/dev-ui/src/inspector/panel.ts b/apps/dev-ui/src/inspector/panel.ts index 7a9f359..2946f2b 100644 --- a/apps/dev-ui/src/inspector/panel.ts +++ b/apps/dev-ui/src/inspector/panel.ts @@ -145,6 +145,12 @@ export async function renderPanel(): Promise { // Top-level composition groups. appendComponentGroup("Uses", relAvail.uses, section); appendComponentGroup("Used by", relAvail.usedBy, section); + // A layout of a project with a website: the pages that render with it, and where each got its layout. + if (relAvail.pages) { + appendPlainGroup("Pages", relAvail.pages.map(p => `${p.path} (${ + p.source === "own" ? "its own layout" : p.source === "default" ? "the default layout" : `childLayout of ${p.from ?? "its folder"}` + })`), section); + } // Style umbrella: groups Style uses + Style modules under a shared heading. const styleUmbrella = document.createElement("div"); diff --git a/docs/guide/storefront.md b/docs/guide/storefront.md index f4f6e34..8a33096 100644 --- a/docs/guide/storefront.md +++ b/docs/guide/storefront.md @@ -199,7 +199,8 @@ lede: Three folders make a site. | Key | | |---|---| -| `layout` | The layout the page renders with: `layouts/` in the skin. `page` when it has none | +| `layout` | The layout the page renders with: `layouts/` in the skin. Without it, its folder's `childLayout`, else `page`. See [A folder's default layout](#a-folders-default-layout) | +| `childLayout` | On a folder's `index.md` only: the layout of the pages under it that name none. See [A folder's default layout](#a-folders-default-layout) | | `order` | Its position in the navigation, see [Pages](#pages) | | `image` | Its link-preview image: a raster file in the assets (PNG, JPEG, GIF or WebP), such as `/assets/images/setup.png`. An SVG, or any file that isn't one of those (read from its bytes, not its name), is a problem. Without it, `storefront.image` | | `index` | `false` keeps the page out of search engines: `noindex`, and no sitemap entry | @@ -210,10 +211,11 @@ lede: Three folders make a site. | `categories` | One category or a list, each declared in `storefront.categories` (or an old key of one), none twice: `categories: [guides]`. See [Categories](#categories) | | `draft` | `true` shows the page in `pd dev` and leaves it out of `pd build`. See [Drafts](#drafts) | | `sort` | On a folder's `index.md` only: `date` lists the folder's pages newest first; `order`, the default, in the folder's order | +| `view` | On a folder's `index.md` only: the view its listing is shown in, `views/` in the skin. See [Listing views](#listing-views) | | any other key | Must be declared by the layout's schema | -`layout`, `order`, `image`, `index`, `redirectFrom`, `date`, `updated`, `tags`, `categories`, `draft` and `sort` -belong to the build: they never reach the layout as keys of their own, and a layout's schema may not declare any of +`layout`, `childLayout`, `order`, `image`, `index`, `redirectFrom`, `date`, `updated`, `tags`, `categories`, `draft`, +`sort` and `view` belong to the build: they never reach the layout as keys of their own, and a layout's schema may not declare any of them (a layout shows them through `page.date`, `page.updated`, `page.tags` and `page.categories`). **The layout's schema is the frontmatter contract.** A layout is a component, and its @@ -230,6 +232,32 @@ page fails when: Frontmatter is a small fixed grammar, not full YAML: one level of `key: value` pairs and lists. +### A folder's default layout + +With many pages in a folder, `childLayout` on its `index.md` saves writing `layout:` on each, and a forgotten line +can no longer give a page the wrong layout: + +```md +--- +title: Articles +layout: listing +childLayout: article +--- +``` + +- **A page without its own `layout:`** takes the `childLayout` of the nearest folder above it that sets one; without + any, `page`. Its own `layout:` always wins. +- **A folder's `index.md` is a page of its parent folder:** its own `childLayout` is for the pages under it, and it + takes its layout from its parent's, as any page there does. +- **Checked:** a `childLayout` that names no layout fails on the `index.md`, at its line, and on every page that + takes it. Each page is checked against the schema of the layout it ends up with, and a problem about that layout + names where it came from: `"subtitle" is required by layout "article" (the childLayout of articles/index.md)`. +- `404.md` is not a page of the site, so it takes no `childLayout`. + +**Which layout a page got:** in the workbench, a layout's Relationships tab lists its **Pages**, each with where its +layout came from ("its own layout", "childLayout of articles/index.md", "the default layout"). `/api/pages` on the +website's host gives each page's `layout`, and `layoutFrom` when it came from a folder. + ### Problems In `pd dev` a page with a problem is replaced by the list of its problems, every one with its file and @@ -348,6 +376,7 @@ keys below, at any depth. | `date` | The page's `date`, else the day git first saw it (`YYYY-MM-DD`), else `null` | | `tags` | The page's `tags`, else `[]` | | `categories` | The page's categories, in its order, each `{ key, label, description }` (`description` `null` when the config gives none), else `[]` | +| `listing` | On a folder's `index.md`: the folder's pages rendered through the view its `view:` names, as HTML for `{{{page.listing}}}` (see [Listing views](#listing-views)); `null` on any other page | ```hbs {{#each page.headings}}{{text}}{{/each}} @@ -447,9 +476,24 @@ To show an entry's image with its variants, pass it to a component with an image {{#each page.children}}
  • {{> components-card }}
  • {{/each}} ``` -where `components/card` declares `image` with `x-pd-image` and writes `{{pd-image image alt=""}}`. A component -a layout includes may not have sample data of keys the layout doesn't declare; give it a variant -(`card~article.json`) to show it filled in the workbench. +where `components/card` declares `image` with `x-pd-image` and writes `{{pd-image image alt=""}}`. + +**The card.** Name that component in the layout's schema, and every page of the listing is checked against the +card's schema: + +```json +"page": { "properties": { "children": { "x-pd-card": "components/card" } } } +``` + +- **A field the card requires** (`required`) that a page doesn't have, `null` or an empty list, fails the listing + page, once per page, naming it and what to add: `articles/index.md: articles/plain.md has no image, which the + listing's card (components/card) requires: give it one (image: ...)`. +- **A value a page has** is checked against the type the card declares. +- **A card declares only fields of an entry** (the table above). The entry's shape is Pattern Dump's and the base + every card shares: a page can't add fields to it, so a card says which of them it shows and which it needs. +- **Its sample data** may set only an entry's fields, since the card renders with an entry as its context. Without + `x-pd-card`, a component the layout includes may only have sample data of keys the layout declares; give it a + variant (`card~article.json`) to show it filled in the workbench. With `sort: date`, a page with no date at all (no `date` and no commit, such as a new file) is a problem in `pd build` and a note in `pd dev`, where it is listed last. From a shallow clone, a date git would give is @@ -469,6 +513,45 @@ set `site.collections`. In `pd dev` an edit to what a listing shows of a page (its date, description, first paragraph, image, tags, categories or draft) reloads every open page, as a title edit does. +### Listing views + +One listing, several ways to show it. A folder's `index.md` names its view: + +```md +--- +title: Articles +layout: listing +view: grid +sort: date +--- +``` + +A **view** is a component directly under `views/` in the skin's style guide (`views/grid`), as a layout is under +`layouts/`. Pattern Dump has no views of its own: every skin defines its own, and the workbench shows and documents +them like any component. + +- **The layout** declares `page.listing` and writes it unescaped where the listing goes: `{{{page.listing}}}`. +- **The view** is rendered once per listing with `entries`, the folder's pages in its sort order (each an entry, as + above), and nothing else. +- **The view names its card** in its schema, and that card's `required` are the fields the view needs. Every page + of the listing is checked against that card, as for `x-pd-card` on `page.children`: + + ```json + { "properties": { "entries": { "type": "array", "x-pd-card": "components/grid-card" } } } + ``` + + So views are separate components with cards of their own, not variants of one card: a grid's card can require an + image while a list's doesn't. +- **Checked:** a view that doesn't exist fails the page with the views there are (and a "did you mean"); a listing + page whose layout shows `page.listing` must name its view; a `view:` on a page whose layout shows no listing, or on + a page that is not a folder's `index.md`, is a problem; a view whose schema names no card is a problem. +- **Sample data:** a view's may set only `entries`, each an entry; its card's only an entry's fields. +- **Styles and scripts** of the view and its card load on the page as those of a placed component do. + +The starter (`pd init --storefront`) ships four plain views, each with its card in `components/`: `list` (title, +date, teaser and tags), `grid` (cards with an image; every page needs one), `featured` (the first page large, the +rest as the grid: with `sort: date`, the newest first) and `compact` (title and date only). + ### Categories Categories say what a page is about, apart from the folder it is in: a page changes category without moving, so diff --git a/packages/cli/src/init/plan.spec.ts b/packages/cli/src/init/plan.spec.ts index 69097f1..02e433c 100644 --- a/packages/cli/src/init/plan.spec.ts +++ b/packages/cli/src/init/plan.spec.ts @@ -17,6 +17,8 @@ const templates: Templates = { { path: "src/patterns/partials/base/base.json", content: '{ "site": { "title": __PD_BRAND_JSON__ } }\n' }, { path: "src/styles/partials/base.scss", content: ".site {}\n" }, { path: "assets/icon.svg", content: "\n" }, + { path: "src/patterns/views/list/list.hbs", content: "
      {{#each entries}}
    • {{title}}
    • {{/each}}
    \n" }, + { path: "src/styles/views/list.scss", content: ".view-list {}\n" }, { path: "src/patterns/components/note/note.hbs", content: "\n" }, { path: ".github/workflows/pages.yml", content: "name: Pages\n" }, ], @@ -67,7 +69,7 @@ describe("planInit — a new folder", () => { describe("planInit — the storefront", () => { const SKIN = ["src/patterns/layouts/page/page.hbs", "src/patterns/partials/base/base.hbs", "src/patterns/partials/base/base.json", - "src/styles/partials/base.scss", "assets/icon.svg"]; + "src/styles/partials/base.scss", "assets/icon.svg", "src/patterns/views/list/list.hbs", "src/styles/views/list.scss"]; const REST = ["pages/index.md", "src/patterns/components/note/note.hbs", ".github/workflows/pages.yml"]; const existing = (files: string[]): ExistingProject => ({ packageJson: null, exists: p => files.includes(p) }); @@ -103,8 +105,14 @@ describe("planInit — the storefront", () => { const paths = p.writes.map(w => w.path); for (const s of SKIN) expect(paths, s).not.toContain(s); expect(paths).toEqual(expect.arrayContaining(REST)); - expect(p.skipped).toEqual([{ path: "src/patterns/partials/base/base.hbs", reason: "already exists: the storefront skin (5 files in src/patterns/layouts, " - + "src/patterns/partials and their styles) was left out as a whole, so it isn't mixed with the skin already here" }]); + expect(p.skipped).toEqual([{ path: "src/patterns/partials/base/base.hbs", reason: "already exists: the storefront skin (7 files in src/patterns/layouts, " + + "src/patterns/partials, src/patterns/views and their styles) was left out as a whole, so it isn't mixed with the skin already here" }]); + }); + + it("counts the views as the skin: a project with views of its own keeps them, and gets none of the starter's skin", () => { + const p = plan({ storefront: true }, existing(["src/patterns/views/list/list.hbs"])); + for (const s of SKIN) expect(p.writes.map(w => w.path), s).not.toContain(s); + expect(p.skipped.map(s => s.path)).toEqual(["src/patterns/views/list/list.hbs"]); }); it("writes the skin beside the project's own other layouts and partials", () => { diff --git a/packages/cli/src/init/plan.ts b/packages/cli/src/init/plan.ts index 0574132..aa0b712 100644 --- a/packages/cli/src/init/plan.ts +++ b/packages/cli/src/init/plan.ts @@ -56,7 +56,7 @@ const RENAMES: Record = { _gitignore: ".gitignore" }; * The storefront's skin: written as one unit or not at all. Mixed with a skin already in the project (its own * `layouts/page` beside the starter's `partials/base`, say), pages would render with parts of two skins. */ -const SKIN_PREFIXES = ["src/patterns/layouts/", "src/patterns/partials/", "src/styles/layouts/", "src/styles/partials/"]; +const SKIN_PREFIXES = ["src/patterns/layouts/", "src/patterns/partials/", "src/patterns/views/", "src/styles/layouts/", "src/styles/partials/", "src/styles/views/"]; const SKIN_FILES = ["assets/icon.svg"]; const isSkin = (path: string): boolean => SKIN_PREFIXES.some(p => path.startsWith(p)) || SKIN_FILES.includes(path); @@ -95,7 +95,7 @@ export function planInit( const skinTaken = skin.map(f => renamed(f.path)).find(p => existing.exists(p)); if (skinTaken) { skipped.push({ path: skinTaken, reason: `already exists: the storefront skin (${skin.length} files in src/patterns/layouts, ` - + `src/patterns/partials and their styles) was left out as a whole, so it isn't mixed with the skin already here` }); + + `src/patterns/partials, src/patterns/views and their styles) was left out as a whole, so it isn't mixed with the skin already here` }); } const files = [...templates.base, ...(answers.examples ? templates.examples : []), ...storefront.filter(f => !skinTaken || !skin.includes(f))]; diff --git a/packages/cli/src/init/starter.spec.ts b/packages/cli/src/init/starter.spec.ts index f5363a5..abce61c 100644 --- a/packages/cli/src/init/starter.spec.ts +++ b/packages/cli/src/init/starter.spec.ts @@ -15,7 +15,7 @@ import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { crc32, deflateSync } from "node:zlib"; -import type { ComponentDetailResponse, ComponentTree, TreeNode } from "@pattern-dump/contracts"; +import { componentCssUrl, type ComponentDetailResponse, type ComponentTree, type TreeNode } from "@pattern-dump/contracts"; import { loadConfig } from "@pattern-dump/core"; import { runDiagnosticsAudit, startDevServer } from "@pattern-dump/dev-server"; import { applyPlan, readTemplates } from "./files.js"; @@ -174,7 +174,9 @@ describe("the starter project with a website (--storefront, no examples)", () => const { graph } = await runDiagnosticsAudit(config, siteDir); expect(graph.occurrences).toEqual([]); expect(graph.components.map(c => [c.id, c.render]).sort()).toEqual( - [["components/note", "ok"], ["layouts/listing", "ok"], ["layouts/page", "ok"], ["partials/base", "ok"], ["partials/head", "ok"]]); + [["components/compact-card", "ok"], ["components/feature-card", "ok"], ["components/grid-card", "ok"], ["components/listing-card", "ok"], ["components/note", "ok"], + ["layouts/listing", "ok"], ["layouts/page", "ok"], ["partials/base", "ok"], ["partials/head", "ok"], + ["views/compact", "ok"], ["views/featured", "ok"], ["views/grid", "ok"], ["views/list", "ok"]]); }, 120_000); it("serves the website: the home page with its placed note, the about page, the 404 page and robots.txt", async () => { @@ -191,7 +193,10 @@ describe("the starter project with a website (--storefront, no examples)", () => // The articles collection: its listing names the example article with its date, and the article shows its tags. const articles = await onHost(server.port, "live.localhost", "/articles/"); expect(articles.status).toBe(200); - expect(articles.body).toMatch(/Hello, articles<\/a>\s*
      \s*
    • \s*
      \s*

      Hello, articles<\/a><\/h2>\s*

      • getting-started
      • notes
      `); @@ -206,6 +211,36 @@ describe("the starter project with a website (--storefront, no examples)", () => } }, 120_000); + it("documents and previews each view and card in the workbench, diagnostic-free", async () => { + const config = await loadConfig(siteDir); + const server = await startDevServer(config, siteDir, { port: 0, wsPort: 0 }); + try { + for (const id of ["views/list", "views/grid", "views/featured", "views/compact", "components/listing-card", "components/grid-card", "components/feature-card", "components/compact-card"]) { + const d = await (await fetch(`http://127.0.0.1:${server.port}/api/component/${id}`)).json() as ComponentDetailResponse; + expect(d.diagnostics, id).toEqual([]); + expect(d.doc, id).toBeTruthy(); + } + } finally { + await server.close(); + } + }, 120_000); + + it("checks each article against the view's card: the grid view reports the article without an image", async () => { + const index = join(siteDir, "pages", "articles", "index.md"); + const before = await readFile(index, "utf8"); + const config = await loadConfig(siteDir); + const server = await startDevServer(config, siteDir, { port: 0, wsPort: 0 }); + try { + await save(index, before.replace("view: list", "view: grid")); + const page = await onHost(server.port, "live.localhost", "/articles/"); + expect(page.status).toBe(500); + expect(page.body).toContain(`articles/index.md: articles/hello.md has no image, which the card of view "grid" (components/grid-card) requires`); + } finally { + await save(index, before); + await server.close(); + } + }, 120_000); + it("type-checks with its own tsconfig", async () => { expect(await typecheck(siteDir)).toEqual({ code: 0, output: "" }); }, 60_000); diff --git a/packages/cli/templates/storefront-fills/readme.md b/packages/cli/templates/storefront-fills/readme.md index 5c9a624..6317b63 100644 --- a/packages/cli/templates/storefront-fills/readme.md +++ b/packages/cli/templates/storefront-fills/readme.md @@ -28,10 +28,14 @@ returns by itself. How `pd-` tags work: | `src/patterns/partials/base/` | the frame around every page: header, navigation, footer | | `src/patterns/partials/head/` | what the skin adds to every page's `` (the icon) | | `src/patterns/components/note/` | the component the home page shows | +| `src/patterns/views/` | the ways a listing can be shown: `list`, `grid`, `featured`, `compact` | +| `src/patterns/components/*-card/` | the card each view shows a page as; its schema says which fields a page needs | | `pattern-dump.config.ts` | `storefront`: the website's name and footer (`site`), and where it is published | -`pages/articles/` is a collection: its `index.md` (layout `listing`, `sort: date`) lists every page in the folder, -newest first, by its `date`. Copy `hello.md` to write another; `draft: true` keeps one out of the build. +`pages/articles/` is a collection: its `index.md` (layout `listing`, `view: list`, `sort: date`) lists every page +in the folder, newest first, by its `date`. Copy `hello.md` to write another; `draft: true` keeps one out of the +build. Each page is checked against the view's card: switch to `view: grid` and the listing names every article +without an `image:`. `childLayout: ` on a folder's `index.md` gives its pages a layout of their own. A page that doesn't exist shows a built-in 404 page; write `pages/404.md` to change it. A page that moved can forward from its old address (`redirectFrom: [/old/]`), and `index: false` keeps a page out of search diff --git a/packages/cli/templates/storefront/pages/articles/index.md b/packages/cli/templates/storefront/pages/articles/index.md index 2543f4b..e30a98b 100644 --- a/packages/cli/templates/storefront/pages/articles/index.md +++ b/packages/cli/templates/storefront/pages/articles/index.md @@ -2,9 +2,10 @@ title: Articles description: Everything written here, newest first. layout: listing +view: list sort: date order: 2 --- -This page is `pages/articles/index.md`. Every page in this folder is listed below, newest first. Add a markdown -file with a `date` and it shows up here, with no link to write. +This page is `pages/articles/index.md`. Every page in this folder is listed below, newest first, in the list view +(`view: list`). Add a markdown file with a `date` and it shows up here, with no link to write. diff --git a/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.hbs b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.hbs new file mode 100644 index 0000000..e628a00 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.hbs @@ -0,0 +1 @@ +

      {{title}}{{#if date}} {{/if}}

      diff --git a/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.json b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.json new file mode 100644 index 0000000..6a4d5a8 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.json @@ -0,0 +1,5 @@ +{ + "route": "/articles/hello/", + "title": "Hello, articles", + "date": "2026-11-14" +} diff --git a/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.md b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.md new file mode 100644 index 0000000..a8a00c1 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.md @@ -0,0 +1,6 @@ +--- +title: Compact card +--- + +One page of a listing, as the compact view (`views/compact`) shows it: its title as a link and its date, on one +line. No heading, so a short list of them can sit in a sidebar or under an article. diff --git a/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.schema.json b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.schema.json new file mode 100644 index 0000000..2fc32e1 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/compact-card/compact-card.schema.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Compact card", + "description": "One page of a listing, as the compact view shows it: its title as a link and its date.", + "type": "object", + "required": [ + "route", + "title" + ], + "properties": { + "route": { + "type": "string", + "description": "The page's address" + }, + "title": { + "type": "string", + "description": "The page's title, as the card's link" + }, + "date": { + "type": [ + "string", + "null" + ], + "description": "The page's date, YYYY-MM-DD" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.hbs b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.hbs new file mode 100644 index 0000000..d9579ae --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.hbs @@ -0,0 +1,6 @@ +
      + {{#if image}}{{pd-image image alt=""}}{{/if}} +

      {{title}}

      + {{#if date}}

      {{/if}} + {{#if description}}

      {{description}}

      {{/if}} +
      diff --git a/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.json b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.json new file mode 100644 index 0000000..a15c563 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.json @@ -0,0 +1,7 @@ +{ + "route": "/articles/hello/", + "title": "Hello, articles", + "image": "/assets/icon.svg", + "date": "2026-11-14", + "description": "The example article. Copy it to start a new one." +} diff --git a/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.md b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.md new file mode 100644 index 0000000..7148387 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.md @@ -0,0 +1,8 @@ +--- +title: Feature card +--- + +The first page of the featured view (`views/featured`), large: its image across the column, its title as a link, +its date and its teaser. Its own card, not a variant of the grid card, so its image slot can be as wide as the +column. It requires what the grid card requires (`route`, `title`, `image`): the featured view names the grid card +in its schema, and every page is checked against that. diff --git a/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.schema.json b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.schema.json new file mode 100644 index 0000000..3cfba99 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/feature-card/feature-card.schema.json @@ -0,0 +1,50 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Feature card", + "description": "The first page of the featured view, large: its image across the column, its title as a link, its date and its teaser.", + "type": "object", + "required": [ + "route", + "title", + "image" + ], + "properties": { + "route": { + "type": "string", + "description": "The page's address" + }, + "title": { + "type": "string", + "description": "The page's title, as the card's link" + }, + "image": { + "type": [ + "string", + "null" + ], + "description": "The page's image, a raster image in the assets: across the column above the title, as decoration (the title says what the page is)", + "x-pd-image": { + "widths": [ + 480, + 672, + 1344 + ], + "sizes": "(min-width: 44rem) 42rem, calc(100vw - 2rem)" + } + }, + "date": { + "type": [ + "string", + "null" + ], + "description": "The page's date, YYYY-MM-DD" + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The teaser: the page's description, or its first paragraph. At most three lines are shown" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.hbs b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.hbs new file mode 100644 index 0000000..43469ee --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.hbs @@ -0,0 +1,5 @@ +
      + {{#if image}}{{pd-image image alt=""}}{{/if}} +

      {{title}}

      + {{#if date}}

      {{/if}} +
      diff --git a/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.json b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.json new file mode 100644 index 0000000..99d86ae --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.json @@ -0,0 +1,6 @@ +{ + "route": "/articles/hello/", + "title": "Hello, articles", + "image": "/assets/icon.svg", + "date": "2026-11-14" +} diff --git a/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.md b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.md new file mode 100644 index 0000000..34b0633 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.md @@ -0,0 +1,10 @@ +--- +title: Grid card +--- + +One page of a listing, as the grid view (`views/grid`) and the featured view (`views/featured`) show it: its image, +its title as a link and its date. The image is decoration (`alt=""`): the title next to it says what the page is. + +It requires `image`, so a grid lists only pages that have one: a page without an `image:` in its frontmatter stops +the listing, and the message names it. The sample shows the site's icon; a page's image is a raster image in the +assets, written with its WebP variants. diff --git a/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.schema.json b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.schema.json new file mode 100644 index 0000000..65f8688 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/grid-card/grid-card.schema.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Grid card", + "description": "One page of a listing, as the grid and featured views show it: its image, its title as a link and its date. Every page needs an image.", + "type": "object", + "required": [ + "route", + "title", + "image" + ], + "properties": { + "route": { + "type": "string", + "description": "The page's address" + }, + "title": { + "type": "string", + "description": "The page's title, as the card's link" + }, + "image": { + "type": [ + "string", + "null" + ], + "description": "The page's image, a raster image in the assets: shown above the title, as decoration (the title says what the page is)", + "x-pd-image": { + "widths": [ + 320, + 640 + ], + "sizes": "(min-width: 44rem) 20rem, calc(100vw - 2rem)" + } + }, + "date": { + "type": [ + "string", + "null" + ], + "description": "The page's date, YYYY-MM-DD" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.hbs b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.hbs new file mode 100644 index 0000000..604272d --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.hbs @@ -0,0 +1,6 @@ +
      +

      {{title}}

      + {{#if date}}

      {{/if}} + {{#if description}}

      {{description}}

      {{/if}} + {{#if tags.length}}
        {{#each tags}}
      • {{this}}
      • {{/each}}
      {{/if}} +
      diff --git a/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.json b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.json new file mode 100644 index 0000000..64c262b --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.json @@ -0,0 +1,10 @@ +{ + "route": "/articles/hello/", + "title": "Hello, articles", + "date": "2026-11-14", + "description": "The example article. Copy it to start a new one.", + "tags": [ + "getting-started", + "notes" + ] +} diff --git a/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.md b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.md new file mode 100644 index 0000000..699f612 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.md @@ -0,0 +1,11 @@ +--- +title: Listing card +--- + +One page of a listing, as the list view (`views/list`) shows it: its title as a link, its date, a teaser of three +lines at most, and its tags. Only the title is a link, so a screen reader reads one link per page. + +The view names this card in its schema (`"x-pd-card": "components/listing-card"`), so every page of a listing is +checked against this schema: a field in `required` that a page doesn't have stops the listing, naming the page. A +card declares only fields a page in a listing has (route, title, description, date, updated, image, tags, +categories, draft, scheduled); its sample data may set only those too. diff --git a/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.schema.json b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.schema.json new file mode 100644 index 0000000..1e4af59 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/components/listing-card/listing-card.schema.json @@ -0,0 +1,41 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Listing card", + "description": "One page of a listing, as the list view shows it: its title as a link, its date, its teaser and its tags. It takes a page of the listing as it is.", + "type": "object", + "required": [ + "route", + "title" + ], + "properties": { + "route": { + "type": "string", + "description": "The page's address" + }, + "title": { + "type": "string", + "description": "The page's title, as the card's link" + }, + "date": { + "type": [ + "string", + "null" + ], + "description": "The page's date, YYYY-MM-DD" + }, + "description": { + "type": [ + "string", + "null" + ], + "description": "The teaser: the page's description, or its first paragraph. At most three lines are shown" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The page's tags" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.hbs b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.hbs index d937be1..e53429b 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.hbs +++ b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.hbs @@ -3,14 +3,6 @@

      {{title}}

      {{#if description}}

      {{description}}

      {{/if}}
      {{{body}}}
      -
        - {{#each page.children}} -
      • - {{title}} - {{#if date}}{{/if}} - {{#if description}}

        {{description}}

        {{/if}} -
      • - {{/each}} -
      + {{{page.listing}}}
      {{/partials-base}} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.json b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.json index 00277c7..d9e6425 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.json +++ b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.json @@ -5,9 +5,6 @@ "site": { "title": __PD_BRAND_JSON__, "footer": "Made with Pattern Dump." }, "nav": [{ "route": "/", "title": "Home" }, { "route": "/articles/", "title": "Articles", "current": true }], "page": { - "children": [ - { "route": "/articles/second/", "title": "A second article", "description": "Its teaser: the page's description, or its first paragraph.", "date": "2026-11-14", "image": null, "tags": ["notes"], "draft": false }, - { "route": "/articles/first/", "title": "A first article", "description": "Listed below the newer one.", "date": "2026-11-01", "image": null, "tags": [], "draft": false } - ] + "listing": "" } } diff --git a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.md b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.md index f56686b..ad850b8 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.md +++ b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.md @@ -3,5 +3,9 @@ title: Listing --- The layout of a folder's `index.md` that lists the folder's pages, such as `pages/articles/index.md`: set -`layout: listing`, and `sort: date` to list the newest first. It declares `page.children`, so the storefront fills -it with the folder's pages, each with its route, title, description (or its first paragraph), date, image and tags. +`layout: listing`, a view with `view: list`, and `sort: date` to list the newest first. It declares `page.listing`, +so the storefront renders the folder's pages through the view and the layout writes the result where it says +`{{{page.listing}}}`. The views are in `views/`: `list`, `grid`, `featured` and `compact`. + +Its pages can take a layout from the folder too: `childLayout: ` on the `index.md` gives every page in the +folder that layout, unless the page names its own. diff --git a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.schema.json b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.schema.json index 207e456..9b11d2b 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.schema.json +++ b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.schema.json @@ -11,7 +11,7 @@ "type": "object", "description": "What the storefront works out for the page", "properties": { - "children": { "description": "The folder's pages, newest first with sort: date" } + "listing": { "description": "The folder's pages, shown through the view its index.md names (view: list), newest first with sort: date" } } } } diff --git a/packages/cli/templates/storefront/src/patterns/views/compact/compact.hbs b/packages/cli/templates/storefront/src/patterns/views/compact/compact.hbs new file mode 100644 index 0000000..33805a6 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/compact/compact.hbs @@ -0,0 +1,5 @@ +
        + {{#each entries}} +
      • {{> components-compact-card }}
      • + {{/each}} +
      diff --git a/packages/cli/templates/storefront/src/patterns/views/compact/compact.json b/packages/cli/templates/storefront/src/patterns/views/compact/compact.json new file mode 100644 index 0000000..1430882 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/compact/compact.json @@ -0,0 +1,14 @@ +{ + "entries": [ + { + "route": "/articles/second/", + "title": "A second article", + "date": "2026-11-14" + }, + { + "route": "/articles/first/", + "title": "A first article", + "date": "2026-11-01" + } + ] +} diff --git a/packages/cli/templates/storefront/src/patterns/views/compact/compact.md b/packages/cli/templates/storefront/src/patterns/views/compact/compact.md new file mode 100644 index 0000000..e5666eb --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/compact/compact.md @@ -0,0 +1,6 @@ +--- +title: Compact +--- + +A listing as a short list of compact cards (`components/compact-card`): each page's title and date, one per line. +For archives, sidebars and related pages. diff --git a/packages/cli/templates/storefront/src/patterns/views/compact/compact.schema.json b/packages/cli/templates/storefront/src/patterns/views/compact/compact.schema.json new file mode 100644 index 0000000..396d487 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/compact/compact.schema.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Compact", + "description": "A listing as a short list of titles and dates.", + "type": "object", + "properties": { + "entries": { + "type": "array", + "x-pd-card": "components/compact-card", + "description": "The pages of the listing, in its order (the folder's sort)" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/views/featured/featured.hbs b/packages/cli/templates/storefront/src/patterns/views/featured/featured.hbs new file mode 100644 index 0000000..b90a322 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/featured/featured.hbs @@ -0,0 +1,8 @@ + diff --git a/packages/cli/templates/storefront/src/patterns/views/featured/featured.json b/packages/cli/templates/storefront/src/patterns/views/featured/featured.json new file mode 100644 index 0000000..22fb06b --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/featured/featured.json @@ -0,0 +1,22 @@ +{ + "entries": [ + { + "route": "/articles/second/", + "title": "A second article", + "date": "2026-11-14", + "image": "/assets/icon.svg" + }, + { + "route": "/articles/first/", + "title": "A first article", + "date": "2026-11-01", + "image": "/assets/icon.svg" + }, + { + "route": "/articles/third/", + "title": "A third article", + "date": "2026-10-20", + "image": "/assets/icon.svg" + } + ] +} diff --git a/packages/cli/templates/storefront/src/patterns/views/featured/featured.md b/packages/cli/templates/storefront/src/patterns/views/featured/featured.md new file mode 100644 index 0000000..dd8a5b1 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/featured/featured.md @@ -0,0 +1,8 @@ +--- +title: Featured +--- + +A listing with its first page large, as a feature card (`components/feature-card`), and the rest as a grid of grid +cards (`components/grid-card`) below. With `sort: date` on the folder's `index.md` the first is the newest: for a +home page or a blog's entry page. Every page needs an `image:`, as in the grid: the view names the grid card in its +schema, and the feature card requires the same fields. diff --git a/packages/cli/templates/storefront/src/patterns/views/featured/featured.schema.json b/packages/cli/templates/storefront/src/patterns/views/featured/featured.schema.json new file mode 100644 index 0000000..d1ffd85 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/featured/featured.schema.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Featured", + "description": "A listing with its first page large and the rest as a grid below.", + "type": "object", + "properties": { + "entries": { + "type": "array", + "x-pd-card": "components/grid-card", + "description": "The pages of the listing, in its order (the folder's sort)" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/views/grid/grid.hbs b/packages/cli/templates/storefront/src/patterns/views/grid/grid.hbs new file mode 100644 index 0000000..3123438 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/grid/grid.hbs @@ -0,0 +1,5 @@ +
        + {{#each entries}} +
      • {{> components-grid-card }}
      • + {{/each}} +
      diff --git a/packages/cli/templates/storefront/src/patterns/views/grid/grid.json b/packages/cli/templates/storefront/src/patterns/views/grid/grid.json new file mode 100644 index 0000000..22fb06b --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/grid/grid.json @@ -0,0 +1,22 @@ +{ + "entries": [ + { + "route": "/articles/second/", + "title": "A second article", + "date": "2026-11-14", + "image": "/assets/icon.svg" + }, + { + "route": "/articles/first/", + "title": "A first article", + "date": "2026-11-01", + "image": "/assets/icon.svg" + }, + { + "route": "/articles/third/", + "title": "A third article", + "date": "2026-10-20", + "image": "/assets/icon.svg" + } + ] +} diff --git a/packages/cli/templates/storefront/src/patterns/views/grid/grid.md b/packages/cli/templates/storefront/src/patterns/views/grid/grid.md new file mode 100644 index 0000000..e073903 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/grid/grid.md @@ -0,0 +1,7 @@ +--- +title: Grid +--- + +A listing as a grid of grid cards (`components/grid-card`): image, title and date. For a section's overview: +`view: grid` on the folder's `index.md`. Every page needs an `image:`, since the card requires one; a page without +stops the listing, and the message names it. diff --git a/packages/cli/templates/storefront/src/patterns/views/grid/grid.schema.json b/packages/cli/templates/storefront/src/patterns/views/grid/grid.schema.json new file mode 100644 index 0000000..e067130 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/grid/grid.schema.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Grid", + "description": "A listing as a grid of cards, each with the page's image.", + "type": "object", + "properties": { + "entries": { + "type": "array", + "x-pd-card": "components/grid-card", + "description": "The pages of the listing, in its order (the folder's sort)" + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/views/list/list.hbs b/packages/cli/templates/storefront/src/patterns/views/list/list.hbs new file mode 100644 index 0000000..83b61a3 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/list/list.hbs @@ -0,0 +1,5 @@ +
        + {{#each entries}} +
      • {{> components-listing-card }}
      • + {{/each}} +
      diff --git a/packages/cli/templates/storefront/src/patterns/views/list/list.json b/packages/cli/templates/storefront/src/patterns/views/list/list.json new file mode 100644 index 0000000..c693135 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/list/list.json @@ -0,0 +1,20 @@ +{ + "entries": [ + { + "route": "/articles/second/", + "title": "A second article", + "date": "2026-11-14", + "description": "Its teaser: the page's description, or its first paragraph.", + "tags": [ + "notes" + ] + }, + { + "route": "/articles/first/", + "title": "A first article", + "date": "2026-11-01", + "description": "Listed below the newer one.", + "tags": [] + } + ] +} diff --git a/packages/cli/templates/storefront/src/patterns/views/list/list.md b/packages/cli/templates/storefront/src/patterns/views/list/list.md new file mode 100644 index 0000000..f9742e3 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/list/list.md @@ -0,0 +1,10 @@ +--- +title: List +--- + +A listing as a list, one listing card (`components/listing-card`) per page: title, date, teaser and tags. A +folder's `index.md` picks it with `view: list`; its layout (`layouts/listing`) shows it where it writes +`{{{page.listing}}}`. + +A view is a component in `views/`, rendered once per listing with `entries`, the folder's pages in its order. Its +schema names its card (`x-pd-card` on `entries`), and every page is checked against that card's schema. diff --git a/packages/cli/templates/storefront/src/patterns/views/list/list.schema.json b/packages/cli/templates/storefront/src/patterns/views/list/list.schema.json new file mode 100644 index 0000000..64c39d6 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/views/list/list.schema.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "List", + "description": "A listing as a list: each page's title, date, teaser and tags.", + "type": "object", + "properties": { + "entries": { + "type": "array", + "x-pd-card": "components/listing-card", + "description": "The pages of the listing, in its order (the folder's sort)" + } + } +} diff --git a/packages/cli/templates/storefront/src/styles/components/compact-card.scss b/packages/cli/templates/storefront/src/styles/components/compact-card.scss new file mode 100644 index 0000000..734d30c --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/components/compact-card.scss @@ -0,0 +1,4 @@ +@use "../base/tokens"; + +.compact-card { margin: 0; } +.compact-card-date { margin-inline-start: tokens.$space-sm; color: var(--color-text-muted, #4b5563); } diff --git a/packages/cli/templates/storefront/src/styles/components/feature-card.scss b/packages/cli/templates/storefront/src/styles/components/feature-card.scss new file mode 100644 index 0000000..ee929cf --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/components/feature-card.scss @@ -0,0 +1,6 @@ +@use "../base/tokens"; + +.feature-card img { display: block; inline-size: 100%; block-size: auto; border-radius: tokens.$radius; } +.feature-card-title { margin: tokens.$space-sm 0 0; font-size: 1.5rem; } +.feature-card-date { margin: tokens.$space-xs 0 0; color: var(--color-text-muted, #4b5563); } +.feature-card-teaser { margin: tokens.$space-xs 0 0; } diff --git a/packages/cli/templates/storefront/src/styles/components/grid-card.scss b/packages/cli/templates/storefront/src/styles/components/grid-card.scss new file mode 100644 index 0000000..abb4138 --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/components/grid-card.scss @@ -0,0 +1,5 @@ +@use "../base/tokens"; + +.grid-card img { display: block; inline-size: 100%; block-size: auto; border-radius: tokens.$radius; } +.grid-card-title { margin: tokens.$space-sm 0 0; font-size: 1.125rem; } +.grid-card-date { margin: tokens.$space-xs 0 0; color: var(--color-text-muted, #4b5563); } diff --git a/packages/cli/templates/storefront/src/styles/components/listing-card.scss b/packages/cli/templates/storefront/src/styles/components/listing-card.scss new file mode 100644 index 0000000..8a5f266 --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/components/listing-card.scss @@ -0,0 +1,14 @@ +@use "../base/tokens"; + +.listing-card-title { margin: 0; font-size: 1.125rem; } +.listing-card-date { margin: tokens.$space-xs 0 0; color: var(--color-text-muted, #4b5563); } +.listing-card-teaser { + margin: tokens.$space-xs 0 0; + // The teaser is never shortened in the data: three lines at most here. + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + line-clamp: 3; + overflow: hidden; +} +.listing-card-tags { display: flex; flex-wrap: wrap; gap: tokens.$space-sm; margin: tokens.$space-xs 0 0; padding: 0; list-style: none; color: var(--color-text-muted, #4b5563); } diff --git a/packages/cli/templates/storefront/src/styles/layouts/listing.scss b/packages/cli/templates/storefront/src/styles/layouts/listing.scss deleted file mode 100644 index 1ed1bd6..0000000 --- a/packages/cli/templates/storefront/src/styles/layouts/listing.scss +++ /dev/null @@ -1,15 +0,0 @@ -@use "../base/tokens"; - -.listing-entries { margin: tokens.$space-lg 0 0; padding: 0; list-style: none; } -.listing-entry { margin-block-end: tokens.$space-lg; } -.listing-title { font-weight: 600; } -.listing-date { margin-inline-start: tokens.$space-sm; color: var(--color-text-muted, #4b5563); } -.listing-teaser { - margin: 0; - // The teaser is never shortened in the data: three lines at most here. - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 3; - line-clamp: 3; - overflow: hidden; -} diff --git a/packages/cli/templates/storefront/src/styles/views/compact.scss b/packages/cli/templates/storefront/src/styles/views/compact.scss new file mode 100644 index 0000000..6427302 --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/views/compact.scss @@ -0,0 +1,4 @@ +@use "../base/tokens"; + +.view-compact { margin: tokens.$space-md 0 0; padding: 0; list-style: none; } +.view-compact > li { margin-block-end: tokens.$space-xs; } diff --git a/packages/cli/templates/storefront/src/styles/views/featured.scss b/packages/cli/templates/storefront/src/styles/views/featured.scss new file mode 100644 index 0000000..7254d06 --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/views/featured.scss @@ -0,0 +1,4 @@ +@use "../base/tokens"; + +.view-featured { margin-block-start: tokens.$space-lg; } +.view-featured-rest { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 12rem), 1fr)); gap: tokens.$space-lg; margin: tokens.$space-lg 0 0; padding: 0; list-style: none; } diff --git a/packages/cli/templates/storefront/src/styles/views/grid.scss b/packages/cli/templates/storefront/src/styles/views/grid.scss new file mode 100644 index 0000000..6730416 --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/views/grid.scss @@ -0,0 +1,3 @@ +@use "../base/tokens"; + +.view-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 12rem), 1fr)); gap: tokens.$space-lg; margin: tokens.$space-lg 0 0; padding: 0; list-style: none; } diff --git a/packages/cli/templates/storefront/src/styles/views/list.scss b/packages/cli/templates/storefront/src/styles/views/list.scss new file mode 100644 index 0000000..6108a72 --- /dev/null +++ b/packages/cli/templates/storefront/src/styles/views/list.scss @@ -0,0 +1,4 @@ +@use "../base/tokens"; + +.view-list { margin: tokens.$space-lg 0 0; padding: 0; list-style: none; } +.view-list > li { margin-block-end: tokens.$space-lg; } diff --git a/packages/contracts/src/dev-protocol.ts b/packages/contracts/src/dev-protocol.ts index 77dd300..06b1f86 100644 --- a/packages/contracts/src/dev-protocol.ts +++ b/packages/contracts/src/dev-protocol.ts @@ -109,7 +109,7 @@ export type DiagnosticKind = | "HIGHLIGHT_FALLBACK" // M4.1 fence/Shiki degradation note | "HANDLE_COLLISION" // M6: component quarantined — handle held by incumbent; rename to resolve | "DATA_INVALID" // a component or variant .json that does not parse; its data was not used - | "SCHEMA_INVALID" // a schema misuses a placement extension (x-pd-component, x-pd-content, contentMediaType), + | "SCHEMA_INVALID" // a schema misuses a schema extension (x-pd-card, x-pd-component, x-pd-content, contentMediaType), // names an unknown x-pd- key, or its template outputs a non-markdown value unescaped; // or a property, at any depth, is named like a registered helper | "HELPER_SHADOW"; // a warning: the template's bare {{name}} calls a registered helper, so the data field of that @@ -478,6 +478,21 @@ export interface RelationshipsAvailable { utilityClasses: boolean; /** CSS classes used in markup whose ownership is unrecognised (typos, dead, unregistered). */ unattributedClasses: string[]; + /** A layout of a project with a website: every page that renders with it, by path, and how each got it. + * Absent for any other component, and in a project without a website. */ + pages?: LayoutPageUse[]; +} + +/** A storefront page that renders with a layout, and where its layout came from. */ +export interface LayoutPageUse { + route: string; + /** The page file, relative to the pages folder ("articles/one.md"). */ + path: string; + /** "own": its `layout:`; "folder": the `childLayout` of the index.md in `from`; "default": it names none, and no + * folder above it sets one. */ + source: "own" | "folder" | "default"; + /** With source "folder": the index.md whose childLayout the page took ("articles/index.md"). */ + from?: string; } export type Relationships = RelationshipsAvailable; @@ -730,6 +745,9 @@ export interface StorefrontPage { title: string; /** The layout it renders with: the component `layouts/`. */ layout: string; + /** Where the layout came from when the page names none: the folder's index.md whose `childLayout` it took + * ("articles/index.md", relative to the pages folder). Absent for the page's own `layout:` and for the default. */ + layoutFrom?: string; /** Old routes that forward to this page (frontmatter `redirectFrom`), each root-relative and slash-wrapped. * `pd build` writes a forwarding page at each. Absent when the page has none. */ redirectFrom?: string[]; diff --git a/packages/dev-server/src/routes.ts b/packages/dev-server/src/routes.ts index a016014..1954cb7 100644 --- a/packages/dev-server/src/routes.ts +++ b/packages/dev-server/src/routes.ts @@ -54,7 +54,7 @@ import { testHook } from "./lazy.js"; import { verboseTiming } from "./timing.js"; import { resolveAxeCore } from "./assets.js"; import { ruleTiers } from "@pattern-dump/a11y"; -import { readPages, todayOf } from "./storefront/pages.js"; +import { layoutPages, readPages, todayOf } from "./storefront/pages.js"; import { assetFile } from "./asset-file.js"; import { decodePath } from "./contained-file.js"; import { isOwnHost, ownHosts } from "./own-hosts.js"; @@ -73,6 +73,15 @@ export const TEST_SETTLE_ROUTE = "/_pd/__test/settle"; /** The storefront notes a server has printed (pd dev), so each is printed once. */ const printedNotes = new WeakMap>(); +/** The website's pages as this server serves them: pd dev shows drafts and scheduled pages; pd build leaves them out, + * as if their files weren't there. */ +function readStorefrontPages(ctx: RouteContext, sf: NonNullable): ReturnType { + return readPages(sf.pagesDir, { + workbenchPath: sameHostWorkbenchPath(sf), drafts: ctx.live ? "show" : "leave-out", scheduled: ctx.live ? "show" : "leave-out", + today: ctx.today ?? todayOf(ctx.now()), categories: sf.categories, + }); +} + export interface RouteContext { readonly cfg: ResolvedConfig; readonly state: ServerState; @@ -465,6 +474,10 @@ async function routeRequest( // Phase 2: render + static checks — the single per-component check unit (also driven by // the corpus sweep). Quarantined → 200 + HANDLE_COLLISION (no render); render failure → // 200 + RENDER_ERROR, not 404. + // A layout of a project with a website: the pages that render with it, and where each got it. + if (cfg.storefront && /^layouts\/[^/~]+$/.test(componentId)) { + detail.relationships.pages = layoutPages(await readStorefrontPages(ctx, cfg.storefront), componentId.slice("layouts/".length)); + } const quarantineEntry = discovery.quarantineMap.get(componentId); const { previewHtml, diagnostics } = await checkComponent(componentId, variant, render, quarantineEntry); @@ -627,11 +640,7 @@ async function routeRequest( if (cfg.storefront && host === cfg.storefront.host) { const discovery = await currentDiscovery(state, patternRoots); const discoveryMap = discovery.discoveryMap; - // pd dev shows drafts and scheduled pages; pd build leaves them out, as if their files weren't there. - const model = await readPages(cfg.storefront.pagesDir, { - workbenchPath: sameHostWorkbenchPath(cfg.storefront), drafts: ctx.live ? "show" : "leave-out", scheduled: ctx.live ? "show" : "leave-out", - today: ctx.today ?? todayOf(ctx.now()), categories: cfg.storefront.categories, - }); + const model = await readStorefrontPages(ctx, cfg.storefront); if (pathname === PD_ROUTES.pages) { if (model.problems.length) { json(res, 500, { error: model.problems.join("\n") } satisfies ApiError); return; } json(res, 200, { pages: model.pages, nav: model.nav } satisfies StorefrontPagesResponse); diff --git a/packages/dev-server/src/storefront/cards.ts b/packages/dev-server/src/storefront/cards.ts new file mode 100644 index 0000000..325e489 --- /dev/null +++ b/packages/dev-server/src/storefront/cards.ts @@ -0,0 +1,89 @@ +// A listing's card: the component each page of a listing is shown as, named by `x-pd-card` on a list property (a +// layout's `page.children`, a view's `entries`). Every page in the listing is checked against the card's schema: +// +// - a field the card `required`s that a page doesn't have (null, or an empty list) fails the listing page, once +// per page and field, naming the page and what to add; +// - a value the page has is checked against the type the card declares; +// - a card may declare only the fields of a listing's entry (ENTRY, derived.ts). That shape is Pattern Dump's and +// the base every card shares: a page can't add fields to it, so a card says which of them it shows, and which it +// needs with `required`. +// +// The renderer checks the reference itself in the workbench (schema-extensions.ts); a page checks it again, since a +// listing can't be checked against a card that isn't there. + +import type { DiscoveryMap } from "@pattern-dump/contracts"; +import { checkDeclared, readSchema, type ObjectSchema, type PropertySchema } from "./declared-values.js"; +import { ENTRY } from "./derived.js"; +import type { Entry } from "./collections.js"; +import type { PageModel } from "./pages.js"; + +export const CARD_KEY = "x-pd-card"; +/** The fields of a page in a listing, in the entry's order. */ +export const ENTRY_FIELDS: readonly string[] = Object.keys((ENTRY as { fields: Record }).fields); + +/** The card a list property names, when it names one. */ +export function cardOf(prop: unknown): string | undefined { + if (typeof prop !== "object" || prop === null) return undefined; + const card = (prop as Record)[CARD_KEY]; + return typeof card === "string" ? card : undefined; +} + +/** A card, read for checking a listing: its schema, and how messages name it. */ +export interface Card { + id: string; + schema: ObjectSchema; + /** "the listing's card (components/card)", or "the card of view "grid" (components/grid-card)". */ + label: string; +} + +/** + * The card `id`, named by `owner` (the layout or view whose schema names it), read for a listing: its schema, and + * every problem with it (no such component, no schema, a field no page in a listing has). `role`: how messages name + * the card ("the listing's card", `the card of view "grid"`). + */ +export async function readCard(id: string, owner: string, role: string, discoveryMap: DiscoveryMap): Promise<{ card?: Card; problems: string[] }> { + const entry = discoveryMap.get(id); + if (!entry) return { problems: [`${owner}: ${CARD_KEY} names "${id}", which is not a component`] }; + const read = await readSchema(entry.schemaPath); + if (read.error !== undefined) return { problems: [`${owner}: the schema of its card ${id} cannot be read: ${read.error}`] }; + if (!read.schema) return { problems: [`${owner}: ${CARD_KEY} names "${id}", which has no schema, so a listing's pages can't be checked against it`] }; + const declared = [...Object.keys(read.schema.properties ?? {}), ...(read.schema.required ?? [])]; + const outside = [...new Set(declared.filter(k => !ENTRY_FIELDS.includes(k)))]; + const problems = outside.map(k => `${id} (${role}, ${owner}) declares "${k}", which a page in a listing doesn't have: ` + + `a card declares only the fields Pattern Dump fills (${ENTRY_FIELDS.join(", ")})`); + return problems.length ? { problems } : { card: { id, schema: read.schema, label: `${role} (${id})` }, problems }; +} + +/** What to write to give a page the field, for the message. */ +const HINTS: Readonly> = { + image: "image: /assets/images/.jpg, a raster image in the assets", + date: "date: YYYY-MM-DD", + updated: "updated: YYYY-MM-DD", + description: "description: one sentence, or a first paragraph in its body", + tags: "tags: [a-tag]", + categories: "categories: [a-category], declared in storefront.categories", +}; + +const missing = (v: unknown): boolean => v === null || v === undefined || (Array.isArray(v) && v.length === 0); + +/** Every page of a listing against its card: `index`, the listing page's path in the pages folder. */ +export function checkEntries(entries: readonly Entry[], card: Card, index: string, model: PageModel): string[] { + const problems: string[] = []; + const props: Record = card.schema.properties ?? {}; + for (const e of entries) { + const file = model.files.get(e.route)?.path ?? e.route; + const values = e as unknown as Record; + for (const key of card.schema.required ?? []) { + if (!missing(values[key])) continue; + const hint = HINTS[key]; + problems.push(`${index}: ${file} has no ${key}, which ${card.label} requires: give it one${hint ? ` (${hint})` : ""}`); + } + for (const [key, prop] of Object.entries(props)) { + const v = values[key]; + if (missing(v)) continue; // no value: only `required` is about that + const r = checkDeclared(prop, v, "json"); + if (!r.ok) problems.push(`${index}: ${file}: ${key} ${r.message} for ${card.label}`); + } + } + return problems; +} diff --git a/packages/dev-server/src/storefront/derived.ts b/packages/dev-server/src/storefront/derived.ts index 4db1114..09e0fac 100644 --- a/packages/dev-server/src/storefront/derived.ts +++ b/packages/dev-server/src/storefront/derived.ts @@ -36,6 +36,8 @@ export interface DerivedPage { tags: string[]; /** The page's categories (categories.ts), in its order; [] when it has none. */ categories: Category[]; + /** 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; } /** A value with no keys of its own; an object with exactly these fields; a list of one shape. */ @@ -66,11 +68,12 @@ export const PAGE_SHAPE: { fields: Record } = { date: "value", tags: "value", categories: { items: CATEGORY }, + listing: "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"]; +export const FILLED: readonly (keyof DerivedPage)[] = ["headings", "section", "breadcrumbs", "prev", "next", "created", "updated", "children", "date", "tags", "categories", "listing"]; /** Sub-keys Pattern Dump filled once and no longer does, with what to declare instead. */ export const RETIRED: Readonly> = { diff --git a/packages/dev-server/src/storefront/frontmatter-contract.ts b/packages/dev-server/src/storefront/frontmatter-contract.ts index 722a3e7..5f78b70 100644 --- a/packages/dev-server/src/storefront/frontmatter-contract.ts +++ b/packages/dev-server/src/storefront/frontmatter-contract.ts @@ -1,11 +1,12 @@ // A storefront page's frontmatter, checked against the layout it uses. // -// Eleven keys belong to the build, not to a layout: `layout` (which layout; `page` when absent), `order` +// Thirteen 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` on a -// folder's index.md. A layout cannot declare any of the eleven. Every other key must be declared by the chosen layout's schema — the +// (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 // `.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 @@ -20,11 +21,11 @@ import { suggest } from "@pattern-dump/config"; import { checkDeclared, readSchema, type PropertySchema } from "./declared-values.js"; import { DEFAULT_LAYOUT, type PageFile } from "./pages.js"; import type { FrontmatterValue } from "../frontmatter.js"; -import { readCategories, readDate, readDraft, readSort, readTags, readUpdated, type Read, type SortBy } from "./listing-keys.js"; +import { readCategories, readChildLayout, readDate, readDraft, readSort, readTags, readUpdated, readView, type Read, type SortBy } from "./listing-keys.js"; import { categoryIndex, type CategoryIndex } from "./categories.js"; /** Keys the build owns: they are read by the storefront, never passed to the layout. */ -export const RESERVED_KEYS = ["layout", "order", "redirectFrom", "index", "image", "date", "updated", "tags", "categories", "draft", "sort"] as const; +export const RESERVED_KEYS = ["layout", "childLayout", "order", "redirectFrom", "index", "image", "date", "updated", "tags", "categories", "draft", "sort", "view"] as const; /** Keys the storefront fills for every page: a page cannot set them. */ export const ASSEMBLY_KEYS = ["body", "nav", "site", "page"] as const; @@ -54,6 +55,8 @@ export interface BuildKeys { draft?: boolean; /** On a folder's index.md: how its pages are listed. */ sort?: SortBy; + /** On a folder's index.md: the view its listing is shown in (views.ts checks that it is one). */ + view?: string; } /** An old route: root-relative, slash-wrapped, plain segments only (no query, fragment, "." or ".."). */ @@ -83,7 +86,7 @@ function checkBuildKeys(values: Record, path: string, if (typeof image === "string" && ASSET_PATH.test(image)) out.image = image; else at("image", `image must be a path to a file in the assets, such as "/assets/images/share.png"`); } - const take = (key: K, r: Read> | undefined): void => { + const take = (key: K, r: Read> | undefined): void => { if (r === undefined) return; if (r.ok) out[key] = r.value; else at(key, r.message); @@ -99,6 +102,7 @@ function checkBuildKeys(values: Record, path: string, } else if (cats) at("categories", cats.message); take("draft", v("draft") === undefined ? undefined : readDraft(v("draft")!)); take("sort", v("sort") === undefined ? undefined : readSort(v("sort")!, path)); + take("view", v("view") === undefined ? undefined : readView(v("view")!, path)); return out; } @@ -138,19 +142,33 @@ export async function checkPageFrontmatter(page: PageFile, discoveryMap: Discove }; const buildKeys = () => checkBuildKeys(values, page.path, at, categories, renamed); - // ---- layout ---- + // ---- layout: its own, else its folder's childLayout (pages.ts), else the default ---- + const known = layoutNames(discoveryMap); + const isLayout = (name: string) => /^[^/~]+$/.test(name) && discoveryMap.has(`layouts/${name}`); + const notALayout = (subject: string) => known.length + ? `${subject} is not a layout: the layouts are ${known.map(n => `"${n}"`).join(", ")}` + : `${subject} is not a layout: the project has no layouts (components in a layouts/ folder of its patterns)`; + // The default layout this index.md gives its folder's pages: checked here, once, whether or not a page takes it. + const rawChild = values["childLayout"]; + if (rawChild !== undefined) { + const r = readChildLayout(rawChild, page.path); + if (!r.ok) at("childLayout", r.message); + else if (!isLayout(r.value)) at("childLayout", notALayout(`childLayout "${r.value}"`)); + } const rawLayout = values["layout"]; - let layout = DEFAULT_LAYOUT; + const inherited = rawLayout === undefined ? page.inherited : undefined; + let layout = inherited?.layout ?? DEFAULT_LAYOUT; if (Array.isArray(rawLayout)) at("layout", "layout must be one layout name, not a list"); else if (rawLayout !== undefined) layout = rawLayout; const layoutId = `layouts/${layout}`; - const known = layoutNames(discoveryMap); - const entry = /^[^/~]+$/.test(layout) ? discoveryMap.get(layoutId) : undefined; + /** The layout as messages name it: with where it came from, when the page took it from its folder. */ + const named = `layout "${layout}"${inherited ? ` (the childLayout of ${inherited.from})` : ""}`; + const entry = isLayout(layout) ? discoveryMap.get(layoutId) : undefined; if (!entry || Array.isArray(rawLayout)) { if (!Array.isArray(rawLayout)) { - at("layout", known.length - ? `layout "${layout}" is not a layout: the layouts are ${known.map(n => `"${n}"`).join(", ")}` - : `layout "${layout}" is not a layout: the project has no layouts (components in a layouts/ folder of its patterns)`); + const problem = notALayout(named); + if (inherited) problems.push({ file: page.path, message: problem }); + else at("layout", problem); } return { layoutId, values: {}, build: buildKeys(), problems, notes }; } @@ -158,7 +176,7 @@ export async function checkPageFrontmatter(page: PageFile, discoveryMap: Discove // ---- the layout's schema: what a page may set ---- const read = await readSchema(entry.schemaPath); if (read.error !== undefined) { - problems.push({ file: page.path, message: `the schema of layout "${layout}" cannot be read: ${read.error}` }); + problems.push({ file: page.path, message: `the schema of ${named} cannot be read: ${read.error}` }); return { layoutId, values: {}, build: buildKeys(), problems, notes }; } const schema: LayoutSchema = read.schema ?? {}; @@ -180,9 +198,9 @@ export async function checkPageFrontmatter(page: PageFile, discoveryMap: Discove if ((ASSEMBLY_KEYS as readonly string[]).includes(key)) { at(key, `"${key}" is filled by the storefront, not by a page`); continue; } const prop = Object.hasOwn(declared, key) ? declared[key] : undefined; if (!prop) { - if (!hasSchema) { at(key, `"${key}" is not declared by layout "${layout}", which has no schema`); continue; } + if (!hasSchema) { at(key, `"${key}" is not declared by ${named}, which has no schema`); continue; } const near = suggest(key, [...Object.keys(declared), ...RESERVED_KEYS]); - at(key, `"${key}" is not declared by layout "${layout}"${near ? `: did you mean "${near}"?` : ""}`); + at(key, `"${key}" is not declared by ${named}${near ? `: did you mean "${near}"?` : ""}`); continue; } const r = checkDeclared(prop, value, "frontmatter"); @@ -193,7 +211,7 @@ export async function checkPageFrontmatter(page: PageFile, discoveryMap: Discove // ---- what the layout requires ---- for (const key of schema.required ?? []) { if ((ASSEMBLY_KEYS as readonly string[]).includes(key)) continue; - if (!(key in values)) problems.push({ file: page.path, message: `"${key}" is required by layout "${layout}"` }); + if (!(key in values)) problems.push({ file: page.path, message: `"${key}" is required by ${named}` }); } return { layoutId, values: out, build, problems, notes }; diff --git a/packages/dev-server/src/storefront/listing-keys.ts b/packages/dev-server/src/storefront/listing-keys.ts index 0affc68..f7361b7 100644 --- a/packages/dev-server/src/storefront/listing-keys.ts +++ b/packages/dev-server/src/storefront/listing-keys.ts @@ -1,4 +1,5 @@ -// The keys a page sets for listings (collections): `date`, `tags`, `categories`, `draft`, and `sort` on a folder's index.md. +// The keys a page sets for listings (collections): `date`, `tags`, `categories`, `draft`, and `sort`, `childLayout` and +// `view` on a folder's index.md. // Reserved like `redirectFrom` and `image`: the build reads them, a layout never declares them. Each is read // from the frontmatter's text by one function here, so the page check (frontmatter-contract.ts) and the page // model (pages.ts) read the same value: the check reports what is wrong, the model takes only what is right. @@ -9,6 +10,8 @@ // categories: [guides] each declared in storefront.categories (or an old key of one), no duplicates // draft: true true or false // sort: date on a folder's index.md: its pages newest first ("order", the default: the nav's order) +// childLayout: article on a folder's index.md: the layout of the pages under it that name none (the nearest wins) +// view: grid on a folder's index.md: how its listing is shown (a component in the skin's views/) import { suggest } from "@pattern-dump/config"; import type { FrontmatterValue } from "../frontmatter.js"; @@ -93,9 +96,30 @@ export function readDraft(v: FrontmatterValue): Read { export type SortBy = "date" | "order"; +/** A folder's index.md (the root's included): the pages that sort, set a default layout and name a view. */ +export const isFolderIndex = (path: string): boolean => path === "index.md" || path.endsWith("/index.md"); + +/** `childLayout: article` on a folder's index.md: the layout of its pages that name none (the name only; whether + * it is a layout is checked against the patterns, in frontmatter-contract.ts). */ +export function readChildLayout(v: FrontmatterValue, path: string): Read { + if (!isFolderIndex(path)) { + return { ok: false, message: `childLayout sets the layout of a folder's pages, so it belongs on the folder's index.md, not on a page` }; + } + return typeof v === "string" ? { ok: true, value: v } : { ok: false, message: "childLayout must be one layout name, not a list" }; +} + +/** `view: grid` on a folder's index.md: how its listing is shown, a component in the skin's views/ folder (whether it + * is one is checked against the patterns, in views.ts). */ +export function readView(v: FrontmatterValue, path: string): Read { + if (!isFolderIndex(path)) { + return { ok: false, message: `view names how a folder's pages are listed, so it belongs on the folder's index.md, not on a page` }; + } + return typeof v === "string" ? { ok: true, value: v } : { ok: false, message: "view must be one view name, not a list" }; +} + /** `path`: the page's path in the pages folder; only a folder's index.md (the root's included) sorts. */ export function readSort(v: FrontmatterValue, path: string): Read { - if (path !== "index.md" && !path.endsWith("/index.md")) { + if (!isFolderIndex(path)) { return { ok: false, message: `sort orders a folder's pages, so it belongs on the folder's index.md, not on a page` }; } return v === "date" || v === "order" ? { ok: true, value: v } diff --git a/packages/dev-server/src/storefront/page.ts b/packages/dev-server/src/storefront/page.ts index f6c3690..306191f 100644 --- a/packages/dev-server/src/storefront/page.ts +++ b/packages/dev-server/src/storefront/page.ts @@ -37,6 +37,8 @@ import { checkLinks } from "./links.js"; import { checkPageBasics } from "./page-basics.js"; import { redirectsOf } from "./redirects.js"; import { dateOf, entriesOf, resolveCollections, type Entry } from "./collections.js"; +import { cardOf, checkEntries, readCard } from "./cards.js"; +import { checkViewSampleData, resolveView } from "./views.js"; import type { Category } from "./categories.js"; /** Said once (the same text from every page) when JSON-LD leaves git's date out for a shallow clone. */ @@ -423,12 +425,41 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem else published ??= dated.dates.created; } // A listing's entries, and the page's own date and tags (collections.ts), for a layout that shows them. - const listing: { children?: Entry[]; date?: string | null; updated?: string | null; tags?: string[]; categories?: Category[] } = {}; + const listing: { children?: Entry[]; date?: string | null; updated?: string | null; tags?: string[]; categories?: Category[]; listing?: string | null } = {}; + // The layout's card for them (x-pd-card on page.children): every page of the listing is checked against it. + const layoutCard = cardOf(layoutSchema?.properties?.["page"]?.properties?.["children"]); if (declares("children")) { const listed = isNotFound ? { entries: [], problems: [], notes: [] } : await entriesOf(route, model, { dates: a.dates, mode }); listing.children = listed.entries; problems.push(...listed.problems); notes.push(...listed.notes); + if (layoutCard !== undefined) { + const read = await readCard(layoutCard, checked.layoutId, "the listing's card", a.discoveryMap); + problems.push(...read.problems); + if (read.card) problems.push(...checkEntries(listed.entries, read.card, page.path, model)); + } + } + // The listing through the view the page names (views.ts), for a layout that shows one (page.listing): every page + // checked against the view's card, the view rendered once the page has no problems. + let view: { id: string; entries: Entry[] } | undefined; + if (!isNotFound) { + const resolved = await resolveView({ + view: checked.build.view, line: page.frontmatter.lines["view"], path: page.path, + layout: checked.layoutId.slice("layouts/".length), shows: declares("listing"), discoveryMap: a.discoveryMap, + }); + problems.push(...resolved.problems); + if (resolved.view) { + let entries = listing.children; + if (entries === undefined) { + const listed = await entriesOf(route, model, { dates: a.dates, mode }); + entries = listed.entries; + problems.push(...listed.problems); + notes.push(...listed.notes); + } + problems.push(...checkEntries(entries, resolved.view.card, page.path, model)); + problems.push(...await checkViewSampleData(resolved.view, a.discoveryMap)); + view = { id: resolved.view.id, entries }; + } } if (declares("date")) { const dated = isNotFound ? { date: null, problems: [], notes: [] } : await dateOf(route, model, a.dates, mode); @@ -444,7 +475,8 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem if (collections) { problems.push(...collections.problems); notes.push(...collections.notes); } notes.push(...site.notes ?? []); if (a.discoveryMap.has(checked.layoutId)) { - problems.push(...await checkSampleData(checked.layoutId, a.discoveryMap, a.composition, layoutDeclared, siteDeclared, pageDeclaration.declared, site.listed, site.collections)); + problems.push(...await checkSampleData(checked.layoutId, a.discoveryMap, a.composition, layoutDeclared, siteDeclared, pageDeclaration.declared, site.listed, site.collections, + layoutCard !== undefined && declares("children") ? [layoutCard] : [])); } // The skin's head partial: the same for every page, so its problems are the whole site's. const hasHead = a.discoveryMap.has(HEAD_PARTIAL); @@ -454,6 +486,13 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem problems.push(...headSample); } if (problems.length) return fail(problems); + if (view) { + try { + listing.listing = (await a.render({ component: view.id, data: { entries: view.entries } })).html; + } catch (e) { + return fail([`${view.id}: ${e instanceof Error ? e.message : String(e)}`]); + } + } else if (declares("listing")) listing.listing = null; notes.push(...checked.notes); // pd dev shows drafts and scheduled pages; each is said once, whichever page is open. if (a.live) { @@ -568,7 +607,7 @@ export async function assemblePage(route: string, model: PageModel, a: PageAssem : []), ...(headExtra ? [headExtra] : []), ...(siteHead ? [siteHead] : []), - await a.head(checked.layoutId, html, [...placedIds]), + await a.head(checked.layoutId, html, [...placedIds, ...(view ? [view.id] : [])]), ].join("\n"); // The 404 page is served at any depth, so every URL in it (its body's, its layout's, the head's) must be // root-relative or absolute: a relative one points somewhere else on every address. diff --git a/packages/dev-server/src/storefront/pages.ts b/packages/dev-server/src/storefront/pages.ts index 4d85637..a49e851 100644 --- a/packages/dev-server/src/storefront/pages.ts +++ b/packages/dev-server/src/storefront/pages.ts @@ -25,11 +25,11 @@ import { readdir, readFile, stat } from "node:fs/promises"; import { join, relative, sep } from "node:path"; -import { PD_ROUTES, type StorefrontNavItem, type StorefrontPage, type StorefrontPagesResponse } from "@pattern-dump/contracts"; +import { PD_ROUTES, type LayoutPageUse, type StorefrontNavItem, type StorefrontPage, type StorefrontPagesResponse } from "@pattern-dump/contracts"; import { frontmatterBody, readFrontmatterStrict, type FrontmatterReading } from "../frontmatter.js"; import { orderSiblings, parseOrder, type Orderable } from "../tree-order.js"; import { redirectProblems, redirectsOf, workbenchPlace } from "./redirects.js"; -import { readCategories, readDate, readDraft, readSort, readTags, readUpdated, type SortBy } from "./listing-keys.js"; +import { readCategories, readChildLayout, readDate, readDraft, readSort, readTags, readUpdated, type SortBy } from "./listing-keys.js"; import { categoryIndex, type Category, type CategoryIndex } from "./categories.js"; import type { StorefrontCategory } from "@pattern-dump/config"; import { teaserOf } from "./teaser.js"; @@ -47,8 +47,14 @@ export interface PageFile { /** The file, relative to pagesDir, with forward slashes ("guides/setup.md"). */ path: string; frontmatter: FrontmatterReading; + /** The layout the page takes when it names none: the `childLayout` of the nearest folder above it that sets one + * (`from`: that folder's index.md). Absent when no folder above it does. */ + inherited?: InheritedLayout; } +/** A default layout from a folder: the name its index.md's `childLayout` gives, and that index.md's path. */ +export interface InheritedLayout { layout: string; from: string } + /** What a listing shows of a page, from its file alone (collections.ts adds the date from git). */ export interface PageEntryFields { /** Its description, else the first paragraph of its body (teaser.ts), else null. */ @@ -104,6 +110,15 @@ export interface PageModel extends StorefrontPagesResponse { problems: string[]; } +/** The pages that render with the layout `name`, by path, each with where it got it (the workbench's Relationships). */ +export function layoutPages(model: PageModel, name: string): LayoutPageUse[] { + return model.pages.filter(p => p.layout === name).map(p => { + const f = model.files.get(p.route)!; + const source = p.layoutFrom !== undefined ? "folder" : f.frontmatter.values["layout"] !== undefined ? "own" : "default"; + return { route: p.route, path: f.path, source, ...(p.layoutFrom !== undefined ? { from: p.layoutFrom } : {}) } satisfies LayoutPageUse; + }).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); +} + /** "guides/setup.md" -> "/guides/setup/", "index.md" -> "/", "guides/index.md" -> "/guides/". */ export function routeFor(path: string): string { const parts = path.replace(/\.md$/, "").split("/"); @@ -221,12 +236,34 @@ export async function readPages(pagesDir: string, opts: { } scheduled.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + // Default layouts: each page that names no layout takes the childLayout of the nearest folder above it that sets + // one. A folder's index.md is a page of its parent folder, so its own childLayout is for the pages under it. + const childLayoutOf = (folder: string): string | undefined => { + const index = files.get(folder); + const v = index?.frontmatter.values["childLayout"]; + if (!index || v === undefined) return undefined; + const r = readChildLayout(v, index.path); + return r.ok ? r.value : undefined; + }; + for (const f of files.values()) { + const segments = f.route.split("/").filter(Boolean); + // The folders above the page, nearest first: for /a/b/c/ (a page, or the index.md of folder c) they are /a/b/, /a/, /. + for (let i = segments.length - 1; i >= 0; i--) { + const folder = i === 0 ? "/" : `/${segments.slice(0, i).join("/")}/`; + const layout = childLayoutOf(folder); + if (layout !== undefined) { f.inherited = { layout, from: files.get(folder)!.path }; break; } + } + } + const pageOf = (f: PageFile): StorefrontPage => { const redirectFrom = redirectsOf(f); + const own = f.frontmatter.values["layout"]; + const inherited = own === undefined ? f.inherited : undefined; return { route: f.route, title: scalar(f.frontmatter.values["title"]) ?? f.route, - layout: scalar(f.frontmatter.values["layout"]) ?? DEFAULT_LAYOUT, + layout: scalar(own) ?? inherited?.layout ?? DEFAULT_LAYOUT, + ...(inherited ? { layoutFrom: inherited.from } : {}), ...(redirectFrom.length ? { redirectFrom } : {}), }; }; diff --git a/packages/dev-server/src/storefront/sample-data.ts b/packages/dev-server/src/storefront/sample-data.ts index 706a84f..3528f46 100644 --- a/packages/dev-server/src/storefront/sample-data.ts +++ b/packages/dev-server/src/storefront/sample-data.ts @@ -19,7 +19,7 @@ import { basename } from "node:path"; import type { DiscoveryMap } from "@pattern-dump/contracts"; import type { CompositionRegistry } from "../composition.js"; import { ASSEMBLY_KEYS } from "./frontmatter-contract.js"; -import { outsideShape, PAGE_SHAPE } from "./derived.js"; +import { ENTRY, outsideShape, PAGE_SHAPE } from "./derived.js"; import { SITE_SCHEMA_OWNER } from "./site.js"; const isPlainObject = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v); @@ -48,6 +48,9 @@ export async function checkSampleData( navigationNames: string[] = [], /** The collection names partials/base lists under site.collections. */ collectionNames: string[] = [], + /** The cards in the tree (x-pd-card): each renders with a page of a listing as its context, so its sample data may + * set only that page's fields (ENTRY), not the layout's keys. */ + cards: readonly string[] = [], ): Promise { const problems: string[] = []; const allowed = new Set([...layoutDeclared, ...ASSEMBLY_KEYS].filter(k => k !== "page" || pageDeclared !== undefined)); @@ -60,6 +63,12 @@ export async function checkSampleData( try { data = JSON.parse(await readFile(jsonPath, "utf8")); } catch (e) { problems.push(`${where} cannot be read: ${e instanceof Error ? e.message : String(e)}`); continue; } if (!isPlainObject(data)) continue; + if (cards.includes(id)) { + for (const at of outsideShape(data, ENTRY, "")) { + problems.push(`${where} sets "${at.slice(1)}", which is not a field of a page in a listing, so it would show on every card of ${layoutId}`); + } + continue; + } for (const [key, value] of Object.entries(data)) { if (!allowed.has(key)) { problems.push(`${where} sets "${key}", which ${layoutId} does not declare, so it would show on every page using that layout`); diff --git a/packages/dev-server/src/storefront/views.ts b/packages/dev-server/src/storefront/views.ts new file mode 100644 index 0000000..e19d978 --- /dev/null +++ b/packages/dev-server/src/storefront/views.ts @@ -0,0 +1,98 @@ +// Listing views: how a listing is shown. A view is a component directly under views/ in the skin's style guide +// (`views/grid`), as a layout is under layouts/; Pattern Dump has none of its own, so every skin defines its own. +// +// - A folder's index.md names its view: `view: grid`. A layout that shows a listing declares `page.listing` and +// writes `{{{page.listing}}}`: the folder's pages rendered through the view, once, with `entries` (the pages, in +// the folder's sort order) as the view's only data. +// - A view's schema declares `entries`, a list, with `x-pd-card` naming the card it shows each page as. That card's +// `required` are the fields the view needs (cards.ts): separate cards per view, not variants of one, so each +// view's fields are checked on their own. +// - Checked: a view that isn't one, a listing page that names none, a view on a page whose layout shows no listing, +// a view that names no card. Its sample data, and its card's, may hold only the fields of a page in a listing. + +import { readFile } from "node:fs/promises"; +import { basename } from "node:path"; +import type { DiscoveryMap } from "@pattern-dump/contracts"; +import { suggest } from "@pattern-dump/config"; +import { readSchema } from "./declared-values.js"; +import { cardOf, readCard, type Card } from "./cards.js"; +import { ENTRY, outsideShape } from "./derived.js"; + +const VIEW_ID = /^views\/[^/~]+$/; +/** The data a view is rendered with: the pages of its listing. */ +export const VIEW_KEY = "entries"; + +/** The views a listing can name: base components directly under views/. */ +export function viewNames(discoveryMap: DiscoveryMap): string[] { + return [...discoveryMap.keys()].filter(id => VIEW_ID.test(id)).map(id => id.slice("views/".length)).sort(); +} + +/** A view, resolved for a listing page: its component and its card. */ +export interface ResolvedView { id: string; card: Card } + +/** + * The view a listing page names (`view`, at `line`), for a layout that shows a listing or not (`shows`). Every + * problem, each with the page's file. Nothing to do for a page that names none and shows none. + */ +export async function resolveView(o: { + view: string | undefined; line: number | undefined; path: string; layout: string; shows: boolean; discoveryMap: DiscoveryMap; +}): Promise<{ view?: ResolvedView; problems: string[] }> { + const at = `${o.path}${o.line !== undefined ? `:${o.line}` : ""}`; + const names = viewNames(o.discoveryMap); + const list = names.length ? `the views are ${names.map(n => `"${n}"`).join(", ")}` : undefined; + if (o.view === undefined) { + if (!o.shows) return { problems: [] }; + return { problems: [`${o.path}: layout "${o.layout}" shows a listing (page.listing), so name its view: view: ` + + `(${list ?? "the skin has no views yet: components in a views/ folder of its patterns"})`] }; + } + if (!o.shows) return { problems: [`${at}: view names how a listing is shown, but layout "${o.layout}" shows none (it doesn't declare page.listing)`] }; + const id = `views/${o.view}`; + if (!VIEW_ID.test(id) || !o.discoveryMap.has(id)) { + if (!list) return { problems: [`${at}: view "${o.view}" is not a view: the skin has no views (components in a views/ folder of its patterns)`] }; + const near = suggest(o.view, names); + return { problems: [`${at}: view "${o.view}" is not a view: ${near ? `did you mean "${near}"? (${list})` : list}`] }; + } + const read = await readSchema(o.discoveryMap.get(id)?.schemaPath); + if (read.error !== undefined) return { problems: [`${id}: its schema cannot be read: ${read.error}`] }; + const cardId = cardOf(read.schema?.properties?.[VIEW_KEY]); + if (cardId === undefined) { + return { problems: [`${id}: its schema declares no "${VIEW_KEY}" list with "x-pd-card": a view names the card it shows each page as, ` + + `so each page can be checked against it`] }; + } + const card = await readCard(cardId, id, `the card of view "${o.view}"`, o.discoveryMap); + return card.card ? { view: { id, card: card.card }, problems: card.problems } : { problems: card.problems }; +} + +const isPlainObject = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v); + +/** + * A view's sample data, and its card's: the view may set only `entries`, each a page of a listing, and the card only + * the fields of one. The renderer merges a component's sample data beneath what it is given, so anything else would + * show on every listing shown in the view. + */ +export async function checkViewSampleData(view: ResolvedView, discoveryMap: DiscoveryMap): Promise { + const problems: string[] = []; + const read = async (id: string): Promise<{ data?: unknown; where: string } | undefined> => { + const jsonPath = discoveryMap.get(id)?.jsonPath; + if (!jsonPath) return undefined; + const where = `the sample data of ${id} (${basename(jsonPath)})`; + try { return { data: JSON.parse(await readFile(jsonPath, "utf8")) as unknown, where }; } + catch (e) { problems.push(`${where} cannot be read: ${e instanceof Error ? e.message : String(e)}`); return undefined; } + }; + const own = await read(view.id); + if (own && isPlainObject(own.data)) { + for (const key of Object.keys(own.data).filter(k => k !== VIEW_KEY)) { + problems.push(`${own.where} sets "${key}", which a view doesn't get: a view gets only ${VIEW_KEY}, the pages of its listing`); + } + for (const at of outsideShape(own.data[VIEW_KEY], { items: ENTRY }, VIEW_KEY)) { + problems.push(`${own.where} sets "${at}", which is not a field of a page in a listing, so it would show on every page using ${view.id}`); + } + } + const card = await read(view.card.id); + if (card) { + for (const at of outsideShape(card.data, ENTRY, "")) { + problems.push(`${card.where} sets "${at.slice(1)}", which is not a field of a page in a listing, so it would show on every card of ${view.id}`); + } + } + return problems; +} diff --git a/packages/dev-server/test/placed-schema.spec.ts b/packages/dev-server/test/placed-schema.spec.ts index 7244d8f..686b2b0 100644 --- a/packages/dev-server/test/placed-schema.spec.ts +++ b/packages/dev-server/test/placed-schema.spec.ts @@ -44,7 +44,7 @@ describe("a schema that misuses a placement extension", () => { const detail = await (await fetch(`http://127.0.0.1:${server.port}/api/component/atoms/note`)).json() as ComponentDetail; expect(detail.diagnostics.filter(d => d.kind === "SCHEMA_INVALID")).toEqual([{ kind: "SCHEMA_INVALID", severity: "error", source: "schema", path: "#/x-pd-contnet", - message: `"x-pd-contnet" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, + message: `"x-pd-contnet" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, location: { file: "src/patterns/atoms/note/note.schema.json" }, }]); }); @@ -61,7 +61,7 @@ describe("a schema that misuses a placement extension", () => { }); expect(r.html).toBeUndefined(); expect(r.problems.map(p => p.message)).toEqual([ - `atoms/note cannot be placed: its schema (src/patterns/atoms/note/note.schema.json, #/x-pd-contnet): "x-pd-contnet" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, + `atoms/note cannot be placed: its schema (src/patterns/atoms/note/note.schema.json, #/x-pd-contnet): "x-pd-contnet" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, ]); }); }); diff --git a/packages/dev-server/test/storefront-bench.spec.ts b/packages/dev-server/test/storefront-bench.spec.ts index 9e794ad..ab2de4c 100644 --- a/packages/dev-server/test/storefront-bench.spec.ts +++ b/packages/dev-server/test/storefront-bench.spec.ts @@ -103,4 +103,20 @@ describe("storefront bench in the workbench", () => { expect(p.text).toContain("Careful"); expect(p.text).toContain("A warning callout marks something that can go wrong."); }); + + // Which pages render with a layout, and how each got it: its own layout:, a folder's childLayout, or the default. + it("lists, on each layout, the pages that use it and where each got it from", async () => { + const pagesOf = async (id: string) => ((await (await fetch(origin + componentUrl(id))).json()) as ComponentDetailResponse).relationships.pages; + expect(await pagesOf("layouts/article")).toEqual([ + { route: "/articles/harbour/", path: "articles/harbour.md", source: "folder", from: "articles/index.md" }, + ]); + expect(await pagesOf("layouts/doc")).toEqual([ + { route: "/about/", path: "about.md", source: "own" }, + { route: "/articles/plain/", path: "articles/plain.md", source: "own" }, + { route: "/guides/setup/", path: "guides/setup.md", source: "own" }, + ]); + expect(await pagesOf("layouts/page")).toEqual([{ route: "/guides/", path: "guides/index.md", source: "default" }]); + // Not a layout: no pages at all. + expect(await pagesOf("components/card")).toBeUndefined(); + }); }); diff --git a/packages/dev-server/test/storefront-build.spec.ts b/packages/dev-server/test/storefront-build.spec.ts index 8e8615a..d46a702 100644 --- a/packages/dev-server/test/storefront-build.spec.ts +++ b/packages/dev-server/test/storefront-build.spec.ts @@ -253,7 +253,7 @@ describe("pd build — the storefront root", () => { } finally { await server.close(); } }, 60_000); - it("leaves the workbench snapshot exactly as a build without a storefront makes it", async () => { + it("leaves the workbench snapshot exactly as a build without a storefront makes it, but for each layout's pages", async () => { // From the same copy: a compiled script's banner names its source path, so two copies' builds would // differ by where they are, whatever the storefront does. const { storefront: _sf, ...noStorefront } = benchConfig; @@ -262,7 +262,16 @@ describe("pd build — the storefront root", () => { const b = await tree(join(root, "..", "wb-none")); expect([...a.keys()].sort()).toEqual([...b.keys()].sort()); const differing = [...a].filter(([k, v]) => !v.bytes.equals(b.get(k)!.bytes)).map(([k]) => k); - expect(differing).toEqual([]); + // A layout's detail lists the pages that render with it (relationships.pages), which only a site has: that, and + // nothing else, differs. + const layouts = ["article", "doc", "home", "listing", "page"].map(l => `api/component/layouts/${l}/index.json`); + expect(differing.sort()).toEqual(layouts); + for (const k of layouts) { + const withSite = JSON.parse(a.get(k)!.bytes.toString("utf8")) as { relationships: { pages?: unknown[] } }; + expect(withSite.relationships.pages?.length, k).toBeGreaterThan(0); + delete withSite.relationships.pages; + expect(withSite, k).toEqual(JSON.parse(b.get(k)!.bytes.toString("utf8"))); + } }, 120_000); }); diff --git a/packages/dev-server/test/storefront-cards.spec.ts b/packages/dev-server/test/storefront-cards.spec.ts new file mode 100644 index 0000000..b055f56 --- /dev/null +++ b/packages/dev-server/test/storefront-cards.spec.ts @@ -0,0 +1,112 @@ +// A listing's card (x-pd-card on a layout's page.children): every page in the listing is checked against the +// card's schema. A field the card requires that a page doesn't have fails the listing page, naming that page and +// what to add; a card may declare only the fields of a listing's entry (Pattern Dump's shape, the base every card +// shares); its sample data is checked against that shape, not against the layout's keys. +import { afterAll, describe, expect, it } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { RenderInput } from "@pattern-dump/contracts"; +import { buildDiscoveryMap } from "@pattern-dump/discovery"; +import { createRenderer } from "@pattern-dump/renderer"; +import { buildCompositionRegistry } from "../src/composition.js"; +import { readPages } from "../src/storefront/pages.js"; +import { assemblePage, type PageAssembly } from "../src/storefront/page.js"; +import { save } from "../../../test-support/save.js"; + +const roots: string[] = []; +afterAll(async () => { await Promise.all(roots.map(r => rm(r, { recursive: true, force: true }))); }); + +const md = (title: string, extra = "", body = `Body of ${title}.`): string => `---\ntitle: ${title}\n${extra}---\n\n${body}\n`; + +/** The listing layout: one card per page.children entry, the card named by x-pd-card. */ +const LISTING = { + "layouts/listing/listing.hbs": `

      {{title}}

      {{{body}}}
        {{#each page.children}}
      • {{> components-card }}
      • {{/each}}
      `, + "layouts/listing/listing.schema.json": JSON.stringify({ + properties: { title: { type: "string" }, page: { type: "object", properties: { children: { "x-pd-card": "components/card" } } } }, + }), + "layouts/page/page.hbs": `

      {{title}}

      {{{body}}}
      `, + "layouts/page/page.schema.json": JSON.stringify({ properties: { title: { type: "string" } } }), + "components/card/card.hbs": ``, +}; +const card = (schema: unknown) => ({ "components/card/card.schema.json": JSON.stringify(schema) }); +const SITE = { + "index.md": md("Home"), + "articles/index.md": md("Articles", "layout: listing\nsort: date\n"), + "articles/one.md": md("One", "date: 2026-11-02\nimage: /assets/images/one.jpg\ntags: [css]\n"), + "articles/two.md": md("Two", "date: 2026-10-01\n"), +}; + +async function assemble(route: string, patterns: Record, pages: Record = SITE) { + const root = await mkdtemp(join(tmpdir(), "pd-cards-")); + roots.push(root); + for (const [rel, body] of Object.entries(patterns)) await save(join(root, "patterns", ...rel.split("/")), body); + for (const [rel, body] of Object.entries(pages)) await save(join(root, "pages", ...rel.split("/")), body); + const dir = join(root, "patterns"); + const { discoveryMap, handleMap } = await buildDiscoveryMap(dir); + const render = createRenderer({ patternsDir: dir, discoveryMap, handleMap }); + const inputs: RenderInput[] = []; + const page = await assemblePage(route, await readPages(join(root, "pages")), { + discoveryMap, handleMap, composition: await buildCompositionRegistry(dir, handleMap, discoveryMap), + site: undefined, workbenchUrl: "https://wb.example/", shown: p => p, head: async () => "", + image: async () => ({ ok: false, message: "no images here" }), + render: input => { inputs.push(input); return render(input); }, + } as PageAssembly); + return page; +} + +const ENTRY_FIELDS = "route, title, description, date, updated, image, tags, categories, draft, scheduled"; + +describe("x-pd-card: each page of a listing, checked against its card", () => { + it("renders a listing whose pages have every field the card requires", async () => { + const p = await assemble("/articles/", { ...LISTING, ...card({ required: ["route", "title", "date"], properties: { route: { type: "string" }, title: { type: "string" }, date: { type: ["string", "null"] } } }) }); + expect(p.problems).toEqual([]); + expect(p.html).toContain(`
    • `); + }); + + it("reports each page without a field the card requires, naming the page and what to add", async () => { + const p = await assemble("/articles/", { ...LISTING, ...card({ required: ["title", "image", "tags"], properties: { title: { type: "string" }, image: { type: ["string", "null"] }, tags: { type: "array" } } }) }); + expect(p.status).toBe(500); + expect(p.problems).toEqual([ + `articles/index.md: articles/two.md has no image, which the listing's card (components/card) requires: give it one (image: /assets/images/.jpg, a raster image in the assets)`, + // An empty list is no tags at all. + `articles/index.md: articles/two.md has no tags, which the listing's card (components/card) requires: give it one (tags: [a-tag])`, + ]); + }); + + it("checks a page's value against the type the card declares", async () => { + const p = await assemble("/articles/", { ...LISTING, ...card({ properties: { title: { type: "string" }, tags: { type: "string" } } }) }); + expect(p.problems).toEqual([`articles/index.md: articles/one.md: tags must be text (got ["css"]) for the listing's card (components/card)`]); + }); + + it("refuses a card that declares a field a listing's page doesn't have, once", async () => { + const p = await assemble("/articles/", { ...LISTING, ...card({ required: ["author"], properties: { title: { type: "string" }, author: { type: "string" } } }) }); + expect(p.problems).toEqual([ + `components/card (the listing's card, layouts/listing) declares "author", which a page in a listing doesn't have: a card declares only the fields Pattern Dump fills (${ENTRY_FIELDS})`, + ]); + }); + + it("checks a card's sample data against a listing's page, not against the layout's keys", async () => { + const schema = card({ properties: { route: { type: "string" }, title: { type: "string" } } }); + // Keys of an entry: fine, though the layout declares none of them. + expect((await assemble("/articles/", { ...LISTING, ...schema, "components/card/card.json": JSON.stringify({ route: "/x/", title: "Sample", tags: ["a"] }) })).problems).toEqual([]); + // A key outside the entry would show on every card of every listing. + expect((await assemble("/articles/", { ...LISTING, ...schema, "components/card/card.json": JSON.stringify({ title: "Sample", author: "Someone" }) })).problems).toEqual([ + `the sample data of components/card (card.json) sets "author", which is not a field of a page in a listing, so it would show on every card of layouts/listing`, + ]); + }); + + it("fails the listing when the card named is not a component with a schema", async () => { + const p = await assemble("/articles/", { ...LISTING, "layouts/listing/listing.schema.json": JSON.stringify({ + properties: { title: { type: "string" }, page: { type: "object", properties: { children: { "x-pd-card": "components/nope" } } } }, + }) }); + expect(p.problems).toEqual([`layouts/listing: x-pd-card names "components/nope", which is not a component`]); + }); + + it("leaves a listing whose layout names no card unchecked, as before", async () => { + const p = await assemble("/articles/", { ...LISTING, ...card({ required: ["image"], properties: { image: { type: "string" } } }), "layouts/listing/listing.schema.json": JSON.stringify({ + properties: { title: { type: "string" }, page: { type: "object", properties: { children: {} } } }, + }) }); + expect(p.problems).toEqual([]); + }); +}); diff --git a/packages/dev-server/test/storefront-child-layout.spec.ts b/packages/dev-server/test/storefront-child-layout.spec.ts new file mode 100644 index 0000000..babe18b --- /dev/null +++ b/packages/dev-server/test/storefront-child-layout.spec.ts @@ -0,0 +1,121 @@ +// A folder's default layout (`childLayout` on its index.md): a page without its own `layout:` takes the +// childLayout of the nearest folder above it that sets one, else `page`. A folder's index.md is a page of its +// parent folder, so its own childLayout is for the pages under it. Each page is checked against the layout it +// ends up with, and every problem about that layout names where it came from. +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import type { DiscoveryMap } from "@pattern-dump/contracts"; +import { buildDiscoveryMap } from "@pattern-dump/discovery"; +import { readPages, type PageModel } from "../src/storefront/pages.js"; +import { checkPageFrontmatter } from "../src/storefront/frontmatter-contract.js"; +import { save } from "../../../test-support/save.js"; + +const roots: string[] = []; +let map: DiscoveryMap; +afterAll(async () => { await Promise.all(roots.map(r => rm(r, { recursive: true, force: true }))); }); + +async function tree(files: Record): Promise { + const root = await mkdtemp(join(tmpdir(), "pd-child-layout-")); + roots.push(root); + for (const [path, body] of Object.entries(files)) { + const file = join(root, ...path.split("/")); + await mkdir(dirname(file), { recursive: true }); + await save(file, body); + } + return root; +} +const md = (title: string, extra = ""): string => `---\ntitle: ${title}\n${extra}---\n\nBody of ${title}.\n`; + +beforeAll(async () => { + const patterns = await tree({ + "layouts/page/page.hbs": "
      {{title}}{{{body}}}
      ", + "layouts/page/page.schema.json": JSON.stringify({ required: ["title"], properties: { title: { type: "string" }, description: { type: "string" } } }), + "layouts/article/article.hbs": "
      {{title}} {{subtitle}}{{{body}}}
      ", + "layouts/article/article.schema.json": JSON.stringify({ required: ["title", "subtitle"], properties: { title: { type: "string" }, subtitle: { type: "string" } } }), + "layouts/doc/doc.hbs": "
      {{title}}{{{body}}}
      ", + "layouts/doc/doc.schema.json": JSON.stringify({ required: ["title"], properties: { title: { type: "string" } } }), + }); + map = (await buildDiscoveryMap(patterns)).discoveryMap; +}); + +const layouts = (model: PageModel) => Object.fromEntries(model.pages.map(p => [p.route, { layout: p.layout, ...(p.layoutFrom ? { from: p.layoutFrom } : {}) }])); +const problemsOf = async (model: PageModel, route: string) => + (await checkPageFrontmatter(model.files.get(route)!, map, model.categories)).problems.map(p => `${p.file}${p.line !== undefined ? `:${p.line}` : ""}: ${p.message}`); + +describe("childLayout: which layout a page gets, and from where", () => { + it("inherits the nearest folder's childLayout; its own layout wins; a folder's index.md takes its parent's", async () => { + const model = await readPages(await tree({ + "index.md": md("Home", "childLayout: article\nsubtitle: s\n"), + "about.md": md("About", "subtitle: s\n"), + "docs/index.md": md("Docs", "childLayout: doc\nsubtitle: s\n"), + "docs/a.md": md("A"), + "docs/own.md": md("Own", "layout: page\n"), + "docs/sub/index.md": md("Sub"), + "docs/sub/x.md": md("X"), + })); + expect(model.problems).toEqual([]); + expect(layouts(model)).toEqual({ + "/": { layout: "page" }, + "/about/": { layout: "article", from: "index.md" }, + "/docs/": { layout: "article", from: "index.md" }, + "/docs/a/": { layout: "doc", from: "docs/index.md" }, + "/docs/own/": { layout: "page" }, + "/docs/sub/": { layout: "doc", from: "docs/index.md" }, + "/docs/sub/x/": { layout: "doc", from: "docs/index.md" }, + }); + // The check takes the same layout: the inherited one's schema applies. + expect((await checkPageFrontmatter(model.files.get("/docs/a/")!, map)).layoutId).toBe("layouts/doc"); + expect(await problemsOf(model, "/docs/a/")).toEqual([]); + }); + + it("checks a page against the schema of the layout it inherits", async () => { + const model = await readPages(await tree({ + "index.md": md("Home"), + "articles/index.md": md("Articles", "childLayout: article\n"), + "articles/one.md": md("One", "description: Not an article key\n"), + })); + expect(await problemsOf(model, "/articles/one/")).toEqual([ + `articles/one.md:3: "description" is not declared by layout "article" (the childLayout of articles/index.md)`, + `articles/one.md: "subtitle" is required by layout "article" (the childLayout of articles/index.md)`, + ]); + }); + + it("fails a childLayout that is not a layout, on the index.md and on each page that inherits it", async () => { + const model = await readPages(await tree({ + "index.md": md("Home"), + "articles/index.md": md("Articles", "childLayout: artcle\n"), + "articles/one.md": md("One"), + })); + const known = `the layouts are "article", "doc", "page"`; + expect(await problemsOf(model, "/articles/")).toEqual([`articles/index.md:3: childLayout "artcle" is not a layout: ${known}`]); + expect(await problemsOf(model, "/articles/one/")).toEqual([ + `articles/one.md: layout "artcle" (the childLayout of articles/index.md) is not a layout: ${known}`, + ]); + }); + + it("belongs on a folder's index.md, and is one name", async () => { + const model = await readPages(await tree({ + "index.md": md("Home", "childLayout: [doc, page]\n"), + "about.md": md("About", "childLayout: doc\n"), + })); + expect(layouts(model)["/about/"]).toEqual({ layout: "page" }); + expect(await problemsOf(model, "/")).toEqual(["index.md:3: childLayout must be one layout name, not a list"]); + expect(await problemsOf(model, "/about/")).toEqual([ + "about.md:3: childLayout sets the layout of a folder's pages, so it belongs on the folder's index.md, not on a page", + ]); + }); + + it("a layout cannot declare childLayout: a page sets it for the build", async () => { + const patterns = await tree({ + "layouts/page/page.hbs": "
      {{title}}
      ", + "layouts/page/page.schema.json": JSON.stringify({ properties: { title: { type: "string" }, childLayout: { type: "string" } } }), + }); + const own = (await buildDiscoveryMap(patterns)).discoveryMap; + const model = await readPages(await tree({ "index.md": md("Home") })); + expect((await checkPageFrontmatter(model.files.get("/")!, own)).problems.map(p => p.message)).toEqual([ + `layout "page" declares "childLayout", which a page sets for the build, not for its layout: rename it in the layout's schema`, + ]); + }); +}); diff --git a/packages/dev-server/test/storefront-derived.spec.ts b/packages/dev-server/test/storefront-derived.spec.ts index c7af6d2..a66c3d0 100644 --- a/packages/dev-server/test/storefront-derived.spec.ts +++ b/packages/dev-server/test/storefront-derived.spec.ts @@ -29,8 +29,8 @@ describe("checkPageDeclaration", () => { }); it("names what Pattern Dump fills today", () => { - const all = "page.headings, page.section, page.breadcrumbs, page.prev, page.next, page.created, page.updated, page.children, page.date, page.tags, page.categories"; - expect(FILLED).toEqual(["headings", "section", "breadcrumbs", "prev", "next", "created", "updated", "children", "date", "tags", "categories"]); + const all = "page.headings, page.section, page.breadcrumbs, page.prev, page.next, page.created, page.updated, page.children, page.date, page.tags, page.categories, page.listing"; + expect(FILLED).toEqual(["headings", "section", "breadcrumbs", "prev", "next", "created", "updated", "children", "date", "tags", "categories", "listing"]); expect(checkPageDeclaration({ properties: { page: { properties: { toc: {} } } } }, "layouts/doc").problems).toEqual([ `layouts/doc declares "page.toc", which Pattern Dump does not fill (it fills ${all})`, ]); @@ -121,7 +121,7 @@ describe("assemblePage — page", () => { it("a declared sub-key Pattern Dump does not fill fails the page, named", async () => { const { page } = await assemble({ properties: { title: { type: "string" }, page: { type: "object", properties: { toc: { type: "array" } } } } }); expect(page.status).toBe(500); - expect(page.problems).toEqual([`layouts/page declares "page.toc", which Pattern Dump does not fill (it fills page.headings, page.section, page.breadcrumbs, page.prev, page.next, page.created, page.updated, page.children, page.date, page.tags, page.categories)`]); + expect(page.problems).toEqual([`layouts/page declares "page.toc", which Pattern Dump does not fill (it fills page.headings, page.section, page.breadcrumbs, page.prev, page.next, page.created, page.updated, page.children, page.date, page.tags, page.categories, page.listing)`]); }); it("a layout that declares page.headings gets every heading, with the anchor its id carries", async () => { diff --git a/packages/dev-server/test/storefront-pages.spec.ts b/packages/dev-server/test/storefront-pages.spec.ts index c1c668a..1e1f645 100644 --- a/packages/dev-server/test/storefront-pages.spec.ts +++ b/packages/dev-server/test/storefront-pages.spec.ts @@ -58,7 +58,7 @@ describe("readPages — the storefront bench", () => { { route: "/guides/setup/", title: "Setup", layout: "doc", redirectFrom: ["/setup/", "/start/"] }, { route: "/about/", title: "About", layout: "doc" }, { route: "/articles/", title: "Articles", layout: "listing" }, - { route: "/articles/harbour/", title: "A harbour of cable cars", layout: "article" }, + { route: "/articles/harbour/", title: "A harbour of cable cars", layout: "article", layoutFrom: "articles/index.md" }, { route: "/articles/plain/", title: "Plain on purpose", layout: "doc" }, ]); expect(model.nav).toEqual([ diff --git a/packages/dev-server/test/storefront-views.spec.ts b/packages/dev-server/test/storefront-views.spec.ts new file mode 100644 index 0000000..9a711a5 --- /dev/null +++ b/packages/dev-server/test/storefront-views.spec.ts @@ -0,0 +1,120 @@ +// Listing views: a folder's index.md names how its listing is shown (`view: grid`), and the view is a component in +// the skin's views/ folder. Pattern Dump has none of its own. Its layout declares page.listing and writes it +// unescaped; Pattern Dump renders the view once with the folder's pages as `entries` and passes the HTML. The view's +// schema names its card (x-pd-card on `entries`), and every page is checked against that card's schema, so a grid +// whose card requires an image reports the pages without one. +import { afterAll, describe, expect, it } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { buildDiscoveryMap } from "@pattern-dump/discovery"; +import { createRenderer } from "@pattern-dump/renderer"; +import { buildCompositionRegistry } from "../src/composition.js"; +import { readPages } from "../src/storefront/pages.js"; +import { assemblePage, type PageAssembly } from "../src/storefront/page.js"; +import { save } from "../../../test-support/save.js"; + +const roots: string[] = []; +afterAll(async () => { await Promise.all(roots.map(r => rm(r, { recursive: true, force: true }))); }); + +const md = (title: string, extra = "", body = `Body of ${title}.`): string => `---\ntitle: ${title}\n${extra}---\n\n${body}\n`; +const json = (v: unknown) => JSON.stringify(v); +const FIELDS = { route: { type: "string" }, title: { type: "string" }, date: { type: ["string", "null"] }, image: { type: ["string", "null"] } }; + +const SKIN: Record = { + "layouts/listing/listing.hbs": `

      {{title}}

      {{{page.listing}}}
      `, + "layouts/listing/listing.schema.json": json({ properties: { title: { type: "string" }, page: { type: "object", properties: { listing: {} } } } }), + "layouts/page/page.hbs": `

      {{title}}

      {{{body}}}
      `, + "layouts/page/page.schema.json": json({ properties: { title: { type: "string" } } }), + // Two cards: one for every page, one that needs an image. + "components/list-card/list-card.hbs": `{{title}}`, + "components/list-card/list-card.schema.json": json({ required: ["route", "title"], properties: FIELDS }), + "components/grid-card/grid-card.hbs": `{{title}} [{{image}}]`, + "components/grid-card/grid-card.schema.json": json({ required: ["route", "title", "image"], properties: FIELDS }), + "views/list/list.hbs": `
        {{#each entries}}
      • {{> components-list-card }}
      • {{/each}}
      `, + "views/list/list.schema.json": json({ properties: { entries: { type: "array", "x-pd-card": "components/list-card" } } }), + "views/grid/grid.hbs": `
        {{#each entries}}
      • {{> components-grid-card }}
      • {{/each}}
      `, + "views/grid/grid.schema.json": json({ properties: { entries: { type: "array", "x-pd-card": "components/grid-card" } } }), +}; +const pagesWith = (indexExtra: string, extra: Record = {}) => ({ + "index.md": md("Home"), + "articles/index.md": md("Articles", `layout: listing\nsort: date\n${indexExtra}`), + "articles/one.md": md("One", "date: 2026-11-02\nimage: /assets/images/one.jpg\n"), + "articles/two.md": md("Two", "date: 2026-10-01\n"), + ...extra, +}); + +async function assemble(route: string, pages: Record, skin: Record = SKIN) { + const root = await mkdtemp(join(tmpdir(), "pd-views-")); + roots.push(root); + for (const [rel, body] of Object.entries(skin)) await save(join(root, "patterns", ...rel.split("/")), body); + for (const [rel, body] of Object.entries(pages)) await save(join(root, "pages", ...rel.split("/")), body); + const dir = join(root, "patterns"); + const { discoveryMap, handleMap } = await buildDiscoveryMap(dir); + const render = createRenderer({ patternsDir: dir, discoveryMap, handleMap }); + const heads: string[][] = []; + const page = await assemblePage(route, await readPages(join(root, "pages")), { + discoveryMap, handleMap, composition: await buildCompositionRegistry(dir, handleMap, discoveryMap), + site: undefined, workbenchUrl: "https://wb.example/", shown: p => p, + head: async (_layout, _html, placed) => { heads.push([...placed]); return ""; }, + image: async () => ({ ok: false, message: "no images here" }), render, + } as PageAssembly); + return { ...page, placed: heads.at(-1) ?? [] }; +} + +describe("listing views", () => { + it("renders the listing through the view its index.md names, in the folder's order, and loads the view's files", async () => { + const p = await assemble("/articles/", pagesWith("view: list\n")); + expect(p.problems).toEqual([]); + expect(p.html).toContain(`

      Articles

      `); + expect(p.placed).toContain("views/list"); + }); + + it("checks every page against the view's card: a grid card that requires an image reports the pages without one", async () => { + const p = await assemble("/articles/", pagesWith("view: grid\n")); + expect(p.problems).toEqual([ + `articles/index.md: articles/two.md has no image, which the card of view "grid" (components/grid-card) requires: give it one (image: /assets/images/.jpg, a raster image in the assets)`, + ]); + }); + + it("fails a view that doesn't exist, naming the skin's views", async () => { + const p = await assemble("/articles/", pagesWith("view: gird\n")); + expect(p.problems).toEqual([`articles/index.md:5: view "gird" is not a view: did you mean "grid"? (the views are "grid", "list")`]); + }); + + it("fails a listing whose layout shows a view, when its index.md names none", async () => { + const p = await assemble("/articles/", pagesWith("")); + expect(p.problems).toEqual([`articles/index.md: layout "listing" shows a listing (page.listing), so name its view: view: (the views are "grid", "list")`]); + }); + + it("says so when the skin has no views at all", async () => { + const skin = Object.fromEntries(Object.entries(SKIN).filter(([k]) => !k.startsWith("views/"))); + const p = await assemble("/articles/", pagesWith("view: list\n"), skin); + expect(p.problems).toEqual([`articles/index.md:5: view "list" is not a view: the skin has no views (components in a views/ folder of its patterns)`]); + }); + + it("fails a view on a page whose layout shows no listing, and on a page that is not a folder's index.md", async () => { + const onIndex = await assemble("/articles/", { ...pagesWith(""), "articles/index.md": md("Articles", "view: list\n") }); + expect(onIndex.problems).toEqual([`articles/index.md:3: view names how a listing is shown, but layout "page" shows none (it doesn't declare page.listing)`]); + const onPage = await assemble("/articles/one/", pagesWith("view: list\n", { "articles/one.md": md("One", "view: list\n") })); + expect(onPage.problems).toEqual([`articles/one.md:3: view names how a folder's pages are listed, so it belongs on the folder's index.md, not on a page`]); + }); + + it("fails a view that names no card for its entries", async () => { + const p = await assemble("/articles/", pagesWith("view: list\n"), { ...SKIN, "views/list/list.schema.json": json({ properties: { entries: { type: "array" } } }) }); + expect(p.problems).toEqual([`views/list: its schema declares no "entries" list with "x-pd-card": a view names the card it shows each page as, so each page can be checked against it`]); + }); + + it("keeps a view's and its card's sample data to the fields of a listing's page", async () => { + const p = await assemble("/articles/", pagesWith("view: list\n"), { + ...SKIN, + "views/list/list.json": json({ entries: [{ route: "/a/", title: "A", author: "x" }], heading: "Latest" }), + "components/list-card/list-card.json": json({ title: "Sample", rating: 5 }), + }); + expect(p.problems).toEqual([ + `the sample data of views/list (list.json) sets "heading", which a view doesn't get: a view gets only entries, the pages of its listing`, + `the sample data of views/list (list.json) sets "entries[0].author", which is not a field of a page in a listing, so it would show on every page using views/list`, + `the sample data of components/list-card (list-card.json) sets "rating", which is not a field of a page in a listing, so it would show on every card of views/list`, + ]); + }); +}); diff --git a/packages/renderer/src/schema-extensions.ts b/packages/renderer/src/schema-extensions.ts index 819dabf..f7ff25e 100644 --- a/packages/renderer/src/schema-extensions.ts +++ b/packages/renderer/src/schema-extensions.ts @@ -5,8 +5,11 @@ // x-pd-content at a schema's top: the property a tag's content fills; it must be a declared string. // contentMediaType only "text/markdown", only on a string: rendered as markdown, HTML escaped. // -// And two that are not about placement, so they don't switch on the template check below: +// And three that are not about placement, so they don't switch on the template check below: // +// x-pd-card on a list property (a layout's `page.children`, a view's `entries`): the card each page of +// the listing is shown as. It names a component with a schema; the storefront checks every page +// in the listing against that schema (cards.ts in the dev-server). // x-pd-image on a string property: the image slot that field fills, `{ widths, sizes }`, which // `{{pd-image field alt=…}}` writes as an with its variants (image-slots.ts). Every // `{{pd-image}}` call in the template is checked against it. @@ -38,9 +41,9 @@ export interface SchemaExtensionContext { } type Prop = Record; -const KNOWN_PROPERTY_KEYS = new Set(["x-pd-component", "x-pd-image"]); +const KNOWN_PROPERTY_KEYS = new Set(["x-pd-card", "x-pd-component", "x-pd-image"]); const KNOWN_TOP_KEYS = new Set(["x-pd-content", "x-pd-example-height", "x-pd-prose-images"]); -const KNOWN_LIST = "x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images"; +const KNOWN_LIST = "x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images"; const isObject = (v: unknown): v is Prop => typeof v === "object" && v !== null && !Array.isArray(v); const typesOf = (p: Prop): unknown[] => p["type"] === undefined ? [] : Array.isArray(p["type"]) ? p["type"] : [p["type"]]; @@ -98,6 +101,16 @@ export function checkSchemaExtensions(schema: unknown, template: string | undefi else if (!ctx.componentExists(component)) problems.push({ path: `${path}/x-pd-component`, message: `x-pd-component names "${component}", which is not a component` }); else if (!ctx.hasSchema(component)) problems.push({ path: `${path}/x-pd-component`, message: `x-pd-component names "${component}", which has no schema, so it cannot be placed with values` }); } + // A listing's card: not a placement, so it switches on no template check. A list, or a property with no type of + // its own (page.children, whose shape is Pattern Dump's). + const card = prop["x-pd-card"]; + if (card !== undefined) { + const types = typesOf(prop); + if (types.length && !types.includes("array")) problems.push({ path: `${path}/x-pd-card`, message: `x-pd-card is only for a list: the pages of a listing, each shown as the card` }); + else if (typeof card !== "string") problems.push({ path: `${path}/x-pd-card`, message: `x-pd-card must name a component` }); + else if (!ctx.componentExists(card)) problems.push({ path: `${path}/x-pd-card`, message: `x-pd-card names "${card}", which is not a component` }); + else if (!ctx.hasSchema(card)) problems.push({ path: `${path}/x-pd-card`, message: `x-pd-card names "${card}", which has no schema, so a listing's pages can't be checked against it` }); + } const image = prop["x-pd-image"]; if (image !== undefined) { if (!typesOf(prop).includes("string")) problems.push({ path: `${path}/x-pd-image`, message: `x-pd-image is only for a string property: the path of an image in the assets` }); diff --git a/packages/renderer/test/schema-extensions.spec.ts b/packages/renderer/test/schema-extensions.spec.ts index 5324c05..3687c1f 100644 --- a/packages/renderer/test/schema-extensions.spec.ts +++ b/packages/renderer/test/schema-extensions.spec.ts @@ -57,8 +57,8 @@ describe("the placement schema extensions", () => { it("an unknown x-pd- key is an error, at the top and in a property", () => { expect(check({ "x-pd-contnet": "caption", properties: { caption: { type: "string", "x-pd-componnet": "atoms/slide" } } })).toEqual([ - `#/x-pd-contnet: "x-pd-contnet" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, - `#/properties/caption/x-pd-componnet: "x-pd-componnet" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, + `#/x-pd-contnet: "x-pd-contnet" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, + `#/properties/caption/x-pd-componnet: "x-pd-componnet" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, ]); }); @@ -74,7 +74,7 @@ describe("the placement schema extensions", () => { } // In a property it is not a known key. expect(check({ properties: { a: { type: "string", "x-pd-example-height": 10 } } })).toEqual([ - `#/properties/a/x-pd-example-height: "x-pd-example-height" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, + `#/properties/a/x-pd-example-height: "x-pd-example-height" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, ]); }); @@ -98,7 +98,7 @@ describe("the placement schema extensions", () => { } // In a property it is not a known key. expect(check({ properties: { body: { type: "string", "x-pd-prose-images": slot } } })).toEqual([ - `#/properties/body/x-pd-prose-images: "x-pd-prose-images" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, + `#/properties/body/x-pd-prose-images: "x-pd-prose-images" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image, x-pd-prose-images)`, ]); }); @@ -106,6 +106,28 @@ describe("the placement schema extensions", () => { expect(check({ "x-pd-prose-images": { widths: [480], sizes: "100vw" }, properties: { body: { type: "string" } } }, `
      {{{body}}}
      `)).toEqual([]); }); + it("x-pd-card: on a list (a layout's page.children, a view's entries), names a component that exists and has a schema", () => { + expect(check({ properties: { + entries: { type: "array", "x-pd-card": "atoms/slide" }, + page: { type: "object", properties: { children: { "x-pd-card": "atoms/slide" } } }, + } })).toEqual([]); + expect(check({ properties: { + a: { type: "array", "x-pd-card": "atoms/nope" }, + b: { type: "array", "x-pd-card": "atoms/plain" }, + c: { type: "array", "x-pd-card": 3 }, + d: { type: "string", "x-pd-card": "atoms/slide" }, + } })).toEqual([ + `#/properties/a/x-pd-card: x-pd-card names "atoms/nope", which is not a component`, + `#/properties/b/x-pd-card: x-pd-card names "atoms/plain", which has no schema, so a listing's pages can't be checked against it`, + `#/properties/c/x-pd-card: x-pd-card must name a component`, + `#/properties/d/x-pd-card: x-pd-card is only for a list: the pages of a listing, each shown as the card`, + ]); + }); + + it("x-pd-card doesn't make a layout placeable: its template is not checked", () => { + expect(check({ properties: { body: { type: "string" }, page: { properties: { children: { "x-pd-card": "atoms/slide" } } } } }, `
      {{{body}}}
      `)).toEqual([]); + }); + it("x-pd-example-height doesn't make a component placeable: its template is not checked", () => { expect(check({ "x-pd-example-height": 80, properties: { body: { type: "string" } } }, `
      {{{body}}}
      `)).toEqual([]); }); diff --git a/packages/renderer/test/schema-helper-names.spec.ts b/packages/renderer/test/schema-helper-names.spec.ts index b29b12e..f6f6884 100644 --- a/packages/renderer/test/schema-helper-names.spec.ts +++ b/packages/renderer/test/schema-helper-names.spec.ts @@ -38,7 +38,7 @@ describe("checkSchemaHelperNames", () => { it("names its own problems, and no other message", () => { expect(isHelperNameProblem(said("id"))).toBe(true); - expect(isHelperNameProblem(`"x-pd-thing" is not a schema extension Pattern Dump knows (x-pd-component, x-pd-content, x-pd-example-height, x-pd-image)`)).toBe(false); + expect(isHelperNameProblem(`"x-pd-thing" is not a schema extension Pattern Dump knows (x-pd-card, x-pd-component, x-pd-content, x-pd-example-height, x-pd-image)`)).toBe(false); }); }); diff --git a/storefront-bench/e2e/workbench.spec.ts b/storefront-bench/e2e/workbench.spec.ts index e13dac7..99f6026 100644 --- a/storefront-bench/e2e/workbench.spec.ts +++ b/storefront-bench/e2e/workbench.spec.ts @@ -41,4 +41,29 @@ test.describe("the skin in the workbench", () => { expect((await page.frameLocator("#preview-frame").locator("body").innerText()).trim()).not.toBe(""); }); } + + // Which pages a layout renders, and how each got it, so nobody has to guess (childLayout on a folder's index.md). + test("lists a layout's pages in its Relationships, each with where its layout came from", async ({ page }) => { + await page.goto(`${WORKBENCH}/layouts/article`); + await page.waitForSelector("#preview-frame[srcdoc]"); + await page.click("button[data-tab='relationships']"); + const pages = page.locator(".rel-panel .rel-group-heading", { hasText: /^Pages$/ }); + await expect(pages).toBeVisible(); + await expect(pages.locator("xpath=following-sibling::ul[1]").locator(".rel-item")).toHaveText([ + "articles/harbour.md (childLayout of articles/index.md)", + ]); + await page.goto(`${WORKBENCH}/layouts/doc`); + await page.waitForSelector("#preview-frame[srcdoc]"); + await page.click("button[data-tab='relationships']"); + await expect(page.locator(".rel-panel .rel-group-heading", { hasText: /^Pages$/ }).locator("xpath=following-sibling::ul[1]").locator(".rel-item")) + .toHaveText(["about.md (its own layout)", "articles/plain.md (its own layout)", "guides/setup.md (its own layout)"]); + }); + + test("shows no Pages group on a component that is not a layout", async ({ page }) => { + await page.goto(`${WORKBENCH}/components/card`); + await page.waitForSelector("#preview-frame[srcdoc]"); + await page.click("button[data-tab='relationships']"); + await expect(page.locator(".rel-panel .rel-group-heading", { hasText: /^Used by$/ })).toBeVisible(); + await expect(page.locator(".rel-panel .rel-group-heading", { hasText: /^Pages$/ })).toHaveCount(0); + }); }); diff --git a/storefront-bench/pages/articles/harbour.md b/storefront-bench/pages/articles/harbour.md index c73f702..1f79753 100644 --- a/storefront-bench/pages/articles/harbour.md +++ b/storefront-bench/pages/articles/harbour.md @@ -1,5 +1,4 @@ --- -layout: article title: A harbour of cable cars date: 2026-11-01 tags: [images, layout] diff --git a/storefront-bench/pages/articles/index.md b/storefront-bench/pages/articles/index.md index a4a0465..de743b8 100644 --- a/storefront-bench/pages/articles/index.md +++ b/storefront-bench/pages/articles/index.md @@ -1,9 +1,11 @@ --- layout: listing +childLayout: article title: Articles description: Everything written for the bench, newest first. order: 3 sort: date --- -This page is `pages/articles/index.md`: its layout lists the folder's pages, newest first. +This page is `pages/articles/index.md`: its layout lists the folder's pages, newest first. Its `childLayout` gives each +of them the article layout, unless the page names its own. diff --git a/storefront-bench/src/patterns/components/card/card.md b/storefront-bench/src/patterns/components/card/card.md index b8104ca..6410d84 100644 --- a/storefront-bench/src/patterns/components/card/card.md +++ b/storefront-bench/src/patterns/components/card/card.md @@ -3,8 +3,8 @@ title: Card description: One entry of a listing (layouts/listing, page.children): a title linking to the page, its date, its teaser and its image. --- -The card is included by a layout, inside `{{#each page.children}}`, so it gets an entry as its context. It has no -sample data of its own, since a layout's include tree may only carry the keys the layout declares; its `article` -variant shows it filled. +The card is included by a layout, inside `{{#each page.children}}`, so it gets an entry as its context. The listing +names it with `x-pd-card`, so each page of the listing is checked against this schema, and sample data of its own +could set only an entry's fields. It has none; its `article` variant shows it filled. The teaser is never shortened in the data: the card limits it to three lines in CSS (`line-clamp`). diff --git a/storefront-bench/src/patterns/layouts/listing/listing.md b/storefront-bench/src/patterns/layouts/listing/listing.md index 888fc2d..85480cf 100644 --- a/storefront-bench/src/patterns/layouts/listing/listing.md +++ b/storefront-bench/src/patterns/layouts/listing/listing.md @@ -5,7 +5,8 @@ description: A folder's index.md that lists the folder's pages, each as a card. For a folder's `index.md`: set `layout: listing`, and `sort: date` to list the newest first. The layout declares `page.children`, so Pattern Dump fills it with the folder's pages (an entry each: route, title, description, date, -image, tags, draft). +image, tags, draft). Its schema names the card each one is shown as (`"x-pd-card": "components/card"`), so every +page of the listing is checked against the card's schema. | Frontmatter | Type | | |---|---|---| diff --git a/storefront-bench/src/patterns/layouts/listing/listing.schema.json b/storefront-bench/src/patterns/layouts/listing/listing.schema.json index 8ba3056..e52cabf 100644 --- a/storefront-bench/src/patterns/layouts/listing/listing.schema.json +++ b/storefront-bench/src/patterns/layouts/listing/listing.schema.json @@ -11,7 +11,7 @@ "type": "object", "description": "What Pattern Dump derives for the page", "properties": { - "children": { "description": "The folder's pages, sorted as its index.md says" } + "children": { "description": "The folder's pages, sorted as its index.md says, each shown as the card", "x-pd-card": "components/card" } } } }