uniweb 1.25.4 → 1.25.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ # Data: records, queries, parametric pages, external sources, Loom
2
+
3
+ On-demand guide (`uniweb guide data`); AGENTS.md is assumed read. Author guide: `authoring/collections.md`. Every query key: `reference/queries.md`. Predicates: `authoring/predicates.md`. Dynamic routes: `reference/dynamic-routes.md`. Component keys: `reference/component-metadata.md`.
4
+
5
+ ## Records
6
+
7
+ A small database, not a page tree. Three things, deliberately separate:
8
+
9
+ ```
10
+ site/
11
+ ├── pages/
12
+ ├── records/ # the site's records — every file in a schema folder is one
13
+ │ ├── article/ # folder names the data schema
14
+ │ ├── person/
15
+ │ └── folder.yml # optional: sorts records into folders
16
+ ├── queries.yml # how content is REACHED
17
+ └── site.yml
18
+ ```
19
+
20
+ | on disk | schema |
21
+ |---|---|
22
+ | `records/article/…` | `@/article` — your foundation's own |
23
+ | `records/std/person/…` | `@std/person` — the shared standard set |
24
+ | `records/acme/project/…` | `@acme/project` — an org's |
25
+
26
+ Keep folders flat — `records/article/2025/x.md` reads as the `2025` schema of an `article` org. A `_`-prefixed file is not a record.
27
+
28
+ **Formats:** `.md` (frontmatter fields, body prose; auto-excerpt and first-image extraction), `.yml`/`.yaml` and `.json` (structured, no body), `.bib` (each `@entry{key, …}` is a record named by its cite key, normalized to CSL-JSON, LaTeX accents → Unicode). Mix freely in one folder. **One record per file**; the file name is `$name`, the one name it carries on every site (no `slug` field). Conventional fields: `title`, `date`, `tags`, `image`, `description`, `author`, plus whatever the content needs. Images sit beside the file (`./`). `draft: true` keeps a record off the live site: still a record, previewed by `pnpm dev`, excluded from a hosting build, kept undelivered on a backend.
29
+
30
+ **Links and files are records too.** `records/uniweb/link/x.yml` holding only `url:` (absolute) is a `@uniweb/link`; any file in `records/uniweb/file/` is a `@uniweb/file` named by its file name. Label and tags go on their `records/folder.yml` entry. Declare `data: { videos: '@uniweb/link' }` → `{ url, $name, $label, $tags }`; `data: { downloads: '@uniweb/file' }` → `{ file: { url, name, mime, size }, $name, $label, $tags }`. Two files of one name with different extensions clash. On a backend a component must declare the type for a query over it to be accepted.
31
+
32
+ **Multi-section schemas are written by section.** A `fields:` schema is flat. A schema with more than one section nests each field under its section; a field left at the top stops the build and a push. `@std/article` has `brief` and `body`:
33
+
34
+ ```markdown
35
+ ---
36
+ brief:
37
+ title: Hello
38
+ author: Ada
39
+ date: 2026-05-01
40
+ ---
41
+ The body — `body.content`.
42
+ ```
43
+
44
+ **References name the record they point at**: `speaker: ada` for `records/speaker/ada.yml`; a `many` ref is a list of names. A component receives `{ entity, brief }` (`talk.speaker.brief.name`). `uniweb validate` and a push report names matching no record; a pull writes names back.
45
+
46
+ **`records/folder.yml`** — optional, only for folders; moves with the directory (`paths.records`). Needed only when a query wants a *slice*:
47
+
48
+ ```yaml
49
+ - folder: archive
50
+ label: The Archive
51
+ records: [article/2025-*.md]
52
+ ```
53
+
54
+ Paths are relative to `records/`, one file or a glob. An entry can be `{ path, tags, label }` — delivered beside the record as `$tags` (in order) and `$label` (one text or `{ en, fr }`, resolved to the page's language); a query reads them like any key (`where: { $tags: featured }`). `scope: archive` reads the folder and everything inside. A record sits in one folder; a computed subset is a query. The build refuses a top-level bare path (every file is a record already).
55
+
56
+ **With a backend, `records/` is what `uniweb push` sends.** No `records/` leaves the backend alone; an *empty* `records/` removes them (the CLI asks). Records with a data schema reach published pages only when `services.records: true`.
57
+
58
+ ## Queries
59
+
60
+ ```yaml
61
+ # queries.yml: a bare map, with no root key (or `queries:` in site.yml)
62
+ recent:
63
+ schema: '@/article'
64
+ sort: date desc # ONE key; text sorts in the page's language; missing values sort last
65
+ limit: 10
66
+ team:
67
+ schema: '@std/person'
68
+ where: { active: true } # a where-object predicate
69
+ ```
70
+
71
+ **Show a query** with `query: name` (whole result) in `page.yml` or a section's frontmatter, or `fetch:` for more. `query: [team, articles]` declares several, each filling its own key. `query:` takes names only.
72
+
73
+ **Who receives it:** a section's own declaration → that section; a page's → every section on the page; a parent page's → sections of pages directly under it; `site.yml`'s → layout areas and top-level pages (homepage included), no deeper. A section on `/docs/setup` needing site-wide data names the query itself.
74
+
75
+ **A fetch always names a query.** `fetch: team` is `fetch: { query: team }`; `fetch: [team, articles]` is a list. Never a file (`/data/<query>.json` is what the build generates; writing it stops the build). A query's `scope`, `where`, `sort`, `limit` decide which records it selects — `limit` included. A fetch's `where` keeps those that also match, `sort` reorders, `limit` takes the first N, never more than the query selected; `scope` belongs to the query only. **Which records get a page is the query's decision**: `recent` (limit 10) gives each of its 10 a page; a list's `limit: 3` still leaves all 10 their pages. Two fetches under one key at one level: the first wins, the build warns.
76
+
77
+ ```yaml
78
+ # pages/blog/page.yml | # a homepage section
79
+ title: Blog | ---
80
+ query: recent | type: ArticleTeaser
81
+ | fetch: { query: recent, limit: 3 }
82
+ ```
83
+
84
+ ### Parametric pages
85
+
86
+ A `[slug]/` folder inside the page that names the query gives each record its own page:
87
+
88
+ ```
89
+ pages/blog/
90
+ ├── page.yml # title: Blog / query: recent
91
+ ├── list.md
92
+ └── [slug]/
93
+ ├── page.yml
94
+ └── article.md # just `type: Article` — the record arrives automatically
95
+ ```
96
+
97
+ `records/article/design-tips.md` → `/blog/design-tips`. Generated pages are excluded from navigation.
98
+
99
+ **Link with `item.$route`, never a composed URL.** Every record a query delivers carries `$route` (the URL of the parametric page whose route query is that query), wherever the list appears. No page or no value → no `$route`, never a broken one. `detailPage: page:<id>` on a fetch links to another page instead. `$` marks framework-filled fields; a record's own `route` is untouched.
100
+
101
+ **The route query** — which query the URL narrows: the `[slug]` page's own `query:`, else its parent's, else `site.yml`'s (top-level `pages/[slug]/` only); if none, the query its sections all declare. The folder name says what the segment matches: `[slug]` the record's name (`$name`) — or the field the route query binds `:slug` to (`where: { slug: :slug }`, how an external API's records get pages); `[uuid]` its `$uuid`; any other `[name]` the record's field of that name (several values → any member matches; non-unique → the build warns). A folder inside `[slug]/` (`[slug]/cv/`) is a parametric page about the same record.
102
+
103
+ **`current:`** on a section's own `fetch:` chooses how it uses the page's record: `only` (default — the record), `exclude` (the others, "related"), `include` (all, a pager). `fetch: { query: articles, as: related, current: exclude, limit: 3 }`. It follows the query, not the key: a fetch of the route query gets the record unless it says otherwise; a fetch of another query reads `current:` only when written.
104
+
105
+ **The record arrives under the key the component declares, as that key says** — one record for `single: true` (`content.data.article`; `null` when the URL names none), a single-element array otherwise; a brief, with the brief's fields at the top (`article.title`), or with `whole: true` the record as stored, each section under its name (`article.brief.title`, `article.body.content`; a flat `fields:` schema's fields sit under `brief`).
106
+
107
+ **`[...path]/`** (exact spelling) captures the rest of the URL: `/blog/my-post` and `/blog/rust/2025/my-post` both reach it. Variables `:path` (whole capture), `:dir` (before the last segment), `:slug` (last segment) exist under every parametric page (under `[slug]`, `:dir` is empty). A record's own URL is its name, wherever `folder.yml` places it. A query may bind a part — `scope: :dir`, `where: { tag: :dir }` — and an unbound variable drops its clause, so one query serves the list page and the record page alike.
108
+
109
+ ### Bigger sets
110
+
111
+ A list carries each record's brief, so heavy parts belong in a section of their own (`@std/article`'s body). A section showing them declares `whole: true`; elsewhere fetch on demand: `const { data: full } = useWholeRecord(record, { query })` holds the record as stored (`full.body.content`). File-based records are written whole at `/data/<name>/<record>.json`; an external query names its one-record request with `record:`. The hook is safe on any query (returns the record you passed when there's no separate source).
112
+
113
+ **`queryable:`** declares reader-filterable fields with enough metadata for the foundation to render controls:
114
+
115
+ ```yaml
116
+ members:
117
+ schema: '@std/person'
118
+ queryable:
119
+ department: { type: enum, label: Department, options: [biology, physics, chemistry] }
120
+ tenured: { type: boolean, label: Tenured }
121
+ start_year: { type: range, label: Start year, min: 1800, max: 2025 }
122
+ ```
123
+
124
+ ## The component side
125
+
126
+ **Keys and schemas.** `meta.js data:` declares each `content.data` key with its shape — a **named ref**, an **inline field map**, an **inline rich form** (`{ fields: [...] }`), or `{}` (a key with no schema — an external API's records). Refs resolve on disk at build time: `@/name` (this foundation's `schemas/`), `@std/name` (from `@uniweb/schemas`), `@org/name` (from `@org/schemas`). A schema drives the editor, checks data (`validate`), lets a fetch of another name fill the key; it fills no field — a record arrives as it is (`record.status ?? 'published'` is yours). A named schema declares no `default:` (inline maps/forms may). `data: false` declares nothing. Keys a foundation's handlers read go in `main.js data:` and reach every section.
127
+
128
+ ```js
129
+ data: {
130
+ articles: '@/article',
131
+ authors: '@std/person',
132
+ pricing: { tier: { type: 'string' } },
133
+ article: { schema: '@std/article', single: true, whole: true }, // long form: schema, single, whole — nothing else
134
+ }
135
+ ```
136
+
137
+ `single`/`whole` are refused over a schema whose root is a list (`@std/nav`, `@std/form`). A `whole` key its source cannot answer whole is `null`. An optional `schemas.config.js` routes a scope to a folder: `export default { '@acme': '../shared/acme-schemas' }` — a routed scope wins, has no package fallback, and `@/`/`@uniweb` are never routable. Worked examples: `development/schemas-in-practice.md`.
138
+
139
+ ```jsx
140
+ function Article({ content, block }) { // data: { article: { schema: '@std/article', single: true } }
141
+ if (block.dataLoading) return <DataPlaceholder />
142
+ if (block.dataError?.article) return <LoadFailed /> // the request failed — not "no records"
143
+ const article = content.data.article
144
+ if (!article) return <NotFound />
145
+ return <ArticleView article={article} />
146
+ }
147
+ ```
148
+
149
+ **Authoring queries** — `where:`, `sort:` (one key), `limit:` — select a query's records and narrow a fetch's. The browser evaluates them over fetched records; a host that answers queries evaluates the same language at the source; a transport receives them under `narrow`. The declaration is identical in every case.
150
+
151
+ **Component-side fetching** for a search box, "load more", a lazy popover: `useFetched`, `useCacheEntry`, `useWholeRecord` share the framework's cache and dedupe same-key requests. On a prerendered page a hook's first render finds only the page's own data; anything else prerenders as the loading state. Declare a key for whatever a page must show without JavaScript.
152
+
153
+ **`uniweb validate`** checks every record file against declared schemas (missing required, type/enum/format, nested fields); a violation fails it (`--lax` only reports), and `push`/`publish` refuse the same findings. External queries are reported as deferred. A `ref` must name a record in the project (a uuid is left alone); an `options` value isn't checked against the entity it names.
154
+
155
+ ## External sources and transports
156
+
157
+ A public keyless JSON API is an **external query**:
158
+
159
+ ```yaml
160
+ posts:
161
+ url: https://api.example.com/posts
162
+ transform: data.items # dot-path to the records
163
+ record: # one whole post, for an [id] page
164
+ url: https://api.example.com/posts/{id}
165
+ ```
166
+
167
+ Also `method: POST` + `body`, `where`/`sort`/`limit` (over what arrived, after `transform`), `queryable`. Its records have no `$name`, so a `[slug]` page over it binds the URL field in the query's own `where` (`where: { slug: :slug }`). `record:` takes `url`, `method`, `body`, `transform` (`url`/`method` default to the query's; a placeholder named by the folder — `{id}` for `[id]` — is the segment). `schema`, `scope`, `deferred`, `excerpt`, `path` are refused beside `url:`. The visitor's browser fetches it (a `fetch:` with `prerender: true` makes the build fetch instead); it compiles no `/data` file. A site's own schema records are another matter: on a published site they need `services.records: true`.
168
+
169
+ A backend needing a key, headers, paging or its own wire language is a **transport** — a named `{ resolve, cacheKey? }` exported by the foundation (or an extension), selected by the site per data key:
170
+
171
+ ```yaml
172
+ # site.yml
173
+ fetcher:
174
+ transports:
175
+ articles: acme # the foundation's transport handles `query: articles`
176
+ events: default
177
+ acme:
178
+ apiKey: pk_public_123 # binding config that transport reads
179
+ ```
180
+
181
+ Selection is explicit and site-owned: `fetcher.transports[as]`, else `fetcher.transports.default`, else the framework's fetcher. Never secrets in `site.yml`/`queries.yml` — proxy through the same origin at the deployment layer. A failed fetch leaves its key `null` and names the message on `block.dataError[key]`; never `[]`. Choosing between an external query and a transport: `development/data-sources.md`. Full model: `reference/data-fetching.md`.
182
+
183
+ ## Content handlers (Loom)
184
+
185
+ Handlers in `main.js` transform every section's data/content before the component sees it. Optional, per block, error-isolated (a failing handler warns and falls back).
186
+
187
+ | Handler | Receives | Returns | Purpose |
188
+ |---|---|---|---|
189
+ | `data` | `(data, block)` | new data, or null | filter, reshape, augment assembled data |
190
+ | `content` | `(data, block)` | ProseMirror doc, or null | transform raw content (Loom, templates) |
191
+ | `props` | `(content, params, block)` | `{ content, params }`, or null | post-process the final shape |
192
+
193
+ The `content` handler receives the section's declared keys (declare in `main.js data:` every key a handler reads), reads raw ProseMirror from `block.rawContent`, and returns a new document the framework re-parses. `null` or the same reference = no change; anything else is ignored with one warning (a pass-through `(x) => x` returns the *data*, not the content). Unwrap defensively: `const doc = block.rawContent?.doc ?? block.rawContent`.
194
+
195
+ ```js
196
+ import { createLoomHandlers } from '@uniweb/loom'
197
+ export default { handlers: createLoomHandlers({ vars: (data) => data?.profile?.[0] }) }
198
+ ```
199
+
200
+ `vars` extracts the variable namespace. The handler reads the `source` and `where` frontmatter params: without `source`, simple substitution; with `source`, it splits the markdown at `---` and repeats the body per item. `where` filters first — `type = 'book'`, `year > 1870`, `refereed`, `type = 'book' AND refereed`; aggregates (`{COUNT OF publications}`) reflect the filtered set. For other cases use `Loom`, `instantiateContent`, `instantiateRepeated` directly. `instantiateContent` resolves placeholders in text and in where a link leads, so `[{email}](mailto:{email})` works; other attributes stay as written, so a value in an image's `src` has to be built in the handler. `source` and `where` are ordinary params (list them in `meta.js` for the editor).
201
+
202
+ **Data-driven dividers.** Header/body/footer in a repeated template, split *before* Loom runs because each segment gets a different variable context:
203
+
204
+ ```markdown
205
+ ---
206
+ type: CvEntry
207
+ source: education
208
+ ---
209
+ # Education
210
+ {COUNT OF education} degrees.
211
+ ---
212
+ ## {degree}
213
+ {institution} — {field} ({start}–{end})
214
+ ```
215
+
216
+ Different data contexts per region → Loom's pre-parse split. Same data, different UI → kit's `splitContent` after parsing.
@@ -0,0 +1,339 @@
1
+ # Guide: foundation
2
+
3
+ Lane guide — AGENTS.md procedure step 6 loads it before any foundation code is written. Signatures and props: the kit is on disk at `node_modules/@uniweb/kit`; full API in `reference/kit-reference.md`.
4
+
5
+ ## Discovery and entry
6
+
7
+ PascalCase files and folders at the root of `sections/` are auto-discovered; nested levels need a `meta.js`; lowercase directories are organizational; `hidden: true` excludes a component entirely. Discovery accepts a `.js` component only without JSX — JSX compiles in `.jsx`/`.tsx` only, and the build stops on a `.js` file holding it.
8
+
9
+ **Source root.** The `src/` folder *is* the foundation; the build reads `package.json::main` (`./_entry.generated.js` for new scaffolds). Older foundations nest source in `foundation/src/` with `main` pointing at `./src/_entry.generated.js`; both work.
10
+
11
+ **`main.js`.** One `export default { … }`: identity (`name`, `description`) and capabilities (`defaultLayout`, `defaultSection`, `viewTransitions`, `defaultInsets`, `xref`, `outputs`, `handlers`, `data`), plus an optional named `vars` export. Section types and layouts are merged in by `@uniweb/build`; you never write that wrapper. The build carries into `dist/entry.js` only what a published page reads — code it calls and lean data (`defaultLayout`, each var's `default`/`type`/`applyTo`, each `data:` key's schema ref); `name`, `description`, labels stay out and reach the editor via the schema. The file is plain JavaScript: a component it declares lives in a `.jsx` it imports. When you import your **own** `main.js` from a component (e.g. `compileDocument(website, { foundation })`), you get the bare default object — pass it through.
12
+
13
+ ## Rendering content with Kit
14
+
15
+ Content fields are HTML strings from markdown (`<strong>`, `<em>`, `<a>`). Kit's text components render them: `H1`–`H6`, `P`, `Span`, `Div`, `Text` (with `as`). They render their own tag — `<H2 text={…} />`, never `<h2><H2 /></h2>`.
16
+
17
+ **Full content rendering** for article/docs sections where the author controls the flow:
18
+
19
+ ```jsx
20
+ import { Section, Prose, Article } from '@uniweb/kit'
21
+ <Section block={block} width="lg" padding="md" /> // the whole section, on its own; no insets
22
+ <Prose content={content} block={block} /> // or only its prose, in your own markup; pass block if the content has insets
23
+ ```
24
+
25
+ `Prose` renders headings, paragraphs, images, snippets, lists with prose typography. Markdown footnotes (`[^1]` and a `[^1]: the note` paragraph in the same file) become numbered links with the notes listed at the end; a section drawing `content.paragraphs` itself sees them as the text they are. Tagged data blocks are skipped (read them from `content.data`). It also works as a typography wrapper: `<Prose>{children}</Prose>`. `Article` is `Prose` in a semantic `<article>`.
26
+
27
+ **Drawing an element your own way.** `components` on `Prose`, `Render`, `Article` or `Section` replaces how one element type is drawn, and kit keeps the rest. An entry receives `{ element, block, children }`: a `codeBlock` has `element.text` and `element.attrs.language`, a `dataBlock` (a tagged fence, drawn where the author put it) has `element.tag` and `element.data`, and a `concept_block` has `element.tag` and `children`. To use it across sections, wrap `Prose` once in a component of your own.
28
+
29
+ ```jsx
30
+ import { Prose, Code, Mermaid } from '@uniweb/kit'
31
+
32
+ function CodeBlock({ element: { text, attrs } }) {
33
+ return attrs?.language === 'mermaid'
34
+ ? <Mermaid source={text} />
35
+ : <Code content={text} language={attrs?.language} />
36
+ }
37
+
38
+ <Prose content={content} block={block} components={{ codeBlock: CodeBlock }} />
39
+ ```
40
+
41
+ **Diagrams.** `Mermaid` draws a ` ```mermaid ` fence, and only where a foundation passes it one like this: elsewhere the fence stays code. The prerendered page holds the source as code, and the diagram replaces it when it comes near the view, so expect the page to move by the difference in height. Its colors come from the section's tokens. It's an image, drawn by an engine in a sandboxed frame loaded from a CDN, so its nodes can't be clicked, its text can't be selected, and its labels use the system font. A foundation that doesn't import it carries none of it.
42
+
43
+ **Prose styling.** `<Prose>` and any container you put `<Render>` output in use kit's `prose` classes, supplied by one import in `styles.css`:
44
+
45
+ ```css
46
+ @import "@uniweb/kit/prose-tokens.css";
47
+ ```
48
+
49
+ Skip it and prose is unstyled (lists lose bullets) while the markup looks right; the build warns and `doctor` flags it. `size` picks a step (`prose-sm`…`prose-2xl`) of the site's reading size, which `theme.yml` sets under `vars:` — `prose-size`, `prose-leading`, `prose-measure`, `prose-flow`, `prose-h1`…`prose-h4`; spread `proseVars` from `@uniweb/kit/prose-vars` into `main.js vars` to declare them. `<Prose>`/`<Article>` fill their box (`max-w-none`); set width on the box around them. Utility classes and element variants (`prose-headings:tracking-tight`, `prose-a:no-underline`) override; there are no palette modifiers and no `prose-invert` — colors are already the theme's.
50
+
51
+ ### The Kit, by use case
52
+
53
+ **Text:** `H1`–`H6`, `P`, `Span`, `Div`, `Text`, `PlainText`
54
+ **Content:** `Section`, `Prose`, `Article`, `Render` (ProseMirror → React), `ChildBlocks`, `ChildGrid`, `splitContent()`
55
+ **Media:** `Visual` (a `content.media` item by kind; or first of inset/video/image), `Image`, `Media` (video), `Icon`, `Asset`, `SectionBackground`
56
+ **Navigation:** `Link`, `useActiveRoute()`, `useWebsite()`, `useRouting()`
57
+ **Header/layout:** `useScrolled(threshold)`, `useMobileMenu()`, `useAppearance()`
58
+ **Overlays:** `Overlay`
59
+ **Keyboard:** `useShortcut('mod+k', fn)`, `useShortcuts({…})`, `useShortcutLabel('mod+k')` — `mod` is Cmd on Apple, Ctrl elsewhere; the label renders per platform
60
+ **Documentation shells:** `useHeadings()` (the page's headings + the one being read, prerenderable), `website.getBranchHierarchy({ route, for })`, `useVersion()` — `versions` for a switcher (`version.href` is where each leads from this page, for `<Link>`), `isOlderVersion` and `latestVersion` for a notice, `hierarchy({ for: 'left' })` for a menu of one version (the whole tree on a site with none). Kit ships no ready-made layout; write yours in `layouts/`.
61
+ **Layout helpers:** `useGridLayout(columns, { gap })`, `useAccordion({ multiple, defaultOpen })`
62
+ **Theming data:** `useThemeData()`, `useColorContext(block)`
63
+ **Data fetching:** `useFetched`, `useCacheEntry`, `useWholeRecord`
64
+ **Forms:** `useFormValues`, `valueAt`, `useFormSubmit`, `submitForm`, `resolveSubmitTarget` (services guide)
65
+ **Utilities:** `cn()`, `SafeHtml`, `SocialIcon`, `filterSocialLinks(links)`, `getSocialPlatform(url)`, `getLocaleLabel(locale)`
66
+ **Other styled:** `Code`, `Mermaid`, `Alert`, `Table`, `Details`, `Divider`, `Disclaimer`
67
+
68
+ Things you won't discover from exports:
69
+
70
+ - **`<Link>` takes `to` or `href`.** `to="page:about"` resolves a page id (survives moves) or a route, never a folder: the homepage is `page:/`, or `page:home` only when its `page.yml` says `id: home`. External URLs get `target="_blank"`; `reload` forces a full load.
71
+ - **A modal needs `<Overlay>`, not a bigger z-index.** Each layout area has its own `view-transition-name`, which makes it a stacking context; a `fixed` dialog inside one paints at its area's place in the stack, under the header/footer. `<Overlay onClose={close}>` renders into `document.body`, contains focus (moves it in, cycles Tab, marks the rest `inert`, returns it), handles Escape, scrim click, scroll lock; a dimmed scrim you override with `className` (`bg-transparent` removes it). `modal={false}` for a toast. Your dialog markup stays yours.
72
+ - **Kit hooks are SSR-safe.** "document is not defined" → use the hook, don't add guards.
73
+ - **`cn()` drops an earlier `leading-*` when a `text-<size>` follows**, since Tailwind's size classes set line height too: `cn('leading-[1.1] text-4xl')` → `text-4xl`. Put the size first, or fold the leading into it (`text-[clamp(2rem,5vw,4rem)]/[1.1]`).
74
+ - **"3 of 12 pages didn't render"** means the build stopped, exit 1, because a section threw while rendering a page, and `dist/` isn't complete. It names the error, the section type and the pages. A section that only fails here reads something only a browser has; `uniweb dev` won't show that one.
75
+
76
+ ### Icon
77
+
78
+ ```jsx
79
+ {content.icons.map((icon, i) => <Icon key={i} {...icon} />)}
80
+ <Icon name="search" /> // Lucide default
81
+ <Icon name="hi2-arrow-right" /> // other library by prefix
82
+ <Icon name="close" /> // built-in, no network: check close menu chevronDown chevronRight externalLink download play …
83
+ ```
84
+
85
+ Other props: `svg`, `url`, `size` (default `'24'`), `className`.
86
+
87
+ ## Section wrapper and sticky
88
+
89
+ The runtime wraps every section in a bare `<section>` with its background, and a context class when the section pins `theme:` — no padding of its own to reset. `Type.className` adds classes to that wrapper; `Type.as` changes its tag. The built-in layout already wraps the header area in `<header>` and the footer area in `<footer>`, so `Header.as = 'header'` gives a header in a header. Use `as` to say something the layout doesn't:
90
+
91
+ ```jsx
92
+ Header.className = 'border-b'
93
+ Header.as = 'div'
94
+ ```
95
+
96
+ **Sticky is a setting.** `sticky: true` in the type's `meta.js` (an author turns it off with `sticky: false`); the runtime makes sticky the box that can stay in view. A body section sticks the same way and stays below the stuck header: the runtime publishes the header's reach as `--uw-sticky-top` (a type's `top` overrides: `sticky: { default: true, top: '4rem' }`). Section links land below the stuck header. A child in `<ChildGrid>` sticks beside its column, and scrolls with the page at one column. A sticky section inside `overflow: hidden` can't stick — use `overflow: clip`. A layout that wraps an area in its own element makes it sticky when `page.isSticky('header')`. `uniweb dev` names a sticky element that cannot move in the console.
97
+
98
+ ## meta.js in full
99
+
100
+ ```js
101
+ export default {
102
+ title: 'Feature Grid',
103
+ description: 'Grid of feature cards with icons',
104
+ family: 'features',
105
+ content: {
106
+ title: 'Section heading',
107
+ paragraphs: 'Introduction [0-1]',
108
+ items: { label: 'Feature cards [3-6]', content: { icon: 'Icon [1]', title: 'Feature', paragraphs: 'Description' } },
109
+ media: 'Photo, video or diagram [1]',
110
+ // sequence: 'Prose and media', // renders content.sequence — the section as written
111
+ },
112
+ params: { … }, vars: { … }, data: { … }, presets: { … },
113
+ context: {}, initialState: {},
114
+ }
115
+ ```
116
+
117
+ **`content:`** names what the component reads, each as an author label with optional count: `title`, `pretitle`, `subtitle`, `paragraphs`, `links`, `lists`, `items`, `media`, `icons`, `documents`, `snippets`, `tables`, `math`, `quotes`, `sequence`. It is a description for the editor and for other agents, not a validation schema. Take what you expect — `content.paragraphs[0]` if you need one paragraph — and render every paragraph or every item only when showing them all is the point. A section may hold content the type never reads; don't enumerate it, validate it or react to it.
118
+
119
+ - **`media`** is an image, a video, or an embedded component. `media: { label, types: ['image'] }` narrows it; `image:`, `videos:`, `insets:` are the same slot narrowed to one type. Read `content.media` (author's order, each with `kind`) and render with `<Visual media={content.media} block={block} />`. `<Image>` would drop a diagram placed there; `<Media>` is a video player. An image's `width` and `height`, when it has them, reach the `<img>` as attributes, so a class that sets only its height needs `w-auto` too (`h-8 w-auto`), or the width stays the file's.
120
+ - **`sequence`** says the component renders the whole section as written. `{ label, except: ['table', 'math'] }` names kinds it leaves out; `placement` the placements it lays out — `true` (all four, what `<Render>`/`<Prose>`/`<Article>` do), a list, or a map per kind. An editor offers an author only those.
121
+ - **`items: { label, content: {…} }`** says what each entry holds.
122
+
123
+ **`family:`** — an editor's section picker needs to know what a type *is* for its illustration, icon and translatable label; the icon is the family's. Name the component for its family (`uniweb families`: `Hero`, `Footer`, `Pricing`, `FAQ`, `CardGrid`, …) or declare `family: 'hero'` for a variant (`HeroWithEstimate`). Leave it off when nothing fits; `uniweb doctor` shows what each section resolved to.
124
+
125
+ **`meta.js` is a user interface.** Published, every `meta.js` becomes the foundation's schema and the visual editor builds controls from it: a `select` with `options` is a dropdown, a `boolean` a toggle, `label`/`description` the words an author reads, each preset a one-click choice.
126
+
127
+ ## Two worlds: section types and your own components
128
+
129
+ `{ content, params, block }` is how **section types** work — a public interface with authors, documented by `meta.js`. Everything under `components/` is a normal React project: any props, any composition, any library — install it and import it — no `meta.js`, no discovery, no author visibility. There is no expected shape for `components/`: presentational primitives shared across section types, a thin wrapper adapting parsed content to a third-party component's props, layout scaffolding, stateful widgets, legacy components carried in during a migration. The only packages a foundation doesn't install are a foundation, `@uniweb/runtime` (it arrives through `@uniweb/build`), font packages (`@fontsource/*` — families are the site's) and `@tailwindcss/typography` (prose comes from kit).
130
+
131
+ Two symptoms of getting it backwards: helper components with a `{ content, params }` signature (a card taking `title`, `price`, `features` is better than one digging through `content`), and helpers in `sections/` (a `Button` in the section picker is a bug in your interface).
132
+
133
+ A section type is usually a composite translating parsed content into your components' props:
134
+
135
+ ```jsx
136
+ // sections/Pricing/index.jsx
137
+ import PricingCard from '#components/PricingCard'
138
+ import formatPrice from '#utils/formatPrice'
139
+ export default function Pricing({ content, params }) {
140
+ return (
141
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto">
142
+ {content.items.map((tier, i) => <PricingCard key={i} tier={tier} price={formatPrice(tier.data, params.currency || 'USD')} />)}
143
+ </div>
144
+ )
145
+ }
146
+ ```
147
+
148
+ ### The Front Desk pattern
149
+
150
+ A section type is triage: it reads params, picks a worker, and translates author vocabulary into developer props — and that is all it does. The workers are ordinary components that know nothing about CCA, and they need not share an interface: a `Hero` might hand off to a `SliderHero` (image carousel) or a `ContactHero` (quote form) that want different content and different props. The front desk declares the **union** of what they need, and unused content for a given variant is normal — params change behavior, and that includes not rendering some content. This is what lets an author (or an A/B test) flip `variant:` on a section without touching its markdown.
151
+
152
+ ```js
153
+ // meta.js
154
+ params: {
155
+ variant: { type: 'select', options: ['slider', 'contact'], default: 'slider' },
156
+ slideInterval: { type: 'number', default: 5 },
157
+ density: { type: 'select', options: ['default', 'compact'], default: 'default' },
158
+ }
159
+ ```
160
+
161
+ ```jsx
162
+ const workers = { slider: SliderHero, contact: ContactHero }
163
+ export default function Hero({ content, block, params }) {
164
+ const Worker = workers[params.variant] || SliderHero
165
+ return <Worker title={content.title} links={content.links} images={content.images} block={block}
166
+ formData={content.data?.quote} interval={params.slideInterval}
167
+ compact={params.density === 'compact'} />
168
+ }
169
+ ```
170
+
171
+ Reach for it when a page type has consistent structural elements (header bars, nav footers, contextual sidebars) an author shouldn't add as separate sections. Don't solve that at the layout level: if only some page types need it, it's a section concern — the layout owns page-wide chrome, the section owns its internal structure.
172
+
173
+ ## Params, component vars, foundation vars
174
+
175
+ | | Declared in | Reaches the component as | Author overrides in | CSS scope |
176
+ |---|---|---|---|---|
177
+ | Param | `meta.js params:` | a JS prop | section frontmatter | — |
178
+ | Component var | `meta.js vars:` | a CSS custom property | frontmatter `vars:` | `#section-{id}` |
179
+ | Foundation var | `main.js vars:` | a CSS custom property | `theme.yml vars:` | `:root` |
180
+
181
+ ```js
182
+ // meta.js — same schema as foundation vars: default, label, type, options, group, description
183
+ vars: {
184
+ 'card-gap': { default: '1.5rem', label: 'Card Gap', type: 'select', options: ['1rem', '1.5rem', '2rem'] },
185
+ 'card-radius': { default: 'var(--radius-md)' },
186
+ }
187
+ // usage: className="grid gap-[var(--card-gap)]"
188
+ ```
189
+
190
+ Unknown var names in frontmatter are ignored; component vars are context-independent (foundation `color`/`gradient` vars resolve per light/dark context). A header height or sidebar width is a **layout param**, not a foundation var.
191
+
192
+ ```js
193
+ // main.js
194
+ export const vars = {
195
+ 'radius-lg': { default: '1rem', description: 'Large border radius' },
196
+ 'section-padding-y': { default: 'clamp(4rem, 6vw, 7rem)' },
197
+ }
198
+ ```
199
+
200
+ Each entry ships its default as a CSS custom property everywhere, in dev and production, bundled or runtime-loaded. A `styles.css` `@theme` block is different: it registers a token so **Tailwind generates utilities** (`@theme { --breakpoint-xs: 30rem }` → `xs:`). A var named after a Tailwind namespace (`radius-*`, `shadow-*`, `spacing`, `font-*`) redefines that scale wherever the utility appears — deliberate when you mean it.
201
+
202
+ Colors, tokens, light and dark, fonts and `styles.css` are in `uniweb guide theme`.
203
+
204
+ ## Composition
205
+
206
+ | Pattern | Authored | Rendered by |
207
+ |---|---|---|
208
+ | Items | heading groups | `content.items.map(…)` |
209
+ | Concept blocks | ` ```md:tag ` | `content.data.tag.items` / `.sequence` |
210
+ | Child sections | `@file.md` + `nest:` | `<ChildBlocks from={block} />`, `<ChildGrid from={block} />` |
211
+ | Insets | `![](@Component)` | `<Visual media={content.media} block={block} />`; `block.insets`, `block.getInset(refId)` |
212
+ | Block insets | ` ```@Component ` fence | the component, receiving parsed `content` |
213
+
214
+ **Concept blocks.** Declare as the author writes the fence: `data: { 'md:faq': 'Questions and answers [3+]' }` (or `{ label, hint, content: { title: 'Question', paragraphs: 'Answer' } }`; `faq: {}` declares with no description). Read `content.data.faq` — `items` for row-shaped rendering, `sequence` to render faithfully when you don't recognise the tag. The shape is fixed by the fence, not the tag; the framework never learns what `faq` means.
215
+
216
+ **A data block whose value is a schema** — an author-designed form at `content.data.form` — is the inverse of every other component: declare the key, receive the fields, draw what you're given. You may declare a schema of the *envelope* (`title`, `description`, `fields`) for validation, never of the form's own fields.
217
+
218
+ **Insets** are full section types: `{ content, params, block }`, alt text → `content.title`, attributes → `params`. `inset: true` in `meta.js`; add `section: true` for a component placed both ways. The hosting section declares a `media` slot and renders `<Visual>`, so one type works whether the author supplies an image, a video or an interactive component. Don't use `hidden: true` on insets — that means "never export".
219
+
220
+ **Block insets** get their whole body parsed (`title`, `paragraphs`, `items`, `sequence`); render with `<Prose content={content} block={block} />` or read fields. Prefer a child section when the author needs their own type and independent editing; a block inset when the wrapper is presentational and inline.
221
+
222
+ **Child sections.** The parent decides *how*, the author decides *what*:
223
+
224
+ ```jsx
225
+ import { ChildBlocks } from '@uniweb/kit'
226
+ export default function Grid({ block, params }) {
227
+ return <div className={`grid grid-cols-${params.columns || 2} gap-6`}><ChildBlocks from={block} /></div>
228
+ }
229
+ ```
230
+
231
+ `ChildBlocks` renders each child bare by default — no wrapper, no context class, no background (right for grid cells, tabs, slides); `wrapAs="div"` makes them independent sections with their own theming. You're in the middle: wrap, filter by type, reorder. A section type offering column layouts declares `children: { grid: [3, 2, '40/60'] }` and renders `<ChildGrid from={block} fallback={3} />`; the author picks with `grid:`, and `fallback` is the default (with none, one column). Don't declare a param named `grid`.
232
+
233
+ Page-level `query:`/`fetch:` reaches children too; each child resolves data through page → parent page → site, or declares its own in frontmatter. SSG: insets, `<ChildBlocks>` and `<Visual>` prerender; hook-using insets produce harmless prerender warnings.
234
+
235
+ **Dividers.** `---` is a boundary; `splitContent(content)` from kit splits `sequence` at dividers for different UI treatment (`const [lesson, challenge] = splitContent(content)`) and leaves the grouped fields whole, so draw each region from its sequence: `<Prose content={lesson} block={block} />`. Different *data* contexts per region → Loom's pre-parse split (data guide). A foundation can use both.
236
+
237
+ ## Custom layouts
238
+
239
+ ```jsx
240
+ // layouts/DocsLayout/index.jsx
241
+ export default function DocsLayout({ header, body, footer, left, right, params }) {
242
+ return (
243
+ <div className="min-h-screen flex flex-col">
244
+ {header && <header>{header}</header>}
245
+ <div className="flex-1 flex">
246
+ {left && <aside className="w-64">{left}</aside>}
247
+ <main className="flex-1">{body}</main>
248
+ {right && <aside className="w-64">{right}</aside>}
249
+ </div>
250
+ {footer && <footer>{footer}</footer>}
251
+ </div>
252
+ )
253
+ }
254
+ ```
255
+
256
+ Layouts are auto-discovered in `layouts/`. Set `defaultLayout` in `main.js` or name one `Default`; with neither, a page gets the built-in layout: header, page, footer and nothing else, so `layout/left.md` isn't drawn. A `defaultLayout` naming no layout stops the build. Layouts have their own `params` in `meta.js` (header height, sidebar width).
257
+
258
+ **Layout `meta.js`:** `{ areas: ['header', 'footer', 'left'], scroll: 'self' }`. Area names are arbitrary; a page renders the areas its site's `layout/` folder fills. `scroll`: unset = runtime manages `window`; `'self'` = the layout scrolls itself; a selector (`'main'`) = runtime manages that element. `transitions` renames or opts areas out of per-area view transitions (`{ left: null }`, or `false`); the body has no name and crossfades — naming it (`{ body: 'main' }`) freezes Safari on long pages. `layers` sets which area paints on top (`{ header: 2, left: 1 }`); every area is above the body by default, and a sticky area above non-sticky ones. A `z-index` inside an area cannot lift it past another — use `layers`, or `<Overlay>` to escape entirely.
259
+
260
+ **Layout content** lives in `site/layout/`: `header.md`, `footer.md` for the default layout, or a named subdirectory (`site/layout/marketing/`) for named layouts — self-contained, no inheritance; the name matches regardless of case and a trailing `Layout` (`layout/docs/` serves `DocsLayout`). An area with several sections is a folder inside a layout's folder (`layout/default/header/1-topbar.md`); areas have no `page.yml` and render in filename order. Cascade: `page.yml → folder.yml → site.yml → defaultLayout → "default"`.
261
+
262
+ Layout sections are regular section types; each content category takes a role:
263
+
264
+ ````markdown
265
+ ---
266
+ type: Header
267
+ ---
268
+ # Acme Inc ← content.title — the logo
269
+ - ![](lu-search) [How It Works](/how) ← content.lists[0] — the nav
270
+ [Get Started](/docs/quickstart) ← content.links[0] — the CTA
271
+ ```yaml:config
272
+ github: https://github.com/acme ← content.data.config (declare data: { config: {} })
273
+ ```
274
+ ````
275
+
276
+ ```jsx
277
+ function Footer({ content }) {
278
+ const tagline = content.paragraphs[0]
279
+ const columns = (content.lists[0] || []).map(g => ({ label: g.paragraphs[0], links: g.lists[0]?.map(i => i.links[0]) }))
280
+ }
281
+ ```
282
+
283
+ ## Cross-block communication
284
+
285
+ A Header adapting to whether the section below supports a translucent overlay: the section that **owns** the capability declares it, the one that **adapts** reads it, via `getNextBlockInfo()` / `getPrevBlockInfo()` / `page.getFirstBodyBlockInfo()`:
286
+
287
+ - **`context`** — static, from `meta.js`.
288
+ - **`state`** — dynamic, via `block.useBlockState()`, initial value from `initialState`.
289
+
290
+ ```js
291
+ // Hero/meta.js
292
+ export default { context: { allowTranslucentTop: true }, initialState: { allowTranslucentTop: true } }
293
+ ```
294
+
295
+ ```jsx
296
+ const [state, setState] = block.useBlockState(useState) // Hero
297
+ const info = block.getNextBlockInfo() // Header
298
+ const isFloating = info?.state?.allowTranslucentTop ?? info?.context?.allowTranslucentTop ?? false
299
+ ```
300
+
301
+ Key names are yours.
302
+
303
+ ## block, website, page
304
+
305
+ | `block` | |
306
+ |---|---|
307
+ | `block.page` / `block.website` | parent page / site data and navigation |
308
+ | `block.type` | component type name |
309
+ | `block.childBlocks` / `block.insets` / `block.getInset(refId)` | nesting |
310
+ | `block.properties` | the section's params (frontmatter without the reserved keys) |
311
+ | `block.rawContent` | the section's ProseMirror document before parsing |
312
+ | `block.themeName` | `"light"`, `"medium"`, `"dark"`, or `""` for a section that follows the scheme |
313
+ | `block.stableId` / `block.key` | stable id from filename or `id:` / unique key across pages — React key |
314
+ | `block.path` | page route |
315
+ | `block.sticky` | whether it sticks |
316
+ | `block.dataLoading` / `block.dataError` | data state (AGENTS.md contract card) |
317
+ | `block.track(name, fields)` | tracking (services guide) |
318
+
319
+ ```js
320
+ const { website } = useWebsite(); const page = website.activePage
321
+ website.getPageHierarchy({ for: 'header' }) // = getHeaderPages(); options: for, nested (default true), includeHidden, under: route, filter, sort
322
+ website.getPageHierarchy({ nested: false }) // = getAllPages()
323
+ // nodes: { id, route, navigableRoute, translatedRoute, title, label, description, hasContent, children }
324
+ website.name, website.basePath
325
+ website.hasMultipleLocales(), website.getLocales(), website.getActiveLocale(), website.getLocaleUrl('es'), website.switchLocale('es')
326
+ page.title, page.getLabel() /* page.label is null unless set */, page.route, page.description
327
+ page.isHidden(), page.showInHeader(), page.showInFooter(), page.hasContent(), page.hasChildren(), page.children, page.parent
328
+ page.getNavigableRoute() // first descendant route with content
329
+ ```
330
+
331
+ Content-less containers appear as group nodes (`hasContent: false`); link with `navigableRoute`.
332
+
333
+ ## Packaging
334
+
335
+ **A heavy library used on demand.** `import('some-package')` where you use it keeps the package out of the page's first load and out of `dist/entry-ssr.js`, the file a host loads to render a page. A dynamic import of your own module only splits the browser's load: `entry-ssr.js` folds that module in, with every package it imports statically, and runs them when the file loads. So put the `import()` on the package, not on a component of yours that imports it. The build is green either way; the size of `entry-ssr.js` shows which you have.
336
+
337
+ **`package.json` `uniweb` block** (all optional): `runtimePolicy` — a statement of how far past the recorded runtime version a host may move a site. The foundation's name and scope are `name` in `main.js` (`'@acme/marketing'`), not here; a name with no scope is unregistered, and the first `uniweb register` writes the scope in (from `--scope` or the Uniweb workspace you are logged in to). A foundation's own schemas register under the same scope (`@/article` → `@acme/article`). `uniweb.supports` is covered in the services guide.
338
+
339
+ **Runtime floor.** Your code externalizes `react`, `react-dom`, both JSX runtimes and `@uniweb/core`; the runtime supplies them. At build time the foundation records the `@uniweb/runtime` version it linked against into `dist/runtime-pin.json`, and `uniweb register` sends that version as its floor. `{ "uniweb": { "runtimePolicy": "exact" } }` asks for no movement past it, for a foundation that reaches into undocumented internals: it is recorded in that file and not sent at register, so whether anything acts on it is the host's to say. `@uniweb/runtime` arrives transitively through `@uniweb/build`; don't add it to the foundation's dependencies — bump `@uniweb/build` instead.