diff --git a/CHANGELOG.md b/CHANGELOG.md index 295e88a..625bfdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,14 @@ 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. +- **A tag is an object now, not a string:** `page.tags` and every listing entry's `tags` are + `{ key, label, description, route }`, as categories are (which gain `route` too). A template that writes a tag as + text (`{{#each page.tags}}{{this}}{{/each}}`) stops the page, naming the template, its line and the fix: write + `{{label}}`. A card whose schema declares `tags` as a list of strings stops its listing the same way. The starter's + layouts and cards write `{{label}}`, linked to the tag's page. +- `article:tag` and the JSON-LD `keywords` write a tag's label, not its key (the same for an undeclared tag). +- A skin with `layouts/tag` or `layouts/category` gets tag or category pages without asking (see Added): a page of the + pages folder at `/tags/` or `/categories/` then stops the build, naming the fix. ### Deprecated @@ -28,6 +36,20 @@ ### Added +- Tag declarations: `storefront.tags`, declared as categories are (label, description, old keys). Optional: without it + any tag works, labelled with its key. With it, a tag that isn't declared stops the page with a "did you mean", and an + old key builds with a warning. A query's `tags` are checked against the declarations. +- Tag and category pages: a page for every tag and every category a published page has (`/tags//`, + `/categories//`), and an index of each (`/tags/`, `/categories/`), through the skin's `layouts/tag`, + `layouts/tags`, `layouts/category` and `layouts/categories`. A term page gets `page.term` and lists its pages + through a query; an index gets `page.terms`. Drafts and scheduled pages never count. `storefront.tagPages` and + `storefront.categoryPages` turn them off (`false`), ask for them (`true`: a missing layout is a problem), or set the + path and the index's title. An old key's route forwards to the new one. They are in the sitemap, with JSON-LD + `CollectionPage`. The starter has plain layouts for all four. +- `same` for a query's `tags` and `categories`: the current page's own (on a tag page, its tag). +- Categories in search and link previews: `article:section` (the first category's label) and the `Article`'s + `articleSection`. + - `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 diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index de7beb7..fbdf50c 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -185,6 +185,9 @@ in [storefront.md](storefront.md). | `storefront.image` | string | (none) | The link-preview image of every page that names none: a PNG, JPEG, GIF or WebP file in the assets, such as `/assets/images/share.png` | | `storefront.images` | object | (none) | The site's own `quality` and `effort` for its images, over `images` (above) | | `storefront.categories` | object | (none) | The categories a page's `categories:` may name, by key (lowercase letters, digits and hyphens): `{ guides: { label: "Guides", description: "…", aliases: ["how-to"] } }`. `label` is required; `aliases` are old keys kept after a rename. Independent of the folders, so a page changes category without changing its URL ([storefront.md](storefront.md#categories)) | +| `storefront.tags` | object | (none) | The tags a page's `tags:` may name, declared as categories are: `{ css: { label: "CSS", aliases: ["styles"] } }`. Without it any tag works, labelled with its key ([storefront.md](storefront.md#tags)) | +| `storefront.tagPages` | boolean or object | on when the skin has `layouts/tag` | A page per tag at `/tags//` and an index at `/tags/`. `false`: off; `true` or `{ path, title }`: on, and a missing layout is a problem ([storefront.md](storefront.md#tag-and-category-pages)) | +| `storefront.categoryPages` | boolean or object | on when the skin has `layouts/category` | The same for categories, at `/categories/` | | `storefront.site` | object | (none) | Values every page shares, such as the site's title or footer line. Every layout gets them as `site`, and a page cannot set them. Their keys and types are what the `site` property of `partials/base`'s schema declares, and they are checked against it. One key is Pattern Dump's: `navigations`, named lists of links ([storefront.md](storefront.md#declared-navigations)) | ## When changes take effect diff --git a/docs/guide/storefront.md b/docs/guide/storefront.md index c6c4878..2910666 100644 --- a/docs/guide/storefront.md +++ b/docs/guide/storefront.md @@ -207,7 +207,7 @@ lede: Three folders make a site. | `redirectFrom` | Old routes that forward to the page, one or a list: `redirectFrom: [/setup/, /start/]`. See [Redirects](#redirects) | | `date` | The page's date, a real calendar date written `YYYY-MM-DD`: what a listing sorts and shows, and its JSON-LD `datePublished`. Without it, the day git first saw the page. A date after today holds the page back from `pd build` until that day, see [Scheduled pages](#scheduled-pages). See [Collections](#collections) | | `updated` | The page's last real change, `YYYY-MM-DD`, set by its author: not before `date`. The only "last changed" date a reader or a search engine sees, see [Dates](#dates) | -| `tags` | One tag or a list, each lowercase letters, digits and hyphens, none twice: `tags: [css, design-systems]` | +| `tags` | One tag or a list, each lowercase letters, digits and hyphens, none twice: `tags: [css, design-systems]`. When the config declares tags (`storefront.tags`), each is a declared one (or an old key of one). See [Tags](#tags) | | `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 | @@ -376,8 +376,10 @@ keys below, at any depth. | `updated` | The page's `updated`, `YYYY-MM-DD`, else `null`. Never git's last commit, see [Dates](#dates) | | `children` | On a folder's `index.md`: the folder's pages, an entry each, sorted as its `sort` says (see [Collections](#collections)); `[]` on any other page | | `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 `[]` | +| `tags` | The page's tags, in its order, each `{ key, label, description, route }` (see [Tags](#tags)), else `[]` | +| `categories` | The page's categories, in its order, each `{ key, label, description, route }` (`description` `null` when the config gives none, `route` the category's page or `null`), else `[]` | +| `term` | On a tag or category page: the tag or category, `{ key, label, description, route, count }` (see [Tag and category pages](#tag-and-category-pages)), else `null` | +| `terms` | On the index of the tags or the categories: every one with a page, by label, each as `term`, else `null` | | `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 @@ -463,8 +465,8 @@ has the same fixed shape: | `date` | The page's `date`, else the day git first saw it, else `null` | | `updated` | The page's `updated`, or `null` | | `image` | The page's `image`, a path in the assets, or `null` | -| `tags` | The page's `tags`, or `[]` | -| `categories` | The page's categories, each `{ key, label, description }`, or `[]` | +| `tags` | The page's tags, each `{ key, label, description, route }`, or `[]` | +| `categories` | The page's categories, each `{ key, label, description, route }`, or `[]` | | `draft` | `true` for a draft in `pd dev` | | `scheduled` | `true` in `pd dev` for a page dated after today | @@ -586,15 +588,16 @@ the sub-keys Pattern Dump fills. |---|---|---| | `pages` | Pages picked by hand, by their path in the pages folder (`articles/a.md`): listed first, in this order | none | | `collections` | Folders' paths (`articles`, `blog/news`), or `same` for the page's own folder | every folder | -| `categories` | Declared categories (an old key works, with a warning) | none | -| `tags` | Tags | none | +| `categories` | Declared categories (an old key works, with a warning), or `same` for the page's own | none | +| `tags` | Tags (declared ones, when the config declares tags), or `same` for the page's own | none | | `match` | `any`: a page needs one of the listed tags, and one of the categories; `all`: every one | `any` | | `sort` | `relevance` (the number of tags and categories a page shares with the current one, then the date), `date` or `title` | `date` | | `order` | `asc` or `desc`; not with `relevance`, which always lists the most relevant first | newest first; A to Z | | `limit` | How many pages in all, picked ones included: a whole number from 1 | no limit | | `view` | A view (`views/`), as for a listing | none | -With both `tags` and `categories`, a page must match both. A page with no date sorts last. Always: the current page +With both `tags` and `categories`, a page must match both. `same` is the current page's own tags (categories); on a page +with none the query lists no page. On a tag page it is that tag. A page with no date sorts last. Always: the current page is left out, a page never comes twice (a picked page isn't repeated), and drafts and scheduled pages never appear, in `pd dev` either. @@ -613,7 +616,8 @@ page, and `related: true` keeps the layout's as it is. The key is the build's: t one place a page's frontmatter nests: one level of keys under a key, each a value or a list. **Every value is checked**, at the page's line or in the layout's schema: an option there isn't, a picked page that -doesn't exist (with a "did you mean"), a folder that isn't one, a category that isn't declared, a tag no page has, an +doesn't exist (with a "did you mean"), a folder that isn't one, a category that isn't declared, a tag that isn't declared (or, without declared tags, a +tag no page has), an unknown `sort`, `match` or `order`, `order` with `relevance`, a `limit` that isn't a whole number from 1, more picked pages than the limit, a page picked twice, and a view that isn't one; every page is checked against the view's card. A picked draft or scheduled page fails `pd build`; in `pd dev` it is a warning, and left out. @@ -645,10 +649,68 @@ storefront: { builds, as the new category, with a warning that names the page and line so it can be updated. An alias that is a key of its own, or that two categories claim, is a config problem. - **A layout** gets `page.categories` (in the page's order) and each listing entry carries them. `site.categories` - is every declared category in the config's order, `{ key, label, description }`, on every page, when + is every declared category in the config's order, `{ key, label, description, route }`, on every page, when `partials/base`'s schema lists `categories` under `site.properties` (no shape of its own, a description at most). The config can't set `site.categories`. +### Tags + +A tag is a URL segment a page lists in `tags:`. Without declarations any tag works, and its label is its key. The +config can declare them, as it declares categories: then they are the list, so a typo stops the page (with a "did you +mean"), and an old key builds as the tag it now is, with a warning. + +```ts +storefront: { + tags: { + css: { label: "CSS", description: "Cascading style sheets", aliases: ["styles"] }, + "design-tokens": { label: "Design tokens" }, + }, +}, +``` + +A layout gets each tag as `{ key, label, description, route }`, as it gets a category: `label` to show it, `key` as its +URL segment, `route` its [tag page](#tag-and-category-pages) or `null`. Write `{{label}}`. + +**Tags were strings before 0.5.0.** A template that still writes one as text, `{{#each page.tags}}{{this}}{{/each}}`, +would print `[object Object]`, so the page stops instead, naming the template and line and what to write +(`{{label}}`). A card whose schema declares `tags` as a list of strings stops the listing the same way: declare the +items as objects, or leave `items` out. + +### Tag and category pages + +Pattern Dump makes a page for every tag and every category a published page has, and an index of each, through the +skin's layouts: + +| Route | Layout | What the layout gets | +|---|---|---| +| `/tags//` | `layouts/tag` | `title` (the label), `description` (when declared), `page.term` | +| `/tags/` | `layouts/tags` | `title` ("Tags"), `page.terms` | +| `/categories//` | `layouts/category` | as a tag page | +| `/categories/` | `layouts/categories` | `title` ("Categories"), `page.terms` | + +- **Their pages are a query** the layout declares, with `tags: same` (`categories: same`), so views, cards and every + check work as on any page: + + ```json + "pages": { "x-pd-query": { "tags": "same", "sort": "date", "view": "list" } } + ``` + +- **Published pages only.** Drafts and scheduled pages never count, in `pd dev` either: a tag only they have gets no + page, and isn't in the index. +- **On and off:** `storefront.tagPages` and `storefront.categoryPages`. Left out, the pages are there when the skin has + the layout (`layouts/tag`; the index when it has `layouts/tags` too), and a skin without it gets none, with no + message. `false` turns them off. `true`, or `{ path, title }`, asks for them: a missing layout is then a problem. + `path` is the URL segment (`{ path: "topics" }` gives `/topics/css/`), `title` the index's title. +- **Old keys forward.** `/tags//` of a declared tag's alias is a redirect to `/tags//`, like a page's + `redirectFrom`. +- **Checked:** a page or folder of the pages folder at a generated route, or a `redirectFrom` claiming one, is a + problem naming both; the two paths can't be the same. +- They are in the sitemap (`lastmod`: the newest change of their pages) and have JSON-LD `CollectionPage`. They are + not in the nav or any listing, and the workbench doesn't list them under a layout's pages yet. +- No pagination yet: a tag page lists every page with the tag. + +The starter (`pd init --storefront`) has plain `tag`, `tags`, `category` and `categories` layouts. + ### Scheduled pages A page whose `date` is after today stays out of `pd build`, as a draft does: no page, no entry in the nav, a @@ -813,9 +875,10 @@ or with a path, such as `https://example.github.io/project/`, for a site publish `og:type` is `website`, except on an article: a page whose frontmatter gives it a `date`, other than the home page and a listing (a folder's `index.md` with pages under it). An article gets `og:type` `article`, with -`article:published_time` (its `date`), `article:modified_time` (its `updated`, when it has one) and one -`article:tag` per tag, and its JSON-LD graph adds an `Article` -(headline, dates, `keywords` from its tags) as the page's main entity. The date git gives a page does not make +`article:published_time` (its `date`), `article:modified_time` (its `updated`, when it has one), `article:section` +(its first category's label: Open Graph has one) and one `article:tag` per tag (its label), and its JSON-LD graph +adds an `Article` (headline, dates, `keywords` from its tags' labels, `articleSection` from its categories' labels: +one string, or a list for several) as the page's main entity. The date git gives a page does not make it an article: every committed page has one. and `pd build` writes `sitemap.xml`. Without it, those are left out and `pd build` says so once. In `pd dev` diff --git a/packages/cli/src/init/starter.spec.ts b/packages/cli/src/init/starter.spec.ts index 1888cc5..21243c8 100644 --- a/packages/cli/src/init/starter.spec.ts +++ b/packages/cli/src/init/starter.spec.ts @@ -175,7 +175,8 @@ describe("the starter project with a website (--storefront, no examples)", () => expect(graph.occurrences).toEqual([]); expect(graph.components.map(c => [c.id, c.render]).sort()).toEqual( [["components/compact-card", "ok"], ["components/feature-card", "ok"], ["components/grid-card", "ok"], ["components/listing-card", "ok"], ["components/note", "ok"], - ["layouts/article", "ok"], ["layouts/home", "ok"], ["layouts/listing", "ok"], ["layouts/page", "ok"], ["partials/base", "ok"], ["partials/head", "ok"], + ["layouts/article", "ok"], ["layouts/categories", "ok"], ["layouts/category", "ok"], ["layouts/home", "ok"], ["layouts/listing", "ok"], ["layouts/page", "ok"], + ["layouts/tag", "ok"], ["layouts/tags", "ok"], ["partials/base", "ok"], ["partials/head", "ok"], ["views/compact", "ok"], ["views/featured", "ok"], ["views/grid", "ok"], ["views/list", "ok"]]); }, 120_000); @@ -203,7 +204,21 @@ describe("the starter project with a website (--storefront, no examples)", () => expect(articles.body).toContain(`href="${componentCssUrl("components/listing-card").replace(/\.css$/, "")}`); const hello = await onHost(server.port, "live.localhost", "/articles/hello/"); expect(hello.status).toBe(200); - expect(hello.body).toContain(`
  • getting-started
  • notes
`); + // Each tag by its label, linked to its tag page. + expect(hello.body).toContain(``); + // The tag and category pages, and their indexes, through the starter's plain layouts. + const notes = await onHost(server.port, "live.localhost", "/tags/notes/"); + expect(notes.status).toBe(200); + expect(notes.body).toContain(`

notes

`); + expect([...notes.body.matchAll(/

m[1])).toEqual(["/articles/related/", "/articles/hello/"]); + const tags = await onHost(server.port, "live.localhost", "/tags/"); + expect(tags.body).toContain(`
  • getting-started (1)
  • `); + expect(tags.body).toContain(`
  • notes (2)
  • `); + const category = await onHost(server.port, "live.localhost", "/categories/notes/"); + expect(category.status).toBe(200); + expect(category.body).toContain(`

    Notes

    `); + expect(category.body).toContain(`

    Short articles about this site

    `); + expect((await onHost(server.port, "live.localhost", "/categories/")).body).toContain(`
  • Notes (2)
  • `); // Its related articles: the article layout's query (the same folder, by relevance, three), in the compact view. expect(hello.body).toMatch(/

    Related articles<\/h2>\s*
      \s*
    • Related articles<\/a>

      {{title}}

      {{#if date}}

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

      {{description}}

      {{/if}} - {{#if tags.length}}
        {{#each tags}}
      • {{this}}
      • {{/each}}
      {{/if}} + {{#if tags.length}}
        {{#each tags}}
      • {{#if route}}{{label}}{{else}}{{label}}{{/if}}
      • {{/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 index 64c262b..1d7dc78 100644 --- 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 @@ -4,7 +4,17 @@ "date": "2026-11-14", "description": "The example article. Copy it to start a new one.", "tags": [ - "getting-started", - "notes" + { + "key": "getting-started", + "label": "getting-started", + "description": null, + "route": "/tags/getting-started/" + }, + { + "key": "notes", + "label": "notes", + "description": null, + "route": "/tags/notes/" + } ] } 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 index 1e4af59..1ffcf2f 100644 --- 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 @@ -33,9 +33,29 @@ "tags": { "type": "array", "items": { - "type": "string" + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "label": { + "type": "string" + }, + "description": { + "type": [ + "string", + "null" + ] + }, + "route": { + "type": [ + "string", + "null" + ] + } + } }, - "description": "The page's tags" + "description": "The page's tags: each its label, linked to its tag page when the site has one" } } } diff --git a/packages/cli/templates/storefront/src/patterns/layouts/article/article.hbs b/packages/cli/templates/storefront/src/patterns/layouts/article/article.hbs index 1ea176d..cb33d68 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/article/article.hbs +++ b/packages/cli/templates/storefront/src/patterns/layouts/article/article.hbs @@ -2,7 +2,7 @@

      {{title}}

      {{#if description}}

      {{description}}

      {{/if}} - {{#if page.date}}
      {{#if page.tags.length}}
        {{#each page.tags}}
      • {{this}}
      • {{/each}}
      {{/if}}
      {{/if}} + {{#if page.date}}
      {{#if page.tags.length}}
        {{#each page.tags}}
      • {{#if route}}{{label}}{{else}}{{label}}{{/if}}
      • {{/each}}
      {{/if}}
      {{/if}}
      {{{body}}}
      {{#if page.related.listing}}
      diff --git a/packages/cli/templates/storefront/src/patterns/layouts/article/article.json b/packages/cli/templates/storefront/src/patterns/layouts/article/article.json index cf60a09..6183797 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/article/article.json +++ b/packages/cli/templates/storefront/src/patterns/layouts/article/article.json @@ -6,7 +6,7 @@ "nav": [{ "route": "/", "title": "Home" }, { "route": "/articles/", "title": "Articles", "current": true }], "page": { "date": "2026-11-14", - "tags": ["notes"], + "tags": [{ "key": "notes", "label": "notes", "description": null, "route": "/tags/notes/" }], "related": { "entries": [{ "route": "/articles/second/", "title": "A second article", "date": "2026-11-15" }], "listing": "" diff --git a/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.hbs b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.hbs new file mode 100644 index 0000000..1a36b88 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.hbs @@ -0,0 +1,10 @@ +{{#> partials-base }} +
      +

      {{title}}

      +
        + {{#each page.terms}} +
      • {{label}} ({{count}})
      • + {{/each}} +
      +
      +{{/partials-base}} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.json b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.json new file mode 100644 index 0000000..6ee99a7 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.json @@ -0,0 +1,14 @@ +{ + "title": "Categories", + "page": { + "terms": [ + { + "key": "notes", + "label": "notes", + "description": null, + "route": "/categories/notes/", + "count": 2 + } + ] + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.md b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.md new file mode 100644 index 0000000..06771f9 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.md @@ -0,0 +1,7 @@ +--- +title: Categories +description: The index of the categories, each linked to its page. +--- + +Pattern Dump makes this page at `/categories/` when the site has category pages: `page.terms` is every category with a published +page, by label, with how many pages have it. diff --git a/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.schema.json b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.schema.json new file mode 100644 index 0000000..4be13ed --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/categories/categories.schema.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Categories", + "description": "The index of the categories, at /categories/: each category with a published page, linked, with its count.", + "type": "object", + "required": [ + "title" + ], + "properties": { + "title": { + "type": "string", + "description": "The index's title: \"Categories\", or categoryPages.title in the config" + }, + "page": { + "type": "object", + "description": "What the storefront works out for the page", + "properties": { + "terms": { + "description": "Every category with a page, by label: key, label, description, route and count" + } + } + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/category/category.hbs b/packages/cli/templates/storefront/src/patterns/layouts/category/category.hbs new file mode 100644 index 0000000..d8dc13a --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/category/category.hbs @@ -0,0 +1,7 @@ +{{#> partials-base }} +
      +

      {{title}}

      + {{#if description}}

      {{description}}

      {{/if}} +
      {{{page.pages.listing}}}
      +
      +{{/partials-base}} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/category/category.json b/packages/cli/templates/storefront/src/patterns/layouts/category/category.json new file mode 100644 index 0000000..68ca6da --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/category/category.json @@ -0,0 +1,29 @@ +{ + "title": "notes", + "page": { + "term": { + "key": "notes", + "label": "notes", + "description": null, + "route": "/categories/notes/", + "count": 1 + }, + "pages": { + "entries": [ + { + "route": "/articles/hello/", + "title": "Hello, articles", + "description": "The example article.", + "date": "2026-11-14", + "updated": null, + "image": null, + "tags": [], + "categories": [], + "draft": false, + "scheduled": false + } + ], + "listing": "

      The pages, in the list view.

      " + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/category/category.md b/packages/cli/templates/storefront/src/patterns/layouts/category/category.md new file mode 100644 index 0000000..47bfd0f --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/category/category.md @@ -0,0 +1,8 @@ +--- +title: Category +description: The page of one category, with every published page that has it. +--- + +Pattern Dump makes this page for every category a published page has, at `/categories//`. Its pages are a query with +`categories: same` (the page's own category), so any view and its card work here. Without this layout the site has no +category pages; `categoryPages: false` in the config turns them off. diff --git a/packages/cli/templates/storefront/src/patterns/layouts/category/category.schema.json b/packages/cli/templates/storefront/src/patterns/layouts/category/category.schema.json new file mode 100644 index 0000000..c77dfbb --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/category/category.schema.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Category", + "description": "The page of one category: Pattern Dump makes one at /categories// for every category a published page has, titled with its label.", + "type": "object", + "required": [ + "title" + ], + "properties": { + "title": { + "type": "string", + "description": "The category's label" + }, + "description": { + "type": "string", + "description": "The category's description, when storefront.categories gives one" + }, + "page": { + "type": "object", + "description": "What the storefront works out for the page", + "properties": { + "term": { + "description": "The category: its key, label, description, route and how many pages have it" + }, + "pages": { + "description": "Every page with the category, newest first, in the list view", + "x-pd-query": { + "categories": "same", + "sort": "date", + "view": "list" + } + } + } + } + } +} 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 d9e6425..0ef6b2a 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.json +++ b/packages/cli/templates/storefront/src/patterns/layouts/listing/listing.json @@ -5,6 +5,6 @@ "site": { "title": __PD_BRAND_JSON__, "footer": "Made with Pattern Dump." }, "nav": [{ "route": "/", "title": "Home" }, { "route": "/articles/", "title": "Articles", "current": true }], "page": { - "listing": "" + "listing": "" } } diff --git a/packages/cli/templates/storefront/src/patterns/layouts/page/page.hbs b/packages/cli/templates/storefront/src/patterns/layouts/page/page.hbs index cbef49b..8581f1f 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/page/page.hbs +++ b/packages/cli/templates/storefront/src/patterns/layouts/page/page.hbs @@ -2,7 +2,7 @@

      {{title}}

      {{#if description}}

      {{description}}

      {{/if}} - {{#if page.date}}
      {{#if page.tags.length}}
        {{#each page.tags}}
      • {{this}}
      • {{/each}}
      {{/if}}
      {{/if}} + {{#if page.date}}
      {{#if page.tags.length}}
        {{#each page.tags}}
      • {{#if route}}{{label}}{{else}}{{label}}{{/if}}
      • {{/each}}
      {{/if}}
      {{/if}}
      {{{body}}}
      {{#if page.next}}

      {{/if}}
      diff --git a/packages/cli/templates/storefront/src/patterns/layouts/page/page.json b/packages/cli/templates/storefront/src/patterns/layouts/page/page.json index 7db4868..7dff17d 100644 --- a/packages/cli/templates/storefront/src/patterns/layouts/page/page.json +++ b/packages/cli/templates/storefront/src/patterns/layouts/page/page.json @@ -4,5 +4,5 @@ "body": "

      The page's markdown, rendered.

      ", "site": { "title": __PD_BRAND_JSON__, "footer": "Made with Pattern Dump." }, "nav": [{ "route": "/", "title": "Home", "current": true }, { "route": "/about/", "title": "About" }], - "page": { "next": { "route": "/about/", "title": "About" }, "date": "2026-11-14", "tags": ["notes"] } + "page": { "next": { "route": "/about/", "title": "About" }, "date": "2026-11-14", "tags": [{ "key": "notes", "label": "notes", "description": null, "route": "/tags/notes/" }] } } diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.hbs b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.hbs new file mode 100644 index 0000000..d8dc13a --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.hbs @@ -0,0 +1,7 @@ +{{#> partials-base }} +
      +

      {{title}}

      + {{#if description}}

      {{description}}

      {{/if}} +
      {{{page.pages.listing}}}
      +
      +{{/partials-base}} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.json b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.json new file mode 100644 index 0000000..3a3fdb7 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.json @@ -0,0 +1,29 @@ +{ + "title": "notes", + "page": { + "term": { + "key": "notes", + "label": "notes", + "description": null, + "route": "/tags/notes/", + "count": 1 + }, + "pages": { + "entries": [ + { + "route": "/articles/hello/", + "title": "Hello, articles", + "description": "The example article.", + "date": "2026-11-14", + "updated": null, + "image": null, + "tags": [], + "categories": [], + "draft": false, + "scheduled": false + } + ], + "listing": "

      The pages, in the list view.

      " + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.md b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.md new file mode 100644 index 0000000..8676dd2 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.md @@ -0,0 +1,8 @@ +--- +title: Tag +description: The page of one tag, with every published page that has it. +--- + +Pattern Dump makes this page for every tag a published page has, at `/tags//`. Its pages are a query with +`tags: same` (the page's own tag), so any view and its card work here. Without this layout the site has no +tag pages; `tagPages: false` in the config turns them off. diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.schema.json b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.schema.json new file mode 100644 index 0000000..0a63eef --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tag/tag.schema.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Tag", + "description": "The page of one tag: Pattern Dump makes one at /tags// for every tag a published page has, titled with its label.", + "type": "object", + "required": [ + "title" + ], + "properties": { + "title": { + "type": "string", + "description": "The tag's label" + }, + "description": { + "type": "string", + "description": "The tag's description, when storefront.tags gives one" + }, + "page": { + "type": "object", + "description": "What the storefront works out for the page", + "properties": { + "term": { + "description": "The tag: its key, label, description, route and how many pages have it" + }, + "pages": { + "description": "Every page with the tag, newest first, in the list view", + "x-pd-query": { + "tags": "same", + "sort": "date", + "view": "list" + } + } + } + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.hbs b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.hbs new file mode 100644 index 0000000..1a36b88 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.hbs @@ -0,0 +1,10 @@ +{{#> partials-base }} +
      +

      {{title}}

      +
        + {{#each page.terms}} +
      • {{label}} ({{count}})
      • + {{/each}} +
      +
      +{{/partials-base}} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.json b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.json new file mode 100644 index 0000000..27b3d56 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.json @@ -0,0 +1,14 @@ +{ + "title": "Tags", + "page": { + "terms": [ + { + "key": "notes", + "label": "notes", + "description": null, + "route": "/tags/notes/", + "count": 2 + } + ] + } +} diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.md b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.md new file mode 100644 index 0000000..dbd0ecc --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.md @@ -0,0 +1,7 @@ +--- +title: Tags +description: The index of the tags, each linked to its page. +--- + +Pattern Dump makes this page at `/tags/` when the site has tag pages: `page.terms` is every tag with a published +page, by label, with how many pages have it. diff --git a/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.schema.json b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.schema.json new file mode 100644 index 0000000..b61dcb1 --- /dev/null +++ b/packages/cli/templates/storefront/src/patterns/layouts/tags/tags.schema.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Tags", + "description": "The index of the tags, at /tags/: each tag with a published page, linked, with its count.", + "type": "object", + "required": [ + "title" + ], + "properties": { + "title": { + "type": "string", + "description": "The index's title: \"Tags\", or tagPages.title in the config" + }, + "page": { + "type": "object", + "description": "What the storefront works out for the page", + "properties": { + "terms": { + "description": "Every tag with a page, by label: key, label, description, route and count" + } + } + } + } +} diff --git a/packages/cli/templates/storefront/src/patterns/views/list/list.json b/packages/cli/templates/storefront/src/patterns/views/list/list.json index c693135..6edfb90 100644 --- a/packages/cli/templates/storefront/src/patterns/views/list/list.json +++ b/packages/cli/templates/storefront/src/patterns/views/list/list.json @@ -6,7 +6,12 @@ "date": "2026-11-14", "description": "Its teaser: the page's description, or its first paragraph.", "tags": [ - "notes" + { + "key": "notes", + "label": "notes", + "description": null, + "route": "/tags/notes/" + } ] }, { diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index 3e5d212..b062997 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -241,8 +241,33 @@ export interface StorefrontConfig { * category, with a note naming the page so it can be updated. */ categories?: Record; + /** + * The tags a page can have (its `tags:`), by key, declared as categories are. Optional: without it every tag works, + * labelled with its key. With it, it is the list, so a typo fails the build; an alias is an old key that still builds. + */ + tags?: Record; + /** + * A page per tag (`/tags//`) and an index of them (`/tags/`), each through the skin's `layouts/tag` and + * `layouts/tags`. Left out: on when the skin has `layouts/tag`. `false`: off. `true` or an object: on, and a missing + * layout is a problem. `path`: the URL segment (default `tags`); `title`: the index page's title (default "Tags"). + */ + tagPages?: boolean | StorefrontTermPages; + /** A page per category and an index of them, as tagPages (`layouts/category`, `layouts/categories`; default path + * `categories`, title "Categories"). */ + categoryPages?: boolean | StorefrontTermPages; } +/** storefront.tagPages and storefront.categoryPages as an object. */ +export interface StorefrontTermPages { + /** The pages' first URL segment: lowercase letters, digits and hyphens. */ + path?: string; + /** The index page's title. */ + title?: string; +} + +/** A declared tag (`storefront.tags.`): the same shape as a category. */ +export type StorefrontTag = StorefrontCategory; + /** A declared category (`storefront.categories.`). */ export interface StorefrontCategory { label: string; diff --git a/packages/config/src/validate.spec.ts b/packages/config/src/validate.spec.ts index 9ff1b2d..3665717 100644 --- a/packages/config/src/validate.spec.ts +++ b/packages/config/src/validate.spec.ts @@ -245,6 +245,40 @@ describe("configProblems — storefront", () => { ]); }); + it("takes tags as categories are: each key a URL segment, with a label, an optional description and old keys", () => { + const base = { pagesDir: "./pages", outDir: "./www" }; + expect(storefront({ ...base, tags: { css: { label: "CSS", aliases: ["styles"] }, "design-tokens": { label: "Design tokens" } } })).toEqual([]); + expect(storefront({ ...base, tags: ["css"] })).toEqual([ + `"storefront.tags" must be an object of tags by key, such as { css: { label: "CSS" } }`, + ]); + expect(storefront({ ...base, tags: { CSS: { label: "CSS" }, js: {}, html: { label: "HTML", aliases: ["js"] } } })).toEqual([ + `"storefront.tags.CSS": a tag's key is part of a URL, so it is lowercase letters, digits and hyphens only`, + `missing required "storefront.tags.js.label"`, + `"storefront.tags.html.aliases": "js" is a tag of its own, so it can't be an old key of "html"`, + ]); + }); + + it("takes tagPages and categoryPages: true, false, or { path, title }", () => { + const base = { pagesDir: "./pages", outDir: "./www" }; + for (const ok of [true, false, {}, { path: "topics" }, { title: "Topics" }, { path: "t2", title: "All tags" }]) { + expect(storefront({ ...base, tagPages: ok }), JSON.stringify(ok)).toEqual([]); + expect(storefront({ ...base, categoryPages: ok }), JSON.stringify(ok)).toEqual([]); + } + expect(storefront({ ...base, tagPages: "yes" })).toEqual([ + `"storefront.tagPages" must be true, false, or { path, title }, such as { path: "topics" }`, + ]); + expect(storefront({ ...base, categoryPages: { path: "Topics/x", slug: 1 } })).toEqual([ + `"storefront.categoryPages.path": the pages' first URL segment, so lowercase letters, digits and hyphens only, such as "topics"`, + `unknown key "storefront.categoryPages.slug"`, + ]); + expect(storefront({ ...base, tagPages: { path: "topics" }, categoryPages: { path: "topics" } })).toEqual([ + `"storefront.tagPages.path" and "storefront.categoryPages.path" are both "topics": tag pages and category pages need a path each`, + ]); + expect(storefront({ ...base, categoryPages: { path: "tags" } })).toEqual([ + `"storefront.tagPages.path" and "storefront.categoryPages.path" are both "tags": tag pages and category pages need a path each`, + ]); + }); + it("accepts a workbench URL with a subpath", () => { const base = { pagesDir: "./pages", outDir: "./www" }; expect(storefront({ ...base, workbenchUrl: "https://htwoo.io/workbench/" })).toEqual([]); diff --git a/packages/config/src/validate.ts b/packages/config/src/validate.ts index 4a14985..c7206eb 100644 --- a/packages/config/src/validate.ts +++ b/packages/config/src/validate.ts @@ -11,7 +11,7 @@ type Rule = | { values: readonly string[]; unsupported?: readonly string[] } | { keys: Shape; required?: readonly string[] } | "packages" | "logo" | "workbench-url" | "site-url" | "lang" | "asset-path" | "host" | "plain-object" | "hbs-file" - | "quality" | "effort" | "categories"; + | "quality" | "effort" | "categories" | "tags" | "term-pages"; type Shape = Readonly>; /** How responsive image variants are encoded: for the project, and overridden per site. */ @@ -63,7 +63,7 @@ const SHAPE: Shape = { keys: { pagesDir: "string", outDir: "string", host: "host", workbenchUrl: "workbench-url", site: "plain-object", url: "site-url", lang: "lang", index: "boolean", image: "asset-path", images: IMAGES, head: "hbs-file", - categories: "categories", + categories: "categories", tags: "tags", tagPages: "term-pages", categoryPages: "term-pages", }, required: ["pagesDir", "outDir"], }, @@ -213,8 +213,17 @@ function checkValue(value: unknown, rule: Rule, at: string, problems: string[]): if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 6) fail("a whole number from 0 to 6 (WebP effort: 0 fastest, 6 smallest)"); return; } - if (rule === "categories") { - checkCategories(value, at, problems); + if (rule === "categories" || rule === "tags") { + checkTerms(value, at, problems, rule === "tags" ? TAG_WORDS : CATEGORY_WORDS); + return; + } + if (rule === "term-pages") { + if (typeof value === "boolean") return; + if (!isObject(value)) { fail(`true, false, or { path, title }, such as { path: "topics" }`); return; } + if (typeof value.path === "string" && !SEGMENT.test(value.path)) { + problems.push(`"${at}.path": the pages' first URL segment, so lowercase letters, digits and hyphens only, such as "topics"`); + } + checkObject(value, TERM_PAGES, [], `${at}.`, problems); return; } if (rule === "plain-object") { @@ -241,36 +250,44 @@ function checkValue(value: unknown, rule: Rule, at: string, problems: string[]): checkObject(value, rule.keys, rule.required ?? [], `${at}.`, problems); } -/** A category's key, and each old key of one: a URL segment (step 4 gives each category a page), as a tag is. */ +/** A category's or tag's key, and each old key of one: a URL segment (each gets a page of its own). */ const SEGMENT = /^[a-z0-9-]+$/; -const CATEGORY: Shape = { label: "string", description: "string", aliases: "strings" }; +const TERM: Shape = { label: "string", description: "string", aliases: "strings" }; +/** storefront.tagPages and storefront.categoryPages as an object. */ +const TERM_PAGES: Shape = { path: "string", title: "string" }; + +/** How the messages name a kind of term. */ +interface TermWords { one: string; example: string } +const CATEGORY_WORDS: TermWords = { one: "category", example: `{ guides: { label: "Guides" } }` }; +const TAG_WORDS: TermWords = { one: "tag", example: `{ css: { label: "CSS" } }` }; /** - * storefront.categories: `{ : { label, description?, aliases? } }`. An alias is a category's old key: pages that - * still name it build, resolved to the category (with a note). So an alias is never a key of its own, and one alias - * leads to one category. + * storefront.categories and storefront.tags: `{ : { label, description?, aliases? } }`. An alias is an old key: + * pages that still name it build, resolved to the term (with a note), and its old page forwards to the new one. So an + * alias is never a key of its own, and one alias leads to one term. */ -function checkCategories(value: unknown, at: string, problems: string[]): void { +function checkTerms(value: unknown, at: string, problems: string[], w: TermWords): void { + const plural = w.one === "category" ? "categories" : `${w.one}s`; if (!isObject(value)) { - problems.push(`"${at}" must be an object of categories by key, such as { guides: { label: "Guides" } }`); + problems.push(`"${at}" must be an object of ${plural} by key, such as ${w.example}`); return; } const claimed = new Map(); for (const [key, category] of Object.entries(value)) { if (!SEGMENT.test(key)) { - problems.push(`"${at}.${key}": a category's key is part of a URL, so it is lowercase letters, digits and hyphens only`); + problems.push(`"${at}.${key}": a ${w.one}'s key is part of a URL, so it is lowercase letters, digits and hyphens only`); continue; } - if (!isObject(category)) { problems.push(`"${at}.${key}" must be an object, such as { label: "Guides" }`); continue; } - checkObject(category, CATEGORY, ["label"], `${at}.${key}.`, problems); + if (!isObject(category)) { problems.push(`"${at}.${key}" must be an object, such as { label: "${w.one === "tag" ? "CSS" : "Guides"}" }`); continue; } + checkObject(category, TERM, ["label"], `${at}.${key}.`, problems); if (!isStrings(category.aliases)) continue; for (const alias of category.aliases as string[]) { if (!SEGMENT.test(alias)) { problems.push(`"${at}.${key}.aliases": "${alias}" is not a key: an old key is lowercase letters, digits and hyphens, as a key is`); } else if (Object.hasOwn(value, alias)) { - problems.push(`"${at}.${key}.aliases": "${alias}" is a category of its own, so it can't be an old key of "${key}"`); + problems.push(`"${at}.${key}.aliases": "${alias}" is a ${w.one} of its own, so it can't be an old key of "${key}"`); } else if (claimed.has(alias)) { - problems.push(`"${at}.${key}.aliases": "${alias}" is an old key of "${claimed.get(alias)}" already: one old key leads to one category`); + problems.push(`"${at}.${key}.aliases": "${alias}" is an old key of "${claimed.get(alias)}" already: one old key leads to one ${w.one}`); } else claimed.set(alias, key); } } @@ -286,6 +303,13 @@ export class ConfigError extends Error { function checkRelations(raw: Record, problems: string[]): void { const sf = raw.storefront; if (!isObject(sf)) return; + // Tag pages and category pages each under a path of their own (when both are on). + const pathOf = (v: unknown, fallback: string): string | undefined => + v === false ? undefined : isObject(v) && typeof v.path === "string" ? v.path : fallback; + const tagPath = pathOf(sf.tagPages, "tags"), categoryPath = pathOf(sf.categoryPages, "categories"); + if (tagPath !== undefined && tagPath === categoryPath) { + problems.push(`"storefront.tagPages.path" and "storefront.categoryPages.path" are both "${tagPath}": tag pages and category pages need a path each`); + } // Three folders that must not share files, so they are pairwise disjoint: not the same folder, and // neither inside the other. Pages are markdown that is not component docs (under patternsDir the // watcher could not tell which an edit belongs to, and the reverse puts component docs among the diff --git a/packages/dev-server/src/routes.ts b/packages/dev-server/src/routes.ts index 1954cb7..8bcc716 100644 --- a/packages/dev-server/src/routes.ts +++ b/packages/dev-server/src/routes.ts @@ -18,7 +18,7 @@ import type { GitDates } from "./storefront/git-dates.js"; import type { IncomingMessage, ServerResponse } from "node:http"; import { basename, extname, join, relative } from "node:path"; import { readFile } from "node:fs/promises"; -import { PD_GENERATION_HEADER, PD_HOSTS, PD_PROTOCOL_HEADER, PD_PROTOCOL_VERSION, PD_ROUTE_PREFIX, PD_ROUTES } from "@pattern-dump/contracts"; +import { PD_GENERATION_HEADER, PD_HOSTS, PD_PROTOCOL_HEADER, PD_PROTOCOL_VERSION, PD_ROUTE_PREFIX, PD_ROUTES, type DiscoveryMap } from "@pattern-dump/contracts"; import type { ApiError, AuditResponse, ComponentDetailResponse, ComponentTree, DiagnosticsGraph, FolderOverview, ImageLookup, RuleTiers, ShellClientConfig, StorefrontPagesResponse, ThemeSummary, VersionInfo, @@ -75,10 +75,12 @@ 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 { +function readStorefrontPages(ctx: RouteContext, sf: NonNullable, discoveryMap?: DiscoveryMap): 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, + today: ctx.today ?? todayOf(ctx.now()), categories: sf.categories, tags: sf.tags, tagPages: sf.tagPages, categoryPages: sf.categoryPages, + // The skin's layouts: tag and category pages are generated through them (terms.ts). + ...(discoveryMap ? { layouts: new Set([...discoveryMap.keys()].filter(id => /^layouts\/[^/~]+$/.test(id)).map(id => id.slice("layouts/".length))) } : {}), }); } @@ -640,7 +642,7 @@ async function routeRequest( if (cfg.storefront && host === cfg.storefront.host) { const discovery = await currentDiscovery(state, patternRoots); const discoveryMap = discovery.discoveryMap; - const model = await readStorefrontPages(ctx, cfg.storefront); + const model = await readStorefrontPages(ctx, cfg.storefront, discoveryMap); 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); @@ -675,7 +677,7 @@ async function routeRequest( } // /404.html, and every address with no page, is the site's 404 page with status 404, as a static host // serves it (a 404 page with problems is a 500 listing them). - const target = pathname === PD_ROUTES.notFound || route === null || (!model.problems.length && !model.files.has(route)) + const target = pathname === PD_ROUTES.notFound || route === null || (!model.problems.length && !model.files.has(route) && !model.generated.has(route)) ? PD_ROUTES.notFound : route; // In pd dev a page links to the workbench of this same process, whatever the config's build-time // URL; pd build passes that URL in, for the built site. diff --git a/packages/dev-server/src/server-config.ts b/packages/dev-server/src/server-config.ts index 5a1e103..5542c00 100644 --- a/packages/dev-server/src/server-config.ts +++ b/packages/dev-server/src/server-config.ts @@ -10,7 +10,7 @@ import { basename, join, resolve } from "node:path"; import type { ImageEncoding } from "@pattern-dump/build"; -import { storefrontBasePath, type PatternDumpConfig, type StorefrontCategory } from "@pattern-dump/config"; +import { storefrontBasePath, type PatternDumpConfig, type StorefrontCategory, StorefrontTermPages } from "@pattern-dump/config"; import { PD_HOSTS, type ThemeSwitch } from "@pattern-dump/contracts"; import type { PatternRoot } from "@pattern-dump/discovery"; import type { ResolvedPackage } from "./packages.js"; @@ -102,6 +102,11 @@ export interface ResolvedConfig { readonly headName: string | undefined; /** storefront.categories: what a page's `categories:` may name. */ readonly categories: Readonly> | undefined; + /** storefront.tags: what a page's `tags:` may name; any tag when left out. */ + readonly tags: Readonly> | undefined; + /** storefront.tagPages and storefront.categoryPages, as the config writes them (terms.ts reads them). */ + readonly tagPages: boolean | StorefrontTermPages | undefined; + readonly categoryPages: boolean | StorefrontTermPages | undefined; } | null; readonly overviewsEnabled: boolean; @@ -242,6 +247,9 @@ export function resolveServerConfig( head: config.storefront.head !== undefined ? resolve(cwd, config.storefront.head) : undefined, headName: config.storefront.head, categories: config.storefront.categories, + tags: config.storefront.tags, + tagPages: config.storefront.tagPages, + categoryPages: config.storefront.categoryPages, } : null, images, overviewsEnabled: config.overviews !== false, diff --git a/packages/dev-server/src/storefront/cards.ts b/packages/dev-server/src/storefront/cards.ts index 325e489..c5129c9 100644 --- a/packages/dev-server/src/storefront/cards.ts +++ b/packages/dev-server/src/storefront/cards.ts @@ -51,6 +51,12 @@ export async function readCard(id: string, owner: string, role: string, discover 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(", ")})`); + // Tags were strings before 0.5.0: a card still declaring them so would fail every page with a type mismatch. + const tagItems = (read.schema.properties?.["tags"] as { items?: { type?: unknown } } | undefined)?.items?.type; + if (tagItems === "string" || (Array.isArray(tagItems) && tagItems.includes("string") && !tagItems.includes("object"))) { + problems.push(`${id} (${role}, ${owner}) declares tags as a list of strings, but a tag is an object since 0.5.0 ` + + `(key, label, description, route): declare its items as "type": "object", or leave items out`); + } return problems.length ? { problems } : { card: { id, schema: read.schema, label: `${role} (${id})` }, problems }; } diff --git a/packages/dev-server/src/storefront/categories.ts b/packages/dev-server/src/storefront/categories.ts index a354310..02f5465 100644 --- a/packages/dev-server/src/storefront/categories.ts +++ b/packages/dev-server/src/storefront/categories.ts @@ -1,34 +1,64 @@ -// Categories: what a page is about, independent of the folder it is in, so a page changes category without changing -// its URL. The config declares them (storefront.categories: key, label, optional description, and old keys kept after -// a rename); a page names them in its reserved `categories:` (listing-keys.ts readCategories). A layout gets them as -// page.categories, a listing entry carries them, and site.categories is every declared one, in the config's order, -// when partials/base lists `categories` under site (no shape of its own: a category's shape is Pattern Dump's). +// Tags and categories, "terms": what a page is about, independent of the folder it is in, so a page changes category +// without changing its URL. +// +// - Categories are declared in the config (storefront.categories: key, label, optional description, and old keys +// kept after a rename); a page names them in its reserved `categories:`. +// - Tags may be declared the same way (storefront.tags). Without declarations every tag works, labelled with its +// key; with them, they are the list, as categories are. +// +// A layout gets a page's terms as page.tags and page.categories, `{ key, label, description, route }`, route the +// term's generated page (terms.ts) or null; a listing entry carries them, and site.categories is every declared +// category, in the config's order, when partials/base lists `categories` under site (no shape of its own). import type { StorefrontCategory } from "@pattern-dump/config"; export const CATEGORIES_KEY = "categories"; +/** A kind of term. */ +export type TermKind = "tag" | "category"; + +/** A tag or a category as layouts get it. */ +export interface Term { key: string; label: string; description: string | null; route: string | null } /** A category as layouts get it. */ -export interface Category { key: string; label: string; description: string | null } +export type Category = Term; -/** The declared categories, ready to resolve a page's values against. */ -export interface CategoryIndex { - /** In the config's order. */ - list: Category[]; - byKey: ReadonlyMap; +/** The declared terms of one kind, ready to resolve a page's values against. */ +export interface TermIndex { + kind: TermKind; + /** Whether the config declares them (storefront.tags may be left out: then any tag is one, labelled with its key). */ + declared: boolean; + /** In the config's order. Their route is set once the generated pages are known (pages.ts). */ + list: Term[]; + byKey: ReadonlyMap; /** Old key → the key it is now. */ aliases: ReadonlyMap; } +export type CategoryIndex = TermIndex; + +/** How messages name a kind. */ +export const TERM_WORDS: Readonly> = { + tag: { one: "tag", many: "tags", config: "storefront.tags" }, + category: { one: "category", many: "categories", config: "storefront.categories" }, +}; -/** storefront.categories (already checked by the config's validation), indexed. */ -export function categoryIndex(declared: Readonly> | undefined): CategoryIndex { - const list: Category[] = []; +/** storefront.tags or storefront.categories (already checked by the config's validation), indexed. */ +export function termIndex(kind: TermKind, declared: Readonly> | undefined): TermIndex { + const list: Term[] = []; const aliases = new Map(); for (const [key, c] of Object.entries(declared ?? {})) { - list.push({ key, label: c.label, description: c.description ?? null }); + list.push({ key, label: c.label, description: c.description ?? null, route: null }); for (const a of c.aliases ?? []) aliases.set(a, key); } - return { list, byKey: new Map(list.map(c => [c.key, c])), aliases }; + // Categories are always the declared list (none declared: no page may name one); tags only when declared. + return { kind, declared: kind === "category" || declared !== undefined, list, byKey: new Map(list.map(c => [c.key, c])), aliases }; +} + +/** storefront.categories, indexed. */ +export const categoryIndex = (declared: Readonly> | undefined): CategoryIndex => termIndex("category", declared); + +/** The term `key` of `index` as layouts get it: the declared one, or (undeclared tags) labelled with its key. */ +export function termOf(index: TermIndex, key: string): Term { + return index.byKey.get(key) ?? { key, label: key, description: null, route: null }; } type Obj = Record; diff --git a/packages/dev-server/src/storefront/collections.ts b/packages/dev-server/src/storefront/collections.ts index 706d4e5..e796d11 100644 --- a/packages/dev-server/src/storefront/collections.ts +++ b/packages/dev-server/src/storefront/collections.ts @@ -15,7 +15,7 @@ import { suggest } from "@pattern-dump/config"; import type { DatesMode, GitDates } from "./git-dates.js"; import type { PageModel } from "./pages.js"; -import type { Category } from "./categories.js"; +import type { Category, Term } from "./categories.js"; /** One page in a listing. */ export interface Entry { @@ -25,7 +25,7 @@ export interface Entry { date: string | null; updated: string | null; image: string | null; - tags: string[]; + tags: Term[]; categories: Category[]; draft: boolean; /** Its date is after today: pd dev only, since pd build leaves it out. */ diff --git a/packages/dev-server/src/storefront/derived.ts b/packages/dev-server/src/storefront/derived.ts index 36ed368..c857e5f 100644 --- a/packages/dev-server/src/storefront/derived.ts +++ b/packages/dev-server/src/storefront/derived.ts @@ -11,7 +11,7 @@ import type { StorefrontNavItem, StorefrontPagesResponse } from "@pattern-dump/contracts"; import type { Entry } from "./collections.js"; -import type { Category } from "./categories.js"; +import type { Category, Term } from "./categories.js"; /** A link to another page. */ export interface PageLink { route: string; title: string } @@ -33,23 +33,33 @@ export interface DerivedPage { children: Entry[]; /** The page's date, YYYY-MM-DD: its own, else the day git first saw it. */ date: string | null; - tags: string[]; + /** The page's tags (categories.ts), in its order; [] when it has none. */ + tags: Term[]; /** The page's categories (categories.ts), in its order; [] when it has none. */ categories: Category[]; + /** A generated tag or category page (terms.ts): its term, with its count of pages; null on any other page. */ + term: TermPage | null; + /** A generated index of tags or categories: every term with a page, by label; null on any other page. */ + terms: TermPage[] | null; /** A folder's index.md: its pages rendered through the view it names (views.ts), as HTML; null on any other page. */ listing: string | null; } +/** A tag or category with a generated page, as its page and its index get it. */ +export interface TermPage { key: string; label: string; description: string | null; route: string; count: number } + /** A value with no keys of its own; an object with exactly these fields; a list of one shape. */ export type Shape = "value" | { fields: Record } | { items: Shape }; const LINK: Shape = { fields: { route: "value", title: "value" } }; -/** A category (categories.ts). */ -export const CATEGORY: Shape = { fields: { key: "value", label: "value", description: "value" } }; +/** A tag or a category (categories.ts). */ +export const TERM: Shape = { fields: { key: "value", label: "value", description: "value", route: "value" } }; +export const CATEGORY: Shape = TERM; +const TERM_PAGE: Shape = { fields: { key: "value", label: "value", description: "value", route: "value", count: "value" } }; /** An entry of a listing (collections.ts). */ export const ENTRY: Shape = { fields: { - route: "value", title: "value", description: "value", date: "value", updated: "value", image: "value", tags: "value", + route: "value", title: "value", description: "value", date: "value", updated: "value", image: "value", tags: { items: TERM }, categories: { items: CATEGORY }, draft: "value", scheduled: "value", }, }; @@ -66,14 +76,16 @@ export const PAGE_SHAPE: { fields: Record } = { updated: "value", children: { items: ENTRY }, date: "value", - tags: "value", + tags: { items: TERM }, categories: { items: CATEGORY }, + term: TERM_PAGE, + terms: { items: TERM_PAGE }, 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", "listing"]; +export const FILLED: readonly (keyof DerivedPage)[] = ["headings", "section", "breadcrumbs", "prev", "next", "created", "updated", "children", "date", "tags", "categories", "term", "terms", "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 00f9f40..5b51bdd 100644 --- a/packages/dev-server/src/storefront/frontmatter-contract.ts +++ b/packages/dev-server/src/storefront/frontmatter-contract.ts @@ -21,8 +21,8 @@ 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, readChildLayout, readDate, readDraft, readSort, readTags, readUpdated, readView, type Read, type SortBy } from "./listing-keys.js"; -import { categoryIndex, type CategoryIndex } from "./categories.js"; +import { readChildLayout, readDate, readDraft, readSort, readTerms, readUpdated, readView, type Read, type SortBy } from "./listing-keys.js"; +import { categoryIndex, termIndex, TERM_WORDS, type CategoryIndex, type TermIndex, type TermKind } from "./categories.js"; import { declaredQueries } from "./query.js"; /** Keys the build owns: they are read by the storefront, never passed to the layout. */ @@ -66,7 +66,7 @@ const OLD_ROUTE = /^\/(?:(?!\.\.?\/)[^/?#\s]+\/)+$/; const ASSET_PATH = /^\/assets\/[^?#]+[^/?#]$/; function checkBuildKeys(values: Record, path: string, at: (key: string, message: string) => void, - categories: CategoryIndex, renamed: (from: string, to: string) => void): BuildKeys { + terms: { categories: CategoryIndex; tags: TermIndex }, renamed: (kind: TermKind, from: string, to: string) => void): BuildKeys { const out: BuildKeys = {}; const redirect = values["redirectFrom"]; if (redirect !== undefined) { @@ -87,7 +87,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); @@ -95,12 +95,13 @@ function checkBuildKeys(values: Record, path: string, const v = (key: string) => values[key]; take("date", v("date") === undefined ? undefined : readDate(v("date")!)); take("updated", v("updated") === undefined ? undefined : readUpdated(v("updated")!, out.date)); - take("tags", v("tags") === undefined ? undefined : readTags(v("tags")!)); - const cats = v("categories") === undefined ? undefined : readCategories(v("categories")!, categories); - if (cats?.ok) { - out.categories = cats.value.keys; - for (const r of cats.value.renamed) renamed(r.from, r.to); - } else if (cats) at("categories", cats.message); + for (const [key, index] of [["tags", terms.tags], ["categories", terms.categories]] as const) { + const r = v(key) === undefined ? undefined : readTerms(v(key)!, index); + if (r?.ok) { + out[key] = r.value.keys; + for (const x of r.value.renamed) renamed(index.kind, x.from, x.to); + } else if (r) at(key, r.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)); @@ -129,8 +130,9 @@ export function layoutNames(discoveryMap: DiscoveryMap): string[] { .sort(); } -/** `categories`: the declared ones (the page model's); none when left out. */ -export async function checkPageFrontmatter(page: PageFile, discoveryMap: DiscoveryMap, categories: CategoryIndex = categoryIndex(undefined)): Promise { +/** `categories` and `tags`: the declared ones (the page model's); no categories and any tag when left out. */ +export async function checkPageFrontmatter(page: PageFile, discoveryMap: DiscoveryMap, categories: CategoryIndex = categoryIndex(undefined), + tags: TermIndex = termIndex("tag", undefined)): Promise { const { values, errors, lines } = page.frontmatter; const problems: PageProblem[] = errors.map(e => ({ file: page.path, line: e.line, message: e.message })); const at = (key: string, message: string): void => { @@ -138,10 +140,11 @@ export async function checkPageFrontmatter(page: PageFile, discoveryMap: Discove }; const notes: string[] = []; const where = (key: string) => `${page.path}${lines[key] !== undefined ? `:${lines[key]}` : ""}`; - const renamed = (from: string, to: string): void => { - notes.push(`warning: ${where("categories")}: category "${from}" is now "${to}" (renamed in storefront.categories): write "${to}"`); + const renamed = (kind: TermKind, from: string, to: string): void => { + const w = TERM_WORDS[kind]; + notes.push(`warning: ${where(w.many)}: ${w.one} "${from}" is now "${to}" (renamed in ${w.config}): write "${to}"`); }; - const buildKeys = () => checkBuildKeys(values, page.path, at, categories, renamed); + const buildKeys = () => checkBuildKeys(values, page.path, at, { categories, tags }, renamed); // ---- layout: its own, else its folder's childLayout (pages.ts), else the default ---- const known = layoutNames(discoveryMap); diff --git a/packages/dev-server/src/storefront/json-ld.ts b/packages/dev-server/src/storefront/json-ld.ts index 6a43da4..26266a4 100644 --- a/packages/dev-server/src/storefront/json-ld.ts +++ b/packages/dev-server/src/storefront/json-ld.ts @@ -19,8 +19,10 @@ export interface JsonLdPage { modified: string | null; /** The page's date: its own (frontmatter `date`, YYYY-MM-DD), else git's first commit of it (ISO 8601), or null. */ published?: string | null; - /** The page is an article: its own date and its tags (page.ts articleOf). */ - article?: { published: string; tags: string[] } | undefined; + /** The page is an article: its own date, its tags' and its categories' labels (page.ts articleOf). */ + article?: { published: string; tags: string[]; sections: string[] } | undefined; + /** A generated tag or category page, or an index of them (terms.ts): a CollectionPage, not a WebPage. */ + collection?: boolean; } /** The page's JSON-LD as a