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.
@@ -1,3263 +1,336 @@
1
1
  # AGENTS.md
2
2
 
3
- ## Part 0 — Read this first
3
+ *This file ends with the line `End of AGENTS.md`. If you can't see that line, your tool cut the file short (Codex stops at `project_doc_max_bytes`, 32 KiB by default): read the rest of `AGENTS.md` yourself.*
4
4
 
5
- A Uniweb project separates **what the site says** from **how it's built**. Content authors write markdown — choosing section types, setting params, composing pages. Component developers build section types that receive pre-parsed content and render it. Neither touches the other's files.
5
+ A Uniweb project separates **what the site says** from **how it's built**. The site is structured content, not prose: a section file's frontmatter names a section type and sets its params; its body is written in markdown but is **parsed into a typed content object** — `title`, `subtitle`, `paragraphs`, `links`, `items`, `data`, … — before any component sees it. Markdown is the authoring syntax, not the thing rendered: headings mark structure, not size, and a heading after body text starts an item.
6
6
 
7
- **Why that separation is cheap rather than ceremonial.** Every Uniweb site ships a runtime. A foundation is an ES module that plugs into it — either **standalone** (inlined into the site's own bundle, one self-describing artifact) or **linked** (loaded by URL at runtime as a federated module). Same foundation either way; the packaging is a deploy-time decision, not something your components know about. The runtime owns the content pipeline, section wrapping, backgrounds, theming, light/dark, prerendering, routing, and i18n; it orchestrates rendering and bridges the author's world into yours. Your components receive `{ content, params }` and render. **These are enforced guarantees, not conventions you have to uphold** — so you can drop the defensive code you'd write elsewhere.
7
+ The foundation is the React that receives that object, under a runtime that owns the content pipeline, section wrapping, backgrounds, theming, light/dark, prerendering, routing and i18n. The components that face authors — **section types**, in `sections/` — receive `{ content, params, block }` and render; they are the only components with that signature. Developers define the vocabulary; authors compose with it. Everything behind one, in `components/`, is ordinary React with ordinary props: install any package, import any library, use any pattern. The foundation is a normal Node project; the few things you don't install (2.1, 2.4) are the exceptions.
8
8
 
9
- | The runtime handles | So components should NOT contain |
10
- |---|---|
11
- | Section backgrounds (image, video, gradient, color, overlay) from `background:` | Background rendering code, `bg-white`/`bg-gray-900` on the wrapper |
12
- | Context classes (`context-light`/`medium`/`dark`) on every section | Theme maps: `const themes = { light: {…}, dark: {…} }` |
13
- | Token resolution — `text-heading` adapts automatically | Conditionals: `isDark ? 'text-white' : 'text-gray-900'` |
14
- | Content parsing with a guaranteed shape | Defensive null checks on content fields |
15
- | Section wrapping in `<section>` with context class | An outer `<section>` with background/theme classes |
16
- | Light/dark scheme resolution before first paint | `localStorage` reads, `typeof window` guards |
17
- | i18n via locale-specific content directories | String wrapping with `t()` or `<Trans>` |
18
-
19
- Concretely, the code you don't write: no theme maps, no `isDark ? … : …`, no null checks on content fields, no `t()` wrapping, no per-component background rendering, no SSR guards, no outer `<section>`. A hero that's 200 lines of undifferentiated React elsewhere is a 40-line component plus a markdown file here — and the markdown is editable by someone who has never opened your code.
20
-
21
- Components *should* contain: layout (`grid`, `flex`, `max-w-7xl`), spacing (`p-6`, `gap-8`), typography scale (`text-3xl`, `font-bold`), animations, border-radius — anything that stays the same regardless of theme context.
22
-
23
- Once content reaches your component, **it's standard React.** Standard Tailwind. Import any library, use any pattern. The `{ content, params }` interface applies only to *section types* (the components authors select in markdown); everything else in your foundation is ordinary React with ordinary props.
24
-
25
- You're building a *system* of section types, not individual pages. That's what makes theming, i18n, and multi-site tractable — they're properties of the system rather than things bolted onto each component.
26
-
27
- ### Route yourself
28
-
29
- | Your situation | Start at |
30
- |---|---|
31
- | Building a whole site for someone, content and code | **Part 3**, *Section format* through *Page organization*, then **Part 4**, *Where things go* through *Section wrapper*, *meta.js*, *Semantic theming*, *theme.yml*, *Fonts*. Read the rest when the site calls for it: *Records, queries and parametric pages* for a blog, *Forms* for a contact form |
32
- | New or nearly empty project | **Part 1**, then Part 4 |
33
- | Existing project, content task (pages, copy, colors, nav) | **Part 2**, then Part 3 |
34
- | Existing project, component task (new section type, restyle) | **Part 2**, then Part 4 |
35
- | Porting a design from React / Next / a generated site | **Part 1**, then Part 5 → *Migrating* |
36
-
37
- ### Four commands that replace guessing
38
-
39
- ```bash
40
- uniweb status # what changed in the app, in git and in Uniweb — and what to run
41
- uniweb inspect <path> # print the parsed content shape of a section or page
42
- uniweb <command> --help # exact flags, always current — no side effects
43
- uniweb doctor # diagnose project configuration (--fix to repair)
44
- ```
45
-
46
- Commands are written `uniweb <command>` throughout this guide. Without a global install, run them in the project as `npx uniweb <command>`.
47
-
48
- `uniweb inspect` is the important one for content. Every parse rule in Part 3 is faster to *confirm* than to re-derive, and re-deriving from memory is where agents go wrong. Don't predict the shape — print it.
49
-
50
- `uniweb status` is the one for a project other people edit. A site in the Uniweb app can change there at any time, teammates push to git, and Uniweb releases often. Run it when you begin, when you come back to the project, before you push, publish or deploy, and after a command refuses: it changes nothing, opens with what the site is — synced where, live where — and ends with the commands to run, in order (`--json` for a script).
51
-
52
- ### The four silent failures
53
-
54
- Most Uniweb mistakes do not fail the build. The build goes green, the terminal is clean, and the page is wrong. If you don't look at the page or run `inspect`, you will report success on broken output.
55
-
56
- 1. **An unknown section type renders a red `Component not found: <Type>` box.** The build does not fail. Never write a `type:` you haven't confirmed exists — see Part 2, step 2.
57
- 2. **An undeclared param is accepted and does nothing.** Frontmatter keys no `meta.js` declares are passed through and ignored, not rejected.
58
- 3. **Content lands in the wrong field.** A heading becomes a `subtitle` when you wanted an item, or the reverse. That's the level rule (Part 3). `uniweb inspect` settles it.
59
- 4. **A section silently doesn't render.** `@`-prefixed files are child sections (only rendered via `nest:`), `_`-prefixed files are drafts, and section types nested below the root of `sections/` without a `meta.js` are never discovered.
60
-
61
- ### Documentation
62
-
63
- This guide covers what you can't derive by reading code. Everything else is in the full documentation — and **you can reach all of it without guessing at URLs.**
64
-
65
- **Start at the index.** One address, and it's the only documentation URL worth memorizing:
66
-
67
- ```
68
- https://uniweb.io/llms.txt
69
- ```
70
-
71
- It lists every documentation page with a one-line description and a fetchable link. Go there whenever your question isn't answered in this file — and *especially* when you don't know whether a feature exists at all. That's where guessing does the most damage: **a 404 on a path you invented tells you your guess was wrong, not that the feature is missing.** Concluding "the framework doesn't support X" from a failed fetch is a mistake worth actively guarding against; the index answers the existence question directly.
72
-
73
- Then **follow the link the index gives you** rather than constructing one yourself. The index is the source of truth for where pages live, so it stays correct when the site's URL conventions change. Each link it gives is the page as Markdown, and a page's own address returns the same Markdown to a request sent with `Accept: text/markdown`.
74
-
75
- **Clone the repo instead** when you expect several lookups, or may lose network access later:
76
-
77
- ```bash
78
- git clone --depth 1 https://github.com/uniweb/docs .uniweb-docs # then gitignore it
79
- ```
80
-
81
- Same content, greppable, and one network operation instead of many. `grep -ri "queryable" .uniweb-docs` beats any number of fetches while you're still exploring.
82
-
83
- Documentation paths in this guide are given bare — `development/creating-components.md` — so they resolve three ways: as a key in the index, as a file in a clone, or at `https://raw.githubusercontent.com/uniweb/docs/main/{path}`.
9
+ §1 says why the constraints are worth keeping; §2 is where your priors are wrong — each row a reflex from React / Next / Astro / Vite habits, what Uniweb does instead, and whether anything will tell you. Read both, then follow §3 before touching a file; its step 6 loads the lane guide and is not optional. Commands are written `uniweb <command>`; without a global install, run them in the project as `npx uniweb <command>`.
84
10
 
85
- > **Don't confuse the two doc sites.** `uniweb.io/docs` is the **developer** documentation — this is the one you want. `docs.uniweb.app` is the *author-facing* app documentation, written for non-technical people using the visual editor; it won't answer framework questions.
11
+ ## 1. Why this is worth doing right
86
12
 
87
- **The table below saves you the round trip** for the tasks that come up most:
13
+ Uniweb is an implementation of **Component Content Architecture (CCA)**: content and components are separate artifacts — different files, packages and maintainers — joined by a thin runtime at build time and in the browser. Full argument: `uniweb.io/docs/architecture/component-content-architecture.md`. What it buys you:
88
14
 
89
- | Task | Page |
90
- |------|------|
91
- | Writing page content | `authoring/writing-content.md` |
92
- | Theming and styling | `authoring/theming.md` |
93
- | Working with records and queries | `authoring/collections.md` |
94
- | Where-object predicate format | `authoring/predicates.md` |
95
- | Data sources / custom transports | `development/data-sources.md` |
96
- | Building components | `development/creating-components.md` |
97
- | Schemas in practice | `development/schemas-in-practice.md` |
98
- | Workspace layouts and their wiring | `development/project-structures.md` |
99
- | Migrating an existing design | `development/converting-existing.md` |
100
- | Internationalization (full model) | `development/internationalization.md` |
101
- | Kit API (hooks, components) | `reference/kit-reference.md` |
102
- | Content shape reference | `reference/content-structure.md` |
103
- | Component metadata (`meta.js`) | `reference/component-metadata.md` |
104
- | Site configuration | `reference/site-configuration.md` |
105
- | Queries — everything a query can say | `reference/queries.md` |
106
- | Data fetching model | `reference/data-fetching.md` |
107
- | Navigation patterns | `reference/navigation-patterns.md` |
15
+ **You write less.** A section type carries no theme maps, null checks, hardcoded strings, wrapper element, sticky-spacer arithmetic or fetch lifecycle: the runtime does each once, for every section. What remains is rendering logic.
108
16
 
109
- For anything not in that table, start at the index. For CLI flags, prefer `uniweb <command> --help` over any of this — it's always current.
17
+ **Your work survives.** A component built on tokens renders correctly in every section context, on every site that adopts the foundation, through every rebrand, in the visual editor and in prerendered HTML. A component with `text-gray-900` breaks the first time an author writes `theme: dark`.
110
18
 
111
- ---
112
-
113
- ## Part 1 — Starting a project
114
-
115
- **Always use the CLI to scaffold — never hand-write `package.json`, `vite.config.js`, `entry.js`, or `index.html`.** The CLI resolves correct versions and structure; hand-written config is the most common way to end up with a project that can't build.
116
-
117
- ```bash
118
- npx uniweb@latest create my-project --template marketing
119
- cd my-project && pnpm install
120
- uniweb dev
121
- ```
122
-
123
- `@latest` matters: a project starts on the packages and templates of the CLI that creates it, and a bare `npx uniweb` runs a globally installed `uniweb` when there is one, however old.
124
-
125
- **Choosing a template.** `--template <name>` gives you a working site plus a foundation you can study and edit. `--template none` gives you the same two packages with no content — the right choice when you're building a foundation from scratch or porting a design. `--blank` gives you an empty workspace and assumes you'll add packages with `uniweb add`; use it only if you already know the framework.
126
-
127
- Official templates include `marketing` (tokens, insets, grids, multi-line headings), `docs` (sidebar nav, code highlighting), `blog` (records of the standard `@std/article` schema, a query, a parametric `[slug]` page), `dynamic` (live API data, loading states), `international` (i18n, records, multi-locale routing), `store` (product grids, e-commerce), `academic` (publications, timeline, math), `extensions` (multi-foundation, runtime loading). `uniweb template list` shows them all.
128
-
129
- **npm or pnpm.** Projects include both `pnpm-workspace.yaml` and npm workspaces. Replace `pnpm` with `npm` in any command in this guide.
130
-
131
- ### What you get
132
-
133
- ```
134
- my-project/
135
- ├── src/ # the foundation — component developer's domain
136
- ├── site/ # the site — content author's domain
137
- └── pnpm-workspace.yaml
138
- ```
139
-
140
- A site is pure content. A foundation is the site's source code — that's why it lives in `src/`. The foundation's `package.json::name` is `src`, symmetric with `site` — a **workspace** name, how the site depends on it. What the foundation **registers as** (`@org/<name>`, the name sites pin) is `name` in its `main.js`, which `uniweb create` sets to the project's name. **`src` and `foundation` are never a foundation's name** — `uniweb register` refuses them, because every project in an org would register the same one. **Nor is any name under `@uniweb`**: that scope is the Uniweb framework's own, and `uniweb create`, `uniweb add` and `uniweb register` refuse it.
141
-
142
- - **Foundation** (`src/`): React components. Those in `sections/` and `layouts/` are *section types* — selectable by authors via `type:`, or used for layout areas. Everything in `components/` and `utils/` is ordinary React and JS: the developer's workbench, not visible to authors.
143
- - **Site** (`site/`): markdown content and configuration, plus optional records of structured content and the queries that reach them or an external data source.
19
+ **Nothing has to be guessed.** The content shape is guaranteed. The directory listing is the catalog. `meta.js` is the interface. `inspect` prints the truth. The architecture removes exactly the uncertainties — what shape, which component, what it accepts — that make agents invent things.
144
20
 
145
- **The composition boundary.** Authors compose pages from finished section types — choosing types, writing content, setting params. Developers compose section types from building blocks — importing helpers, using libraries, writing JSX. Two different levels of composition, and the section type is the boundary between them. Don't expose building-block composition to authors; build complete, self-contained section types that handle their own internal structure.
21
+ **Other people can act without you.** Every param you declare and every content slot you name is something an author can change in markdown or in the visual editor with no developer, no build and no pull request. The care you put into `meta.js` is the autonomy someone else gets.
146
22
 
147
- ### Growing the workspace
23
+ **A section type is a front desk, not a worker.** It reads params, picks a worker, and translates author vocabulary (`content`, `params`) into developer vocabulary (ordinary props). The workers live in `components/` and know nothing about CCA. That is the whole shape of a foundation: thin section types at the boundary, ordinary React behind them.
148
24
 
149
- ```bash
150
- uniweb add project docs # co-located pair → docs/src + docs/site
151
- uniweb add foundation [name|path] [--path parent] # no name → ./src/, bare name → ./name/, slash → that path
152
- uniweb add site [name|path]
153
- uniweb add extension <name> [--site <name>] # secondary foundation, wired to a site
154
- uniweb add section Hero [--foundation ui] # sections/Hero/{index.jsx,meta.js}
155
- ```
156
-
157
- The CLI creates exactly the folder you ask for — no silent nesting under `foundations/` or `sites/`. If the target exists or the package name is taken, it stops with a precise error and suggests alternatives (using the same `classifyPackage` logic the build uses, so cross-type collisions are caught: you can't `add site marketing` when a foundation named `marketing` exists).
158
-
159
- `uniweb add section` scaffolds a CCA-proper starter, and the dev server picks it up with no build or install.
160
-
161
- ### Learn from a working template
162
-
163
- **When you're unsure how to implement a pattern — data fetching, i18n, layouts, insets, theming — read a real one instead of guessing.** Install an official template as a second project in your workspace:
164
-
165
- ```bash
166
- uniweb add project marketing --from marketing
167
- pnpm install
168
- ```
169
-
170
- That creates `marketing/src/` + `marketing/site/` alongside your project. You don't need to build or run it. Read:
171
-
172
- - `marketing/src/sections/` — components with `meta.js`: what content they expect, what params they accept, what presets they define
173
- - `marketing/site/pages/` — real content files, showing the markdown → component mapping
174
- - `marketing/site/theme.yml` and `site.yml` — theming and configuration in practice
175
-
176
- This is the highest-bandwidth way to learn the framework, and it works with no network access. Install several if you like; each is independent. To run one: `cd marketing/site && pnpm dev`.
177
-
178
- ### The loop
179
-
180
- ```bash
181
- uniweb dev # the site you are in; from the workspace root, it picks one for you
182
- pnpm build # production build (SSG + SPA)
183
- pnpm preview # preview the production build
25
+ ```jsx
26
+ const workers = { slider: SliderHero, contact: ContactHero }
27
+ export default function Hero({ content, params, block }) {
28
+ const Worker = workers[params.variant] || SliderHero
29
+ return <Worker title={content.title} links={content.links} images={content.images} block={block} />
30
+ }
184
31
  ```
185
32
 
186
- Markdown, `theme.yml`, and component edits hot-reload. New section types are picked up without a restart.
187
-
188
- **The dev server says where it is — read it, never assume a port.** `uniweb dev` takes a free port and, once the server listens, prints `Serving <site> at <url>`. The usual port may be another project's server, and reviewing that page reports success on the wrong site. Run `uniweb dev` in the background when you need your shell back: `uniweb dev --status` prints the address later, a second `uniweb dev` points at the running server instead of starting another, and `uniweb dev --stop` stops it when you are done. They know the server `uniweb dev` started, not one you start with `vite` or `npm run dev` inside the site. Pass `--port <n>` only when a port is required: you get that one or an error, never another.
33
+ One `type:` for the author, as many renderings as the design needs. A second section type that differs only in layout, or a conditional tree inside one, means you want a param and a worker.
189
34
 
190
- ---
35
+ **Content is an offer, not a contract.** As the developer: a section type takes what it expects from `content` — the first paragraph if it needs one, every paragraph or every item only when showing them all is the point — and neither touches nor reacts to the rest. No check for unexpected content, no warning. `meta.js content:` says what the type *reads*, not what a section may hold, and a param combination that leaves some content unused is normal. As the author: write what the type reads; extra content isn't a goal. The tolerance exists so that switching `type:` or a `variant` is a one-line trial — change it, compare, switch back — with nothing to rewrite first. When you make such a switch, don't strip what the new rendering ignores; whether it stays is the author's decision once the trial is settled.
191
36
 
192
- ## Part 2 — Working in an existing project
37
+ The principles to reason from when a table in §2 doesn't cover the case:
193
38
 
194
- The rest of this guide explains how Uniweb works. This part is what to do *first* when you've been handed a project that already uses it, plus a task.
39
+ - **The foundation provides options; the site configures.** The foundation doesn't know which site it serves; the site doesn't know how the foundation is built.
40
+ - **Components render from content, not context.** Never the URL, the router or the layout; variation comes through params or a different type, chosen by the author.
41
+ - **Configuration cascades** page → folder → site → foundation, like CSS specificity: defaults high, exceptions local.
42
+ - **Metadata declares the interface.** `meta.js` drives defaults, the editor's controls, the schema and the docs.
43
+ - **The site owns the theme.** Foundations declare variables, sites set values, components use tokens.
195
44
 
196
- ### 1. Orient — what kind of workspace is this?
45
+ When a rule in §2 feels like friction, that is the moment you are about to take back a job the runtime already does — and do it worse, once per component instead of once per site. The architecture doesn't limit what you can build; it fixes where each decision lives.
197
46
 
198
- **Run `uniweb status` first.** It says where the site sits and what it is made of — the workspace's sites and foundations, the foundation this site is built with and which other sites a change to it reaches, pages it takes from outside its folder (another repository, sometimes), the languages it is written in — then whether it changed in the app since this copy last synced, whether git or Uniweb has something newer, and what to run about each, before you edit something someone else just changed. Run at the root of a workspace with several sites, it says what each one is. The rest of this step is how to read the same wiring by hand.
47
+ ## 2. Where your priors are wrong
199
48
 
200
- **There is no single layout. Read `pnpm-workspace.yaml` first** — its `packages:` globs name the shape in one glance:
49
+ ### 2.1 Project and tooling
201
50
 
202
- | Globs | Layout | What it implies |
51
+ | By reflex you'd… | Here | Signal |
203
52
  |---|---|---|
204
- | `src`, `site` | **single** (the default) | foundation in `src/`, site in `site/` |
205
- | `foundations/*`, `sites/*` | **segregated** | several sites may share one foundation — a foundation edit hits all of them |
206
- | `*/src`, `*/site` | **co-located projects** | one self-contained pair per project: `docs/src` + `docs/site` |
207
- | `*/src`, `*/sites/*` | **projects with several sites** | each project's foundation with its sites: `memberships/src` + `memberships/sites/fitness`, `memberships/sites/society` — a foundation edit hits every site in its project |
208
- | a package whose `main.js` says `extension: true` — `effects`, `extensions/*` (alongside any of the above) | extensions present | extra section types, runtime-loaded — see step 2 |
209
-
210
- Those names are convention; the globs are the truth. Full guide with the wiring for each: `development/project-structures.md`.
53
+ | Write `package.json`, `vite.config.js`, `index.html`, an entry file | `npx uniweb@latest create <name> --template <t>`; `uniweb add site / foundation / section / project / extension`. The CLI owns those files. | build fails far from the cause |
54
+ | `npm install` a foundation or theme; `npm install @uniweb/runtime` | A foundation is a workspace `file:` dependency or a catalog ref in `site.yml`, never an npm package. In a foundation the runtime arrives through `@uniweb/build`. Everything else — a carousel, a chart library, a date utility, `@uniweb/api` — you install in the foundation as in any project. | npm 404 / silent version skew |
55
+ | `npm update` / `pnpm update` the `@uniweb/*` packages; `npx uniweb update` | `npx uniweb@latest update --yes` (`--yes` because there is no terminal to answer the prompt). The packages are a matched set and AGENTS.md updates with them. Without `@latest` it runs the CLI the project already pins and reports "aligned". | `status` and `doctor` name the drift |
56
+ | Assume `localhost:5173`; run `npm run dev` inside the site | `uniweb dev` serves the site you are in (from the workspace root, the first, with a notice); read `Serving <site> at <url>`. `uniweb dev --status` / `--stop` know only that server. | wrong server, silent |
57
+ | Read `foundation:` in `site.yml` as a path | A **package name**. Follow the `file:` dep in the site's `package.json`. `@org/name@1.2.3` means the source is not in this repo. | the build: `did not resolve` |
58
+ | Trust folder names for the workspace layout | `pnpm-workspace.yaml` globs decide (§3.2). | — |
59
+ | `main.jsx`; JSX in a `.js` file | `main.js` is plain JS; JSX lives in `.jsx`. | build stops |
60
+ | Guess which section types exist or what a param is called | `ls <foundation>/sections/`, `cat …/<Type>/meta.js`. Every foundation's vocabulary is different; `uniweb docs --from-source` writes it all to `COMPONENTS.md`. | red box / silent |
61
+ | Predict what markdown parses to | `uniweb inspect <file>` prints the shape. | silent (wrong field) |
62
+ | Rely on what you remember about Uniweb | The pinned version is the truth: `uniweb <cmd> --help`, `uniweb guide`, `uniweb.io/llms.txt` (§6). A 404 on a URL you invented means your guess was wrong. | — |
63
+ | `--force` past a refusal; treat `git push` as deploy; publish on the person's behalf | Never force. Commit your own work as you go. `git push`, creating a site on a backend, going live, spending money and whatever `status` marks "ask the person first" are theirs. | push refused / money |
64
+
65
+ ### 2.2 Content
66
+
67
+ | By reflex you'd… | Here | Signal |
68
+ |---|---|---|
69
+ | Pick heading levels for size | Levels are **structure**: `#` title; exactly one step smaller = `subtitle`; two steps smaller, a `---`, or any heading after body text = an `item`. `###` right after `#` is an item; `##` is a subtitle line. A later heading as large as the first leaves no `title`: all of them become items. | silent |
70
+ | Order the file the way the page should look | Write semantically; the component arranges. | — |
71
+ | Put an icon or image above the title, as it will look | Anything above the first heading empties `title`: an icon or text puts the heading in `items[0]`, an image puts it in `headings`. Write it under the heading — it is still `icons[0]` or `images[0]`. | silent; `inspect` shows it |
72
+ | `<span class>`, `<div>` in markdown | Shown as text. `[text]{accent}`, `**bold**`; a line break is `<br>` or a trailing `\`. | build names the file |
73
+ | Write `pages: [a, b]` or `sections: [a, b]` to set order | Those lists are **strict**: an unlisted page leaves every menu, an unlisted section leaves the page. `[a, b, ...]` means "these first". At the site root the first of `pages:` is `/`, whatever `index:` says. | silent |
74
+ | `primary: #3b82f6` | `'#3b82f6'` — an unquoted `#` starts a YAML comment. | build warns |
75
+ | Expect any frontmatter key to do something, any `type:` name to work | A key reaches `params` and does nothing unless the type reads it (its `meta.js` says which); one named for a content field (`title:`) replaces that field. Only types present in `sections/` work. | silent / red box |
76
+ | Strip the content a new `type:` / `variant:` won't render before switching | Nothing to strip (§1): the switch is a one-line trial, and what stays afterwards is the author's call. | content loss |
77
+ | `pages/fr/about.md` for French | `locales/` beside `pages/`; `pages/` holds the default language only. | silent — it becomes a page at `/fr` |
78
+ | `t('key')`, `<Trans>` | Nothing — content arrives translated; each language is its own build. | — |
79
+ | `src/assets/`, `assets/img.png` | `./img.png` beside the page, or `/img.png` in `public/`. There is no assets folder. | build stops, or warns |
80
+ | `fetch: /api/posts`, `fetch: ./data.json` | `fetch:` names a query from `queries.yml`; a URL belongs on the query (`url:`). | build stops |
81
+ | `records/blog/2025/post.md`; one YAML file holding a list | Flat: `records/<schema>/<name>.md`, one record per file; the file name is `$name`. | folder read as a schema, silent |
82
+ | `` `/blog/${slug}` `` | `item.$route` — never compose a URL. | works until a page moves |
83
+ | `page.yml` in a folder of pages | It makes one page, each `.md` a section. `folder.yml` keeps them pages and carries `layout`, `title` and SEO. Over a mount, `page.yml` with markdown of its own is a landing page *above* the mounted pages; a mount is one level under `pages/`, and a local subfolder beside it isn't read. | silent; the build names that subfolder |
84
+ | Paste the gtag / GTM / Meta pixel snippet into a component, `index.html`, or `services.tracking.scripts` | Uniweb Cloud (`publish`): `services.google: { id: G-… }`, or `GTM-…` for a container, and the host loads Google's tag, free, with no code, on any foundation. `head.html` isn't applied there, and `scripts` takes URLs only. Static build (`export`, `deploy --host`): the snippet in `head.html` beside `site.yml`. More: `uniweb guide services`. | silent — Google reports nothing |
85
+ | Expect `{company}` to resolve | Only under a foundation with `createLoomHandlers`; otherwise it renders literally. | build warns if `site.yml` has `placeholders:` |
86
+ | `hidden: true` on `pages/404/` to keep it out of nav | That makes it a draft. `hideIn: ['*']` controls nav. | silent |
87
+ | Treat `@child.md` / `_draft.md` as names | `@` = child section, placed by `nest:` (with none it renders last; a `sections:` list drops it); `_` = ignored. | build warns, unless `sections:` dropped it |
88
+
89
+ ### 2.3 Section types and the components behind them
90
+
91
+ | By reflex you'd… | Here | Signal |
92
+ |---|---|---|
93
+ | Wrap the component in `<section>`; `Header.as = 'header'` | The runtime wraps every section in a bare `<section>` (no padding to reset); `Type.className` adds classes to it. The built-in layout already wraps the header and footer areas in `<header>`/`<footer>`. | double element |
94
+ | `{content.title}` in JSX | Content fields are **HTML strings**: `<H1 text={content.title} />`. | tags show as text |
95
+ | `<h2><H2 text=… /></h2>` | Kit text components render their own tag. | double tag |
96
+ | `content.items?.map`, `content.title ?? ''` | Never null — strings and arrays, always. | — |
97
+ | `className="sticky top-0"` | `sticky: true` in the type's `meta.js`. | `uniweb dev` names it |
98
+ | `fixed inset-0 z-[9999]` for a modal | `<Overlay>` from kit — layout areas are stacking contexts, no z-index escapes one. | silent — under the header |
99
+ | `typeof window`, `localStorage.theme`, a theme `useEffect` | `useAppearance()`; the scheme is resolved before first paint; kit hooks are SSR-safe. | theme flash |
100
+ | `<a href="/about">` | `<Link to="page:about">` (an `id:` survives moves) or `<Link href="/about">`. A bare `<a>` still routes but resolves no `page:` and adds no base path or locale. | silent |
101
+ | `window.location.href = '/fr'` to switch language | `<Link reload href={website.getLocaleUrl('fr')}>` or `website.switchLocale('fr')`. | base-path bug |
102
+ | `useEffect(() => fetch(…))` for records | Declare the key in `meta.js data:`; it arrives in `content.data`, prerendered. | prerenders as loading |
103
+ | A `Button` or `Card` in `sections/` | `components/`. Everything at the root of `sections/` becomes author vocabulary. | appears in the section picker |
104
+ | Helpers that take `{ content, params }` | Ordinary props. That signature is for section types only. | — |
105
+ | One section type per visual variant; or one with a conditional tree inside | A front desk (§1): one `type:`, a `variant` param, workers in `components/` with ordinary props. | author vocabulary bloats; variants invisible to the editor |
106
+ | Validate, enumerate or warn on content the component doesn't use; treat `content:` as an exact schema | Take what you expect and don't touch the rest (§1). `content:` declares what the type reads. | — |
107
+ | `params: { theme, background, grid, sticky, query }` | Section settings — read from `block`, never declared. | build warns |
108
+ | Write `meta.js` as internal metadata | It is the visual editor's UI and other agents' catalog. Labels for people, defaults for everything, author words for params (`columns`, not `gridCols`). | — |
109
+ | `window.uniweb`, `globalThis.uniweb` | `@uniweb/kit` and `block.*` only. | — |
110
+ | `<P text={member.bio} />` | Member and API text is **text**: `{value}` or `<PlainText>`. Only parser strings are safe HTML. | XSS |
111
+ | "Search unavailable" / a disabled control when a service is off | Draw nothing. `isSearchEnabled()`, `isSubmitEnabled()`, `isBackendEnabled()`, `isAssistantEnabled()`. | — |
112
+ | `fetch('/_agent/chat')`, a hardcoded search URL | `resolveService(website, 'assistant')`. | 404 on static hosts |
113
+ | `if (enabled) track(…)` | Never guard; with no destination `track()` is a no-op. | — |
114
+ | framer-motion `initial` / `animate` for an entrance | CSS animation — JS misses the prerendered first paint. | silent; only a build shows it |
115
+
116
+ ### 2.4 Styling and theme
117
+
118
+ | By reflex you'd… | Here | Signal |
119
+ |---|---|---|
120
+ | `bg-white` / `bg-gray-900` on the section | `background:` in frontmatter; the runtime paints it. | breaks in dark context |
121
+ | `dark:text-white`, `isDark ? … : …` | Tokens adapt per **section context** (`theme:` on the section): `text-heading`, `text-body`, `bg-section`, `bg-card`, `border-border`. | breaks in context |
122
+ | `text-slate-900`, `text-blue-600` | Tokens, or palette shades from `theme.yml`: `text-primary-600`, `bg-neutral-100`. | silent |
123
+ | `:root { --brand: #… }` | `theme.yml colors:` → 11 shades + semantic tokens. | bypasses theming |
124
+ | `font-serif`, `font-sans` | Tailwind's stack, not the site's — unless the foundation declares it as a `font-*` var in `main.js`. Families are the site's (`theme.yml fonts:`). | silent |
125
+ | `@import url(fonts.googleapis…)` in CSS | `theme.yml fonts.import` / `faces`. | — |
126
+ | `@tailwind base;` | Tailwind v4: `@import "tailwindcss"` plus kit's token imports (theme guide). | silent — most utilities missing |
127
+ | Trust the foundation's own build to prove a class works | A site build and `uniweb dev` read only the folders `@source` names — one line per folder that writes classes (`sections`, `components`, `layouts`). | each names a folder you missed, as does `doctor` |
128
+ | `prose` from `@tailwindcss/typography`, `prose-invert` | `@import "@uniweb/kit/prose-tokens.css"`; no invert — colors are already the theme's. | build warns; unstyled lists |
129
+ | `html { scroll-behavior: smooth }` | Never on `html`/`body`; the runtime owns scrolling. | route transitions misbehave |
130
+ | `filter: blur(80px)` for a glow | Radial gradient + `mask-image`. | Safari jank |
211
131
 
212
- **A site is any package with a `site.yml` and a `pages/` folder** — a workspace can hold several. Everything below calls yours `<site>/`.
132
+ ## 3. The procedure, every task
213
133
 
214
- **Find the foundation by following the wiring, not by guessing the folder.** `foundation:` in `site.yml` is a **package name**, not a path, and folder name matches package name only by convention — co-located projects break it deliberately (folder `docs/src`, package `docs-src`). Go from name to folder via the matching `file:` dependency in `<site>/package.json`:
134
+ **1. `uniweb status`.** It says what the site is, where it's synced and live, what changed since this copy last synced, and ends with the commands to run, in order. Run it when you begin, when you return, before push/publish/deploy, and after any refusal. Two things it will not decide for you:
215
135
 
216
- ```json
217
- // docs/site/package.json → the foundation is at docs/src/
218
- { "dependencies": { "docs-src": "file:../src" } }
219
- ```
136
+ - Never `--force` past a refusal, and leave the person's decisions to them (2.1).
137
+ - A copied project still carries the original's `sync.json`. `uniweb forget --all` in the copy before its first push, or the push updates the original's site.
220
138
 
221
- If `foundation:` isn't a workspace package name, the source isn't in this repo at all:
139
+ **2. Read the workspace shape** from `pnpm-workspace.yaml` globs:
222
140
 
223
- | `foundation:` value | What it means | Can you add a section type? |
141
+ | Globs | Layout | Implies |
224
142
  |---|---|---|
225
- | a workspace package name (`src`, `docs-src`, `marketing`) | source is in this repo — follow the `file:` dep to it | **Yes** |
226
- | a versioned registry ref (`@org/name@1.2.3`) | published; **its source is not in this repo** | **No** — work within the types it offers |
227
- | an `https://…` URL, or `{ url: … }` | same, loaded from that URL | **No** |
143
+ | `src`, `site` | single (default) | foundation `src/`, site `site/` |
144
+ | `foundations/*`, `sites/*` | segregated | a foundation edit hits every site sharing it |
145
+ | `*/src`, `*/site` | co-located | one pair per project: `docs/src` + `docs/site` |
146
+ | `*/src`, `*/sites/*` | projects with sites | each project's foundation with its own sites |
147
+ | plus a package whose `main.js` has `extension: true` | extensions | extra section types, runtime-loaded |
228
148
 
229
- A versionless `@org/name` is an error rather than a shorthand — the build rejects it and asks for a version.
149
+ A site is any package with a `site.yml`. `paths:` in `site.yml` can mount another folder or repo into the page tree, so a route's markdown may not live under `pages/`.
230
150
 
231
- > **Foundations are never npm packages.** They're runtime federated modules, not libraries. Don't `npm install` one, and don't add one to `dependencies` by hand. The four supported shapes are exactly the ones above: a workspace sibling, a `file:` dependency, a versioned registry ref, or a full URL.
151
+ **3. Find the foundation by the wiring.** `"docs-src": "file:../src"` in the site's `package.json` → `docs/src/`.
232
152
 
233
- > **The same `@scope/name` shape means different things in different places.** As a `foundation:` value it is a **catalog** ref (never npm). As a data-schema ref in `meta.js` it resolves on disk from an **npm package** — `@std/*` from `@uniweb/schemas`, any other `@org/*` from that org's `@org/schemas`. And `@uniweb/kit` in `dependencies` is an ordinary npm package. Position decides the registry; the shape tells you nothing.
234
-
235
- **Check `paths:` in `site.yml` before going looking for content.** It mounts outside directories into the page tree (`paths: { pages/docs: ../../../docs }`), so a route's markdown may live in another repo or a submodule rather than under `<site>/pages/`.
153
+ | `foundation:` value | Source in this repo? | Can you add a section type? |
154
+ |---|---|---|
155
+ | a workspace package name | yes — follow the `file:` dep | yes |
156
+ | `@org/name@1.2.3` (catalog ref; `@org/name` with no version must be a workspace package) | no | no — work within its types |
157
+ | `https://…` or `{ url: … }` | no | no |
236
158
 
237
- ### 2. Learn this project's vocabulary — before you write anything
159
+ `extensions:` entries take the same shapes, plus `/<name>/entry.js` for a static build, which `add extension` writes and `publish` refuses (`uniweb guide ship`). The primary foundation wins on a name collision.
238
160
 
239
- **A foundation is a fixed vocabulary of section types, and every project's is different.** Nothing in the framework tells you what a given project offers; you read it — in the foundation folder you resolved in step 1, not a guessed `src/`:
161
+ **4. Learn the vocabulary.**
240
162
 
241
163
  ```bash
242
- ls <foundation>/sections/ # the section types available
243
- cat <foundation>/sections/Hero/meta.js # what one expects and accepts
164
+ ls <foundation>/sections/ # the section types that exist (repeat per extension)
165
+ cat <foundation>/sections/Hero/meta.js # what it expects, what it accepts, its presets
244
166
  ```
245
167
 
246
- **Extensions add to that vocabulary.** If `site.yml` carries an `extensions:` list, each entry is a second foundation contributing its own section types, usable by name in exactly the same way. Enumerate their `sections/` too. The primary foundation wins on a name collision, and extensions are checked in declared order.
247
-
248
- **An extension *is* a foundation** — same build, same output; it just contributes no Layout or theme variables. So each entry takes the **same shapes** `foundation:` does: a workspace package name, a versioned catalog ref (`@org/name@1.2.3`), or a full URL. Use the same table above to decide whether you can add a section type to one.
249
-
250
- > **A site-relative URL (`/effects/entry.js`) only works where the site serves its own files** — `uniweb export` and `uniweb deploy --host=<adapter>`. A site published to Uniweb hosting ships no JS, so nothing serves that path, and `uniweb publish` rejects it with a pointer to the catalog-ref form. Register the extension (`uniweb register` in its directory) and reference it like any other foundation. When you reference a workspace-local extension, `uniweb publish` brings it along exactly as it does the primary — releasing it if its code changed, and pinning the released version on the published site.
251
-
252
- Each `meta.js` is a catalog entry: `description` (what the type is for), `content:` (what markdown it expects), `params:` (what frontmatter it accepts, with defaults), `presets:` (named param bundles), and optionally `family:` (the standard section family it belongs to). Read them as a menu — that is what they are. There is no CLI command that lists them; reading the folder *is* the discovery step.
253
-
254
- > **Never write a `type:` or a param you haven't confirmed exists.** Both failures are silent (Part 0) — invisible from the terminal, visible only on the page.
255
-
256
- #### `family:` — so an editor can draw your section
257
-
258
- An editor showing an author a section picker has to know what each section type
259
- **is**, to pick its illustration, its icon and a label it can translate. The icon
260
- is the family's — there is no `icon:` to declare. Two ways to tell it, in this
261
- order:
168
+ **5. Pick a lane.**
262
169
 
263
- 1. **Name the component for its family.** Run `uniweb families`, and use one of
264
- those names when it fits — `Hero`, `Footer`, `Pricing`, `FAQ`, `CardGrid`.
265
- Then there is nothing to declare: the name resolves on its own.
266
- 2. **Declare `family:`** when the name is yours — a variant, or your own
267
- vocabulary:
268
- ```js
269
- // sections/ProfileHero/meta.js
270
- export default { title: 'Researcher Profile', family: 'profile' }
271
- ```
272
- One value, the dominant shape: a `HeroWithEstimate` is `family: 'hero'`.
273
-
274
- **Leave it off when nothing fits.** A section that is genuinely specific to this
275
- site gets a generic illustration, and that is the right outcome — do not force it
276
- into the nearest family. `uniweb doctor` shows what each of your sections
277
- resolved to, and suggests a family for any it recognises by another name.
278
-
279
- ### 3. Find your lane
280
-
281
- The architecture exists to keep content and code separate. Your task sits in one of them. Decide before you edit, then stay there.
282
-
283
- | Task | Lane | Files you touch |
170
+ | Task | Lane | Files |
284
171
  |---|---|---|
285
- | Add / edit / reorder a section on a page | content | `<site>/pages/**` |
286
- | Add a page | content | `<site>/pages/<name>/` |
287
- | Change colors, fonts, light/dark | content | `<site>/theme.yml` |
288
- | Change header, footer, or nav content | content | `<site>/layout/*.md`, or page order in `site.yml` |
289
- | Change how a section type *looks* everywhere | foundation | `<foundation>/sections/<Type>/` |
290
- | Add a new section type | foundation | `<foundation>/sections/<NewType>/` |
291
- | Expose a new knob to authors | foundation | `<foundation>/sections/<Type>/meta.js` + the component |
172
+ | Add / edit / reorder a section; add a page | content | `<site>/pages/**` |
173
+ | Colors, fonts, light/dark | content | `<site>/theme.yml` |
174
+ | Header, footer, nav content | content | `<site>/layout/*.md`, page order in `site.yml` |
175
+ | How a section type looks everywhere; a new type; a new knob | foundation | `<foundation>/sections/<Type>/` (+ `meta.js`) |
292
176
 
293
- **If you're on a content task and find yourself wanting to open the foundation, stop.** Usually it means you missed a param the section type already exposes — re-read its `meta.js`. If the knob genuinely doesn't exist, that's a foundation change: say so explicitly rather than quietly crossing the boundary. Editing a section type changes it for every page that uses it — and in a segregated workspace, for **every site in the repo sharing that foundation**, which is exactly the layout chosen when a foundation is the primary deliverable. Check who else depends on it before you edit.
177
+ On a content task and tempted to open the foundation: stop — usually a param already exists; re-read that type's `meta.js`. If it doesn't, that's a foundation change: say so rather than crossing quietly, because it changes every page using the type and, in a segregated workspace, every site sharing the foundation.
294
178
 
295
- ### 4. The loop
179
+ **6. Run `uniweb guide <lane>` — before writing, not when stuck.** `uniweb guide content` or `uniweb guide foundation` prints the lane's guide; read all of it, and if your tool cuts long output, `--path` gives you the file. The parse rules, the kit API and the layout system live there, not in your memory of other frameworks. A task that touches colors or fonts, or crosses into records, services, a backend, another language or shipping, runs that guide too (§6). This file is deliberately the short part; the guide is the rest of it.
296
180
 
297
- ```bash
298
- uniweb dev # the site you are in; from the workspace root, it picks one
299
- uniweb dev --status # the address it is serving at — read it, never assume a port
300
- uniweb dev --stop # stop it when you are done
301
- ```
302
-
303
- **When you're unsure what shape your markdown produces, don't reason about it — run it.** From the *site* directory (paths resolve against your shell's working directory):
181
+ **7. Work in the lane, and check as you go.**
304
182
 
305
183
  ```bash
306
- uniweb inspect pages/home/hero.md # the parsed content shape
307
- uniweb inspect pages/home/ # every section on the page
308
- uniweb inspect pages/home/hero.md --full # include empty fields (matches runtime)
309
- uniweb inspect pages/home/hero.md --sequence # include the sequence array
310
- uniweb inspect pages/home/hero.md --raw # the ProseMirror AST
184
+ uniweb inspect pages/home/hero.md # from the site dir: the parsed shape (--full, --sequence, --raw; a folder = the page)
185
+ uniweb doctor # project configuration (--fix repairs)
186
+ uniweb validate # records against declared schemas
187
+ uniweb <command> --help # exact flags, no side effects
311
188
  ```
312
189
 
313
- This settles any question in Part 3 — whether a heading became a subtitle or an item, whether the parser saw your data block, why `content.title` is an array. One command beats re-deriving the rules.
314
-
315
- ### 5. Recipes
316
-
317
- Paths are relative to the site package you identified in step 1 — `site/` in the default layout, `sites/main/` or `docs/site/` in others.
318
-
319
- **Add a section to a page.** `ls <site>/pages/<page>/` to see the existing sections and their numeric prefixes → pick a `type:` from the vocabulary (step 2) → create `<site>/pages/<page>/N-name.md` with frontmatter plus markdown. Use a decimal (`2.5-…`) to slot between existing sections without renaming them.
320
-
321
- **Add a page.** Create `<site>/pages/<name>/`, add `page.yml` (at minimum `title:`), add one or more section `.md` files. It gets the route `/<name>` automatically. Only touch `pages:` in the parent `page.yml` / `site.yml` if you need a specific order.
322
-
323
- **Change the brand color.** `<site>/theme.yml` → `colors.primary`. One line, and every component follows. Do **not** edit Tailwind color classes in components to change brand color — that is the exact anti-pattern this system removes.
324
-
325
- **Change how code blocks look.** `<site>/theme.yml` → `code:`. Name one of Shiki's 65 bundled themes (`code: dracula`), name one per scheme (`code: { light: github-light, dark: github-dark }`), or take a theme and adjust it (`code: { theme: github-dark, background: '#0D0D0D' }`). Hand-picking every syntax colour is possible and is the last thing to reach for. A block paints its theme's background and text colour before the highlighter loads when they are known — the default theme's, or the `background` and `foreground` the site declares — so declare both beside a named theme to paint them from the start.
326
-
327
- **Change a nav item.** First check how nav is produced. If `<site>/layout/header.md` lists the links (a markdown list, or a `yaml:nav` block), edit it there. If it doesn't, the Header is generating nav from the page hierarchy — change page titles and order in `site.yml` / `page.yml` instead.
328
-
329
- **Update the project's Uniweb dependencies — and this file.** `npx uniweb@latest update`. One command aligns every `@uniweb/*` dependency *and* refreshes this AGENTS.md together. Preview with `--dry-run`. ⛔ **The `@latest` is doing the work** — a bare `uniweb update` runs the CLI this project already pins, which aligns you to the matrix you already have and correctly reports nothing to do. **Don't reach for `npm update` / `pnpm update`** — see *Staying current* in Part 5 for why that breaks things quietly.
330
-
331
- **Change one section's columns / spacing / variant.** Check that type's `meta.js` `params:` first. If the knob exists, set it in that section's frontmatter and you're done, in the content lane. If it doesn't, it's a foundation change — see the warning in step 3.
190
+ `inspect` every section you write. Look at the page — the terminal won't report most of §4.
332
191
 
333
- ---
334
-
335
- ## Part 3 — The content lane
192
+ ## 4. The build is green and the page is wrong
336
193
 
337
- ### Section format
338
-
339
- Each `.md` file is a section. Frontmatter on top, content below:
194
+ | Symptom | Cause |
195
+ |---|---|
196
+ | Red `Component not found: <Type>` box | `type:` not in `sections/` (or an extension) |
197
+ | A section doesn't render | left out of a strict `sections:` list; `_`-prefixed; a type nested below the root of `sections/` without `meta.js` |
198
+ | A heading landed in the wrong field | the step rule (2.2) — `inspect` |
199
+ | `title` empty | something (an icon, an image, a line of text) sits above the first heading, or a later heading is as large as the first |
200
+ | Pages missing from the nav | a strict `pages:` list — add `...` |
201
+ | A color is empty | unquoted `#` in YAML |
202
+ | Literal `{name}` on the page | no Loom content handler |
203
+ | A class works in the foundation's build, not in the site's or `uniweb dev` | its folder has no `@source` line — `uniweb doctor` names it |
204
+ | Sticky header scrolls away | `sticky` class instead of `sticky: true` in `meta.js` |
205
+ | Modal under the header | z-index instead of `<Overlay>` |
206
+ | Entrance animation never plays | JS-started; write it in CSS; `uniweb dev` doesn't prerender |
207
+ | Colors wrong in one section only | hardcoded color classes instead of tokens |
208
+ | Wrong typeface | `font-serif` / `font-sans` without a `font-*` var |
209
+ | Prose lost its bullets | `prose-tokens.css` not imported |
210
+
211
+ ## 5. Contract cards
212
+
213
+ ### Content
214
+
215
+ One `.md` file per section.
340
216
 
341
217
  ```markdown
342
218
  ---
343
219
  type: Hero
344
220
  theme: dark
345
221
  ---
222
+ #> Eyebrow │ pretitle (label line)
223
+ # Build [faster]{accent} │ title — consecutive same-level headings merge into a title array
224
+ ## Not every page │ subtitle — exactly one step smaller, directly after the title
346
225
 
347
- #> New in v1 ← pretitle (the label line above the title)
226
+ We help teams ship faster. │ paragraphs[0]
348
227
 
349
- # Build the system. ← title (the big headline)
228
+ [Get Started](/start) │ links[0] — a link alone in its paragraph; with no blank line it joins the text above
350
229
 
351
- ## Not every page. ← subtitle (one step smaller, directly below)
230
+ ![](lu-zap) │ icons[0] = { library: 'lu', name: 'zap' } — also lu:zap, lucide:zap
352
231
 
353
- Description paragraph.
354
-
355
- [Call to Action](/link)
356
-
357
- ![Image](./image.jpg)
232
+ ### Fast │ items[0].title — two steps smaller, or ANY heading once body content has begun
233
+ Lightning quick. │ items[0].paragraphs[0]
358
234
  ```
359
235
 
360
- Heading levels set *structure* (pretitle, title, subtitle), not font size — the component controls visual sizing. Write a pretitle as a `#>` label line — any number of leading `#`s spells the same label, so match the heading you are labelling. A smaller ordinary heading directly above the title is *also* read as a pretitle, which is how files written before label lines keep working; prefer `#>`, because it says what it is wherever it lands rather than depending on what follows it.
361
-
362
- **A section with no `type:` renders through the foundation's default section type — a component named `Section`, unless the foundation's `main.js` sets `defaultSection` to something else.** This is what lets a folder of plain markdown with no frontmatter at all become pages: mounted documentation, an imported wiki, anything written before it met this framework. If such content renders blank, the foundation has no `Section` — that, not the markdown, is what to fix.
363
-
364
- **Markdown order ≠ rendering order.** The parser extracts content into a flat structure; the component decides how to arrange it visually. Write markdown in semantic order, not visual order — start with the heading, then add icons, images, and text in any order.
365
-
366
- **Placing content *before* the first heading changes the parse:** headings after body content become items, not the section title. This is by design — it's how repeating content groups are created. An icon counts: `![](lu-globe)` above `# Title` leaves `content.title` empty, and the heading in `items[0]`. For an icon that belongs to the title, write it under the heading, where it's still `content.icons[0]`; `uniweb inspect` flags the shape.
367
-
368
- ### The parsed object
369
-
370
- The semantic parser produces a flat, guaranteed structure. No null checks needed — empty strings and arrays when content is absent:
371
-
372
236
  ```js
373
- content = {
374
- title: '', // Main heading (string or string[] for multi-line)
375
- pretitle: '', // `#>` label line(s) — also filled by smaller headings
376
- // stacked above the title, for older content
377
- // (string or string[])
378
- subtitle: '', // Line(s) one step below the title — each further
379
- // one-step descent is another line (string or string[])
380
- paragraphs: [], // Text blocks
381
- links: [], // { href, label, role } — links on their own line. Not a sentence's, and a list item has its own
382
- images: [], // { url, alt, caption, role, href, target } — `url`, where a video has `src`
383
- icons: [], // { library, name, role }
384
- videos: [], // { src, alt, caption, role, poster, href, target }
385
- media: [], // Images, videos and insets on their own line, in the order written, each with its `kind`
386
- documents: [], // { url, alt, caption, role: 'pdf', preview?, author?, description? } — from {role=pdf}
387
- insets: [], // Inline @Component references — { refId }
388
- lists: [], // [[{ paragraphs, links, lists, … }]] — each item is an object, not a string
389
- quotes: [], // Blockquotes
390
- snippets: [], // Fenced code — [{ language, code }]
391
- data: {}, // Tagged blocks — ```yaml:tag / ```json:tag give the parsed value,
392
- // ```md:tag gives { items, sequence } (see Concept blocks)
393
- tables: [], // Only when present — [{ rows: [{ cells: [{ children, header, align }] }], attrs? }] — attrs: caption, id, placement, from the caption line
394
- headings: [], // Only from nested content (quote/list bodies) — a
395
- // section's headline never spills here
396
- items: [], // Each has the same flat structure — from headings after body content
397
- sequence: [], // All elements in document order
398
- }
399
- ```
400
-
401
- > **Don't predict this — print it.** `uniweb inspect <path>` shows the actual parsed shape of any section or page. The rules below are the ones most often gotten wrong from memory.
402
-
403
- ### Markdown → content, side by side
404
-
405
- ```markdown
406
- #> Eyebrow │ content.pretitle = "Eyebrow"
407
- # Our Features │ content.title = "Our Features"
408
- ## Build better products │ content.subtitle = "Build better products"
409
- │
410
- We help teams ship faster. │ content.paragraphs[0] = "We help teams…"
411
- │
412
- [Get Started](/start) │ content.links[0] = { href: "/start", label: "Get Started" }
413
- │
414
- ### Fast │ content.items[0].title = "Fast"
415
- ![](lu-zap) │ content.items[0].icons[0] = { library: "lu", name: "zap" }
416
- Lightning quick. │ content.items[0].paragraphs[0] = "Lightning quick."
417
- │
418
- ### Secure │ content.items[1].title = "Secure"
419
- ![](lu-shield) │ content.items[1].icons[0] = { library: "lu", name: "shield" }
420
- Enterprise-grade security. │ content.items[1].paragraphs[0] = "Enterprise-grade…"
237
+ content = { title, pretitle, subtitle, paragraphs, links, images, icons, videos, documents, insets,
238
+ media /* images, videos and insets on their own line, in written order, each with `kind` */,
239
+ lists, quotes, snippets, data, items, sequence,
240
+ tables, math /* only when present */, headings /* from quote/list bodies, or when an image sits above the title */ }
241
+ // strings and arrays, never null · items carry this same full shape · sequence = everything in document order
242
+ // an image's address is `url`; a video's is `src` · a link inside a sentence stays in `paragraphs`, never in `links`
421
243
  ```
422
244
 
423
- The staircase rule produces this — each heading relates to the one before it: the same size adds another line to the same part; **one step smaller** joins the headline as the next part down (the subtitle, then further subtitle lines); **two steps smaller** starts an item; and once body content has begun, *any* heading starts an item. `#>` label lines become `pretitle`; so do smaller headings stacked above the title, which is the older spelling.
424
-
425
- ### Items have the full content shape
426
-
427
- This is the most commonly overlooked feature. Each item has `title`, `pretitle`, `subtitle`, `paragraphs`, `links`, `icons`, `lists`, `snippets`, and `data` — you don't need workarounds for structured content inside items. Heading hierarchy within an item follows the same rules (`####` inside a `###` item becomes that item's `subtitle`).
245
+ **Fenced blocks.** ` ```yaml:tag ` / ` ```json:tag ` → `content.data.tag`, **only when the component declares that key in `meta.js` `data:`** (an undeclared key stays out of `data`; inside an item no declaration is needed). ` ```md:tag ` → `content.data.tag = { items, sequence }` — a named *kind* of prose (FAQ, callout), declared the same way. A bare language → `content.snippets`. ` ```@Component{params} ` wraps parsed content in an inset component.
428
246
 
429
- ````markdown
430
- ### Starter ← items[0].title
431
- $9/month ← items[0].paragraphs[0]
247
+ **Media and links.** `![alt](./img.jpg){role=banner}`; `{role=video}` → `videos`; `{role=pdf}` → `documents`; `![](@Component){param=x}` → inset. `page:about#team` links a section (id = file name without its number, or `id:`). Quote attribute values with spaces.
432
248
 
433
- ```yaml:details
434
- trial: 14 days
435
- seats: 1
436
- ``` ← items[0].data.details = { trial: "14 days", seats: 1 }
437
- ````
438
-
439
- ### Subtitle vs items — the step rule
440
-
441
- A heading directly after the title becomes `subtitle` **only when it is exactly one step smaller** (H1→H2, H2→H3) — and each *further* one-step line continues the subtitle (a three-line header is `subtitle: [line2, line3]`). **Two steps smaller starts items** — the idiom for entries with no lead paragraph:
442
-
443
- ```markdown
444
- # Our Stats │ content.title = "Our Stats"
445
- ### 15,000+ │ content.items[0].title = "15,000+"
446
- Students from 90 countries │ content.items[0].paragraphs[0]
447
- │
448
- ### 200+ │ content.items[1].title = "200+"
449
- Programs offered │ content.items[1].paragraphs[0]
450
- ```
249
+ **Backgrounds and theme are frontmatter.** `background:` takes an image, video, gradient, quoted color or palette token, or an object (`image`, `video`, `overlay`); `theme: light | medium | dark`, or a map with token overrides (`section: neutral-100`).
451
250
 
452
- With `## 15,000+` instead, the first stat would join the headline as `content.subtitle`. A `---` divider, or any body content after the headline, also closes it — after body, headings of *any* size start items.
251
+ **Pages.** `pages/<name>/` → `/<name>`. `page.yml`: `title`, `description`, `id`, `order`, `sections: [a, b, ...]`, `pages: [...]`, `nest`, `redirect`, `slug: { fr: … }`, `hidden` (draft; takes the pages below it), `hideIn` (nav only), `knowledge` (agent-only, never rendered — not a security control), `query` / `fetch`, `seo`, `layout`. `folder.yml` for a folder *of pages*. Numeric prefixes order sections; `2.5-x.md` slots between. Config cascades `page.yml → folder.yml → site.yml → foundation`. `layout/header.md`, `footer.md` render on every page — a markdown list is the nav, a standalone link the CTA, `yaml:nav` for richer menus. Child sections: `@child.md` + `nest: { parent: [child] }`.
453
252
 
454
- ### Multi-line headings
253
+ **`site.yml`.** `index`, `pages`, `foundation`, `extensions`, `paths`, `placeholders`, `languages`, `services`, `agents`, `seo` (`origin`: scheme + host, `image`: 1200×630), `favicon`, `touchIcon`. Everything in `site.yml` and `queries.yml` ships to the browser — **never a secret**.
455
254
 
456
- Consecutive headings at the same level merge into a title array — one heading split across visual lines. Kit's `<H1>`, `<H2>`, … render arrays as a single tag with line breaks.
255
+ **Records — run `uniweb guide data` before touching them.** `records/<schema>/<name>.md|yml|json|bib` (`records/article/` → `@/article`); `queries.yml` names → `{ schema, where, sort, limit, scope }`; a page or section shows one with `query: name` or `fetch: { query, … }` (narrows, never widens); a `[slug]/` folder inside the query's page gives each record a page.
457
256
 
458
- ```markdown
459
- # Build the future │ content.title = ["Build the future", "with confidence"]
460
- # with confidence │
257
+ ### Foundation
461
258
 
462
- # Build the future │ content.title = [
463
- # [with confidence]{accent} │ "Build the future",
464
- │ "<span accent=\"true\">with confidence</span>"
465
- │ ]
466
259
  ```
467
-
468
- **Rule:** a repeated size always continues the part it repeats — title lines, or subtitle lines once the headline has stepped down. Use `---` to force separate items where adjacent headings would otherwise continue the headline.
469
-
470
- ### Sequential content
471
-
472
- `content.sequence` is the flat, ordered list of all elements before any grouping. Each element has a `type` (`heading`, `paragraph`, `image`, `codeBlock`, `dataBlock`, `list`, `link`, `divider`, `inset`, …) plus type-specific fields. Use it when grouping isn't the right lens — rendering prose in document order, or finding elements regardless of which group they landed in:
473
-
474
- ```js
475
- const allData = {}
476
- for (const el of content.sequence) {
477
- if (el.type === 'dataBlock') allData[el.tag] = el.data
478
- }
260
+ src/
261
+ ├── sections/ # section types — PascalCase file or folder at the root; a folder when it needs meta.js
262
+ ├── layouts/ # custom layouts, auto-discovered
263
+ ├── components/ # ordinary React — any props, any library, no meta.js, invisible to authors
264
+ ├── utils/
265
+ ├── main.js # export default { name, description, defaultLayout, defaultSection, handlers, … } + export const vars
266
+ └── styles.css # @import "tailwindcss" + kit's theme-tokens.css + prose-tokens.css; one @source per folder with classes
479
267
  ```
480
268
 
481
- Grouped fields and `sequence` are two interpretations of the same content. Grouped suits structured layouts (cards, features); sequential suits prose and cross-group searching.
269
+ `uniweb add section Hero` scaffolds `sections/Hero/{index.jsx,meta.js}`. Import shared code as `#components/*`, `#utils/*`.
482
270
 
483
- ### Choosing how to model content
271
+ **Props.** `function Type({ content, params, block })`. Frontmatter becomes `params` except the reserved keys:
484
272
 
485
- The decision rule: **would a content author need to change this?** Yes → markdown, frontmatter, or a tagged data block. No → component code.
486
-
487
- Start with the content, not the component. Write the markdown an author would naturally write, check what shape the parser produces (`uniweb inspect <file>`), *then* build the component to receive it. You have three layers, and most of the design skill is choosing between them:
488
-
489
- **Pure markdown** — headings, paragraphs, links, images, lists, items. The default. If the content reads naturally as markdown and the parser captures it, stop here.
490
-
491
- **Frontmatter params** — `columns: 3`, `variant: centered`. Configuration an author might change but that isn't *content*. Would changing this alter the section's *meaning* or just its *presentation*? Presentation → param. Meaning → content.
492
-
493
- **Tagged data blocks** — for content that doesn't fit markdown patterns: products with SKUs, team members with roles, event schedules, form definitions. When information is genuinely structured data that an author still owns, a well-named block (`yaml:pricing`, `yaml:speakers`) is clearer than contorting markdown. Formats: `yaml` and `json`. Parsed at build time into `content.data.tagName`.
494
-
495
- Read the markdown out loud. If an author would understand what every line does, you've chosen right. The moment markdown feels like it's encoding data rather than expressing content, step up to a tagged block.
496
-
497
- **When you are building the foundation, you are designing these, not choosing from a menu.** The examples in this guide illustrate patterns, not exhaustive inventories. Any param name works in `meta.js`, any tag name works for data blocks, any section type name works. The framework has fixed mechanisms (content shape, context modes, token system); nearly everything else is yours to define.
498
-
499
- **When you are writing content against a foundation that already exists, the opposite holds.** The vocabulary is fixed and finite: the section types are exactly what `sections/**` declares, and their params are exactly what each `meta.js` lists. Inventing a name there doesn't extend the system — it renders a red `Component not found` box on a build that otherwise reports success.
500
-
501
- **Parameter naming matters.** Would an author understand it without reading code? `columns: 3` yes, `gridCols: 3` no. `variant: centered` yes, `renderMode: flex-center` no. `align: left` yes, `contentAlignment: flex-start` no.
502
-
503
- ### Repeated values — `placeholders:`
504
-
505
- A value that appears on many pages goes in `site.yml` once, not in a dozen markdown files:
273
+ | Reserved | What it is | Read from |
274
+ |---|---|---|
275
+ | `type`, `id`, `hidden` | the section itself | — |
276
+ | `query`, `fetch` | its data | `content.data[key]`, for keys declared in `data:` |
277
+ | `theme`, `background`, `grid`, `vars`, `sticky` | settings the runtime applies | `block` — `useColorContext(block)`, `<SectionBackground block>`, `<ChildGrid from={block}>`, `block.sticky` |
278
+ | `props` | params as one map | merged into `params` |
279
+ | `data`, `preset`, `input` | `data:` stops the build (it was `query:`); the others warn and do nothing | — |
506
280
 
507
- ```yaml
508
- placeholders:
509
- product: Uniweb
510
- vendor:
511
- email: billing@acme.example
281
+ ```jsx
282
+ import { H1, P, Prose, Visual, Icon, Link, ChildBlocks, Overlay, PlainText } from '@uniweb/kit'
283
+ <H1 text={content.title} className="text-heading text-5xl font-bold" /> // renders its own tag
284
+ <P text={content.paragraphs} className="text-body" />
285
+ <Prose content={content} block={block} /> // the whole section in document order
286
+ <Visual media={content.media} block={block} /> // image, video or inset, by kind
512
287
  ```
513
288
 
514
- Any page then references it by name — `Write to {vendor.email}.` Dot paths work, and a record's own field of the same name always wins, so `{title}` on an article page is that article's title regardless of what the site declares.
515
-
516
- ⛔ **Resolution is a foundation capability, not a framework one.** `{…}` is resolved by the foundation's `handlers.content` hook — normally `createLoomHandlers` from `@uniweb/loom`. Under a foundation without one, `placeholders:` is inert and pages render the literal `{vendor.email}`, which reads as a typo. The build warns when a site declares the key and the foundation has no content handler.
517
-
518
289
  ```js
519
- // main.js — a foundation opts in
520
- import { createLoomHandlers } from '@uniweb/loom'
521
- export default { handlers: createLoomHandlers({ vars: (data) => data?.profile?.[0] }) }
522
- ```
523
-
524
- Placeholders are the simplest case of a larger language: the same expressions filter, sort, count and format live data (`{COUNT OF publications WHERE refereed}`). Reach for one when a value repeats; reach for the rest when content is genuinely derived from records.
525
-
526
- ### Icons
527
-
528
- Image syntax with a library prefix — **two interchangeable spellings, the same everywhere** (markdown, and Kit's `<Icon name>`):
529
-
530
- ```markdown
531
- ![](lucide:house) colon + friendly name — every library
532
- ![](lu:house) colon + short code
533
- ![](lu-house) dash — short codes only, to stay unambiguous with ordinary paths
534
- ```
535
-
536
- Short codes: `lu` (Lucide), `hi` / `hi2` (Heroicons v1 / v2), `fi` (Feather), `pi` (Phosphor), `tb` (Tabler), `bs` (Bootstrap), `md` (Material), `ai` (Ant Design), `ri` (Remix), `si` (Simple Icons), `io5` (Ionicons), `bi` (Boxicons), `vsc` (VS Code), `wi` (Weather), `gi` (Game), `fa` / `fa6` (Font Awesome 5 / 6). Browse at [react-icons.github.io/react-icons](https://react-icons.github.io/react-icons/): an icon's name is its component name without the prefix, in kebab case (`LuBuilding2` → `lu-building2`, `LuGrid2X2` → `lu-grid2-x2`). For Lucide, Heroicons and Feather the family's own spelling works too (`lu-building-2` and `lu-grid-2x2`, as lucide.dev writes them). An icon the build cannot fetch is named in its prerender warning.
537
-
538
- Optional attributes: `{size=20}`, `{color=red}`. Custom SVGs: `![Logo](./logo.svg){role=icon}` (or `![Logo](icon:./logo.svg)`) — always available, no library needed.
539
-
540
- ### Links and media attributes
541
-
542
- ```markdown
543
- [text](url){target=_blank} <!-- Open in new tab -->
544
- [text](./file.pdf){download} <!-- Download -->
545
- ![alt](./img.jpg){role=banner} <!-- Role determines array: images, icons, videos or documents -->
546
- ![alt](./demo.mp4){role=video} <!-- → content.videos[], not content.images[] -->
547
- ![alt](./report.pdf){role=pdf} <!-- → content.documents[] — a file, drawn as a link -->
548
- ![alt](./img.jpg){href=/products} <!-- Clickable media: href + target ride along -->
549
- ```
550
-
551
- A link to a section names its page and its id: `page:about#team` goes to `/about#section-team`, and `page:/#features` to a section of the homepage. The id comes from the file's name without its number (`2-features.md` is `features`), or from `id:` in its frontmatter.
552
-
553
- Sizing and loading ride on the image: `{width=800 height=600 loading=lazy fit=cover position=center}`, and its credit as `{author="Jane Doe"}`. A video adds `{poster=./thumb.jpg autoplay muted loop controls}`; a `{role=pdf}` document adds `{preview=./cover.jpg author=… description=…}` and arrives in `content.documents` — `{ url, name, mime, size?, alt, caption, … }` — declare it in `content:` as `documents`. Name a video's poster: a static build makes one from the video only when none is named and ffmpeg is installed, and `uniweb publish` sends only the poster you name.
554
-
555
- **Where media lives.** `./x` names a file beside the page, `/x` a file in `public/`, and both reach a static build and a site published with Uniweb. Keep a page's media beside it, and in `public/` what belongs to the whole site: the favicon, fonts. Only a static host gives a file a fixed address, at the site root. A site published with Uniweb serves a file that something names from an address the upload gives it, and nothing at `/x`, so for a file other sites or scripts fetch by URL, keep it somewhere with its own address and add a page whose `redirect:` goes there. A static build copies `public/` whole and adds its own copy of each file a page names there, so a video only a page shows is in `dist/` twice from `public/` and once from beside the page. `uniweb push` uploads a file beside a page wherever the page is, in a folder `paths:` mounts too; a file outside the site and the folders it mounts is not uploaded, so put that in `public/`. A site has no `assets/` folder for media: a build stops on a `/x` only `assets/` holds.
556
-
557
- **Placement — where a block sits in a section rendered in order.** `{placement=left}` (or `right`, `wide`, `full`) on an image or a video; a table takes it on its **caption line**, the paragraph after the table, after a blank line — `: Plans and prices {placement=wide #tbl-plans}`, which also gives the table a caption and a cross-reference id. It is the author's intent, not a size: kit's `<Render>`, `<Prose>` and `<Article>` lay all four out (`data-placement`, styled by `prose-tokens.css`), and any other component ignores it. A section type says which it honours in `meta.js` — `sequence: { label, placement: true }` — and the build warns when a file asks for one its type does not offer.
558
-
559
- **Quote values containing spaces:** `{note="Ready to go"}`, not `{note=Ready to go}` — unquoted values end at the first space.
560
-
561
- **Separators are forgiving.** `:` works wherever `=` does, and pairs may be separated by whitespace, a comma, or both — `{role=banner width=1200}`, `{role:banner, width:1200}` and `{role:banner,width:1200}` are identical. `=` and spaces are canonical, and that is what gets written back on save. Two rules keep it unambiguous: the separator must **touch** the key (`{note:warning}` is one pair, `{note : warning}` is two flags), and a value containing a **comma** must be quoted (`{style="a, b"}`). A value containing a colon needs no quoting — only the first colon separates, so `{href:https://example.com}` is fine.
562
-
563
- Standalone links (alone on a line) are promoted to `content.links[]`. How they're drawn is the component's choice. A link inside a sentence stays an `<a>` tag in `content.paragraphs[]`, and isn't in `content.links[]`. Multiple links sharing a paragraph are all promoted:
564
-
565
- ```markdown
566
- [Primary](/start) ← standalone → content.links[0]
567
- [One](/a) [Two](/b) ← links-only paragraph → both in content.links[]
568
- Check out [this](/a) link. ← inline → stays in paragraphs as an <a> tag
569
- [Go](/start){button} ← a link with role "button" (also `button:/start`), and a `variant`
570
- ```
571
-
572
- ### Inline text styling
573
-
574
- ```markdown
575
- # Build [faster]{accent} with structure
576
- This is [less important]{muted} context.
577
- ```
578
-
579
- `accent` and `callout` (both accent-colored + bold) and `muted` (subtle) are built-in defaults that adapt to context. `--accent` is your brand color unless you declare a separate `colors.accent`, and resolves to the shade you authored — not a darkened one, since accent is decorative emphasis rather than body-size link text. Components receive HTML strings with spans applied: `<span accent="true">faster</span>`.
580
-
581
- Sites can adjust these or add named styles in `theme.yml`'s `inline:` section — a name is a letter, then letters, digits, `_` or `-`, and never starts with `on` (a handler's prefix, so it is dropped). Overrides merge **property by property**, so declare only what differs (`accent: { font-weight: inherit }` keeps the default color); to drop a default property rather than change it, give it a neutral value (`initial`, `inherit`, `unset`).
582
-
583
- > **On a site synced with Uniweb Cloud, the built-in style names round-trip *editable*** — an author who opens a page containing `[Get started]{accent}` gets the editor's own styling control for it, and can change or remove it like any text they styled there.
584
- >
585
- > **A name the editor doesn't know is preserved exactly, but not editable** — a style you defined yourself in `inline:`, two names on one span, or a `class`/`id` set. Nothing is lost and nothing is approximated: it survives every edit and save untouched, the editor simply offers no control for it. That is a permanent property rather than a gap, because the name set is open by design — you can add styles the editor has no way to know about.
586
-
587
- ### HTML is not content
588
-
589
- Content is markdown. Components decide how it renders, so a tag written in it — `<strong>`, `<span class=…>`, `<div>` — is not markup: it **shows as written**, and the build names the file. Use markdown's own forms instead: `**bold**`, a named style (`[text]{accent}`), a link.
590
-
591
- The one exception is `<br/>`, a line break where markdown has no other spelling — inside a heading. For a headline split across lines, the multi-line heading above usually says it better.
592
-
593
- A plain newline inside a paragraph is a space, so wrap prose however you like — re-wrapping a paragraph changes nothing, and pushes nothing. A line break in a paragraph is written on purpose: a backslash (`\`) at the end of the line.
594
-
595
- ### Fenced code: data blocks vs snippets
596
-
597
- Fenced code serves three purposes depending on its info string: `yaml:`/`json:` for data, `md:` for a named kind of prose (see *Concept blocks*), and a bare language for a code sample.
598
-
599
- **Tagged data blocks** — structured data parsed into JS objects. The tag is the key in `content.data` — for a section whose component declares that key in `meta.js` `data:`; the format (`yaml`/`yml`/`json`) is a serialization format, not a display language.
600
-
601
- ````markdown
602
- ```yaml:form
603
- - name: email
604
- type: string
605
- format: email
606
- label: Email
607
- ```
608
- ````
609
-
610
- → `content.data?.form` = `[{ name: "email", type: "string", format: "email", label: "Email" }]`, when the component declares `data: { form: … }`. A block under a key the component does not declare stays out of `content.data` (the dev console says so) and is still in `content.sequence`. A block inside an item is that item's (`content.items[n].data`) and needs no declaration.
611
-
612
- **Code snippets** — display content with a language for syntax highlighting, collected in `content.snippets` as `[{ language, code }]`. Filter with `content.snippets.filter(s => s.language === 'css')`.
613
-
614
- Both appear in `content.sequence`. `<Prose>` handles the difference automatically — it renders snippets with highlighting and skips tagged data blocks, which components access separately via `content.data`.
615
-
616
- ### Math (LaTeX)
617
-
618
- Authors write LaTeX directly; it compiles to MathML Core **at build time** — no runtime math library, no extra CSS. Three forms, matching Pandoc / GitHub / VS Code / Jupyter / Obsidian convention:
619
-
620
- | Form | Mode |
621
- |---|---|
622
- | `$x^2$` | Inline |
623
- | `$$x^2$$` | Display (block on its own line, inline display mid-paragraph) |
624
- | ` ```math ` fence | Display (multi-line friendly) |
625
- | `\$` | Literal `$` |
626
-
627
- **Disambiguation gotcha:** a `$…$` span counts as math only when the body has no whitespace next to the delimiters *and* the closing `$` isn't immediately followed by a digit. So `It costs $5 and $10 total` and `Budget: $200` stay prose without escaping, while `Let $f(x) = 5$ be a function` is math. Use `\$` when the rules would otherwise trip.
628
-
629
- Math rides the normal content pipeline — it appears in prerendered HTML, survives `compile('epub')` and `compile('pagedjs')`, and roundtrips through the editor. Component code needs nothing special.
630
-
631
- ### Lists as navigation menus
632
-
633
- Markdown lists model nav, menus, and grouped links. Each list item is a full content object with `paragraphs`, `links`, `icons`, and nested `lists`.
634
-
635
- ```markdown
636
- - ![](lu-home) [Home](/) ← content.lists[0], each item.links[0] + item.icons[0]
637
- - ![](lu-book) [Docs](/docs)
638
-
639
- - Product ← nested: group.paragraphs[0] is the label,
640
- - [Features](/features) ← group.lists[0] holds sub-items
641
- - [Pricing](/pricing)
642
- ```
643
-
644
- **For richer navigation** with icons, descriptions, or hierarchy, use a `yaml:nav` tagged block:
645
-
646
- ````markdown
647
- ```yaml:nav
648
- - label: Dashboard
649
- href: /
650
- icon: lu:layout-grid # same icon spellings as anywhere else —
651
- - label: Docs # lu:name, lucide:name, lu-name, or an SVG path
652
- href: /docs
653
- icon: /icons/book.svg
654
- children:
655
- - label: Getting Started
656
- href: /docs/quickstart
657
- ```
658
- ````
659
-
660
- Access: `content.data?.nav`, with `data: { nav: {} }` in the component's `meta.js` — an array of `{ label, href, icon, text, children, target }`. Components can support both modes: use `content.data?.nav` when provided, fall back to `website.getPageHierarchy()`. Full pattern: `reference/navigation-patterns.md`.
661
-
662
- ### Section backgrounds
663
-
664
- Set `background` in frontmatter — the runtime renders it:
665
-
666
- ```yaml
667
- background: /images/hero.jpg # Image
668
- background: /videos/hero.mp4 # Video
669
- background: linear-gradient(135deg, #667eea, #764ba2) # Gradient
670
- background: '#1a1a2e' # Color (hex — quote in YAML)
671
- background: primary-900 # Palette token (bare name or var())
672
-
673
- background: # Object form for more control
674
- image: { src: /img.jpg, position: center top }
675
- overlay: { enabled: true, type: dark, opacity: 0.5 }
676
-
677
- background:
678
- video: { src: /videos/hero.mp4, poster: /images/hero.jpg } # the poster shows until the video plays
679
- ```
680
-
681
- Components that render their own background declare `background: 'self'` in `meta.js`, and the runtime then draws none; to draw the author's background themselves they render kit's `<SectionBackground block={block} />`.
682
-
683
- ### Page organization
684
-
685
- ```
686
- site/layout/ # header.md, footer.md, left.md — rendered on every page
687
- site/pages/home/
688
- ├── page.yml # title, description, order
689
- ├── 1-hero.md # Numeric prefix sets order
690
- ├── 2-features.md
691
- └── 3-cta.md
692
- ```
693
-
694
- Decimals insert between: `2.5-testimonials.md` goes between `2-` and `3-`. **Ignored:** `README.md`, and `_*.md` / `_*/` (drafts and private files).
695
-
696
- ```yaml
697
- # page.yml
698
- title: About Us
699
- id: about # Stable identity (for page: links, survives moves)
700
- order: 2 # Navigation sort position
701
- sections: [hero, team, ...] # Section order within this page (same ... rule)
702
- pages: [team, history, ...] # Child page order, when this page has child folders
703
- redirect: academic # Redirect to a child page (relative/absolute path, or URL)
704
- slug: { fr: a-propos } # Localized URL segment per language
705
-
706
- # folder.yml — a folder OF PAGES, where page.yml means a page built from sections
707
- title: Getting Started
708
- pages: [quickstart, app-tour, ...] # Child page order (... = rest)
709
-
710
- # site.yml
711
- index: home # Just set the homepage
712
- pages: [home, about, ...] # Order pages (... = rest, first = homepage)
713
- foundation: '@acme/ui@1.2.0' # The component system (see Part 2, step 1)
714
- extensions: ['@acme/fx@0.3.1'] # Secondary foundations — same shapes as foundation:
715
- ```
716
-
717
- **On a site the Uniweb app edits too, a page's `id:` may be a code the app made** (`id: 3f58142d`): the app links a page by it. `uniweb pull` writes such a link as the page's path (`[AI](page:ai)`), and `uniweb push` stores the path by the code again, so the link survives a rename in the app. An id you chose (`id: about`) stays as you wrote it, in links too. Keep the `id:` line the app wrote: it is how a push knows which page a path names.
718
-
719
- **The trailing `...` is not decoration — dropping it changes behaviour.** `pages:`
720
- in `folder.yml` and `site.yml`, and `sections:` in `page.yml`, all read it the same way:
721
-
722
- | written | means |
723
- |---|---|
724
- | `[a, b, ...]` | **inclusive** — `a` and `b` pinned in that order, **everything else follows** |
725
- | `['...']` | identical to omitting the key |
726
- | `[a, b]` — no `...` | **strict** — and every unlisted sibling is dropped from **every** menu |
727
-
728
- ⚠️ **Strict is a navigation filter, not a delete, which is what makes it easy to
729
- miss.** Unlisted pages stay routed, stay in `dist/`, stay in `llms.txt` and still
730
- resolve by URL — only the links to them disappear. Your route count does not
731
- change and nothing warns. **If you list pages in order and mean "these first",
732
- end the list with `...`.**
733
-
734
- **Configuration cascades: `page.yml` → `folder.yml` → `site.yml` → foundation defaults.** Each level inherits from the one above and overrides specific values, the way CSS specificity works. This is what makes bulk assignment natural — put `layout: marketing` in a `folder.yml` and every page in that folder inherits it, while one page can still override with its own `page.yml`. Reach for `folder.yml` before editing the same key into a dozen `page.yml` files.
735
-
736
- **Route mapping:** folder structure maps 1:1 to routes. Every folder keeps its natural route — `pages:` controls **order only**, not which child "becomes" the parent. The only exception is the site root, where `index:` (or first in `pages:`) sets `/` — declared in `site.yml`, or in the pages directory's own `folder.yml` / `page.yml` (how a content repo carries its order), with `site.yml` winning.
737
-
738
- **Content-less containers:** folders with `page.yml` but no markdown are structural groups (`hasContent: false`). Visiting one auto-redirects to the first descendant with content — this is what supports courses → modules → lessons at any depth.
739
-
740
- **A local folder for a mounted route says how this site presents it.** Keep `layout:`, `title:` and SEO in a `folder.yml` there; the mounted repo's own `folder.yml` supplies its ordering and title where the stub is silent. A `page.yml` with markdown of its own makes a real page above the mounted pages, a landing page for the branch. A mount is one level under `pages/`, and a subfolder in the local folder isn't read, since the branch's pages come from the mount; the build says so. What a site can't do from outside a repo it mounts: leave a file out, title or order a nested folder, or use a `README.md` as a page. Those are the mounted repo's to do. A relative link to a markdown file (`./deploying.md#setup`), which is how docs in a repo link to each other, leads to the page that file became, built or pushed; the build names one that leads nowhere.
741
-
742
- **SEO & social cards:** set site-wide defaults in `site.yml`; any page overrides per-field in `page.yml` (page wins, site fills gaps). Each page's static `<head>` carries its own tags — Open Graph, Twitter Card, canonical, robots, and hreflang on a multilingual site — so shares and crawlers see them without running JS. The social `image` is the field most worth setting once at site level — a 1200×630 JPEG or PNG, since link previews draw 1.91:1 and most draw no SVG; the site's `description` is the home page's alone, and each page's own reads best under about 160 characters. These tags are the framework's: a `head.html` tag of the same name is replaced. `uniweb doctor` checks what a link shows: the image is there, in a format previews draw and close to 1200×630, and each page has a description of a length search results show whole.
743
-
744
- **The tab icon:** `favicon: /favicon.svg` in `site.yml`, a file in `public/`. Name it even when the file is `public/favicon.svg`: a static build finds `public/favicon.{svg,ico,png}` on its own, but a site published with `uniweb publish` links only the favicon `site.yml` names (`uniweb doctor --fix favicon-unnamed` writes the line).
745
-
746
- **The home-screen icon:** `touchIcon: /touch-icon.png` in `site.yml` — the icon iOS puts on a home screen, which an SVG favicon never is. Make it a 180×180 PNG in `public/` with no transparency: iOS draws a transparent pixel black. Name it even when the file is `public/apple-touch-icon.png`, which iOS finds on a static host by itself: a site published with `uniweb publish` has only the touch icon `site.yml` names. `uniweb doctor` checks the file.
747
-
748
- ```yaml
749
- # site.yml
750
- keywords: [components, react, cms]
751
- seo:
752
- origin: https://acme.com # where the site is served from — only where no host states it
753
- image: /og-default.png
754
- noindex: false # true keeps the WHOLE site out of search
755
-
756
- # page.yml
757
- seo:
758
- image: /og-about.png
759
- canonical: https://acme.com/team # only to name ANOTHER URL — a page is its own canonical by default
760
- ```
761
-
762
- **Where the site lives — every absolute URL is made on it:** a page's canonical and `og:url`, its social image, its sitemap entry, the links in `llms.txt`. It is the site's origin plus its base path, and whoever serves the site states it: the GitHub Pages workflow `uniweb add ci --host=github-pages` writes asks GitHub; Netlify and Vercel state their production URL during the build; on any other static host, set `seo.origin` — a scheme and a host, `https://acme.com`, never with a path (a path is the site's `base:`; `seo.origin: https://user.github.io/repo` is refused). `seo.baseUrl` is retired, and refused. With no address, pages state no canonical, no `sitemap.xml` is written, and the social image and `llms.txt` links are root-relative — `uniweb doctor` says when that is so, and how to fix it for your host.
763
-
764
- **Localized URLs:** on a multilingual site (`languages:` in site.yml), `slug: { <lang>: <segment> }` gives a page a native URL segment per language; the folder name stays the canonical route. Nested folders compose automatically, and localized URLs flow through navigation, the language switcher, and the sitemap. See Part 5 for the translation workflow.
765
-
766
- **Knowledge pages — content for an AI agent, not for a visitor.** `knowledge: true` in a `page.yml` or `folder.yml` marks a page as agent-only: it is **never rendered** — no route, no HTML — and it cascades to the whole subtree by route prefix, so one marker on `pages/kb/` covers everything under it and `/kb` never claims `/kbase`. Write plain markdown; a section `type:` there never selects a component, because nothing renders these pages.
767
-
768
- ⚠️ **A knowledge page is not published to anyone — it powers a service your site offers.** Everything your site *does* publish is published on equal terms: an AI visiting your site sees exactly what a person sees. `llms.txt` and the per-page `.md` files are a convenience for that reader, not a privileged tier — no visitor, human or machine, gets more than another.
769
-
770
- A knowledge page is different in kind, not in audience. It is never a page anyone reads; it is source material for an assistant the site offers **to its visitors** — they ask, they get an answer, and the material behind it stays unpublished. That is why it is kept out of `llms.txt`, the `.md` projections and the search index: not because some readers are trusted less, but because a knowledge page was never a page.
771
-
772
- ⇒ If what you want is "make this readable by any AI that visits", write an ordinary page. It is already published to them, on the same terms as to everyone else.
773
-
774
- ⛔ **`knowledge:` is not a security control — don't put secrets there.** "Not published" is about who the prose is *written for*, not about confidentiality. The assistant's job is to answer visitors using this material and it can quote it back to whoever asks, so a visitor who prompts it can surface what a knowledge page says — **by design, not by leak.** The test for what belongs here is "is this written for the assistant to reason with?", not "do I want to keep this from people?" Anything that genuinely must not reach a visitor doesn't belong in your site's content at all.
775
-
776
- ```yaml
777
- # pages/kb/page.yml
778
- title: Product Knowledge
779
- knowledge: true
780
- ```
781
-
782
- What can actually *read* it depends on where you deploy, because reading it needs a server:
783
-
784
- - **`uniweb deploy`** (backend-hosted) — the content travels with the site, so an assistant running over it can grep and read your knowledge material alongside the public content when answering a visitor's question.
785
- - **`uniweb export` / `uniweb deploy --host <adapter>`** (static host) — **the build drops these pages and says so**: `Dropped 2 knowledge page(s) from this build: /kb, /kb/pricing`. Files are served as files here; there is no assistant, so nothing would read them. The warning means the flag was honoured.
786
-
787
- The artifacts **your build emits** to describe the public site never name them — `llms.txt`, the per-page `.md` projections, and the search index all describe pages a visitor reads, and a knowledge page's prose was written for the assistant instead. Two settings **outrank** `knowledge:`, so a contradiction resolves toward the narrower reach: `agents.exclude` in `site.yml`, and any `_`-prefixed route segment. *(A host that derives these artifacts itself, rather than serving the ones your build produced, applies its own rules — ask your host what it does with `knowledge:` before relying on it there.)*
788
-
789
- Don't confuse it with the visibility flags: `hidden: true` is a **draft** (not published at all), `hideIn` only controls **nav placement** (still reachable by URL: `hideIn: ['*']` leaves it out of every menu, `hideIn: [header]` out of one), and `knowledge: true` is a **different audience** (never rendered for anyone). ⛔ `hidden: true` on `pages/404/` means a **draft 404** — it is not published and the site falls back to the generic `404.html`; an authored 404 needs no flag, since it is never listed in navigation anyway. A **section** takes `hidden: true` in its frontmatter with the same meaning: previewed in `uniweb dev`, left out of a published build with its child sections, and never passed to the component as a param. (`_name.md` is the other way to keep a section out: no build reads it, dev included.)
790
-
791
- **A site can be nothing but knowledge — that is a real and useful shape.** A site is a set of routes; it does not have to have HTML pages. Mark the root `knowledge: true` and every page inherits it, so the site renders nothing at all and exists to *be* an agent: a `/_agent/chat` URL that a web app, a mobile app, or someone else's backend sends requests to.
792
-
793
- ```
794
- site/pages/
795
- ├── page.yml # knowledge: true — cascades to everything
796
- ├── house-style.md
797
- ├── pricing.md
798
- └── support.md
290
+ // meta.js — the catalog entry other agents read and the visual editor's UI
291
+ export default {
292
+ title: 'Feature Grid', description: 'Grid of feature cards with icons',
293
+ family: 'features', // the standard kind it is (`uniweb families`); a name like `Hero` resolves on its own
294
+ // hidden: true · inset: true · section: true · children: true · background: 'self' · sticky: true
295
+ content: { title: 'Heading', paragraphs: 'Intro [0-1]', media: 'Photo [1]',
296
+ items: { label: 'Cards [3-6]', content: { icon: 'Icon [1]', title: 'Name', paragraphs: 'Text' } } },
297
+ params: { columns: { type: 'number', default: 3 },
298
+ variant: { type: 'select', options: ['default', 'centered'], default: 'default' } },
299
+ vars: { 'card-gap': { default: '1.5rem' } }, // CSS-only knobs, emitted on #section-{id}
300
+ data: { articles: '@std/article', // every content.data key the component reads
301
+ article: { schema: '@std/article', single: true, whole: true },
302
+ 'md:faq': 'Questions [3+]', nav: {} }, // {} = the key, no schema
303
+ presets: { compact: { label: 'Compact', params: { columns: 4 } } },
304
+ }
799
305
  ```
800
306
 
801
- Measured on exactly that shape: **the agent corpus holds every page; the public projections hold nothing** — `llms.txt` lists no pages, the search index has 0 entries, and no `.md` files are emitted. Nothing leaks, by construction rather than by configuration, because there is no public surface to leak onto.
802
-
803
- ⛔ **This shape needs a host that actually runs an agent, and deploying is not the same as having one.** Two ways to end up with nothing:
804
-
805
- - **A static host** (`uniweb export`, `deploy --host`) drops every page — they have no reader there — and you get an empty SPA shell. The build still says *"complete"*, because 0 pages is not an error: it reports `Collected 0 pages` and pre-renders none.
806
- - **A backend-hosted deployment that does not offer the service.** Whether an agent endpoint exists is the host's to decide, per site — it is not implied by deploying successfully.
307
+ Where a value lives: a **param** when JS branches on it; a **component var** (`meta.js vars:`) when only CSS reads it; a **foundation var** (`main.js export const vars`) when it must hold across components.
807
308
 
808
- ⇒ **The way to know is to ask, at render:** `isAssistantEnabled()` from `@uniweb/kit` is true only where an agent endpoint is declared. On a site that is *only* knowledge there is no component to ask — so confirm with your host that the agent is enabled for that site before you build an integration against it. If you meant to build an agent endpoint and got silence, this is where to look.
309
+ **Data keys.** A section receives exactly the keys its `data:` declares, each filled by a tagged block, else by a fetch whose `as` (default: the query's name) or schema matches, else `null`. A ref = a list of briefs, the brief's fields at the top (`article.title`); `single: true` = one or `null`; `whole: true` = each section under its name (`article.brief.title`, `article.body.content`). `null`: unfilled, loading (`block.dataLoading`) or failed (`block.dataError[key]`); `[]`: answered, no records.
809
310
 
810
- ### Older versions of docs
311
+ **Tokens.** Semantic (as `text-*`, `bg-*`, `border-*`): `heading body subtle section card muted border ring link link-hover primary primary-foreground primary-hover primary-border secondary(…) success warning error info` (+ `-subtle`). Palette: `primary | secondary | accent | neutral` × `50…950`, from `theme.yml colors` (your hex is shade 500; buttons use 600). Tailwind `dark:` tracks the site scheme only with `@custom-variant dark (&:where(.scheme-dark, .scheme-dark *));`.
811
312
 
812
- Most docs need one version. When a release is about to stop being the latest and its readers need its docs kept, run `uniweb add version v2` (`--in <folder>`, `--label "2.x"`). It copies the docs to a folder named `v2` beside them, at `/docs/v2/…`, with the copy's links leading to the copy, no page ids in it, and search engines told to leave it out. Keep writing where you were: the pages beside version folders are the latest, and their URLs never change. Don't copy a version folder by hand. A foundation draws versions with kit's `useVersion`: `versions` for a switcher (`version.href` is where each leads from this page, for `<Link>`), `isOlderVersion` and `latestVersion` for a notice, and `hierarchy({ for: 'left' })` for a menu of one version, which is the whole tree on a site with none. See [versioning](https://github.com/uniweb/docs/blob/main/reference/versioning.md).
313
+ **Composition.** Items (repeating groups in one file) · `md:tag` concept blocks · child sections (`@file.md` + `nest:`, rendered with `<ChildBlocks from={block} />`; `children: true`) · insets (`![](@Component)` via `<Visual>`; `inset: true`) · block insets (` ```@Component ` fence) · `---` + `splitContent(content)` for regions (it splits `sequence` only). Author writes inside it → child section or block inset; self-contained → inset; repeating → items.
813
314
 
814
- ### Your site is readable by agents, automatically
315
+ ## 6. Guides
815
316
 
816
- Every build emits two things an AI agent can use directly, alongside the HTML. **Free, on by default, nothing to install.**
317
+ Every guide ships with the CLI this project pins, so it describes the version in front of you. Step 6 runs `content` or `foundation` before any writing; you will know when you need the rest. `uniweb guide` alone lists them.
817
318
 
818
- | Artifact | What it is |
319
+ | When you… | Run |
819
320
  |---|---|
820
- | `/llms.txt` | An annotated index of the site — every page, with a one-line description, linking to the `.md` below |
821
- | `/{route}.md` | Each page as clean markdown: the content, no navigation, no chrome |
822
-
823
- The point is the pair. An agent fetches the index, *reads* what each page is about, and goes straight to the one it needs — two requests, no HTML stripping, no guessing at URLs. Descriptions come from `page.yml`'s `description:`, then `seo.ogDescription`, then the page's opening paragraph, so a site usually gets a complete index without writing any of them.
824
-
825
- **Large sites also get per-branch indexes.** A branch with at least 5 pages gets its own — `/docs/llms.txt` lists just the docs, titled by that folder. The site index still lists everything; a branch index is an extra entry point, not a replacement, so an agent that starts at `/llms.txt` still reaches any page in two hops.
826
-
827
- **Each language gets its own.** A site in several languages has `/fr/llms.txt` beside `/llms.txt`, listing the French pages, record pages included, and linking each at its French address (`/fr/a-propos.md`). Its search index is per language the same way (`/fr/search-index.json`).
828
-
829
- ```yaml
830
- # site.yml — all optional; these are the defaults
831
- agents:
832
- index: true # /llms.txt
833
- markdown: true # /{route}.md
834
- branchIndexes: true # /docs/llms.txt for branches big enough to want one
835
- branchMinPages: 5 # how big is big enough
836
- exclude: [/internal] # keep a branch out of both (cascades)
837
-
838
- agents: false # or turn the whole thing off in one word
839
- ```
840
-
841
- #### Expecting agent traffic from somewhere specific
842
-
843
- If your site runs an agent (see *Knowledge pages* above), you can declare where its requests are expected to come from. Useful when the site exists to serve someone else's app rather than its own visitors — a chat endpoint your web app calls.
844
-
845
- ```yaml
846
- # site.yml
847
- agents:
848
- expectedOrigins:
849
- - https://app.example.com
850
- - https://partner.example.org
851
- ```
852
-
853
- **It is a declaration, not a gate — the name is the contract.** You are telling the host where you expect callers from; a host that offers an agent may then decline requests whose browser-sent `Origin` is not one of them, before it spends anything answering. Behaviour where it is honoured:
854
-
855
- | | |
856
- |---|---|
857
- | not declared | no check at all — nothing happens unless you ask for it |
858
- | your own site's origin | always fine, without listing it — declaring a partner must not take down your own chat box |
859
- | a request with **no** `Origin` | **allowed** — see below, this is deliberate |
860
- | matching | by origin: `https://app.example.com/` is `https://app.example.com`, and a path is ignored; no wildcards. An entry that is not an `http(s)` URL matches nothing |
861
-
862
- ⛔ **It is not a spend limit, and it cannot be.** `Origin` is set by the browser and enforced by the browser: anything that is not a browser sends whatever it likes, or nothing at all. So this stops **casual misuse and third-party embedding** — someone dropping your endpoint into their own page — and it does **not** stop anyone determined to run up your bill. Do not size your budget on it.
863
-
864
- ⭐ **And that is why a request with no `Origin` is allowed rather than refused.** There are two shapes of caller and this check only sees one:
865
-
866
- - your app's **JavaScript**, in a browser — sends `Origin`, covered here;
867
- - your app's **server**, calling from its own backend — never sends one, and refusing it would break the integration this feature partly exists for.
868
-
869
- Server-to-server callers are authenticated by other means, arranged with your host — not by anything in `site.yml`. **Never put a shared secret in `site.yml`:** everything in it is delivered to every visitor as part of the site payload.
870
-
871
- ⚠️ Spelling matters and nothing downstream will catch it — the block is forwarded to your host as opaque data, so a typo is carried and simply never acted on. `uniweb doctor` flags unknown keys in `agents:` for exactly this reason; run it before you rely on one.
872
-
873
- **The index links absolutely on the site's address** (see *Where the site lives*) — without one the links are root-relative, which still works for an agent that arrived via the index. Each record of a parametric page is listed as a page, with a `.md` of its own.
874
-
875
- **What's excluded, and it's deliberate:** `seo.noindex` pages, `hidden` pages, `_`-prefixed drafts, and a parametric page's URL pattern (`/blog/:slug`). An index *describes* pages rather than merely listing them, so an unlinked page would become both discoverable and summarized — which is why these exclusions are load-bearing rather than tidy-up. `noindex` or `hidden` on a **folder** takes the whole branch with it.
876
-
877
- **Declaring how your content may be used** is a separate axis from whether it may be fetched, and it goes in `seo.robots`:
878
-
879
- ```yaml
880
- # site.yml
881
- seo:
882
- robots:
883
- contentSignals:
884
- search: true # may appear in search results
885
- ai-input: true # may be retrieved at inference time
886
- ai-train: false # may not be used to train a model
887
- ```
888
-
889
- That emits a `Content-Signal:` line in `robots.txt`. Declare only what you mean — an omitted signal says nothing, which is not the same as saying no.
890
-
891
- ### Records, queries and parametric pages
892
-
893
- Most content lives in `pages/` — a fixed composition of sections on a fixed set of pages. **The other kind is a set of records: repeating content managed as one file per item**, that pages pull from. Blog posts, team members, products, case studies, bibliographies.
894
-
895
- It is a small database, not a page tree. Three things, deliberately separate:
896
-
897
- ```
898
- site/
899
- ├── pages/
900
- ├── records/ # your site's records — every file in a schema folder is one
901
- │ ├── article/ # the folder names their data schema
902
- │ │ ├── getting-started.md
903
- │ │ └── design-tips.md
904
- │ ├── person/
905
- │ │ └── alice.yml
906
- │ └── folder.yml # optional: sorts records into folders
907
- ├── queries.yml # how content is REACHED
908
- └── site.yml
909
- ```
910
-
911
- **`records/{schema}/` — the site's records.** Putting a file here is what makes it a record; nothing else lists it. The folder names the data schema and nothing else:
912
-
913
- | on disk | schema |
914
- |---|---|
915
- | `records/article/…` | `@/article` — your foundation's own |
916
- | `records/std/person/…` | `@std/person` — the shared standard set |
917
- | `records/acme/project/…` | `@acme/project` — an org's |
918
-
919
- Keep those folders flat: `records/article/design-tips.md` works; `records/article/2025/design-tips.md` is read as the `2025` schema of an `article` org, which is not what you meant. Organise in `records/folder.yml` instead. A file whose name starts with `_` is not a record — somewhere to keep work in progress.
920
-
921
- **Links are records too — `@uniweb/link`.** A file in `records/uniweb/link/` holding `url:` and nothing else is a link record (one per file; no body, no other fields). Its display text and tags go on its `records/folder.yml` entry (`- path: uniweb/link/launch-video.yml` with `label:` / `tags:`), like any record's. Select links with a query `schema: '@uniweb/link'` and declare them in `meta.js` as `data: { videos: '@uniweb/link' }`; each arrives as `{ url, $name, $label, $tags }`. A link's `url` is absolute (`https://…`), and `uniweb push` refuses a relative one and a `draft: true` link.
922
-
923
- **Files are records too — `@uniweb/file`.** The file itself is the record: any file dropped into `records/uniweb/file/` (a PDF, a spreadsheet, any type) is a record named by its file name without the extension; nothing in it is read. Its label and tags go on its `records/folder.yml` entry (`- path: uniweb/file/brochure.pdf`). Query with `schema: '@uniweb/file'`, declare with `data: { downloads: '@uniweb/file' }`; each arrives as `{ file: { url, name, mime, size }, $name, $label, $tags }` — link to `file.url`. `uniweb push` uploads the file with the site's media; a pull fetches it back. Two files of one name with different extensions clash — rename one. On a site that goes to a backend, a component must declare the type (`@uniweb/link` or `@uniweb/file`) for a query over it to be accepted.
924
-
925
- **Four formats, one shape.** All of these produce the same records at runtime:
926
-
927
- | Format | Best for | Notes |
928
- |---|---|---|
929
- | `.md` | Items with prose — articles, case studies | Frontmatter holds fields, body holds text; auto-excerpt and first-image extraction |
930
- | `.yml` / `.yaml` | Structured records with no prose body — team, products | Cleaner than a markdown file with an empty body |
931
- | `.json` | Same as YAML | When the data comes out of another tool |
932
- | `.bib` | Bibliographies | Each `@entry{key, …}` is a record, its cite key its name (`$name`); normalized to CSL-JSON, LaTeX accents converted to Unicode |
933
-
934
- **One record per file.** A file's name is its record's name (`records/team/alice.yml` is `alice`); a `slug:` key at its top, or a file holding a list, stops the build — to rename a record, rename its file. A `.bib` file holds many entries, each named by its cite key. **A component reads a record's name as `$name`** — the one name it carries on every site; the delivered record has no `slug`. You can mix both in one folder — an exported `refs.bib` beside a hand-written `extras.yml`.
935
-
936
- Item frontmatter conventionally uses `title`, `date`, `tags`, `image`, `description`, `author` — plus any fields your content needs (`price`, `role`, `order`). Images can sit beside the item file and be referenced with `./`. **`draft: true` keeps a record off the live site without deleting it**: it is still a record, in `records/`, and `pnpm dev` shows it so you can preview it, but a build for hosting leaves it out, and a backend you `uniweb push` it to keeps it in the site's folder without delivering it. (`published: false`, an older spelling, is refused.)
937
-
938
- **A record's file follows its data schema's sections.** A schema with one section (the `fields:` form) is written flat, as above. A schema with more than one is written **by section** — each field under its section's name — and a field left at the top stops the build and a push, naming where it goes. `@std/article` has two, its card `brief` and `body`:
939
-
940
- ```markdown
941
- <!-- records/std/article/hello.md -->
942
- ---
943
- brief:
944
- title: Hello
945
- author: Ada
946
- date: 2026-05-01
947
- ---
948
-
949
- The body — the value of the schema's content field, `body.content`.
950
- ```
951
-
952
- **A component receives it in one of two shapes, and its `meta.js` says which**, per `data:` key — the same on a static site and a hosted one. `data: { articles: '@std/article' }` gets **briefs**: the brief's fields at the top (`article.title`), no other section. `data: { articles: { schema: '@std/article', whole: true } }` gets each record **whole**, as stored: every section under its own name, the brief's included (`article.brief.title`, `article.body.content`). Both carry `$name`, the handle. Lists carry briefs; a section that shows a record in full declares `whole: true`. A `fields:` schema's brief is the whole record, so its components need no `whole: true`. Full rules: `reference/entity-content.md`.
953
-
954
- **A reference names the record it points at.** A `{ ref: '@/speaker' }` field is written as that record's name — `speaker: ada` for `records/speaker/ada.yml` (its file's name) — and a `many` one as a list of names. A component receives `{ entity, brief }`: the record reduced to its brief, so `talk.speaker.brief.name`. `uniweb validate` and a push report a name that matches no record; a push sends each reference to the record it names (in the same push when that record is new too), and a pull writes the name back.
955
-
956
- **`records/folder.yml` — optional, and only for folders.** It is the one file in `records/` that is not a record, it moves with the directory (`paths.records`), and like a pages folder's `folder.yml` it describes the folder it sits in. Every record sits at the top of the site's records folder unless `folder.yml` places it in a sub-folder. Add one only when a query needs to ask for a *slice* of the records rather than all of them — most sites never do:
957
-
958
- ```yaml
959
- - folder: archive
960
- label: The Archive
961
- records:
962
- - article/2025-*.md
963
- ```
964
-
965
- A path under a folder is relative to `records/`, naming one file or matching many. A record's entry can instead be `{ path, tags, label }` — what the folder says about the record: a component receives them beside it as `$tags` (in the order written) and `$label`, and a query reads them like any key (`where: { $tags: featured }`); such an entry may sit at the top level, where a bare path is refused. A `label` — a record entry's or a folder's — is one text in the site's language, or one per language (`label: { en: Launch video, fr: Vidéo de lancement }`); `$label` is the page's language, else its base language, else the site's. A folder takes `tags:` too. A query reads one folder with `scope: archive` — the folder and everything inside it. A record sits in one folder; if you want a computed subset, that is a query, not a second placement. Structure is for querying, not for navigation — and `folder.yml` never lists a record at the top level (the build refuses it: every file in `records/` is a record already).
966
-
967
- ⚠️ **With a backend, `records/` is what `uniweb push` sends** — every record in it. A site with no `records/` at all leaves the backend's records alone; an *empty* `records/` removes them, and the CLI asks before it does. Records pushed to a backend are served once the site is published: a record with a data schema reaches the published pages only when `services:` asks for `records: true`, and one with none travels as the published site's files.
968
-
969
- **`queries.yml` — how content is reached.** A bare map of name → query. A query names a schema and the site's records of that schema are its rows:
970
-
971
- ```yaml
972
- recent:
973
- schema: '@/article'
974
- sort: date desc # `date desc`, `title asc`, …
975
- limit: 10
976
-
977
- team:
978
- schema: '@std/person'
979
- where: { active: true } # a predicate — see authoring/predicates.md
980
- ```
981
-
982
- You can keep the same declarations under `queries:` in `site.yml` instead, if you would rather have one file.
983
-
984
- **Show a query on a page** with `query:` in `page.yml` or a section's frontmatter (the whole result), or `fetch:` for anything more — a `limit`, a `where`. A list — `query: [team, articles]` — declares several, each filling its own key in the sections whose components declare it. `query:` takes names only; `data:`, its old name, is now an error.
985
-
986
- **Who receives it:** a section's own declaration reaches that section; a page's, every section on the page; a parent page's, the sections of the pages directly under it. **The site is the root page:** `query:` in `site.yml` reaches the layout areas (header, footer, …) and the sections of top-level pages — the homepage included — and no page further down. A section on `/docs/setup` that needs site-wide data names the query itself.
987
-
988
- **A fetch always names a query.** A string in `fetch:` is a query name: `fetch: team` is `fetch: { query: team }`, and `fetch: [team, articles]` is a list of those. A fetch never names a file — `/data/<query>.json` is what the build generates from a query for a site with no backend, and writing that path in a `fetch:` stops the build. That is what keeps a site portable: name the query, debug locally against the generated data, publish, and the same page reads live records from the host with nothing changed.
989
-
990
- **A query selects a set of records; a `fetch:` takes from that set, never adding to it.** The query's `scope`, `where`, `sort` and `limit` decide which records it selects — its `limit` included: `recent` above is the 10 newest articles. A fetch's `where` keeps the ones that also match, its `sort` re-orders them, and its `limit` takes the first N — never more than the query selects. That is the whole list — `scope` belongs to the query, and the build stops on a `fetch:` that carries one; for another folder branch, declare another query. **Which records get a page is the query's to decide, never a fetch's:** each record `recent` selects gets its page, an 11th-newest article gets none, and a list's `limit: 3` still leaves all 10 their pages — so a condition or count that should decide which pages exist belongs on the query. Two fetches under one key at one level: the first is used, and the build warns.
991
-
992
- ```yaml
993
- # pages/blog/page.yml | # a section on the homepage
994
- title: Blog | ---
995
- query: recent | type: ArticleTeaser
996
- | fetch: { query: recent, limit: 3 }
997
- | ---
998
- ```
999
-
1000
- **Give each record its own page with a `[slug]/` folder** — a *parametric page*, what other frameworks call a dynamic route — inside the page that names the query:
1001
-
1002
- ```
1003
- pages/blog/
1004
- ├── page.yml # title: Blog / query: recent
1005
- ├── list.md
1006
- └── [slug]/
1007
- ├── page.yml
1008
- └── article.md # just `type: Article` — the record arrives automatically
1009
- ```
1010
-
1011
- `records/article/design-tips.md` becomes `/blog/design-tips`. The section inside `[slug]/` needs no special markdown — the matched record is delivered to it. Generated pages are excluded from navigation menus.
1012
-
1013
- **Link a card with `item.$route` — never compose the URL.** Every record a query delivers carries `$route`, the URL of the parametric page whose route query is that query (`/blog/design-tips`), wherever the list appears — the query's own page, the homepage, a sidebar. No page for the query, or no value for the field its URL is built from, means no `$route`, never a broken one. `detailPage: page:<id>` on a fetch links the records to another page instead. `$` marks a field the framework fills, so a record's own `route` field is left alone. ⛔ `route:` on a query is retired and stops the build.
1014
-
1015
- **Which query the URL narrows — the page's route query:** the `[slug]` page's own `query:`, else its parent page's (the usual shape, above), else `site.yml`'s (for a top-level `pages/[slug]/` only — the site's reaches no deeper page); if none declares one, the query its sections all declare. The first query of that level wins. Every section the route query reaches gets the one record; a section declaring a *different* query of its own gets that query as declared. The folder name says what the URL segment matches: `[slug]` the record's name (`$name`, a compiled record's file name) — or the field its route query binds `:slug` to (`where: { slug: :slug }`, how an external API's records, which have no `$name`, get pages), `[uuid]` its `$uuid`, any other `[name]` the record's own field of that name — and when that field holds several values, **any member** matches (the record's own link is its first value). Routing by a field that is not unique picks one record and which one is not guaranteed; the build warns. A folder inside `[slug]/` (`[slug]/cv/` → `/blog/:slug/cv`) is a parametric page too, about the same record: its route query is the `[slug]` page's, wherever that is declared, and a query `cv/` declares itself arrives under its own key. **A section chooses how it uses the page's record with `current:`** on its own `fetch:` — `only` (the default: the record), `exclude` (the others: "related"), `include` (all of them: a pager) — e.g. `fetch: { query: articles, as: related, current: exclude, limit: 3 }`, where `limit` counts the others, all from the query's set. **`current:` follows the query, not the key:** a fetch of the route query gets the record unless it says otherwise, whatever its `as`; a fetch of another query gets that query's records and reads `current:` only when written (`exclude` drops the page's record, `only` keeps just it). `refine: true` / `detail: false` are retired and stop the build. `[dir]` and `[path]` are refused as folder names, and so is any folder inside `[...path]/`.
1016
-
1017
- > **The record arrives under the key the component declares, as that key says** — one record for a key declared `single: true` (`content.data.article` for `article: { schema: '@std/article', single: true }` over an `@std/article` query; `null` when the URL names none), a single-element array for any other key (`content.data.recent[0]`). It is the record's brief, or the record whole where the key declares `whole: true` — a section that shows an article's body declares `whole: true`. See *Data* in Part 4.
1018
-
1019
- **Records with URLs of their own shape — `[...path]/`.** A folder named exactly `[...path]` (one fixed spelling) captures the rest of the URL: `/blog/my-post` and `/blog/rust/2025/my-post` both reach it. The capture yields three standard variables — `:path` (the whole capture), `:dir` (everything before the last segment), `:slug` (the last segment, the record's handle) — and the record is still delivered by its handle, so the section reads it as before. The same three variables exist under every parametric page: under `[slug]`, `:slug` and `:path` are the segment and `:dir` is empty. A record's own URL (`$route`, and the page a static build writes) is its name, as under `[slug]`: `/blog/my-post` wherever `records/folder.yml` places it — a record does not carry its folder. A query may bind a part — `scope: :dir` exposes the folder branch, `where: { tag: :dir }` keeps it private — and an unbound or empty variable drops its clause, so one saved query serves the query's page and its parametric page, on a static site and a hosted one alike. Without `scope: :dir` the directory is decoration: the record is found by its handle wherever it sits. Reference: `reference/dynamic-routes.md`.
1020
-
1021
- **Two options for bigger sets:**
1022
-
1023
- A list carries briefs, so a schema that keeps its heavy parts out of the brief — `@std/article`'s body is its own section — keeps lists light with no configuration, while a section declaring `whole: true` still receives the whole record on a `[slug]` page, and other components fetch it on demand with `useWholeRecord`. File-based records are written one file per record, whole, at `/data/<name>/<name of the record>.json`; an external query names its one-record request with `record:` instead (*Fetching from other sources* in Part 4). (`deferred:` is removed: a schema's brief decides what a list holds.)
1024
-
1025
- `queryable:` declares which fields a reader may filter on, with enough metadata for the foundation to render controls:
1026
-
1027
- ```yaml
1028
- # queries.yml
1029
- members:
1030
- schema: '@std/person'
1031
- queryable:
1032
- department: { type: enum, label: Department, options: [biology, physics, chemistry] }
1033
- tenured: { type: boolean, label: Tenured }
1034
- start_year: { type: range, label: Start year, min: 1800, max: 2025 }
1035
- ```
1036
-
1037
- The site declares the *surface*; the foundation reads the metadata, renders matching controls (dropdown, toggle, slider), and composes the predicate when the reader picks values.
1038
-
1039
- Full author guide: `authoring/collections.md`. Every key a query takes: `reference/queries.md`. Predicate operators: `authoring/predicates.md`.
1040
-
1041
- ---
1042
-
1043
- ## Part 4 — The foundation lane
1044
-
1045
- You're not building pages — you're building a **system** of section types that authors compose into pages. Name by purpose, not content: `Testimonial` not `WhatClientsSay`, `SplitContent` not `AboutSection`. Expect consolidation: a React site with 30+ components typically maps to 8–15 Uniweb section types.
1046
-
1047
- ### Where things go
1048
-
1049
- ```
1050
- src/ # the foundation package (folder name is `src`)
1051
- ├── sections/ # Section types (auto-discovered)
1052
- │ ├── Hero.jsx # Bare file — no folder needed
1053
- │ ├── Features/ # Folder when you need meta.js
1054
- │ │ ├── index.jsx
1055
- │ │ └── meta.js
1056
- │ └── insets/ # Organizational subdirectory (lowercase)
1057
- ├── layouts/ # Custom layouts (optional, auto-discovered)
1058
- ├── components/ # Your React components — any props you like, no meta.js
1059
- ├── utils/ # Helper functions, non-React logic
1060
- ├── main.js
1061
- ├── styles.css
1062
- └── package.json # name: "src"
1063
- ```
1064
-
1065
- **Discovery:** PascalCase files and folders at the root of `sections/` are auto-discovered. Nested levels require a `meta.js`. Lowercase directories are organizational only. `hidden: true` excludes a component entirely. Everything outside `sections/` and `layouts/` is ordinary React.
1066
-
1067
- **JSX goes in `.jsx` files** (or `.tsx`). Discovery also accepts a `.js` component, but only one without JSX: JSX compiles in no `.js` file, and the build stops on one, naming the file to rename.
1068
-
1069
- **Source root.** The foundation package's source lives at the package root — the `src/` folder *is* the foundation. The build reads `package.json::main` (for new scaffolds, `main: "./_entry.generated.js"`). Older foundations nest source in `foundation/src/` with `main` pointing at `./src/_entry.generated.js`; both work through the same code path.
1070
-
1071
- **Import aliases.** Foundations include subpath imports for shared internals — use them instead of brittle relative paths:
1072
-
1073
- | Alias | Maps to | Use for |
1074
- |-------|---------|---------|
1075
- | `#components/*` | `./components/*` | Shared React components |
1076
- | `#utils/*` | `./utils/*` | Helper functions, non-React logic |
1077
-
1078
- ```jsx
1079
- import LessonHeader from '#components/LessonHeader' // ✅
1080
- import LessonHeader from '../../components/LessonHeader' // ❌ breaks if you reorganize sections/
1081
- ```
1082
-
1083
- Within the same directory, use normal relative imports (`./AIFeedbackCard`).
1084
-
1085
- **Foundation entry (`main.js`).** A single `export default { … }` whose top-level keys are the foundation's identity — `name` (what it registers as, `@org/<name>`) and `description` — and the capabilities it provides — `defaultLayout`, `defaultSection`, `viewTransitions`, `defaultInsets`, `xref`, `outputs`, `handlers` — plus an optional named `vars` export. The capabilities are read at render; the one thing a foundation declares that *isn't* — which host services it supports — lives in `package.json` instead (see [Declaring what your foundation supports](#declaring-what-your-foundation-supports)). Section types and layouts are auto-discovered and merged in by `@uniweb/build`. The build carries into `default.capabilities` in `dist/entry.js` only what a published page reads of your default export — the code it calls (`handlers`, `defaultInsets`, `xref`, `transports`, `outputs`) and its data, lean (`defaultLayout`, `defaultSection`, `viewTransitions`, `scroll`, each var's `default`, `type` and `applyTo`, each `data:` key's schema ref). `name`, `description`, a var's label or description and any key the framework does not read stay out of the published bundle: they are for the editor, which reads them from the foundation's schema. You never write that wrapper. The file is `main.js` — never `main.jsx`, which the build refuses — and it is plain JavaScript: a component it declares (in `defaultInsets`, `xref`) lives in a `.jsx` file it imports. The one place it matters: when you import your **own** `main.js` from a component (e.g. a download button calling `compileDocument(website, { foundation })`), you get the bare default object — pass it through directly, Press handles both shapes.
1086
-
1087
- ### Props interface
1088
-
1089
- ```jsx
1090
- function MyComponent({ content, params, block }) {
1091
- const { title, paragraphs, links, items } = content // Guaranteed shape
1092
- const { columns, variant } = params // Defaults from meta.js
1093
- const { website } = useWebsite() // Or block.website
1094
- }
1095
- ```
1096
-
1097
- **Frontmatter becomes `params` — except the names framework keeps for itself.** Every section can be given these, whatever its type, and none of them reaches your component as a param. So **never declare one in `meta.js` `params:`** — a component that does never receives what an author writes.
1098
-
1099
- | in a section's frontmatter | what it is | a component reads it from |
1100
- |---|---|---|
1101
- | `type`, `id`, `hidden` | the section itself — its section type, its id, and a draft (`hidden: true`: left out of a published build, kept by `uniweb dev`) | — |
1102
- | `query`, `fetch` | the section's data | `content.data`, under the keys its `meta.js` `data:` declares |
1103
- | `theme`, `background`, `grid`, `vars`, `sticky` | the section's settings, which framework applies — the color context and the background around your component, the section's theme and your component's CSS variables in the page stylesheet, the child layout, and whether the section stays in view as the page scrolls | `block`, when the component needs one for its own logic: `useColorContext(block)` for the context (a light vs. dark logo, say), `<SectionBackground block={block} />` to draw the background itself, `<ChildGrid from={block} />` for the grid, `block.sticky` for whether it sticks |
1104
- | `props` | params written as one map | `params` — its keys are merged in, one by one |
1105
- | `data`, `preset`, `input` | nothing: `data:` is refused (it was `query:`'s old name); `preset:` and `input:` are ignored with a warning | — |
1106
-
1107
- The build warns when `params:` declares any of them. A preset may still set `theme` or `background` — a preset's params are written into the section's frontmatter when an author starts a section from it, so `dark: { label: 'Dark', params: { theme: 'dark' } }` is a dark section. Every other key is a param, declared or not; components ignore the ones they don't use.
1108
-
1109
- ### Rendering content with Kit
1110
-
1111
- Content fields are **HTML strings** — they contain `<strong>`, `<em>`, `<a>` from markdown. **Never render them with raw `{content.title}` in JSX** — that shows HTML tags as visible text. Use Kit components:
1112
-
1113
- ```jsx
1114
- import { H1, H2, H3, P, Span } from '@uniweb/kit'
1115
-
1116
- <H1 text={content.title} className="text-heading text-5xl font-bold" />
1117
- <H2 text={content.subtitle} className="text-heading text-2xl" />
1118
- <P text={content.paragraphs} className="text-body" />
1119
- <Span text={listItem.paragraphs[0]} className="text-subtle" />
1120
- ```
1121
-
1122
- These strings are safe to render as HTML because the parser builds them from structure and escapes every character of the text. **A string from anywhere else is not** — a field a member wrote, a value an API returned. Render it as text: `{value}` in JSX, or `<PlainText text={value} />`.
1123
-
1124
- Kit provides `H1`–`H6`. These render their own HTML tag — **don't wrap them**: `<H2 text={…} />`, not `<h2><H2 text={…} /></h2>`.
1125
-
1126
- **Full content rendering** (article/docs sections where the author controls the flow):
1127
-
1128
- ```jsx
1129
- import { Section, Prose } from '@uniweb/kit'
1130
-
1131
- <Section block={block} width="lg" padding="md" /> // the whole section, on its own
1132
- <Prose content={content} block={block} /> // or only its prose, in your own markup
1133
- ```
1134
-
1135
- `Prose` renders from the parsed sequence — 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**; access them via `content.data` for custom rendering. Pass `content` (needs `.sequence`), and `block` too if the content uses insets. Also works as a pure typography wrapper: `<Prose>{children}</Prose>`.
1136
-
1137
- `Article` is `Prose` in a semantic `<article>` element — the same rendering, for content that is a self-contained document.
1138
-
1139
- ### The Kit, by use case
1140
-
1141
- Names only — for signatures and props, read the package: it's on disk at `node_modules/@uniweb/kit`, and `reference/kit-reference.md` has the full API.
1142
-
1143
- **Text:** `H1`–`H6`, `P`, `Span`, `Div`, `Text` (with `as`)
1144
- **Content:** `Section`, `Prose`, `Article`, `Render` (ProseMirror → React), `ChildBlocks`, `splitContent()`
1145
- **Media:** `Visual` (a `content.media` item by its kind; or the first of inset/video/image), `Image`, `Media` (video), `Icon`, `Asset`
1146
- **Navigation:** `Link`, `useActiveRoute()`, `useWebsite()`, `useRouting()`
1147
- **Header/layout:** `useScrolled(threshold)`, `useMobileMenu()`, `useAppearance()`
1148
- **Overlays:** `Overlay` (modals, palettes, drawers, toasts — portals out of the layout, contains focus; read the note below before hand-rolling one)
1149
- **Keyboard:** `useShortcut('mod+k', fn)`, `useShortcuts({…})`, `useShortcutLabel('mod+k')` — `mod` is Cmd on Apple platforms and Ctrl elsewhere, and the label renders per-platform so a hint never shows the wrong key
1150
- **Long-form prose:** `<Prose>` and the container you put `<Render>` output in both use kit's `prose` classes. One line in the foundation's `styles.css` supplies the rules, colored by the section's theme:
1151
-
1152
- ```css
1153
- @import "@uniweb/kit/prose-tokens.css"; /* kit's prose layer, wired to theme.yml */
1154
- ```
1155
-
1156
- Nothing to install. **Skip the import and prose is completely unstyled** — lists lose their bullets and numbers, and text its typography — while the markup looks right. The foundation build warns about it, and `uniweb 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`'s `vars` to declare them. `<Prose>` and `<Article>` fill their box (`max-w-none`), so `prose-measure` reaches only a `prose` element written without it — set their width on the box around them. A utility class or an element variant (`prose-headings:tracking-tight`, `prose-a:no-underline`) overrides any rule; `prose-a:` leaves a content button its own look. There are no palette modifiers and no `prose-invert` — the colors are already the theme's, light and dark.
1157
-
1158
- **Documentation shells:** `useHeadings()` (the page's headings + the one being read, derived from content so it prerenders), `website.getBranchHierarchy({ route, for })` (the page tree for one branch). Kit ships no ready-made layout — a layout is your foundation's design; write it in `src/layouts/` and use these for the behaviour.
1159
- **Layout helpers:** `useGridLayout(columns, { gap })`, `useAccordion({ multiple, defaultOpen })`
1160
- **Theming data:** `useThemeData()`, `useColorContext(block)`
1161
- **Data fetching:** `useFetched`, `useCacheEntry`, `useWholeRecord`
1162
- **Forms:** `useFormValues` (an author-designed form's state), `valueAt(values, path)`, `useFormSubmit`, `submitForm`, `resolveSubmitTarget` — see *Forms* below
1163
- **Utilities:** `cn()`, `SafeHtml`, `SocialIcon`, `filterSocialLinks(links)`, `getSocialPlatform(url)`, `getLocaleLabel(locale)`
1164
- **Other styled:** `Code`, `Alert`, `Table`, `Details`, `Divider`, `Disclaimer`
1165
-
1166
- Four things you won't discover by reading exports:
1167
-
1168
- > **Content fields are HTML strings.** Covered above — it's the single most common rendering bug.
1169
-
1170
- > **`<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"` automatically, and `reload` forces a full page load.
1171
-
1172
- > **`cn()` gotcha — a later `text-<size>` silently drops an earlier `leading-*`.** Tailwind's size classes set line height too, so `cn()` treats the size as replacing the leading: `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]`). Most likely to bite when the size comes from a lookup and the leading sits in a shared base string.
1173
-
1174
- > **Kit hooks are SSR-safe by design.** If you hit "document is not defined" during a build, don't add `typeof document` guards — reach for the hook instead (`useAppearance()` for scheme, `useScrolled()` for scroll position).
1175
-
1176
- > **A modal needs `<Overlay>`, not a bigger z-index.** The runtime gives each layout area its own `view-transition-name` so header, rails and body animate independently, and that makes each area a stacking context: a `fixed` dialog inside one is still placed against the viewport, but whatever z-index it carries, it paints at its area's place in the stack. Areas sit above the body, so a dialog opened from a section paints *under* the header and footer, and one opened from your Header paints under a footer or sidebar on the header's layer that comes after it. Raising the number looks like it should work and never does. `<Overlay onClose={close}>…</Overlay>` renders into `document.body`, where the z-index means what you expect.
1177
- >
1178
- > It also does the part that is easy to skip: a modal overlay **contains focus** — moves focus in, cycles Tab within, marks the rest of the page `inert`, and returns focus to whatever opened it. That is what makes the `role="dialog" aria-modal="true"` on your box true rather than merely asserted; without it a keyboard user Tabs straight out into a page a screen-reader user has been told is unreachable. Plus Escape, the scrim click, the scroll lock, and a dimmed scrim you override with `className` (`bg-transparent` removes it). `modal={false}` for a toast: it escapes the stacking context and nothing else, so the page stays usable. Your dialog's markup stays yours.
1179
-
1180
- ### Icon component
1181
-
1182
- ```jsx
1183
- {content.icons.map((icon, i) => <Icon key={i} {...icon} />)} // From content
1184
- <Icon name="search" /> // Lucide (default)
1185
- <Icon name="hi2-arrow-right" /> // Other library by prefix
1186
- <Icon name="close" /> // Built-in (no network)
1187
- ```
1188
-
1189
- Built-ins (instant, no network): `check`, `close`, `menu`, `chevronDown`, `chevronRight`, `externalLink`, `download`, `play`, and a few others. Other props: `svg`, `url`, `size` (default `'24'`), `className`.
1190
-
1191
- ### Section wrapper
1192
-
1193
- The runtime wraps every section in `<section>` with its context class and background. Customize with static properties:
1194
-
1195
- ```jsx
1196
- function Hero({ content, params }) {
1197
- return <div className="max-w-7xl mx-auto px-6">…</div>
1198
- }
1199
-
1200
- Hero.className = 'pt-32 md:pt-48' // adds classes to the runtime wrapper
1201
- Hero.as = 'div' // changes the wrapper element
1202
- export default Hero
1203
- ```
1204
-
1205
- **A section's wrapper is a bare `<section>`**, with no padding of its own to reset. `className` adds classes to it, and `as` changes its tag. The built-in layout already wraps the header area in `<header>` and the footer area in `<footer>`, so there `Header.as = 'header'` gives a header in a header. Use `as` to say something the layout doesn't:
1206
-
1207
- ```jsx
1208
- Header.className = 'border-b'
1209
- Header.as = 'div'
1210
- ```
1211
-
1212
- **A header that stays in view is a setting, not a class.** `sticky top-0` on your component's outermost element does nothing: a sticky element moves only within its parent, and the section's wrapper and the area's are as tall as your header. (An element inside your component is different: a form beside a long list sticks within the row the two share, a box you draw.) Declare `sticky: true` in the type's `meta.js` — an author turns it off with `sticky: false` — and the runtime makes sticky the box that can stay in view. A section in the body sticks the same way and stays below the stuck header by itself: the runtime measures how far the header reaches and publishes it as `--uw-sticky-top` (a type's `top` overrides it). A link to a section lands below the stuck header too. A child section in kit's `<ChildGrid>` stays in view beside the column it sits next to, and on a phone, at one column, scrolls with the page. A sticky section inside a box with `overflow: hidden` cannot stick — clip with `overflow: clip`. A layout of your own that wraps an area in an element makes that element sticky when `page.isSticky('header')`. `uniweb dev` names a sticky element that cannot move in the console, once the page's data is in, and says which box holds it.
1213
-
1214
- ### meta.js
1215
-
1216
- ```javascript
1217
- export default {
1218
- title: 'Feature Grid',
1219
- description: 'Grid of feature cards with icons',
1220
- family: 'features', // the standard section type it is — the editor's
1221
- // illustration, icon and label (`uniweb families`). Optional;
1222
- // a name like `Features` resolves on its own
1223
- // hidden: true, // Exclude from export entirely (internal helpers)
1224
- // background: 'self', // Component renders its own background
1225
- // inset: true, // Available for @ComponentName in markdown
1226
- // children: true, // Accepts child sections
1227
-
1228
- content: {
1229
- title: 'Section heading',
1230
- paragraphs: 'Introduction [0-1]',
1231
- items: {
1232
- label: 'Feature cards [3-6]',
1233
- content: { icon: 'Icon [1]', title: 'Feature', paragraphs: 'Description' }, // one entry
1234
- },
1235
- // media: 'Photo, video or diagram [1]', // an image, a video, or an embedded component
1236
- // sequence: 'Prose and media', // renders content.sequence — the section as written
1237
- },
1238
-
1239
- params: {
1240
- columns: { type: 'number', default: 3 },
1241
- variant: { type: 'select', options: ['default', 'centered', 'split'], default: 'default' },
1242
- },
1243
-
1244
- presets: {
1245
- default: { label: 'Standard', params: { columns: 3 } },
1246
- compact: { label: 'Compact', params: { columns: 4 } },
1247
- },
1248
-
1249
- // context / initialState: keys are developer-defined, not framework fields.
1250
- context: {}, // Static — neighbors read via getNextBlockInfo().context
1251
- initialState: {}, // Dynamic — neighbors read .state; component updates via useBlockState()
1252
- }
1253
- ```
1254
-
1255
- **All defaults belong in `meta.js`, not inline in component code.** `meta.js` is also the catalog entry another agent reads to discover your section type (Part 2, step 2) — write `description` and `content:` for that reader.
1256
-
1257
- **`content:` names what the component reads**, each as a label for the author with an optional count (`'Cards [3-6]'`): `title`, `pretitle`, `subtitle`, `paragraphs`, `links`, `lists`, `items`, `media`, `icons`, `documents`, `snippets`, `tables`, `math`, `quotes`, `sequence`.
1258
-
1259
- - **`media` is an image, a video, or an embedded component.** `media: 'Hero media [1]'` takes any of the three; `media: { label, types: ['image'] }` narrows it; `image:`, `videos:` and `insets:` are the same slot narrowed to one type. Read it as `content.media` — the author's order, each item with its `kind` — and render it with `<Visual media={content.media} block={block} />`. Rendering the slot with `<Image>` drops a diagram an author placed there, and kit's `<Media>` is a video player.
1260
- - **`sequence`** says the component renders `content.sequence` — the whole section as written, headline included. `{ label, except: ['table', 'math'] }` names the kinds it leaves out, and `placement` the placements it lays out — `true` for all four (what `<Render>`, `<Prose>` and `<Article>` do), a list (`['wide', 'full']`), or a map per kind (`{ image: ['left', 'right'], table: ['wide'] }`). A visual editor offers an author only those; declare none, and it offers none.
1261
- - **`items: { label, content: { … } }`** says what each entry holds, in the same vocabulary.
1262
- - The build warns on what it can't read, and refuses `visuals:` (declare `media`) and the `content:` element `data` (declare the block's tag in `data:`).
1263
-
1264
- > **`meta.js` is a user interface, not just metadata.** When a foundation is published, every `meta.js` is registered as the foundation's schema, and the visual editor builds its controls from it: the build generates a `schema.json` from every `meta.js` in the foundation, and the editor renders it: a `select` param with `options` becomes a dropdown, a `boolean` becomes a toggle, `label` and `description` become the words a non-technical author reads, and each entry in `presets` becomes a one-click choice. That's the real reason param naming matters — `variant: centered` and `renderMode: flex-center` aren't a style preference, they're the difference between a legible control and a baffling one. Write `meta.js` as though someone who will never see your code has to use it, because that's exactly who does.
1265
-
1266
- ### Two worlds: section types and your own components
1267
-
1268
- The `{ content, params, block }` interface is not "how components work in Uniweb." It is how **section types** work — the components an author names with `type:` in frontmatter. A section type is a *public interface*: its name, params, and content expectations are a contract with content authors, and `meta.js` is its documentation.
1269
-
1270
- **Everything under `components/` is yours.** It's a normal React project in there, and the framework has no opinion about it:
1271
-
1272
- - **Any props you want** — `<PricingCard tier={tier} price={price} featured />`. No `content`, no `params`, no `block` unless you choose to pass them.
1273
- - **Any composition** — children, render props, context, `forwardRef`, custom hooks, whatever the job needs.
1274
- - **Any library** — install it and import it.
1275
- - **No `meta.js`, no naming convention, no auto-discovery, no author visibility.**
1276
-
1277
- Two symptoms of getting this backwards, both worth checking yourself against:
1278
-
1279
- > **Don't give helper components a `{ content, params }` signature.** Copying the section interface downward is the most common version of this mistake. It makes every helper harder to reuse and hides what it actually needs. A card that takes `title`, `price`, and `features` is better than one that takes `content` and digs through it.
1280
-
1281
- > **Don't put helpers in `sections/`.** Anything at the root of `sections/` becomes author-selectable vocabulary. A `Button` or `Card` appearing in the editor's section picker is a bug in your foundation's interface design, not a harmless extra.
1282
-
1283
- **A section type is usually a composite.** Its job is to translate parsed content into whatever your own components expect, then arrange them:
1284
-
1285
- ```jsx
1286
- // sections/Pricing/index.jsx
1287
- import PricingCard from '#components/PricingCard'
1288
- import formatPrice from '#utils/formatPrice'
1289
-
1290
- export default function Pricing({ content, params }) {
1291
- const currency = params.currency || 'USD'
1292
- return (
1293
- <div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto">
1294
- {content.items.map((tier, i) => (
1295
- <PricingCard key={i} tier={tier} price={formatPrice(tier.data, currency)} />
1296
- ))}
1297
- </div>
1298
- )
1299
- }
1300
- ```
1301
-
1302
- The author writes `type: Pricing` and defines tiers as content items. `PricingCard` knows nothing about Uniweb — it takes a tier and a price. That boundary is what makes it testable, reusable across section types, and replaceable without touching the author-facing contract.
1303
-
1304
- **There are many ways to use `components/`**, and no expected shape. Presentational primitives shared across section types (buttons, cards, badges). A thin wrapper adapting the parsed content shape to a third-party component's props. Layout scaffolding several section types share. Stateful widgets. Legacy components carried in during a migration. The Front Desk pattern below is *one* specific arrangement worth knowing — not a requirement, and not the main reason to have helper components.
1305
-
1306
- ### The Front Desk pattern
1307
-
1308
- One arrangement of the above is worth naming, because it comes up whenever a single `type:` needs to cover genuinely different renderings.
1309
-
1310
- Section types naturally use params to adjust their own rendering — `variant: flipped` reverses a flex direction, `columns: 3` sets a grid. That's the baseline, not a pattern. The **Front Desk pattern** is the step beyond it: a section type that does virtually no rendering itself, instead reading the author's params, picking the right helper component, and translating author-friendly vocabulary into developer-oriented props.
1311
-
1312
- The workers behind the desk need not share an interface. A `Hero` might delegate to a `SliderHero` (image carousel) and a `ContactHero` (quote form) expecting different content and different props. The front desk declares the **union** of everything its workers might need — some content goes unused for a given variant, and that's normal in CCA: params change behavior, and that includes not rendering some content.
1313
-
1314
- ```js
1315
- // meta.js — the union of all variants' needs
1316
- export default {
1317
- params: {
1318
- variant: { type: 'select', options: ['slider', 'contact'], default: 'slider' },
1319
- slideInterval: { type: 'number', default: 5 },
1320
- density: { type: 'select', options: ['default', 'compact'], default: 'default' },
1321
- style: { type: 'select', options: ['default', 'dramatic'], default: 'default' },
1322
- }
1323
- }
1324
- ```
1325
-
1326
- ```jsx
1327
- // sections/Hero/index.jsx — the front desk
1328
- import { SliderHero } from '#components/SliderHero'
1329
- import { ContactHero } from '#components/ContactHero'
1330
-
1331
- const variants = { slider: SliderHero, contact: ContactHero }
1332
-
1333
- export default function Hero({ content, block, params }) {
1334
- const Variant = variants[params.variant] || SliderHero
1335
- return (
1336
- <Variant
1337
- title={content.title} subtitle={content.paragraphs[0]} links={content.links} block={block}
1338
- images={content.images} // only some variants use these
1339
- formData={content.data?.quote}
1340
- interval={params.slideInterval} // author vocabulary → developer props
1341
- compact={params.density === 'compact'}
1342
- transition={params.style === 'dramatic' ? 'zoom' : 'fade'}
1343
- />
1344
- )
1345
- }
1346
- ```
1347
-
1348
- `SliderHero` uses `images`, `interval`, `transition` and ignores the rest; `ContactHero` uses `formData` and `compact` and ignores the rest. The author writes `variant: contact` — they don't know or care that `ContactHero` exists.
1349
-
1350
- This is the system-building pattern at its clearest: **section types are the public interface** (author-friendly names, documented in `meta.js`); **helper components are the implementation** (ordinary React props). The section type is the thin translation layer between the two worlds.
1351
-
1352
-
1353
- **When to reach for this pattern:** when a page type has consistent structural elements — header bars, navigation footers, contextual sidebars — that the content author shouldn't have to add as separate sections. If the author would otherwise repeat the same boilerplate sections on every page of a given type, the section component should compose them internally.
1354
-
1355
- **Common mistake:** solving structural repetition at the layout level. If only some page types need a content header (lessons do, the homepage doesn't), that's a section concern. The layout owns page-wide chrome; the section owns its internal structure.
1356
-
1357
- ### Params, component vars, foundation vars
1358
-
1359
- Three places a value can live, and picking the right one is most of the design:
1360
-
1361
- | | Declared in | Reaches the component as | Author overrides in | CSS scope |
1362
- |---|---|---|---|---|
1363
- | **Param** | `meta.js` `params:` | a JS prop | section frontmatter | — |
1364
- | **Component var** | `meta.js` `vars:` | a CSS custom property | section frontmatter `vars:` | `#section-{id}` |
1365
- | **Foundation var** | `main.js` `vars:` | a CSS custom property | `theme.yml` `vars:` | `:root` (global) |
1366
-
1367
- **Param when the value drives logic** — a count, a variant name, a boolean the JSX branches on. **Component var when it only drives CSS** and belongs to one section type; it never enters JS, so it doesn't re-render anything:
1368
-
1369
- ```js
1370
- // meta.js — same schema as foundation vars (default, label, type, options, group, description)
1371
- vars: {
1372
- 'card-gap': { default: '1.5rem', label: 'Card Gap', type: 'select', options: ['1rem', '1.5rem', '2rem'] },
1373
- 'card-radius': { default: 'var(--radius-md)', description: 'Inherits the foundation var by default' },
1374
- }
1375
- ```
1376
-
1377
- ```jsx
1378
- <div className="grid gap-[var(--card-gap)]"> // emitted on #section-{id}
1379
- ```
1380
-
1381
- ```yaml
1382
- ---
1383
- type: PricingTable
1384
- vars: { card-gap: 2rem } # author override — only declared names apply
1385
- ---
1386
- ```
1387
-
1388
- Unknown var names in frontmatter are ignored, and component vars are always context-independent (unlike foundation `color`/`gradient` vars, which resolve per light/dark context).
1389
-
1390
- **Foundation var when the value must stay consistent *across* components** — shared radii, spacing scales, extra typefaces. A header height is a layout param, not a foundation var; a sidebar width is a layout param too. Declare foundation vars in **`main.js`**, the single source of truth:
1391
-
1392
- ```js
1393
- export const vars = {
1394
- 'radius-lg': { default: '1rem', description: 'Large border radius' },
1395
- 'section-padding-y': { default: 'clamp(4rem, 6vw, 7rem)', description: 'Vertical section padding' },
1396
- }
1397
- ```
1398
-
1399
- Each entry ships the default as a CSS custom property (so `var(--section-padding-y)` resolves everywhere), gives the visual editor a description and type, and is what a site overrides under `vars:` in `theme.yml`. You don't declare these anywhere else — the defaults reach the browser on their own, in dev and production, bundled or runtime-loaded.
1400
-
1401
- A `styles.css` `@theme` block is a different tool: it registers a token so **Tailwind generates utilities** from it (`@theme { --breakpoint-xs: 30rem }` → `xs:` variants). Use it to extend Tailwind's vocabulary, not to ship a plain default.
1402
-
1403
- **A name matching a Tailwind namespace is an intentional override.** A var named after a Tailwind v4 scale — `radius-*`, `shadow-*`, `spacing`, `font-*` — redefines that scale wherever the matching utility appears: declaring `radius-lg` retunes every `rounded-lg` in the foundation. That's the point when you mean it — name deliberately so you don't reshape a utility by accident.
1404
-
1405
- ### Semantic theming
1406
-
1407
- Components use **semantic CSS tokens** instead of hardcoded colors. The runtime applies a context class (`context-light`, `context-medium`, `context-dark`) to each section from its `theme:` frontmatter.
1408
-
1409
- ```jsx
1410
- <h2 className="text-slate-900">…</h2> // ❌ Hardcoded — breaks in dark context
1411
- <h2 className="text-heading">…</h2> // ✅ Semantic — adapts to any context and brand
1412
- ```
1413
-
1414
- **Semantic tokens** (available as Tailwind `text-*`, `bg-*`, `border-*` classes):
1415
-
1416
- | Token | Purpose |
1417
- |-------|---------|
1418
- | `heading` | Heading text |
1419
- | `body` | Body text |
1420
- | `subtle` | Secondary/de-emphasized text |
1421
- | `section` | Section background |
1422
- | `card` | Card/panel/well background |
1423
- | `muted` | Hover states, zebra rows |
1424
- | `border` | Lines, dividers |
1425
- | `ring` | Focus indicators |
1426
- | `link` / `link-hover` | Link colors |
1427
- | `primary` / `primary-foreground` / `primary-hover` / `primary-border` | Primary actions |
1428
- | `secondary` / `secondary-foreground` / `secondary-hover` / `secondary-border` | Secondary actions |
1429
- | `success` / `warning` / `error` / `info` | Status colors |
1430
- | `success-subtle` / `warning-subtle` / `error-subtle` / `info-subtle` | Status backgrounds (alerts) |
1431
-
1432
- **Palette shades** are also available — `text-primary-600`, `bg-neutral-100`, `border-accent-300` — 11 shades (50–950) per palette color (primary, secondary, accent, neutral). See `theme-tokens.css` for the complete mapping.
1433
-
1434
- > **Debugging a token that "does nothing": don't probe it in the browser.** Tailwind v4 is JIT — it emits only the classes it finds in *scanned source*. So a class you assign from JavaScript, to a `<div>` you created in the console, **has never been scanned and can never resolve**, whatever the token. A comparison against a deliberately bogus class agrees with you either way, because both are ungenerated, and classes that happen to appear in source elsewhere look like they "pass" — so the probe confirms whichever answer you started with.
1435
- >
1436
- > **Ask the build instead.** The one command that splits the question:
1437
- >
1438
- > ```bash
1439
- > grep -o '\.text-link{[^}]*}' dist/assets/*.css
1440
- > ```
1441
- >
1442
- > A rule prints → the utility exists, and something at runtime is overriding it. Nothing prints → Tailwind never generated it, and there are only two reasons: your `styles.css` doesn't `@import "@uniweb/kit/theme-tokens.css"` (or declares its own `@theme inline` that omits the token), or your `@source` globs don't cover the file the class is written in. Either way, write the class into a real source file first — a token that's only ever composed at runtime is invisible to the scanner by design.
1443
-
1444
- **Authors control context** via `theme: dark` in frontmatter, alternating `light` (default), `medium`, and `dark` across sections for visual rhythm. **The three presets aren't the limit** — a section's `theme:` is `theme.yml` for that section: tokens beside `mode`, and `theme.yml`'s own `colors`, `contexts` and `vars`, scoped to it:
1445
-
1446
- ```yaml
1447
- theme:
1448
- mode: light
1449
- section: neutral-100 # Subtle off-white surface
1450
- card: neutral-50 # Cards lighter than surface
1451
- primary: neutral-900 # Dark buttons instead of brand color
1452
- colors: { accent: '#e65100' } # A palette for this section only
1453
- contexts: # Per context, for a section that follows the site's scheme
1454
- dark: { link: accent-300 }
1455
- ```
1456
-
1457
- `background:` also accepts CSS variables and hex, so authors can alternate `var(--neutral-50)` / `var(--primary-50)` surfaces with no component code. If a source design uses subtle surface variations (`--surface-base` vs `--surface-sunken`), map those to backgrounds or token overrides in frontmatter — not to component code.
1458
-
1459
- ### Section context vs site scheme
1460
-
1461
- Uniweb splits what other frameworks fuse into one "dark mode":
1462
-
1463
- - **Section context** — the `theme:` field on one section (`light`/`medium`/`dark`). Per-section, author-controlled.
1464
- - **Site scheme** — the global light/dark preference under `appearance:` in `theme.yml`. The site-wide toggle a visitor flips.
1465
-
1466
- They compose rather than fight: a section with **no `theme:`** inherits the site scheme and follows the toggle; a section that **pins** `theme: dark` stays dark in either scheme. A dark site can carry one bright white CTA. You never write `isDark ? … : …` — semantic tokens adapt to whichever scheme and context resolve around them.
1467
-
1468
- ```yaml
1469
- appearance:
1470
- default: light # 'light' | 'dark' | 'system'
1471
- allowToggle: true # offer a visitor switch (also generates the dark tokens)
1472
- respectSystemPreference: true # first visit follows the OS; false pins `default`
1473
- schemes: [light, dark] # optional — declares the available set
1474
- ```
1475
-
1476
- Shorthands: `appearance: light` / `dark` (fixed, no toggle), `appearance: system` (follow the OS).
1477
-
1478
- A site **has dark mode** whenever it offers a toggle, defaults to `dark`/`system`, or lists `dark` in `schemes:`. Precedence: a stored choice wins over the OS, which wins over `default:`. Note that `default: light` is a *fallback*, not a guarantee — a dark OS still wins on first visit unless `respectSystemPreference: false`. (`default: system` is just the honest way to say "there is no fixed default — use the OS.")
1479
-
1480
- | Goal | `theme.yml` |
1481
- |---|---|
1482
- | Always light, no switch | `appearance: light` |
1483
- | Always dark, no switch | `appearance: dark` |
1484
- | Toggle, follow the OS on first visit | `appearance: { default: system, allowToggle: true }` |
1485
- | Toggle, but always start light | `appearance: { default: light, allowToggle: true, respectSystemPreference: false }` |
1486
-
1487
- **Rendering a toggle.** The runtime resolves the scheme and applies it to `<html>` (`scheme-dark`/`scheme-light`) *before the page paints* — never touch `localStorage` or `document` yourself, and there's no flash of the wrong scheme. A section type only renders the button:
1488
-
1489
- ```jsx
1490
- import { useAppearance } from '@uniweb/kit'
1491
-
1492
- function SchemeToggle() {
1493
- const { scheme, toggle, canToggle } = useAppearance()
1494
- if (!canToggle) return null // hidden unless the site enables toggling
1495
- return <button onClick={toggle}>{scheme === 'dark' ? 'Light' : 'Dark'}</button>
1496
- }
1497
- ```
1498
-
1499
- **Tailwind `dark:` variant.** If your foundation uses `dark:` utilities, bind them to the site scheme so they track the toggle. In `styles.css`:
1500
-
1501
- ```css
1502
- @custom-variant dark (&:where(.scheme-dark, .scheme-dark *));
1503
- ```
1504
-
1505
- Without this, `dark:` falls back to `@media (prefers-color-scheme: dark)` and ignores the site's setting. Prefer semantic tokens over `dark:` where you can — they adapt to per-section context, which a global `dark:` cannot.
1506
-
1507
- ### theme.yml
1508
-
1509
- ```yaml
1510
- # site/theme.yml
1511
- colors:
1512
- primary: '#3b82f6' # Your exact hex appears at shade 500
1513
- secondary: '#64748b'
1514
- accent: '#8b5cf6'
1515
- neutral: stone # Named preset: stone, zinc, gray, slate, neutral
1516
-
1517
- contexts:
1518
- light:
1519
- section: '#fafaf9' # Override individual tokens per context
1520
-
1521
- appearance: { default: light, allowToggle: true }
1522
-
1523
- fonts:
1524
- heading: "'Inter', system-ui, sans-serif"
1525
- body: "'Inter', system-ui, sans-serif"
1526
-
1527
- inline:
1528
- callout: { color: var(--accent), font-weight: '600' }
1529
-
1530
- vars:
1531
- radius: 0.75rem
1532
- ```
1533
-
1534
- Each color generates 11 OKLCH shades (50–950); shade 500 is your exact input. `neutral` takes a named preset rather than hex. Context override keys match token names: `section:` not `bg:`, `primary:` not `btn-primary-bg:`.
1535
-
1536
- **Quote a color, and any value with one inside it — here, in `site.yml`, in a section's frontmatter.** In YAML a `#` after a space starts a comment: `primary: #3b82f6` leaves `primary` empty, and `gradient: linear-gradient(165deg, #0c1226 0%, #05060f 100%)` keeps only `linear-gradient(165deg,`, which the browser drops. The YAML is valid, so nothing fails — the color is just not there. The build warns when it can tell (*is cut short*, *is empty*) and gives the quoted value to write.
1537
-
1538
- **How colors reach components:** your hex → 11 shades → semantic tokens → components. In light/medium, `--primary` uses shade 600, `--link` 600, `--ring` 500; in dark, `--primary` uses 500 and `--link` 400.
1539
-
1540
- **Buttons use shade 600 — darker than your input color.** That's an accessibility choice for contrast with white text. For brand-exact buttons:
1541
-
1542
- ```yaml
1543
- colors: { primary: "#E35D25" }
1544
- contexts:
1545
- light:
1546
- primary: primary-500 # Your exact color on buttons
1547
- primary-hover: primary-600
1548
- ```
1549
-
1550
- > **Contrast warning:** bright brand colors (orange, yellow, light green) at shade 500 may fail WCAG 4.5:1 against white text. Test for readability — if contrast is insufficient, keep the default 600 mapping.
1551
-
1552
- ### Fonts
1553
-
1554
- Font families are a **site** setting, under `fonts:` in `theme.yml`. A foundation never installs a font package (no `@fontsource/*`) and never hardcodes a family — if you reach for either, you're off the paved path. Three roles are wired onto standard elements for you:
1555
-
1556
- | Role | Wired onto | Typical use |
1557
- |---|---|---|
1558
- | `body` | `body` (all text by default) | paragraphs, UI |
1559
- | `heading` | `h1, h2, h3` | titles |
1560
- | `code` | `code, pre, kbd, samp` | code, monospace |
1561
-
1562
- (`code` was previously named `mono`; `fonts.mono` is no longer an alias — rename it.)
1563
-
1564
- A role's face on an element it isn't wired onto, such as a wordmark in the heading face: `font-family: var(--font-heading)`, or a utility of your own with `@theme inline { --font-display: var(--font-heading); }` in `styles.css`, then `font-display`.
1565
-
1566
- Because the site wires families onto real elements, **the norm is that a foundation doesn't set fonts itself** — render semantic markup (`<H1>`, `<P>`, `<code>` from the kit) and the roles apply. Everything else stays Tailwind.
1567
-
1568
- **In a component, weight is yours; family is the site's.** Weight/size/style utilities (`font-bold`, `italic`, `text-xl`) are ordinary design vocabulary. A font-**family** utility is different: `font-sans`/`font-serif` resolve to Tailwind's built-in stacks unless the foundation makes them site-controlled, so a bare `font-serif` silently hardcodes a typeface.
1569
-
1570
- **When a design needs typefaces the three roles can't express** — an editorial serif, a display face for hero titles — declare each as a **font var** in `main.js`. A `font-*`-named var is recognized as a typeface automatically (no `type` needed); a bare-named one takes `type: 'font'`. Either way the site loads and owns the family:
1571
-
1572
- ```js
1573
- // foundation src/main.js
1574
- export const vars = {
1575
- 'font-serif': {
1576
- default: 'ui-serif, Georgia, serif',
1577
- description: 'Editorial serif — blurbs, taglines, quotes',
1578
- applyTo: ['blockquote', '.tagline'], // framework emits the rule, like a built-in role
1579
- },
1580
- 'font-display': {
1581
- default: 'ui-sans-serif, system-ui, sans-serif',
1582
- // no applyTo → the component wires it (a `font-display` utility, or var(--font-display))
1583
- },
1584
- }
1585
- ```
1586
-
1587
- The `fonts:` block takes **any** role name, built-in or foundation-added, so a site sets its whole type system in one place. The three roles are defaults you can **retarget** too — redeclaring a role's var with a new `applyTo` changes which elements it paints, while the site still owns the family.
1588
-
1589
- ```yaml
1590
- # site/theme.yml — loading, hosted or self-hosted; both config-only, no dependency
1591
- fonts:
1592
- heading: "Poppins, sans-serif"
1593
- serif: '"Fraunces", Georgia, serif' # a foundation-declared role, set by name
1594
- import:
1595
- - url: "https://fonts.googleapis.com/css2?family=Poppins:wght@600;700"
1596
- faces:
1597
- - { family: "Fraunces", src: /fonts/fraunces.woff2, weight: "100 900" }
1598
- ```
1599
-
1600
- The build auto-adds preconnect hints for imports, emits `@font-face` + preload for faces, and drops any family no role references. `uniweb push` uploads each face's file (under `public/`) with the site's media, so self-hosted faces work on a site published with Uniweb too.
1601
-
1602
- > **`serif` and `font-serif` are the same font var** — the `font-` spelling is just the one Tailwind's `font-serif` utility reads. Declare it either way in `main.js`; the site sets it by the bare role name under `fonts:`.
1603
-
1604
- > The `code` role owns `--font-code`. Tailwind's `font-mono` utility (which reads `--font-mono`) is a **separate** concern — control it by declaring your own `font-mono` font var. So `fonts.code` styles code without disturbing `font-mono`-styled labels, and vice-versa.
1605
-
1606
- ### Tailwind v4 and styles.css
1607
-
1608
- ```css
1609
- @import "tailwindcss";
1610
- @import "@uniweb/kit/theme-tokens.css";
1611
- @source "./sections/**/*.{js,jsx}";
1612
- @source "./components/**/*.{js,jsx}";
1613
- @source "./layouts/**/*.{js,jsx}";
1614
-
1615
- @theme {
1616
- --breakpoint-xs: 30rem;
1617
- }
1618
- ```
1619
-
1620
- **Name every folder that writes classes.** The foundation's own build finds them all, but a site build and `uniweb dev` read only what these lines name, so a class in a folder left out is in one CSS and missing from the other. `uniweb dev`, a site build and `uniweb doctor` (`unread-folder`) give the line to add.
1621
-
1622
- Semantic tokens come from `theme-tokens.css` (populated from `theme.yml`). It also tells Tailwind to read kit's source, so kit's own classes reach your CSS wherever your package manager put kit. A foundation that skips the import names kit itself, by where kit is: `./node_modules/@uniweb/kit/src/**` under pnpm, `../node_modules/@uniweb/kit/src/**` under npm. Use `@theme` only for values tokens don't cover. **Custom CSS is expected alongside Tailwind** — shadow systems, border hierarchies, gradients, glassmorphism. Tailwind handles layout; tokens handle context; `styles.css` handles everything else.
1623
-
1624
- **Tokens are a floor, not a ceiling.** They solve context adaptation — the hard problem. A great foundation adds design vocabulary on top:
1625
-
1626
- ```css
1627
- .border-subtle { border-color: color-mix(in oklch, var(--border), transparent 50%); }
1628
- .text-tertiary { color: color-mix(in oklch, var(--body), var(--subtle) 50%); }
1629
- ```
1630
-
1631
- These compose with tokens — they adapt per context because they reference token variables — while adding nuance the token set doesn't provide. Use palette shades directly (`var(--primary-300)`, `bg-neutral-200`) for fine-grained control. **The priority: design quality > portability > configurability.** A beautiful foundation for one site is worth more than a generic one that looks flat.
1632
-
1633
- Four things a ported design will try to bring with it, each of which breaks something:
1634
-
1635
- > **Don't set `scroll-behavior: smooth` globally.** The runtime owns scrolling: it already smooth-scrolls anchor targets itself (`scrollIntoView({ behavior: 'smooth' })`), so the CSS adds nothing there — but it resets and restores scroll on route changes with the two-argument `scrollTo(x, y)`, which *inherits* the property. Route changes then animate their scroll-to-top, and back-button restoration (which scrolls, checks the position on the next frame, and retries) keeps interrupting its own animation. Scope it to a specific scrollable element if you need it; never to `html` or `body`.
1636
-
1637
- > **Paint a decorative glow with a gradient, not `filter: blur()`.** A `bg-primary-400 blur-[100px]` box is a soft glow, and a browser paints the filter again whenever it captures the page for a view transition. Safari does that on the main thread at device resolution, so on a phone a tap can freeze the page for seconds; a desktop in Chrome shows nothing. A radial mask looks the same and costs a fraction, and the box keeps its colour classes: `mask-image: radial-gradient(closest-side, #000, rgb(0 0 0 / 0.6) 40%, rgb(0 0 0 / 0.09) 80%, transparent)`.
1638
-
1639
- > **Font smoothing is a per-scheme decision, not a reset.** `-webkit-font-smoothing: antialiased` (macOS only) forces grayscale rasterization, which thins strokes. On dark surfaces that usefully counteracts the bloom of light text on near-black; on light surfaces it costs contrast and makes body text spindly. Scope it — `.scheme-dark { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }` — rather than putting it on `html`.
1640
-
1641
- > **Write an entrance animation in CSS, not in JavaScript.** A CSS animation on a prerendered page starts at first paint and carries on when the browser renders over that page, so a hero fades in once. One a component starts when it mounts (a motion library, a `useEffect`) can only start when the page boots. Until then the visitor sees its first frame, which for a fade is nothing, or the finished section, which then animates in. `uniweb dev` does not prerender, so only a built site shows this.
1642
-
1643
- ### Composition: items, child sections, insets
1644
-
1645
- Pages are sequences of sections — the obvious layer. The framework also supports real nesting, without leaving markdown.
1646
-
1647
- | Pattern | How authored | Use when |
1648
- |---|---|---|
1649
- | **Items** (`content.items`) | Heading groups within one `.md` | Repeating content in one section: cards, features, FAQ entries |
1650
- | **Concept blocks** (`content.data[tag]`) | ` ```md:<tag> ` fence around markdown | A named *kind* of content — an FAQ, a callout, a set of steps |
1651
- | **Child sections** (`block.childBlocks`) | `@`-prefixed `.md` files + `nest:` | Children needing their own section type, rich content, or independent editing |
1652
- | **Insets** (`block.insets`) | `![](@Component)` in markdown | Self-contained visuals/widgets: charts, diagrams, code demos |
1653
- | **Block insets** (`block.insets`) | ` ```@Component ` fence around markdown | A component that *wraps* authored prose: callouts, disclosures, admonitions |
1654
-
1655
- Does the author write content *inside* the nested element? **Yes** → child sections, or a block inset when the wrapper is presentational and lives mid-page. **No** (self-contained, param-driven) → inset. Repeating same-structure groups → items. These compose: a child section can contain insets; items work inside children; a block inset can contain both.
1656
-
1657
- **Child sections in columns.** A section type that lays its children out in a grid offers layouts in `meta.js` — `children: { grid: [3, 2, '40/60'] }`, the first being its default — and renders them with kit's `<ChildGrid from={block} fallback={3} />`. The author picks one with `grid:` in the parent's frontmatter (`grid: 3`, `grid: '40/60'`), a section key like `type`, not a param. Each child renders as a section, so its own `theme:` and `background:` apply. Don't declare a param named `grid`.
1658
-
1659
- ### Concept blocks — naming *what* content is
1660
-
1661
- A ` ```md:<tag> ` fence marks a run of prose as a named kind of thing. The author writes ordinary markdown; the tag says what it is:
1662
-
1663
- ````markdown
1664
- ```md:faq
1665
- # What plans do you have?
1666
- Three — Starter, Team and Enterprise.
1667
-
1668
- # Can I change later?
1669
- Any time, and we prorate the difference.
1670
- ```
1671
- ````
1672
-
1673
- Every `#` heading starts an item, so this arrives as `content.data.faq`:
1674
-
1675
- ```js
1676
- {
1677
- items: [ { title, paragraphs, links, … }, … ], // one per heading
1678
- sequence: [ … ] // the same content, in document order
1679
- }
1680
- ```
1681
-
1682
- **The shape is fixed by the fence, not by the tag.** Any tag works and none is special — the framework never learns what `faq` means. A body with **no** headings is the same block with a single titleless item, which is what a callout is:
1683
-
1684
- ````markdown
1685
- ```md:warning
1686
- Back up your database **before** running this. It is not reversible.
1687
- ```
1688
- ````
1689
-
1690
- **Why this instead of a component reference.** ` ```@Alert ` names *which component renders this*, which is a rendering decision sitting in content. `md:warning` names *what the content is* and leaves rendering to the foundation — so the same content works under a different foundation, and an editor can recognize the concept and offer a surface built for it.
1691
-
1692
- **A data block whose value is itself a schema.** An author can design a form in the visual editor; it lands as a ` ```yaml:form ` block at `content.data.form`. A component that renders one is the inverse of every other component: it declares the key (`data: { form: … }`) but not the fields — it *receives* them and draws whatever it's given, since the field names are the author's and aren't knowable when you write `meta.js`.
1693
-
1694
- That makes one distinction worth holding onto. You **may** declare a schema describing the form *definition's envelope* — `title`, `description`, `fields` as a map — and get build-time validation that an authored form is well-formed. What you can't declare is a schema whose fields are *the form's* fields (`name`, `email`, …); that's describing the visitor's answers, which arrive at runtime and belong to a form you've never seen. Declare the key either way — it is what delivers the block — and give it a schema only if you want it checked, and only of the envelope (`{}` declares the key with none).
1695
-
1696
- **Reading one in a component.** Declare it the way the author writes the fence — `data: { 'md:faq': 'Questions and answers [3+]' }`. The value is the author's label (its count counts the entries), or `{ label, hint, content: { title: 'Question', paragraphs: 'Answer' } }` to say what each entry holds. The component still reads `content.data.faq`, which gives you both views: `items` for anything row-shaped (an accordion, a step list), `sequence` when you don't recognize the tag and want to render it faithfully in document order. Both are derived, so nothing is stored twice. (`faq: {}` also declares the key, saying nothing about the block.)
1697
-
1698
- ```jsx
1699
- function Faq({ content }) {
1700
- const faq = content.data?.faq
1701
- if (!faq) return null
1702
- return faq.items.map((item, i) => <Disclosure key={i} q={item.title} a={item.paragraphs} />)
1703
- }
1704
- ```
1705
-
1706
- **Two tags, not a tag plus a variant.** A warning and a note are different concepts, so they are `md:warning` and `md:note`. The fence takes no params.
1707
-
1708
- **Insets — embedding components in content.** Many section types need a "visual" — a hero's illustration, a split-content section's media. Classically an image or video. But what if it's a JSX + SVG diagram, a ThreeJS animation, an interactive playground? Elsewhere you'd reach for MDX or prop-drilling. Here the author writes standard image syntax:
1709
-
1710
- ```markdown
1711
- ![Architecture overview](@NetworkDiagram){variant=compact}
1712
- ```
1713
-
1714
- The developer builds `NetworkDiagram` as an ordinary React component with `inset: true` in `meta.js`. The section that hosts it declares a `media` slot, and kit's `<Visual>` renders the author's item by its kind — so one section type works whether the author supplies an image, a video, or an interactive component:
1715
-
1716
- ```jsx
1717
- // meta.js: content: { title: 'Headline', media: 'Illustration [1]' }
1718
- <Visual media={content.media} block={block} className="rounded-2xl" />
1719
- ```
1720
-
1721
- **Insets are full section types** — they receive `{ content, params, block }`. The alt text becomes `content.title` and attributes become `params`: `![npm create uniweb](@CommandBlock){note="Ready to go"}` → `content.title = "npm create uniweb"`, `params.note = "Ready to go"`.
1722
-
1723
- **Don't use `hidden: true` on insets.** `hidden` means "don't export this component at all" (internal helpers); `inset: true` means "available for `@Component` references in markdown" — and a visual editor then offers it as an inset only. For a component placed both as a section and as an inset, add `section: true`.
1724
-
1725
- **Block insets — a component that wraps content.** The image form is a leaf: it takes params but no body. When the component should surround authored prose — a callout, a disclosure, an admonition — use the fenced form instead. Same `@Component{params}` reference, written as a code fence's info string:
1726
-
1727
- ````markdown
1728
- ```@Alert{type=warning}
1729
- Back up your database **before** running this.
1730
-
1731
- - The migration is not reversible
1732
- - Allow ten minutes of downtime
1733
- ```
1734
- ````
1735
-
1736
- The body is ordinary content, not text: it is parsed exactly like the rest of the page, so headings, lists, tables, icons, inline styling, leaf insets and further containers all work inside one. To nest a code block or another container, open the outer fence with more backticks than the inner one.
1737
-
1738
- **The component is yours, and it receives parsed content.** `@Alert` resolves against the foundation through the same lookup as `![](@NetworkDiagram)` — declare it with `inset: true` in `meta.js`. Where a leaf inset gets its alt text as `content.title` and nothing else, a container gets its whole body parsed: `title`, `paragraphs`, `items`, `sequence`. Render it with `<Prose content={content} block={block} />` or read the fields directly. A name the foundation doesn't define renders a visible `Component not found: <Name>` error in place of the inset — deliberately, so a typo or a missing declaration is obvious on the page instead of quietly looking like a design choice.
1739
-
1740
- Prefer a **child section** when the author needs their own section type and independent editing; prefer a **block inset** when the wrapper is presentational and belongs inline in a single file's prose.
1741
-
1742
- **Child sections.** You hit a complex layout — a 2:1 split with a panel and a main area. Your instinct says build a specialized component. Step back: the panel is a reusable section type, the main area is another, and the split is a Grid with `columns: "1fr 2fr"`. Your child components already adapt to narrow containers — container queries handle that. But hardcoding which components go where means the author can't rearrange or swap them. Child sections solve that:
1743
-
1744
- ```
1745
- pages/home/
1746
- ├── page.yml
1747
- ├── 2-dashboard.md # Parent section (type: Grid, columns: "1fr 2fr")
1748
- ├── @sidebar-stats.md # Child (@ = not top-level)
1749
- └── @main-chart.md
1750
- ```
1751
-
1752
- ```yaml
1753
- # page.yml
1754
- nest:
1755
- dashboard: [sidebar-stats, main-chart]
1756
- ```
1757
-
1758
- **Rules:**
1759
- - `@`-prefixed files are excluded from the top-level section list; `@@` nests deeper (grandchildren)
1760
- - `nest:` maps parent name → child names, and is **flat**: `{ features: [a, b], a: [sub-1] }`
1761
- - Children are ordered by position in the `nest:` array
1762
-
1763
- ```jsx
1764
- import { ChildBlocks } from '@uniweb/kit'
1765
-
1766
- export default function Grid({ block, params }) {
1767
- return <div className={`grid grid-cols-${params.columns || 2} gap-6`}><ChildBlocks from={block} /></div>
1768
- }
1769
- ```
1770
-
1771
- `ChildBlocks` renders each child as a **bare component by default** — no wrapper, no context class, no background. That's right for grid cells, tab panels, carousel slides. For the rare case where children should be independent sections with their own theming and backgrounds, pass `wrapAs="div"`.
1772
-
1773
- Each child is a regular section with its own type, params, and content — and you're in the middle: wrap each child, filter by type, reorder, add container classes. The author decides *what* goes in the grid; your component decides *how* it renders. Tomorrow the author can swap a child for a different section type with no code change, and your components stay reusable wherever child sections are accepted.
1774
-
1775
- **Data and child blocks:** page-level `query:` (or `fetch:`) is available to all blocks including children, and each child resolves data independently through the page → parent page → site hierarchy (the site's only on a top-level page). If a child needs data no ancestor declares, give it its own in its frontmatter (`query: articles`, or `fetch:`). Its `meta.js` `data:` declares the keys it receives and their shapes, never where the data comes from — it fetches nothing.
1776
-
1777
- **SSG:** insets, `<ChildBlocks>`, and `<Visual>` all render correctly during prerender. Inset components using React hooks internally trigger prerender warnings — expected and harmless; the page renders correctly client-side.
1778
-
1779
- ### Dividers — content boundaries
1780
-
1781
- `---` creates a boundary between content regions; the developer decides what each region means.
1782
-
1783
- **UI regions.** `splitContent()` from `@uniweb/kit` splits parsed content at divider elements — e.g. lesson prose vs challenge content:
1784
-
1785
- ```jsx
1786
- const [lesson, challenge] = splitContent(content)
1787
- ```
1788
-
1789
- <!-- template:loom -->
1790
- **Data-driven iteration (Loom).** Dividers separate header/body/footer in a repeated template. The split happens *before* Loom runs, because each segment gets a different variable context — the body contains item-level fields that don't exist on the top-level data. Header and footer are instantiated once against the full data; the body repeats per item.
1791
-
1792
- ```markdown
1793
- ---
1794
- type: CvEntry
1795
- source: education
1796
- ---
1797
- # Education
1798
- {COUNT OF education} degrees.
1799
- ---
1800
- ## {degree}
1801
- {institution} — {field} ({start}–{end})
1802
- ```
1803
-
1804
- **Which to use:** different data contexts per region → Loom pre-parse split (content handler). Same data, different UI treatment → kit post-parse split (`splitContent`). A foundation can use both — Loom splits and iterates to produce final content, then the component splits the result to route regions to different UI.
1805
- <!-- /template:loom -->
1806
-
1807
- ### Custom layouts
1808
-
1809
- Layouts live in `layouts/` inside the foundation and are auto-discovered. Set `defaultLayout` in `main.js`, or name a layout `Default`. With neither, a page that names no layout gets the built-in layout — `header`, the page, `footer`, nothing else — and a `defaultLayout` that names none of your layouts stops the build.
1810
-
1811
- ```jsx
1812
- // layouts/DocsLayout/index.jsx
1813
- export default function DocsLayout({ header, body, footer, left, right, params }) {
1814
- return (
1815
- <div className="min-h-screen flex flex-col">
1816
- {header && <header>{header}</header>}
1817
- <div className="flex-1 flex">
1818
- {left && <aside className="w-64">{left}</aside>}
1819
- <main className="flex-1">{body}</main>
1820
- {right && <aside className="w-64">{right}</aside>}
1821
- </div>
1822
- {footer && <footer>{footer}</footer>}
1823
- </div>
1824
- )
1825
- }
1826
- ```
1827
-
1828
- Layouts are full components with their own `params` in `meta.js`, not just structural wrappers — a header height or sidebar width is a layout param.
1829
-
1830
- **Layout `meta.js`** declares areas and optional scroll behavior: `{ areas: ['header', 'footer', 'left'], scroll: 'self' }`. Area names are arbitrary. `areas` tells an editor what to offer; a page renders the areas its site's `layout/` folder fills. `scroll` controls scroll restoration: unset = runtime manages `window` (default), `'self'` = the layout scrolls itself, or a CSS selector (`'main'`) = runtime manages that element.
1831
-
1832
- Two optional keys tune how areas behave across a navigation. `transitions` renames or opts regions out of per-area view transitions (`{ left: null }`, or `false` for the whole layout). The body has no name and crossfades with the page: Safari captures a named element whole, so naming it (`{ body: 'main' }`, for a body that morphs between layouts) freezes a phone on a long page. `layers` sets which area paints on top — every area is stacked above the body by default, so a fixed header works without declaring anything, and a sticky area (one with a `sticky` section) above every area that does not stick, since the page scrolls under it. Otherwise areas are equal to each other, so a layout whose chrome overlaps says which wins: `layers: { header: 2, left: 1 }`, which also ranks a sticky area it names. Both take an object to override per region, or `false` to opt out. **A `z-index` inside an area cannot lift it past another area** — each area is its own stacking context — so reach for `layers` rather than a bigger number, and for `<Overlay>` when a modal needs to escape the area entirely.
1833
-
1834
- **Layout content** lives in `site/layout/` — `header.md`, `footer.md` for the default layout, or a named subdirectory (`site/layout/marketing/`) for named layouts. Named subdirectories are self-contained — no inheritance. Cascade: `page.yml` → `folder.yml` → `site.yml` → foundation `defaultLayout` → `"default"`. The structure alone decides what an entry is: every folder directly under `layout/` is a named layout (its name matched regardless of case and of a trailing `Layout` — `site/layout/docs/` serves the foundation's `DocsLayout`), and an area with several sections is a folder inside a layout's folder — `site/layout/default/header/1-topbar.md` for the default layout. An area has no `page.yml`; its sections render in filename order.
1835
-
1836
- Layout sections are regular section types — they support the full content shape, including tagged data blocks, lists, links, and items. The only difference is they render on every page. Each content category takes a different role:
1837
-
1838
- ````markdown
1839
- ---
1840
- type: Header
1841
- ---
1842
- # Acme Inc ← content.title — the logo
1843
-
1844
- - ![](lu-search) [How It Works](/how) ← content.lists[0] — the nav
1845
- - ![](lu-book) [Docs](/docs)
1846
-
1847
- [Get Started](/docs/quickstart) ← content.links[0] — the CTA
1848
-
1849
- ```yaml:config
1850
- github: https://github.com/acme ← content.data.config — everything else
1851
- ```
1852
- ````
1853
-
1854
- ```jsx
1855
- function Header({ content }) {
1856
- const logo = content.title
1857
- const navItems = content.lists[0] || []
1858
- const cta = content.links[0]
1859
- const config = content.data?.config // with `data: { config: {} }` in Header's meta.js
1860
- }
1861
-
1862
- function Footer({ content }) {
1863
- const tagline = content.paragraphs[0] // a plain paragraph
1864
- const columns = (content.lists[0] || []).map(group => ({
1865
- label: group.paragraphs[0], // nested list → columns
1866
- links: group.lists[0]?.map(item => item.links[0])
1867
- }))
1868
- }
1869
- ```
1870
-
1871
- ### Cross-block communication
1872
-
1873
- Section types sometimes coordinate — the typical case is a Header that needs to know whether the section below supports a floating translucent overlay (a Hero with a full-bleed background does, a plain text section doesn't). The section that **owns the capability declares it**; the section that **needs to adapt reads it**. `getNextBlockInfo()` — and `getPrevBlockInfo()`, `page.getFirstBodyBlockInfo()` — expose two channels:
1874
-
1875
- - **`context`** — static capabilities from `meta.js`. Never changes.
1876
- - **`state`** — dynamic runtime state via `useBlockState()`. Initial value from `initialState` in `meta.js`.
1877
-
1878
- ```js
1879
- // Hero/meta.js
1880
- export default {
1881
- context: { allowTranslucentTop: true }, // "I always support this"
1882
- initialState: { allowTranslucentTop: true }, // …or start true and let logic change it
1883
- }
1884
- ```
1885
-
1886
- ```jsx
1887
- // Hero/index.jsx — dynamic case
1888
- const [state, setState] = block.useBlockState(useState)
1889
-
1890
- // Header/index.jsx — reads dynamic state, falls back to static context
1891
- const info = block.getNextBlockInfo()
1892
- const isFloating = info?.state?.allowTranslucentTop ?? info?.context?.allowTranslucentTop ?? false
1893
- ```
1894
-
1895
- The key names are yours to design — they're not framework fields.
1896
-
1897
- ### block, website, and page
1898
-
1899
- ```jsx
1900
- const { website } = useWebsite()
1901
- const page = website.activePage
1902
- ```
1903
-
1904
- | `block` property | Description |
1905
- |----------|-------------|
1906
- | `block.page` / `block.website` | Parent page / site-level data and navigation |
1907
- | `block.type` | Component type name |
1908
- | `block.childBlocks` / `block.insets` | Child sections / inline `@Component` references |
1909
- | `block.getInset(refId)` | Lookup an inset by refId |
1910
- | `block.properties` | Raw frontmatter |
1911
- | `block.rawContent` | The section's ProseMirror document, before parsing — what a content handler reads |
1912
- | `block.themeName` | `"light"`, `"medium"`, `"dark"` |
1913
- | `block.stableId` / `block.key` | Stable ID from filename or `id:` / unique key across pages — use as React key |
1914
- | `block.path` | Page route this block belongs to |
1915
- | `block.dataLoading` | True while declared data is still resolving — also on a pre-rendered page, for data the browser fetches, so the loading state is what that page first shows |
1916
- | `block.dataError` | `{ <key>: message }` when the fetch filling a declared key FAILED, else `null`. A failed key is `null` in `content.data` — never `[]`, which means "no records" |
1917
-
1918
- ```jsx
1919
- // getPageHierarchy(options) →
1920
- // [{ id, route, navigableRoute, translatedRoute, title, label, description, hasContent, children }]
1921
- // Options: for: 'header'|'footer'|<area> (respects hideIn) · nested: true (default)
1922
- // includeHidden: false · under: route · filter: (page) => bool · sort: (a, b) => number
1923
- website.getPageHierarchy({ for: 'header' }) // = website.getHeaderPages()
1924
- website.getPageHierarchy({ nested: false }) // = website.getAllPages()
1925
-
1926
- website.name, website.basePath
1927
- website.hasMultipleLocales(), website.getLocales(), website.getActiveLocale(), website.getLocaleUrl('es')
1928
- website.switchLocale('es') // a language switch from code (a <select>, a button)
1929
-
1930
- page.title, page.label, page.route, page.description
1931
- page.isHidden(), page.showInHeader(), page.showInFooter()
1932
- page.hasContent() // true if the page has its own content (not just a folder)
1933
- page.hasChildren(), page.children, page.parent
1934
- page.getNavigableRoute() // first descendant route with content (for linking)
1935
- ```
1936
-
1937
- Content-less containers appear as group nodes (`hasContent: false`) — use `navigableRoute` for links, `title` for display, `hasContent` to style differently.
1938
-
1939
- ### Data
1940
-
1941
- **A section receives the keys its component declares in `meta.js` `data:` — and nothing else** (plus any its foundation declares in `main.js` `data:`). A component that reads `content.data.articles` declares `articles`. Each declared key is filled by, in order: a tagged data block in the section; else the fetch that fills it, level by level from the section's own to the site's — a fetch whose `as` (its query's name by default) is the key, or else, **automatic `as`**, the first fetch under an undeclared key whose query's schema is the key's (`@/x` matches any scope's `x`); else `null`. So `data: { related: '@std/article' }` receives an `articles` query under `related`. `as:` on a fetch picks the key when two keys or two fetches share a schema. A fetch that fills none of a section's keys is not requested for it.
1942
-
1943
- **A key says how many records it holds, and how much of each — two flags, independent.** A ref alone (`'@std/article'`) is a **list of briefs**: on the query's own page every record the fetch takes, on a parametric page (`[slug]/`) a single-element array, `[]` when nothing matches. Write the key long to change either:
1944
-
1945
- ```js
1946
- data: {
1947
- articles: '@std/article', // a list of briefs
1948
- article: { schema: '@std/article', single: true, whole: true }, // one record, whole
1949
- card: { schema: '@std/article', single: true }, // one record's brief
1950
- archive: { schema: '@std/article', whole: true }, // a list of whole records
1951
- }
1952
- ```
1953
-
1954
- - **`single: true`** — the key holds **one record**: the first its binding selects (on a `[slug]` page, the record the URL names), or `null` when there is none. The runtime asks for just that one. A binding over many gives the first: sort the query, or give the binding `limit: 1`.
1955
- - **`whole: true`** — each record **whole**, as stored: every section under its own name, the brief's included — `article.brief.title`, `article.body.content`. Without it, each record is its **brief**: the brief section's fields at the top, the section not named. The runtime asks for what the key declares; a `whole` key its source cannot answer whole is `null`. A `fields:` schema's brief is the whole record, so `whole` is only needed for a schema with more than one section.
1956
- - The long form takes `schema`, `single` and `whole`, nothing else — the build stops on any other property, and on `single` or `whole` over a schema whose root is a list (`@std/nav`, `@std/form`: the key holds that list). ⛔ `'@std/article/*'` is retired and stops the build: write `whole: true`.
1957
-
1958
- When nothing fills a key it is `null`. An external query's records have no schema and arrive as its source answers them. Reference: `reference/component-metadata.md` § *One record, or a list* and § *Briefs or whole records*.
1959
-
1960
- ```jsx
1961
- function Article({ content, block }) { // data: { article: { schema: '@std/article', single: true } }
1962
- if (block.dataLoading) return <DataPlaceholder />
1963
- if (block.dataError?.article) return <LoadFailed /> // the request failed — not "no records"
1964
- const article = content.data.article // the record the [slug] page's URL names, or null
1965
- if (!article) return <NotFound />
1966
- return <ArticleView article={article} />
1967
- }
1968
- ```
1969
-
1970
- Any other reshaping is the foundation's job — once, with a `handlers.data` hook.
1971
-
1972
- **Declaring keys and schemas.** `meta.js` declares each `content.data` key the component receives, with its schema, in a single `data:` field — there is no separate `schemas:` key. Each value is a **named ref**, an **inline field map**, an **inline rich-form** (`{ fields: [...] }`, an editor form), or `{}` for a key with no schema (an external API's records). Refs resolve on disk at build time, never fetched: `@/name` (this foundation's `schemas/`), `@std/name` (shared standards, from `@uniweb/schemas`), `@org/name` (an org's own `@org/schemas` package). A schema drives the editor, checks your data (`uniweb validate`), and lets a fetch of another name fill the key — it fills no field: **a record reaches the component as it is**, so a field it lacks is absent, and what that renders as is your component's choice (`record.status ?? 'published'`). **A named schema declares no `default:`** — the build refuses one; a `default:` belongs only in an inline field map or form, where an editor pre-fills from it. ⛔ **Delivery was default-on until this change** — every fetched key reached every component, and `data:` was a hint; a component that reads a key it does not declare now receives nothing under it. `data: false` declares nothing, like no `data:`. Keys a foundation's handlers (or a shared hook) read go in `main.js` `data:`, in the same form, and every section receives them.
1973
-
1974
- ```js
1975
- // meta.js
1976
- export default {
1977
- data: {
1978
- articles: '@/article', // named ref (this foundation)
1979
- authors: '@std/person', // named ref (shared standard)
1980
- pricing: { tier: { type: 'string' } }, // inline field map
1981
- },
1982
- }
1983
- ```
1984
-
1985
- A foundation can route a scope to a plain folder of schema files instead of a package via an optional `schemas.config.js` at its root — `export default { '@acme': '../shared/acme-schemas' }`. A routed scope wins over the package convention; `@/` and `@uniweb` are never routable; a routed scope has no package fallback for a missing schema (it errors rather than silently loading a different definition). Per-schema keys override single entries (most-specific wins: file › directory › package). Worked examples: `development/schemas-in-practice.md`.
1986
-
1987
- **Authoring queries.** Queries and fetch declarations accept `where:` (a where-object predicate), `sort:` (ONE key, e.g. `date desc` — text sorts in the page's language, and a record with no value for the key sorts last either way), and `limit:` — on a query they select its records, on a fetch they take from those. The framework evaluates them in the browser over the records it fetched, the query's first; a host that answers queries evaluates the same language at the source; a foundation transport decides for itself — it receives the query's fields and the fetch's own under `narrow`. The declaration is identical in every case.
1988
-
1989
- ```yaml
1990
- # pages/blog/page.yml
1991
- fetch:
1992
- query: recent
1993
- where: { tags: featured }
1994
- sort: date desc
1995
- limit: 3
1996
- ```
1997
-
1998
- **Lean lists.** A list carries each record's brief, so heavy parts belong in a section of their own — `@std/article`'s body is `body` — and never ride a list. A section that shows them declares its key `whole: true`; elsewhere components fetch the whole record on demand with `useWholeRecord(record, { query })`, which returns it as stored — `full.body.content`. Every file-based record gets its own file, `/data/<name>/<name of the record>.json`. An external query's whole record comes from its `record:` request, below. (`deferred:` is removed — the build stops on it.) The hook is safe to call on any query: when the query has no separate source for one record it returns the record you passed in.
1999
-
2000
- **Component-side fetching.** When a component genuinely needs to fetch on its own (a search box, "load more", a lazy popover), use the kit hooks — `useFetched`, `useCacheEntry`, `useWholeRecord`. They share the framework's cache and dispatcher with declarative fetches; same-key requests dedupe automatically. On a pre-rendered page a hook's first render finds only what that page's own data holds — a declared key's answer, or its page's or the site's `fetch:`. Anything else is pre-rendered as the hook's loading state and fetched by the browser after it loads, so declare a key (`data:` in `meta.js`) for whatever a page must show without JavaScript.
2001
-
2002
- **Validate before shipping.** `uniweb validate` checks file-based data against your declared schemas — missing required fields, type/enum/format mismatches, nested fields. A violation fails it (`--lax` only reports); it checks every record file in `records/`, and `push` / `publish` refuse the same findings before sending anything. Distinct from `uniweb doctor` (project structure): `validate` checks your *data* against the schemas you *declared*. External queries (`url:`) are reported as deferred — their data isn't in the project; the value of a `ref`/`options` field is not checked against the entity it names.
2003
-
2004
- ### Fetching from other sources (`fetcher:`)
2005
-
2006
- A site isn't limited to its own records. A public, keyless JSON API is an **external query** — a query with `url:`, declared beside the others and named by pages the same way (`query: posts`):
2007
-
2008
- ```yaml
2009
- # queries.yml
2010
- posts:
2011
- url: https://api.example.com/posts
2012
- transform: data.items # dot-path to the records in the response
2013
- record: # one whole post, for a [id] page
2014
- url: https://api.example.com/posts/{id}
2015
- ```
2016
-
2017
- It also takes `method: POST` with a `body`, `where` / `sort` / `limit` (evaluated over what arrived, after `transform`), and `queryable`. Its records are entries in no folder and have no `$name`, so a `[slug]` page over it names the field the URL is in the query's own `where` — `where: { slug: :slug }` — which drops on the query's own page. `record:` takes `url`, `method`, `body` and `transform`: `url` and `method` default to the query's, `body` and `transform` never carry over, and a placeholder named by the page's folder (`{id}` for `[id]`, `{slug}` for `[slug]`) is its URL segment. `schema`, `scope`, `deferred`, `excerpt` and `path` are refused beside `url:` — they describe the site's own records. The visitor's browser fetches an external query (a `fetch:` with `prerender: true` makes the build fetch it instead); it is never asked of a host's records service and compiles no `/data` file. On a `[id]` page the list still decides which records exist — `record:` fetches the one it found, whole. A site published to a Uniweb host reads the host's records with no configuration at all.
2018
-
2019
- ⛔ A `fetch:` never carries a source: `path`, `url`, `method`, `body`, `transform`, `detail` and `scope` on a fetch stop the build. The `detail:` forms (`rest`, `query`, a URL pattern) are now an external query's `record:`, and `detailUrl:` is `record.url`.
2020
-
2021
- A backend that needs a key, headers, paging, its own wire or query language is a **transport**: a named `{ resolve, cacheKey? }` exported by the foundation (or an extension), which the site selects per data key in `fetcher:` — the only thing that block is for:
2022
-
2023
- ```yaml
2024
- # site.yml
2025
- fetcher:
2026
- transports:
2027
- articles: acme # a foundation-registered transport handles `query: articles`
2028
- events: default # explicitly route back to the default fetcher
2029
- acme: # binding config that transport reads
2030
- apiKey: pk_public_123
2031
- ```
2032
-
2033
- **Selection is explicit and site-owned.** For each request: `fetcher.transports[as]` wins if set; otherwise `fetcher.transports.default` if set; otherwise the framework's default fetcher. No route-walking, no `match()` predicates, no silent foundation-owned routing — the site picks.
2034
-
2035
- ⛔ `fetcher.baseUrl`, `headers`, `envelope`, `supports` and `request.*` are **retired**: a third party's conventions belong in a transport, not in the runtime every site loads. The build warns once and ignores them.
2036
-
2037
- > **Never put secrets in `site.yml` or `queries.yml`** — every value in them is public to the browser. Sites needing private credentials proxy through the same origin at the deployment layer, so the site fetches `/api/…` and the proxy attaches the credential server-side.
2038
-
2039
- **Failures are visible, not empty:** a fetch that failed leaves its key `null` in `content.data` and names the message on `block.dataError[key]`; it is never delivered as `[]`, which means "no records". The page still renders — a section reads `dataError` to tell the two apart.
2040
-
2041
- When an external query is enough and when a transport is the answer: `development/data-sources.md`.
2042
-
2043
- Full model: `reference/data-fetching.md`. Where-object format with examples: `authoring/predicates.md`.
2044
-
2045
- ### Search (`services.search`)
2046
-
2047
- Search follows the same arrangement as `fetcher:` — the **site** declares where results come from, and a search UI reads them the same way regardless. Never hardcode a search endpoint in a component; that couples the foundation to one host. Search is on by default; its entry under `services:` (see *Services*, below) turns it off, sets options, or — on a site you publish — asks the host for it:
2048
-
2049
- ```yaml
2050
- # site.yml
2051
- services:
2052
- search:
2053
- provider: index # default — download an index, match in the browser
2054
- ```
2055
-
2056
- | Provider | Answers with | Trade-off |
2057
- |---|---|---|
2058
- | `index` (default) | `search-index.json`, ranked in the browser | Free, works on **any** host including a plain static one, tolerates typos. Contains only what existed at build time. |
2059
- | `endpoint` | A server-side search API | Can cover records fetched from an API, and can be re-indexed without rebuilding the site. Requires a host that serves one. |
2060
- | *any other name* | A foundation-supplied search transport | Fully open — Typesense, Meilisearch, Pagefind, a vendor API |
2061
-
2062
- ```yaml
2063
- services:
2064
- search:
2065
- provider: endpoint
2066
- endpoint: _search # REQUIRED — there is no default
2067
- ```
2068
-
2069
- `endpoint:` is **required** with `provider: endpoint`; omit it and the provider refuses the query rather than guessing a path. It resolves against the site's base path — `/` → `/_search`, `base: /docs/` → `/docs/_search`, a subpath-served site follows its subpath. An absolute `https://…` URL points at another origin. A host that serves the site may offer search itself: `search: true` asks for it, and the host supplies the address. An endpoint of your own asks the host to leave its search off, so yours answers.
2070
-
2071
- **Results have one shape, whatever the provider.** Always present: `id`, `type`, `route`, `href`, `title`, `pageTitle`, `excerpt`, `snippetHtml`. Provider-optional (`null` when absent): `sectionId`, `anchor`, `description`, `component`, `snippetText`, `matches`, `group`, `item`. `type` is `page`, `section` or `record`; on a record hit, `item` holds the record's fields and `group` names the set it came from. Whether an optional field arrives is a deployment fact, not a content fact — the same site yields `item` from a server provider and `null` from the local index — so guard them: `result.item?.image`.
2072
-
2073
- `snippetHtml` is HTML with `<mark>`. Render it through `SafeHtml`, never as text.
2074
-
2075
- **Failures degrade rather than break** — a failing provider falls back to the local index when one exists, otherwise returns no results with a console warning. A search box never throws at a visitor.
2076
-
2077
- ```jsx
2078
- import { useSearch } from '@uniweb/kit'
2079
-
2080
- const { results, isLoading, query } = useSearch(website) // `query` is a function
2081
- <input onChange={e => query(e.target.value)} /> // debounced internally
2082
- ```
2083
-
2084
- Full reference: `authoring/search.md`.
2085
-
2086
- ### Forms (`services.submit`)
2087
-
2088
- Drawing a form is a foundation's job; delivering what a visitor typed needs a
2089
- server. Where that server is comes from the **site or its host** — never from a
2090
- section type, same arrangement as `fetcher:` and search.
2091
-
2092
- A form gets its destination from the first of these that applies:
2093
-
2094
- 1. **One the host supplies** — `config.services.submit` in the payload it serves. Where the
2095
- host handles submissions, that is the destination. A site published to Uniweb
2096
- Cloud asks for it with `submit: true` under `services:` and names no address.
2097
- 2. **An address of the site's own** — `submit: <url>` under `services:`, for a
2098
- static site or a host that does not handle submissions. On a host that does, it
2099
- asks the host to leave its own off, so this one answers.
2100
- 3. **Neither** — there is no destination: render no form, or fall back to contact
2101
- details the site already carries.
2102
-
2103
- In `uniweb dev` the dev server is the host: `submit: true` is answered there, so a form shows and
2104
- can be sent while you work. Each submission is printed in the terminal and kept in the site's
2105
- `.uniweb/dev-submissions/` — read it there to see exactly what an endpoint would receive.
2106
-
2107
- That is the general arrangement, not a forms-only one. A host states everything
2108
- it offers in the served payload's `config.services`, keyed by name, and every service
2109
- resolves by the same rule — the host's offer, then the site's own address, then
2110
- neither.
2111
-
2112
- ⭐ **Before you render UI for a service, ask whether the site has it** — one predicate per service,
2113
- no arguments: `isSearchEnabled()`, `isSubmitEnabled()`, `isBackendEnabled()`, `isAssistantEnabled()`,
2114
- `isTrackingEnabled()`.
2115
-
2116
- ```jsx
2117
- import { isSearchEnabled } from '@uniweb/kit'
2118
-
2119
- if (!isSearchEnabled()) return null // false ⇒ draw nothing
2120
- ```
2121
-
2122
- Each answers the same question — *would UI for this service work on this site?* — and `false`
2123
- always means the same thing: **draw nothing.** `isSearchEnabled()` is true whenever *any* provider
2124
- answers, including the prebuilt index a static site ships, so a search box gated on it appears
2125
- wherever search works. The hooks that draw a feature hand you the same answer as a field
2126
- (`useSearch().isEnabled`, `useFormSubmit().canSubmit`), so a component already using one needs
2127
- nothing extra.
2128
-
2129
- When you need the **address** itself, not just whether one exists, ask for it:
2130
-
2131
- ```jsx
2132
- import { resolveService } from '@uniweb/kit'
2133
-
2134
- const { url, source } = resolveService(website, 'assistant') // or 'search', or your own
2135
- ```
2136
-
2137
- **The name is open**: the framework ships clients for what it implements and
2138
- resolution for anything, so a foundation can define a service the framework has
2139
- never heard of and a host can fill it — ask for it with
2140
- `website.isServiceEnabled('booking')`. Same escalation `fetcher.transports`
2141
- offers for data.
2142
-
2143
- **Building an "Ask AI" component?** The service name is `assistant`, and a host that runs an agent for a site typically serves it at the conventional path `/_agent`. **You should never need to write that path** — ask the runtime instead:
2144
-
2145
- ```jsx
2146
- const { url } = resolveService(website, 'assistant')
2147
- if (!url) return null // this site has no agent — render nothing, or a static fallback
2148
- ```
2149
-
2150
- **This is a synchronous read, not a request.** Which services a site has was settled when the site was last published and travels in its metadata, so the runtime already holds the answer — there is no handshake, no probe, no await. Your component asks the runtime; the runtime does not ask anyone.
2151
-
2152
- ⛔ **Absent is the answer, not a lookup that failed.** No `url` means the site has no agent — never enabled, or this host runs none. Render for that case; don't retry it. And don't hardcode `/_agent/chat` when nothing was declared: on a static host that turns "no agent here" into a 404 your component can't tell from a broken endpoint. The path is named above so you recognize the shape, not so you can construct it.
2153
-
2154
- ⛔ **And don't tell the visitor.** `resolveService` returns `{ url, source }` and **deliberately nothing else** — there is no explanatory string and there was one, removed because it was a mistake. A visitor has no stake in which services the operator provisioned, and "this site has no assistant configured" reports someone's billing state to the public while reading like a breakage. It is neither. Worse, it is unfixably the wrong language: sites here are multilingual, or unilingual and not English, and a canned constant bypasses the site's whole localization pipeline. **Absence is a rendering decision, not a message**, and a generic component is expected to be smart about it. No assistant → no Ask-AI affordance. No submit endpoint → no form, or degrade to a `mailto:` the site already carries in its content. Any text a visitor should read is *site content* — authored and localized.
2155
-
2156
- `source` is `'site'`, `'host'` or `null`, and it is a **diagnostic for you** while you wire a site up: it says which tier answered, which is the thing to check when a host's value appears not to be taking effect. `'host'` with a null `url` means the host answered and offered no address.
2157
-
2158
- *(A live agent that errors mid-conversation is a different problem — that's ordinary request failure, handled where you make the request.)*
2159
-
2160
- ### Declaring what your foundation supports
2161
-
2162
- The predicates above, and `resolveService`, are how you ask at render time. The other direction — telling a
2163
- host, *before* anything renders, which services your foundation is built to use —
2164
- is one line in the foundation's `package.json`:
2165
-
2166
- ```json
2167
- {
2168
- "uniweb": { "supports": ["search", "submit", "tracking"] }
2169
- }
2170
- ```
2171
-
2172
- Service names, the same ones you pass to `resolveService`. It reaches a host when
2173
- the foundation is registered, and it answers a question a host cannot otherwise
2174
- answer: **a service only does something if the foundation renders something
2175
- against it.** A host that offers search has no way to know whether your sections
2176
- draw a search box, so without this it either offers a site something its code
2177
- will ignore, or withholds something it would have used.
2178
-
2179
- **What a host receives is one of three answers:**
2180
-
2181
- | | |
2182
- |---|---|
2183
- | a list — `["search"]` | the services this foundation renders against, and only these |
2184
- | `[]` | none — proven by the build, not assumed |
2185
- | absent | *unknown* — the build could not tell, and nothing was declared |
2186
-
2187
- ⭐ **The build reads the set off your code.** When the foundation is built, `supports` is derived
2188
- from what the bundle actually reaches — `resolveService(website, 'search')`, or a predicate like
2189
- `isSearchEnabled()` — so a foundation that never writes the key still publishes an accurate set.
2190
- What you write in `package.json` is a **supplement**: the build publishes the union, so a
2191
- declaration can add a service but never remove one the code reaches.
2192
-
2193
- **Declare only what the build cannot see.** A service reached through a *computed* name —
2194
- `resolveService(website, name)` where `name` is a variable — is invisible to it, and the build
2195
- warns when that happens. List those. `uniweb doctor` compares what you declared with what the build
2196
- found.
2197
-
2198
- ⚖️ **Baseline behaviour is not yours to declare.** Some services do something for
2199
- a site whether or not a foundation cooperates — the runtime reports page views
2200
- wherever tracking is configured, with no help from your components. List
2201
- `tracking` when you go *beyond* that (your own events on your own components);
2202
- leaving it out does not switch the baseline off.
2203
-
2204
- ```yaml
2205
- # site.yml
2206
- services:
2207
- submit: true # your host's form handling (Uniweb Cloud)
2208
- ```
2209
-
2210
- ```yaml
2211
- # site.yml — when YOU are providing the endpoint: `uniweb export`, most `deploy --host` targets
2212
- services:
2213
- submit: https://forms.example.com/intake # or /forms, base-relative like search's endpoint
2214
- ```
2215
-
2216
- ```jsx
2217
- import { useFormSubmit } from '@uniweb/kit'
2218
-
2219
- const { submit, status, error, canSubmit } = useFormSubmit({
2220
- block, // supplies section + page context
2221
- context: { formId: 'contact' },
2222
- summary: (v) => ({ title: v.name, subtitle: v.email }),
2223
- })
2224
-
2225
- if (!canSubmit) return null // nowhere to send — render no form, or fall back
2226
- // to contact details from the site's own content
2227
-
2228
- <button type="submit" disabled={status === 'submitting'}>Send</button>
2229
- ```
2230
-
2231
- > **The framework never invents an endpoint — but a host may supply one.** Don't
2232
- > write an address reflexively: on Uniweb Cloud an address asks the host to turn its
2233
- > own form handling off — `submit: true` is the whole declaration there. Reach for an
2234
- > address when you are the one hosting.
2235
- >
2236
- > `canSubmit` is false only when neither the host nor an address of the site's own
2237
- > supplies a destination. **Check it when you render, not only on the button press** — a
2238
- > form nobody can send should not be on the page at all. A read that 404s
2239
- > degrades to `[]` and the page still renders; a write that 404s loses what a
2240
- > person typed, so it gets no silent fallback.
2241
- >
2242
- > ⛔ **Don't tell the visitor why.** There is deliberately no explanatory string:
2243
- > which services an operator bought is none of a visitor's business, "not enabled
2244
- > for this site" reads like a breakage when nothing is broken, and any such
2245
- > sentence would be one language on a site that is often multilingual and rarely
2246
- > English. Text a visitor reads is **site content** — authored, and localized with
2247
- > everything else. Degrade to something useful instead: a `mailto:`, a phone
2248
- > number, an address the site already carries.
2249
-
2250
- `status` runs `idle → submitting → success | error`; a non-2xx becomes a thrown
2251
- `Error` carrying the endpoint's own `error` message when it sends one. For file
2252
- fields, declare `fileSlots` and the endpoint replies with `uploadUrls` — the
2253
- bytes never ride inside the JSON. `submitForm()` / `resolveSubmitTarget(website)`
2254
- are the same behaviour without React.
2255
-
2256
- **Rendering a form the AUTHOR designed** — a `yaml:form` block at
2257
- `content.data.form` — is the inverse of every other component: you don't declare
2258
- the fields, you receive them and draw whatever you're given. `useFormValues` owns
2259
- the part that's identical in every such component, so you write only the controls:
2260
-
2261
- ```jsx
2262
- import { useFormValues, useFormSubmit, valueAt } from '@uniweb/kit'
2263
-
2264
- const { controls, values, setValue, missing, formData, files } =
2265
- useFormValues(content.data.form)
2266
- const { submit, canSubmit, status } = useFormSubmit({ block })
2267
-
2268
- {controls.map((c) => (
2269
- <MyControl key={c.path} control={c} // branch on c.type — your design
2270
- value={valueAt(values, c.path)}
2271
- onChange={(v) => setValue(c.path, v)} />
2272
- ))}
2273
- <button disabled={!canSubmit || missing.length > 0} onClick={() => submit(formData, { files })}>
2274
- ```
2275
-
2276
- `valueAt(values, path)` reads one control's value back out. It is the companion
2277
- of `setValue` and is exported for exactly this loop: `values` is **nested**, so a
2278
- control at `address.street` lives at `values.address.street`, and `values[c.path]`
2279
- returns `undefined` for every nested control — a form that silently renders blank
2280
- inputs and submits empty answers. Use `valueAt`, never index by path.
2281
-
2282
- It seeds each control's `default`, tracks edits, and reports `missing` — the
2283
- `required` controls still empty — without enforcing anything, the same line
2284
- `canSubmit` draws. **Submit `formData`, not `values`:** they differ because a
2285
- `File` inside `formData` would be JSON-serialized to `{}`, so file controls are
2286
- omitted from it and ride in `files` instead, each tagged with the control it came
2287
- from. `values` keeps the `File` so your input can show its selection.
2288
-
2289
- Full reference: `development/receiving-form-submissions.md`.
2290
-
2291
- ### Tracking (`services.tracking`)
2292
-
2293
- A site may declare one **tracking destination**, and everything worth counting
2294
- goes there as an event on a single stream. A page visit is just the event the
2295
- runtime emits by itself.
2296
-
2297
- ```yaml
2298
- # site.yml — your own collector, on any host
2299
- services:
2300
- tracking: https://collector.example.com/events
2301
- ```
2302
-
2303
- ```yaml
2304
- # or, when it needs more than an address
2305
- services:
2306
- tracking:
2307
- endpoint: /collect
2308
- consent: required
2309
- ```
2310
-
2311
- A host may also supply one — `tracking: true` asks for it on a site you publish —
2312
- and the usual precedence applies: the host's, then yours, then neither. An
2313
- endpoint of your own asks the host to leave its collector off, so yours answers.
2314
-
2315
- ⚠️ **The endpoint has to accept the framework's own format** — a batched
2316
- `{ "events": [ … ] }` POST, documented in `reference/site-configuration.md`. It
2317
- is not a third-party analytics product's public API, which expects that
2318
- product's own shape.
2319
-
2320
- A site may also name a vendor's own script under `services.tracking.scripts`, which the
2321
- runtime loads once, after consent when a gate is declared, and never in a frame
2322
- or during prerender. That is a **separate path with no connection to the stream
2323
- below** — the vendor measures its own way, and nothing you `track()` reaches it. On a
2324
- site you publish, an entry with no endpoint also asks the host for its collector;
2325
- `enabled: false` beside `scripts` loads the script alone.
2326
-
2327
- ⛔ **An entry is a URL and nothing else, so Google Analytics, Google Tag Manager and
2328
- Meta's pixel can't be installed this way.** Each one's install runs inline lines, and
2329
- from a URL alone Google Analytics sends nothing and Tag Manager never gets its
2330
- page-load event. A tag carrying an attribute the vendor reads, like `data-domain` or
2331
- `data-website-id`, has the same problem. What works for these depends on who builds
2332
- the pages:
2333
-
2334
- - **The framework builds them** (`uniweb export`, `uniweb deploy --host=<adapter>`): the
2335
- vendor's snippet goes in `head.html` next to `site.yml`, and the build adds it to every
2336
- page's `<head>`. A `services.google` entry does nothing here.
2337
- - **Uniweb Cloud builds them** (`uniweb publish`): `head.html` is kept and synced but not
2338
- applied. For Google's two, name the ID and the host loads the tag from the next publish,
2339
- with no code, on any foundation:
2340
-
2341
- ```yaml
2342
- services:
2343
- google:
2344
- id: G-XXXXXXXXXX # or GTM-XXXXXXX, or a list of both
2345
- ```
2346
-
2347
- The app's site settings edit the same entry, and a pull or a push carries a change across.
2348
- Leave `services.tracking.scripts` unset beside it: a site's own list replaces what the host
2349
- states, so Google's tag would not load. `tracking: { enabled: false, consent: required }`
2350
- beside it holds the tag until a visitor answers, and takes a component using
2351
- `useTrackingConsent()`, or it never loads.
2352
-
2353
- Any other such vendor has to run from the foundation's code, so a site whose foundation you
2354
- can't change can't add one. Say so to the person rather than writing a `head.html` that does
2355
- nothing.
2356
-
2357
- Either way, tell the person that Google Analytics counts in-app navigation only with the
2358
- browser-history setting on, under Enhanced measurement in their data stream's settings.
2359
-
2360
- **Some events you get for free.** These are reported for you, with no call from
2361
- your foundation and regardless of how it renders:
2362
-
2363
- | event | when |
2364
- |---|---|
2365
- | `page_view` | every route change, including the first |
2366
- | `outbound_click` | a visitor follows a link off the site — the destination **host** only, never the full URL |
2367
- | `section_view` | a section first becomes half-visible, on pages that ask for it (`trackSections`, below) |
2368
- | `conversion` | a phone or email tap (`name: phone`, `email`), and a link or page the site lists in `services.tracking.conversions`; also a form accepted by a provider of the site's own through `useFormSubmit`, and a sign-up through `@uniweb/api` |
2369
- | `engagement` | a sign-in through `@uniweb/api` (`name: sign_in`) |
2370
-
2371
- A `services.tracking.conversions` list is public, since it is in every page's data, so a
2372
- listed link must not carry a token. On a site you publish it also asks the host for its
2373
- collector, as any `tracking` entry with no endpoint does.
2374
-
2375
- ⛔ **So don't write your own link-click or scroll-into-view listener for these,**
2376
- and don't report a sign-up, a sign-in or an accepted form that goes through kit or
2377
- `@uniweb/api`. A second report double-counts against a collector that already has them.
2378
-
2379
- Everything else is yours to report:
2380
-
2381
- ```jsx
2382
- // In a section type, the block is already in your props.
2383
- block.track('video_milestone', { milestone: 50 })
2384
- ```
2385
-
2386
- `block.track` attaches the page path and the section type for you. For an event
2387
- with no block in hand, use the hook:
2388
-
2389
- ```jsx
2390
- import { useTracker } from '@uniweb/kit'
2391
-
2392
- const { track } = useTracker()
2393
- <button onClick={() => track('brochure_download', { file: 'specs.pdf' })}>…</button>
2394
- ```
2395
-
2396
- The event name is yours — there is no list of permitted names. Seven are already
2397
- in use, so reach for these rather than inventing a synonym: the automatic ones
2398
- above — **`page_view`**, **`outbound_click`**, **`section_view`**, **`conversion`**,
2399
- **`engagement`** — plus **`video_milestone`**, which kit's `<Media>` reports for any
2400
- video you render through it, and **`read_depth`** from `useReadingDepth()` below.
2401
- What your foundation alone can see that a site counts is
2402
- `block.track('conversion', { name: 'quote_requested' })`, with a short name. Put the
2403
- varying part in a **field**, never in the name — four names for one event turn a
2404
- collector's event dimension into a cardinality problem.
2405
-
2406
- ### Choosing what a site sends
2407
-
2408
- By default a site sends `page_view`, `outbound_click` and `section_view` — or,
2409
- where a host supplies the collector, whatever that host declares it collects.
2410
- Narrow or widen that with `emit`:
2411
-
2412
- ```yaml
2413
- # site.yml — your own collector
2414
- services:
2415
- tracking:
2416
- endpoint: https://collector.example.com/events
2417
- emit: standard # minimal | standard | all — or a list of event names
2418
- ```
2419
-
2420
- ```yaml
2421
- # site.yml — a host that supplies the collector: say what to send, not where
2422
- services:
2423
- tracking:
2424
- emit: minimal
2425
- ```
2426
-
2427
- ⭐ **`emit` needs no endpoint of its own.** Where a host provides one, the site
2428
- declares only what it wants sent and the address comes from the host. The two
2429
- are read key by key, so naming `emit` alone overrides nothing else the host
2430
- declared. An `endpoint:` of your own means you collect yourself, and asks the host
2431
- to leave its collector off.
2432
-
2433
- `minimal` is `page_view` alone. `standard` is the default when the collector is
2434
- your own. `all` is a standing yes, so an event added in a later framework
2435
- release is included without you changing anything — which is exactly why
2436
- `standard` exists as well: it is a curated set that a release cannot grow behind
2437
- your back.
2438
-
2439
- ⭐ **Saying nothing means two different things, and which one depends on who
2440
- supplies the address.** A site sending to its own `endpoint:` gets `standard`. A site
2441
- on a **host-supplied** collector gets **whatever that host declares it
2442
- collects** — it has no address of its own, so the arrangement is that the host
2443
- does analytics for it, and the set grows when the host starts collecting
2444
- something new. **Naming `emit` always wins**, so pin it if you would rather not
2445
- follow your host.
2446
-
2447
- A site can also set **`flushIntervalMs`** to widen the batching window (default
2448
- 5000, milliseconds — `30` is thirty *milliseconds*). A host that supplies your
2449
- collector may set it for you and your own value wins; the trade is fewer
2450
- requests against more tail loss at the end of a visit.
2451
-
2452
- ⚠️ **`emit` never limits what YOU send.** `block.track()` and `useTracker()` are
2453
- not filtered by it — the registry is open, and your events are yours. It governs
2454
- only the ones the framework emits on its own. A host may narrow the list further
2455
- if it will not store an event, and it can never widen past what you asked for.
2456
-
2457
- ### Reading depth in a long section
2458
-
2459
- `section_view` tells you a reader *arrived* at a section. For a long-form one —
2460
- an article, a report, a case study — the question is how far they got:
2461
-
2462
- ```jsx
2463
- import { useRef } from 'react'
2464
- import { useReadingDepth } from '@uniweb/kit'
2465
-
2466
- export default function Article({ content, block }) {
2467
- const ref = useRef(null)
2468
- useReadingDepth({ ref, block })
2469
- return <article ref={ref}>{/* … */}</article>
2470
- }
2471
- ```
2472
-
2473
- That reports `read_depth` at 25 / 50 / 75 / 100% **of that element**, once each.
2474
- Measuring the element rather than the page is the point: two long sections on
2475
- one page report independently, and adding a section above them changes neither.
2476
-
2477
- ⭐ **This one is a hook rather than automatic because only you know a section is
2478
- long-form reading.** The framework cannot tell an essay from a row of logos, so
2479
- it does not guess — and a foundation that never calls this pays nothing for it.
2480
-
2481
- **`trackSections`** is one page's answer on `section_view`, and it overrides the
2482
- site in **both** directions — instrument one page of a site that sends `minimal`,
2483
- or exempt a noisy page of a site that sends `standard`. Say nothing and the
2484
- site's `emit` decides.
2485
-
2486
- ⭐ **This is the only event with a per-page control, and the asymmetry is the
2487
- point.** A page view is one event whatever the page and an outbound click is
2488
- bounded by what a visitor does, but a section view is **one per section** — so a
2489
- long page costs many times what a short one does. The control sits at the
2490
- granularity the cost actually varies at.
2491
-
2492
- ```yaml
2493
- # page.yml
2494
- trackSections: true # or false to exempt this page
2495
- ```
2496
-
2497
- ⛔ **Never guard a `track()` call.** A site with **no** tracking destination is
2498
- the default and the majority: the call returns having done nothing, opened no
2499
- connection, and thrown nothing. Absent is the normal state, not an error — so
2500
- don't check whether tracking is on, and never render differently because of it.
2501
- There is no "is tracking enabled" question a component should be asking.
2502
-
2503
- ⚠️ **If a site asks for consent**, tracking holds everything until a visitor
2504
- answers; granting sends what was buffered, denying discards it. A consent banner
2505
- is an ordinary component:
2506
-
2507
- ```jsx
2508
- import { useTrackingConsent } from '@uniweb/kit'
2509
-
2510
- const { status, grant, deny } = useTrackingConsent()
2511
- if (status !== 'pending') return null
2512
- return <CookieBanner onAccept={grant} onReject={deny} />
2513
- ```
2514
-
2515
- Without `consent: required`, tracking starts immediately — declaring a
2516
- destination is the site owner's decision to make, not the framework's.
2517
-
2518
- Every event carries a **`visit`** key on the envelope — opaque, generated at page
2519
- load, the same for every event of that page load — so a collector can order what
2520
- happened into a journey.
2521
-
2522
- > **What is never sent:** no visitor id, no fingerprint, no session spanning days
2523
- > or tabs, and **nothing is written to the visitor's device** — no cookie, no
2524
- > local storage. The `visit` key lives in memory and dies with the document, so
2525
- > it identifies one page load rather than a person. A `page_view` carries the
2526
- > path; two booleans about the page load — `first_of_load` on the view that
2527
- > opened the document, and `continues` when the load came from one of your own
2528
- > pages; and — captured once when the page first loads, then replayed on each
2529
- > view — the external referrer and any `utm_*` the visitor arrived with. Nothing
2530
- > else. **Both booleans describe the load, never the visitor**, and neither links
2531
- > two loads to each other.
2532
-
2533
- ### ⛔ Use kit. Never touch the `uniweb` global
2534
-
2535
- Everything above reaches the runtime through `@uniweb/kit` or through something
2536
- handed to your component as a prop. That is the rule, not a stylistic preference:
2537
-
2538
- - ✅ `useWebsite()`, `useTracker()`, `isSearchEnabled()` and the other service
2539
- predicates, `resolveService(website, …)` — kit hooks and utilities.
2540
- - ✅ `block.track(…)`, `block.page`, `block.website` — the block **arrives in your
2541
- props**, so calling methods on it is not reaching for a global.
2542
- - ⛔ `globalThis.uniweb`, `window.uniweb` — never, in a foundation.
2543
-
2544
- The singleton is framework internals: its shape is not part of the contract with
2545
- foundations, and code that reads it directly breaks on changes that were never
2546
- breaking changes. If you need something kit does not expose yet, that is worth
2547
- reporting — not worth reaching around.
2548
-
2549
- <!-- template:loom -->
2550
- ### Content handlers
2551
-
2552
- Content handlers are a transform layer between data assembly and the component, declared in `main.js` and applied to every section in the foundation. The standard content shape is the default; handlers reshape it. All three are optional, run per block, and are error-isolated — a failing handler logs a warning and falls back to default behavior.
2553
-
2554
- | Handler | When it runs | Receives | Returns | Purpose |
2555
- |---|---|---|---|---|
2556
- | `data` | After data assembly, before content transform | `(data, block)` | New data object, or null | Filter, reshape, or augment assembled data |
2557
- | `content` | After the data handler | `(data, block)` | ProseMirror document, or null | Transform raw content (Loom instantiation, template expansion) |
2558
- | `props` | After parsing, defaults, and guarantees | `(content, params, block)` | `{ content, params }`, or null | Post-process the final shape before the component sees it |
2559
-
2560
- The `content` handler receives `block.parsedContent.data` — the section's declared keys, its foundation's `main.js` `data:` included, so **declare there every key a handler reads** — and reads raw ProseMirror from `block.rawContent`, returning a new ProseMirror document that the framework re-parses through the semantic parser. Returning `null` — or the same reference as `block.rawContent` — signals no change. Anything that is not a document is ignored, with a warning once per handler: the first argument is the section's *data*, so a pass-through `(x) => x` returns the data, not the content.
2561
-
2562
- > **`block.rawContent` may or may not be wrapped.** Unwrap it defensively — `const doc = block.rawContent?.doc ?? block.rawContent` — before passing it to `instantiateContent` / `instantiateRepeated`. This is the first thing a hand-written handler gets wrong.
2563
-
2564
- **Loom integration** is the most common use: resolving `{placeholder}` expressions against live data. `@uniweb/loom` provides a factory:
2565
-
2566
- ```js
2567
- import { createLoomHandlers } from '@uniweb/loom'
2568
-
2569
- export default {
2570
- handlers: createLoomHandlers({ vars: (data) => data?.profile?.[0] }),
2571
- }
2572
- ```
2573
-
2574
- `vars` extracts the Loom variable namespace. The returned `content` handler reads the `source` and `where` frontmatter params: without `source` it does simple substitution; with `source` it splits the markdown at `---` dividers and repeats the body per data item. `where` filters the source array first — `type = 'book'` (equality), `year > 1870` (comparison), `refereed` (truthy), `type = 'book' AND refereed` (combination). Aggregates like `{COUNT OF publications}` reflect the filtered set.
2575
-
2576
- For cases the factory doesn't cover, write handlers directly using `Loom`, `instantiateContent`, and `instantiateRepeated` from `@uniweb/loom`.
2577
-
2578
- > **`instantiateContent` resolves `{placeholders}` in text nodes only** — not in link `href`s or other node/mark attributes. So `[{email}](mailto:{email})` fills the visible label but leaves the `mailto:` URL literal. For dynamic URLs, emit the value as plain text and let the component linkify it, or build the href in the handler yourself.
2579
-
2580
- **`source` and `where` are ordinary params** that the Loom handler reads — they reach both `block.properties` (for handler access) and `params` (visible to components). Components can ignore them. List them in `meta.js` params with descriptions so the editor and schema recognize them. (Unlike `theme` and `background`, which are the section's own settings and never reach `params` — see the table under *Frontmatter becomes `params`*.)
2581
- <!-- /template:loom -->
2582
-
2583
- ---
2584
-
2585
- ## Part 4b — When the site is also an app
2586
-
2587
- Everything above is a site: content the author writes, built into pages. Some sites
2588
- also have **their own backend, the `backend` service** — accounts, per-visitor data, records their members
2589
- create and edit. `@uniweb/api` is its client.
2590
-
2591
- ⛔ **Only reach for this when the site actually has one.** A site without one is
2592
- the normal case, and a foundation that assumes one breaks on every other site it is
2593
- used with.
2594
-
2595
- ```bash
2596
- npm install @uniweb/api # in the FOUNDATION, beside @uniweb/kit
2597
- ```
2598
-
2599
- ### Ask before you draw
2600
-
2601
- ```jsx
2602
- import { isBackendEnabled } from '@uniweb/kit'
2603
- import { useSession, SignedIn, SignedOut } from '@uniweb/api'
2604
-
2605
- if (!isBackendEnabled()) return <StaticVersion /> // synchronous — nothing to await
2606
- ```
2607
-
2608
- ⛔ **When the site has no `backend` service, draw nothing** — not a disabled control, and not an
2609
- explanation. Same rule as `services` in Part 4: which capabilities a site's operator
2610
- set up is none of a visitor's business, and "sign-in unavailable" reads as breakage
2611
- when it is simply a feature this site does not have. Render the version of your
2612
- component that never needed one.
2613
-
2614
- ### Reading
2615
-
2616
- ```jsx
2617
- const { status, records } = useRecords({ schema: '@/track' }) // summaries: record.brief, no items
2618
- const { entity } = useEntity({ schema: '@/track', uuid: record.uuid })
2619
- const sessions = entity?.hydrated?.items.filter((item) => item.section === 'sessions')
2620
- ```
2621
-
2622
- ⭐ **Name your foundation's own types `@/track`**, as `meta.js` and `queries.yml` do. A built
2623
- foundation sends one in the scope in its name — `@acme/track` for `@acme/marketing`, the name
2624
- `register` stored it under — and `uniweb dev` sends it as written, which is how your mock's
2625
- seed names it. Name any other type in full (`@std/person`). Real-backend testing is a job for a
2626
- built foundation. Outside a Uniweb build nothing knows your scope, so `@/track` is refused
2627
- before anything is sent (`kind: 'invalid'`).
2628
-
2629
- ⛔ **What a member wrote is text.** Render a field as `{record.brief.name}` or `<PlainText text={…} />` — never `<P text>`, `<H1>`–`<H6>` or `SafeHtml`, which render HTML: a member who typed `<img src=x onerror=…>` would run it as whoever views the page. A rich-text field (a ProseMirror document) renders through kit's `Render`, which escapes its text.
2630
-
2631
- ⛔ **A listed record is a summary, not the entity.** `record.brief` holds the brief
2632
- section's fields (`record.brief.name`, not `record.name`), and a record carries **no
2633
- items**. Read one entity for its items. Each item carries `section`, its section's name
2634
- (the word a write takes), and `id`, which is what the writer takes to update, move or
2635
- remove it. `scope: 'mine'` lists only the viewer's own records; without it, a list also
2636
- holds what was shared with the viewer, and what a role of theirs reaches.
2637
-
2638
- ⭐ **`absent` and an empty `ready` are different answers, and confusing them is the
2639
- mistake to avoid.** `absent` = there is no live source (no `backend` service, or nobody signed
2640
- in) → render the site's authored content. `ready` with `records: []` = the service
2641
- answered and there is nothing there → render your empty state. Showing "nothing yet"
2642
- for the first tells a visitor their content is gone when it was never requested.
2643
-
2644
- ### Writing
2645
-
2646
- ```jsx
2647
- const writer = useEntityWriter({ schema: '@/track', uuid: track.uuid })
2648
-
2649
- await writer.create({ title: 'Keynote' }, { section: 'sessions', position: 'last' })
2650
- await writer.update(itemId, { ...item.data, room: 'Hall A' }) // whole-data replace
2651
- await writer.move(itemId, { after: previousItemId }) // never an index
2652
- await writer.remove(itemId)
2653
- ```
2654
-
2655
- - **`section` is required on `create`.** An entity has several, and a rule declared on
2656
- one — insert-only, say — does not reach an item that landed in another. Getting it
2657
- wrong stores the item happily and quietly voids the rule.
2658
- - **`update` replaces the item's data whole.** Spread what you are not editing.
2659
- - **Ordering is the server's.** Say `'first'`, `'last'` or `{ after }` — never compute
2660
- an order number, or two people arranging one list will produce an order neither
2661
- chose.
2662
- - ⛔ **`writer.conflict` is reported, not retried.** Someone else changed the item
2663
- first; a retry would succeed by overwriting a change nobody looked at. Tell the
2664
- person.
2665
-
2666
- ### Translated fields
2667
-
2668
- A `localized` field holds `{ en: '…', fr: '…' }`, or one plain value that is every
2669
- language, and a read answers it in the page's language. ⛔ **Never write that one value
2670
- back as the whole field** — it becomes the value in every language. To edit one:
2671
-
2672
- ```jsx
2673
- const { entity } = useEntity({ schema: '@/profile', uuid, languages: 'all' }) // every language, as stored
2674
- await writer.update(item.id, { ...item.data, bio: 'Bonjour' }, { language: 'fr' }) // one language, merged
2675
- ```
2676
-
2677
- - **`update` with `{ language }`** merges each translated field you name into the languages
2678
- the item holds, and keeps a translated field you leave out. On a site with more than one
2679
- language, an update without it that writes a plain value over a translated field read in
2680
- the page's language is refused.
2681
- - **`languagesOf`, `inLanguage` and `withLanguage`** read and set one language of a value
2682
- yourself, its `@` metadata kept.
2683
-
2684
- ### ⛔ Permissions are the SERVER'S, and your UI is only a courtesy
2685
-
2686
- Gate your controls on what the viewer may do — a record's own `can_edit` from a
2687
- single-entity read — but **never rely on that for safety**. A foundation runs with
2688
- exactly the viewer's own authority, so hiding a button hides a button. ⛔ **Not on
2689
- `viewer.roles` alone:** on a site a session holds its roles as a reader's until it is
2690
- elevated (*Acting as an administrator*, below), so a gate on `system_admin` shows the
2691
- operator nothing until then — and a role never says what the session may do to one
2692
- record. Draw a control that acts through a role from `useElevation().rolesInFull`, and
2693
- let the record answer.
2694
-
2695
- What protects content is the **entry**: a member writes their own entries and not
2696
- another's, and the store enforces it. **Models are open** — anyone signed in may
2697
- create entries of any Model, so a data schema does not restrict who creates
2698
- (`creatable_by` is retired and refused). What a schema can protect is how an item
2699
- changes:
2700
-
2701
- ```yaml
2702
- # foundation/schemas/attendance.yml
2703
- sections:
2704
- checkins:
2705
- many: true
2706
- append_only: true # may be added; never edited or removed, by anyone
2707
- ```
2708
-
2709
- `append_only` holds against the item's own author. That is the difference between a
2710
- permission model and a CSS one.
2711
-
2712
- A schema can also open entries by relationship, and keep them from being shared:
2713
-
2714
- ```yaml
2715
- # foundation/schemas/submission.yml
2716
- grantable: false # no entry is shared one at a time
2717
- fields:
2718
- course: { ref: '@/course', readable_with: edit } # the course's editors read it
2719
- ```
2720
-
2721
- `readable_with` — `read`, `edit` or `admin`, and only on a reference — opens the entry, to
2722
- read and never to change, to whoever holds that level on the entry the reference points to:
2723
- a submission's `course` at `edit` reaches the course's staff and none of its students. A row
2724
- read that way comes back with `via: 'rbac'`. It is one step, and a backend refuses adding it
2725
- to a field entries already fill. `grantable: false` keeps entries from being shared with a
2726
- person or a team; omitted, they can be.
2727
-
2728
- A reference can also carry a purchase. `sold_with: true` — a boolean, and only on a reference
2729
- or a list of them — means a buyer of the entry reads what the field names, through it, and onward
2730
- along those entries' own `sold_with` fields, up to three steps:
2731
-
2732
- ```yaml
2733
- # foundation/schemas/course.yml
2734
- fields:
2735
- lessons: { ref: '@/lesson', many: true, sold_with: true } # a buyer of the course reads its lessons
2736
- ```
2737
-
2738
- An unmarked reference carries nothing, and `false` is the same as leaving it out.
2739
-
2740
- ### Acting as an administrator
2741
-
2742
- On a site, an administrator's session reads what their role reaches — the operator reads
2743
- every member's records — and changes nothing through the role until they confirm it is
2744
- them. Their own records they edit, delete and share as always.
2745
-
2746
- ```jsx
2747
- const { available, elevated, until, elevate, lower, error } = useElevation()
2748
- // available: the account holds a role that does more than read — offer it only then
2749
- // elevate({ password, code }) — code when the account has a second factor; a refusal is error.kind === 'auth'
2750
- // elevated, until: true while it lasts, and when it ends; lower() ends it early
2751
- ```
2752
-
2753
- - It lasts as long as the backend decides; `elevated` turns false by itself at `until`,
2754
- and elevating again starts the time again. Nothing says whether the account has a
2755
- second factor, so offer the code field to whoever might.
2756
- - While it lasts `viewer.roles` names the role, and every record read before is read
2757
- again, so `entity.can_edit` answers for the session as it is now.
2758
- - An account with no password: `elevateWithProvider(provider)` goes to the provider's
2759
- sign-in and back to the page.
2760
- - It does not open the backend's administration — the Admin link does.
2761
-
2762
- ### The Admin link
2763
-
2764
- ```jsx
2765
- const { adminHref } = useSession()
2766
- {adminHref && <a href={adminHref}>Admin</a>}
2767
- ```
2768
-
2769
- `adminHref` is set only for a signed-in account the backend's administration admits —
2770
- the operator, and whoever else administers it — and is `null` for everyone else. It
2771
- takes them there already signed in. ⛔ **Navigate to it, never `fetch` it**: the answer is
2772
- a redirect carrying a one-time credential no script on the site is to hold. It decides
2773
- what to offer, not what is allowed — on the site the operator acts through their role
2774
- only while elevated.
2775
-
2776
- ### The links the backend mails
2777
-
2778
- A sign-up's confirmation, a password reset and an invitation to an address with no
2779
- account all arrive as a link to the site's root, a token in the query — `?verify=`,
2780
- `?reset=`, `?offer=` — and the page it lands on finishes the step:
2781
-
2782
- ```jsx
2783
- const { step, status, result, error, confirm } = useMailedLink()
2784
- // step: null | 'verify' | 'reset' | 'offer' status: 'idle' | 'working' | 'done' | 'error'
2785
- ```
2786
-
2787
- - `verify` finishes by itself; then the member signs in.
2788
- - `reset` waits for `confirm({ new_password })`, and the hook supplies the token. A
2789
- password the rule refuses is `error.extensions.reason === 'password_too_short'`, and
2790
- the same link works again.
2791
- - `offer` waits for a sign-in, then claims by itself. `result` is counts,
2792
- `{ invitations, grants }`, never names. ⛔ `error.kind === 'absent'` means unknown,
2793
- revoked or already used, alike: one sentence, no cause. It does not mean "no
2794
- invitation": a member who confirmed the invited address already holds it.
2795
-
2796
- Render it where the root renders it — a header or a layout is on every page. ⛔ Never
2797
- copy the token anywhere: it is a credential, it stays in the URL until the backend has
2798
- judged it, and then the hook takes it off.
2799
-
2800
- ### Invitations
2801
-
2802
- An invitation to join an organization waits for the member's answer, whether it was
2803
- sent to their account or taken up from an `?offer=` link:
2804
-
2805
- ```jsx
2806
- const { status, invitations, accept, decline, answering } = useInvitations()
2807
- // invitations: [{ id, unit_uuid, unit_handle, unit_name, invited_by_account_id, created_at }]
2808
- ```
2809
-
2810
- Draw it wherever a signed-in member lands, not only after a mailed link — an invitation
2811
- sent to an account comes with no link to follow. `unit_name` may be `null`.
2812
- `accept(id)` and `decline(id)` answer one, and the list reads again. One that no longer
2813
- waits — answered in another tab, or withdrawn — is refused with `kind: 'rule'` and
2814
- leaves the list; its `detail` is for people, so branch on `kind`.
2815
-
2816
- ### Access to an entry
2817
-
2818
- Whoever administers an entry — its owner, someone given `admin` on it, or a role that
2819
- reaches it while the session is elevated — gives other people `read`, `edit` or `admin` on
2820
- it, and takes it back. An instructor enrolling students in a course is this; name it as
2821
- your solution does ("enrolled", "course staff"):
2822
-
2823
- ```jsx
2824
- const { status, grants, grant, revoke, working } = useAccess({ schema: '@/course', uuid: course.uuid })
2825
- // status 'ready' for whoever administers it; 'forbidden' for everyone else — draw nothing
2826
- // grants: [{ account_id, permission, account: { handle, uuid, … }, … }]
2827
- await grant({ handle: 'sam' }, 'read') // or an account id: a candidate, a grant's account, an owner_id
2828
- await grant([12, 15, 21], 'read') // many by account id, each on its own: { results }
2829
- await revoke(grants[0])
2830
- ```
2831
-
2832
- - ⛔ **Not a grant per entry from your code** — giving access is a person's decision, made
2833
- through your UI. For "the course's staff read every submission", declare it on the schema
2834
- (`readable_with`, above) instead of granting each submission as it is created.
2835
- - Giving again replaces: `read` after `edit` lowers it. On a site's backend an entry is
2836
- given only to the site's members, so an address with no account is refused.
2837
- - An entry given to the viewer lists for them with `via: 'grant'`; they can give it up with
2838
- `leaveAccess({ schema, uuid })`.
2839
-
2840
- ### Where a create lands
2841
-
2842
- Everything a member creates lands at the root of the organization the site's backend is
2843
- founded with — unless the create names one of its units, a department or a course, that the
2844
- viewer is placed in:
2845
-
2846
- ```jsx
2847
- const { units } = useUnits() // [{ unit, id, handle?, name?, parent?, depth, primary }]
2848
- await createEntity({ schema: '@/submission', unit: course.unit, items: [...] })
2849
- ```
2850
-
2851
- Landing decides where an entry is, not who may open it.
2852
-
2853
- **An entry and its nested items in one create:** give an item `uuid: uuidv7()`, and a later
2854
- item names it as its `parent` — `{ section: 'degrees/thesis', parent: degree, data }`. The
2855
- uuids serve that write alone: no read returns them, and items are read by `id`.
2856
-
2857
- ### A backend on your machine
2858
-
2859
- You do not need a live backend to build against one. In `site.yml`:
2860
-
2861
- ```yaml
2862
- services:
2863
- backend: true # ask your host for it when you publish
2864
- $devBackend: ./mock/api.js # what answers it in `uniweb dev`; `$` keys are never published
2865
- ```
2866
-
2867
- ```js
2868
- // site/mock/api.js
2869
- import { createMockBackend } from '@uniweb/api/mock'
2870
- export default createMockBackend({ seed }).fetch
2871
- ```
2872
-
2873
- `uniweb dev` answers your site's `backend` service with it, at an address the dev server
2874
- supplies on its own origin, so cookies behave exactly as they will in production. Write
2875
- no address of your own for it: under `services:` an address means a backend you run, and
2876
- asks your host to leave its own off. It **enforces** who
2877
- may edit an entry and `append_only`, so a permission you are relying on fails on your
2878
- machine rather than in front of a user. The mail it would send is printed in the dev
2879
- server's terminal, its link on your site's root — follow it to try your page. Seed
2880
- `offers: [{ email, invitations: 1 }]` to try an invitation: mailed to an address no
2881
- account holds, or waiting at once for the seeded account whose address it is. A seeded
2882
- entity takes `grants: { member: 'read' }`, and `units: [{ handle, parent?, members, floor? }]`
2883
- gives a create somewhere to land. A seed names your own types `@/track`, as `uniweb dev` sends
2884
- them, and any other in full; it matches a name exactly. State is in memory; restart to reset.
2885
-
2886
- `uniweb create my-event --template conference` is a worked example of all of this.
2887
-
2888
- ---
2889
-
2890
- ## Part 5 — Commands, shipping, and migration
2891
-
2892
- ```bash
2893
- uniweb dev # Start dev server (picks the site for you; prints its address)
2894
- uniweb dev --status / --stop # The running dev server's address / stop it
2895
- pnpm build / pnpm preview # Build for production / preview the build (SSG + SPA)
2896
-
2897
- uniweb deploy # Wizard: pick a destination, then deploy (or set up CI)
2898
- uniweb deploy --host=<adapter> # Build + upload now, from this machine
2899
- uniweb add ci --host=<adapter> # CI so every push deploys — usually best for a free host
2900
- uniweb export # Build dist/ for any static host (no Uniweb account)
2901
- uniweb publish # Ship to Uniweb hosting, foundation included (needs `uniweb login`)
2902
-
2903
- uniweb add ci --target foundation # Publish a foundation for free at permanent versioned URLs
2904
- # (GitHub Pages → foundations/<name>/<version>/entry.js)
2905
-
2906
- uniweb status # What changed in the app, in git and in Uniweb — and what to run
2907
- uniweb push / pull / clone # Git-style content sync with the Uniweb backend
2908
- uniweb refresh / sync # Catch up (git + backend, never pushes) / catch up, then push
2909
- uniweb login --org @acme # The workspace you work in — new sites are created there (see below)
2910
- uniweb register [--scope @scope] # Register a foundation + its data schemas to the registry
2911
- uniweb login / logout # One backend, one workspace at a time: log in (--server, --org) or out
2912
- uniweb org list / create <handle> # Your personal scope, and the orgs you belong to
2913
- uniweb content export [dir] # Package a site (or a built foundation's schema) as .uwx
2914
-
2915
- uniweb rename <foundation|site|extension> <old> <new> # Rename across the whole workspace
2916
- uniweb i18n extract / init / sync / status / audit # Translation workflow (build first)
2917
- uniweb i18n init-freeform / update-hash / move / rename / prune --freeform
2918
-
2919
- uniweb -v # CLI version — only a global install also says whether a newer one exists
2920
- uniweb doctor # Diagnose project configuration (--fix to auto-repair)
2921
- uniweb validate # Check file-based data against declared schemas (fails on a violation; --lax)
2922
- npx uniweb@latest update # Align @uniweb/* deps + AGENTS.md (--dry-run, --yes)
2923
- # bare `uniweb update` aligns to the CLI you ALREADY have
2924
- uniweb inspect <path> # Show parsed content for a section or page (--raw for the AST)
2925
- uniweb snapshot # Compose site/public/preview.webp from the site; sets preview: if unset
2926
- # needs `pnpm add -D -w @uniweb/snapshot` and Chrome or Edge
2927
- uniweb snapshot --compare # Several looks on one sheet; take one with its flags + --save (site/snapshot.yml)
2928
- uniweb snapshot --share # The first view as a 1200×630 link preview; sets seo.image if unset (--css arranges it)
2929
-
2930
- uniweb <command> --help # Per-command flags — no side effects. Prefer this over guessing.
2931
- ```
2932
-
2933
- ### Where a site can live
2934
-
2935
- **There is no lock-in, and no default you're pushed toward.** Four independent paths, and a project can change its mind:
2936
-
2937
- | Path | Command | Good for |
2938
- |---|---|---|
2939
- | Free static host, via CI | `uniweb add ci --host=<adapter>` | most self-hosted sites — one command, then every push deploys |
2940
- | Free static host, from this machine | `uniweb deploy --host=<adapter>` | one-off or manual deploys |
2941
- | Any static host at all | `uniweb export` | full control; no Uniweb account needed |
2942
- | Uniweb Cloud | `uniweb publish` | teams with non-technical content authors, or client work |
2943
-
2944
- `uniweb deploy` never assumes a host: with nothing configured it opens a picker listing only destinations it can act on, and records the choice in `deploy.yml` so later runs go straight there. On Cloudflare Pages / Netlify / Vercel, `add ci` also adds per-PR previews that comment the URL. GitHub runs workflows only from the top of the repository: in a project that is a folder of a larger repository, the project's own `.github/` never runs — `uniweb status` says so, and `uniweb add ci` refuses to write one there — as it says when a target in `deploy.yml` was never deployed from this copy. Adapters: `github-pages`, `cloudflare-pages`, `netlify`, `vercel`, plus `s3-cloudfront` for `deploy`. That record is `deploy.yml`, beside `site.yml` — **the CLI writes it, you don't create it**: the first successful deploy scaffolds the whole file, and later deploys rewrite only its `deploys:` block. Edit `targets:` when you want to change where a site ships. Host credentials come from the environment, never from that committed file.
2945
-
2946
- Foundations have their own free path too: `uniweb add ci --target foundation` publishes to permanent versioned URLs on GitHub Pages.
2947
-
2948
- **Three facts about a site, and they are independent — `uniweb status` opens with all three:**
2949
-
2950
- - **Synced** — the project has a site on a backend, so authors can edit it in the Uniweb app. `sync.json` names it on each backend: `https://uniweb.app` by default, or a server of your own (`uniweb login --server <url>`).
2951
- - **Published** — that backend serves it live: Uniweb Cloud, on `https://uniweb.app`. A published site is a synced site; a synced site need not be published — it can sit in the app as a draft. A publish is recorded in `deploy.yml` too, under a `host: uniweb` target: `deploys.<target>.url` is the address that publish delivered to. Where visitors go now (a custom domain, while one is active) is the backend's answer, and `uniweb status` shows it.
2952
- - **Deployed** — a build of it is on another host, such as GitHub Pages or S3: by CI on every push (`uniweb add ci`), or by hand (`uniweb deploy`). `deploy.yml` lists those hosts beside the one a publish records, and a bare `uniweb deploy` goes to its default target.
2953
-
2954
- A site can be in more than one place — usually while it moves from one host to another. Before you ship, read where it is: `publish` makes a change live on Uniweb Cloud, `git push` on a CI-deployed host, and `uniweb deploy --target <name>` on one deployed by hand — and each of these is the person's to decide. `uniweb status` also lists the services the live site has (`services:` in `site.yml` is the request, never proof of what the site has).
2955
-
2956
- ### Uniweb Cloud and the two-sided workflow
2957
-
2958
- `uniweb publish` ships to Uniweb Cloud, and it's worth understanding what that buys, because it isn't only hosting — it's how a team of technical and non-technical people works on one site.
2959
-
2960
- **Content authors work visually in the Uniweb App.** They compose the same extended markdown and set the same component params you defined, through a visual editor — never touching code, git, or the CLI. They see exactly the section types your foundation offers and exactly the knobs each one exposes, because **every `meta.js` is registered as the foundation's schema** when you publish. Your `meta.js` is the app's UI (see *meta.js* in Part 4).
2961
-
2962
- > ⚠️ **Every push, pull and publish works in ONE workspace — the one chosen at `uniweb login`.**
2963
- > A workspace is your personal one, an organization's, or a sub-organization's or project's in one
2964
- > (`@studio:acme`). A site a push or publish **creates** is
2965
- > created — owned, and its storage billed — there, and there is no CLI command to move it
2966
- > afterwards. A site the backend keeps in **another** workspace stops the command, which says how
2967
- > to switch. With no organization or project, the login works in your personal workspace;
2968
- > otherwise the login asks, or you name it:
2969
- >
2970
- > ```bash
2971
- > uniweb login --org @acme # work in an organization
2972
- > uniweb login --personal # work in your personal workspace
2973
- > uniweb push --org @acme # this command only
2974
- > ```
2975
- >
2976
- > Already logged in, `uniweb login --org @other` (or `--personal`) switches the workspace on the
2977
- > backend you are logged in to, without logging in again. **Without a
2978
- > terminal — you, an agent — a login with organizations or projects and no workspace named signs you in but
2979
- > exits 2**: `uniweb login --org @acme` (or `--personal`) finishes it without signing in again.
2980
- > Until then every command that works on a site refuses, and so does registering a foundation whose
2981
- > name has no scope. A process logged in with `UNIWEB_TOKEN` names its workspace with
2982
- > `UNIWEB_WORKSPACE=@acme` (or `personal`). **Ask the human which workspace to use** rather than
2983
- > picking for them — a site created in the wrong one cannot be moved from here.
2984
- >
2985
- > Relatedly: these commands now **reject flags they do not recognize** instead of ignoring them.
2986
- > If you get `Unknown flag`, read the suggestion — it is usually a near miss.
2987
-
2988
- **Sync is developer-only and one-sided by design.** `uniweb push` and `uniweb pull` are your commands, not theirs:
2989
-
2990
- - **The app is the live source of truth for content** — where authors work and where your push lands live.
2991
- - **Git is the reviewed, durable record** — you `pull` content back, read it with `git diff`, and commit.
2992
- - **Authors never push or pull.** For them, content simply updates, whether the change came from another author or from a developer's CLI.
2993
-
2994
- **Working on a site others edit — run `uniweb status` when you begin, when you come back to it, before you push, publish or deploy, and after any refusal.** It reads the backend without taking anything: what changed there since this copy last synced, file by file — as `uniweb pull` would write it, translations and records included; what you hold that it lacks; where the site is live, and what services it has; who has it open in the app right now, and on which file; and what else in the project is not committed — an update, the foundation's source — which a push neither sends nor waits for, though your team builds what git holds and a push or publish releases a changed foundation from the files. Then it lists the commands to run, in an order that works from the top — `uniweb pull` before the push it would otherwise refuse. Three habits go with it: take what changed (`pull`, or `refresh`) before you edit; never `--force` past a refusal; and when someone has a page open in the app, tell the person before you change that page. A step marked *ask the person first* — a commit, sharing commits, going live, which may cost money — is theirs to decide.
2995
-
2996
- **Nobody's work is overwritten without asking.** `uniweb push` is refused if the site changed on the backend since your last pull — usually an author editing in the app — and reports what changed; nothing is written. Edits to different sections never collide. **In a git repository `uniweb pull` merges, like `git pull`:** it commits the backend's content (*"The site's content on …"*) and merges that commit into your branch, against the last state of the site your history shares with the backend. Your work, committed or not, and a teammate's arriving through git are kept; a file the backend never had is never deleted; changes to different parts of a file combine silently; and only a genuine overlap leaves conflict markers and a non-zero exit — so `uniweb pull && uniweb push` never ships markers. Settle a conflict as in any merge, then `git commit`; where your uncommitted changes overlap what the pull brought, the markers are theirs — settle them and `git add` each file, then `git stash drop` (git keeps them in the stash too). A push or publish is refused while a file under the site is in conflict. **In a git repository a push sends what you have committed:** with the site's content not committed it is refused before anything is sent, naming the files — commit them, or run `uniweb push --commit -m "…"` (it commits the site's content only, and leaves anything else staged as it is); `publish` and `sync` take `--commit` too. That commit is where the next pull merges from, which is how the pull tells your changes from the backend's. What the push writes back into the files — the ids the backend assigned — it commits itself, as `uniweb`. When the backend has nothing new, a pull says so and lists the files where yours hold changes it lacks. `uniweb refresh` runs `git pull` first, then the same pull. A push is also refused when your branch does not hold what this copy last took from the backend — after `git merge --abort`, or in a fresh clone that has not pulled — so pull, then push. Outside git — which includes a folder the repository around it ignores, such as a scratch directory — `uniweb pull` takes the backend's version over your files, asking first. `--force` is the deliberate overwrite (on `push` it replaces the backend's changes, on `pull` it discards yours); don't use it to get past a refusal. `uniweb sync` is `refresh` then `push`; neither publishes.
2997
-
2998
- **Moving a synced project to another repository.** Where the copy last met the backend is in its git history, and in `.uniweb/`, which git never holds — both stay behind; `sync.json` comes along, so the copy still knows its site. Move one this way: `uniweb sync` in the old copy, then copy the project in without its `.git/` and commit it, then sign in to the site's workspace and `uniweb pull` once — it records where the copy and the site meet, with nothing to settle when the old copy had synced. When it had not, `uniweb status` says the copy shares no history with the site's content and lists the files that say something else; the first pull makes each a conflict. Settle each by what you know: an edit made in the app since the last push is the backend's side, a change made in the copy and never pushed is yours — ask the person when you cannot tell. Never `--force` it in either direction: one side's edits would be gone from every file.
2999
-
3000
- **`sync.json` says which site this is, on each backend.** The first push to a backend records what that backend assigned — the site's id and owner, the ids of its records and uploaded files — in `sync.json` beside `site.yml`. In a git repository the push commits it; never edit it. **To make a new site from a copy of a project, run `uniweb forget --all` in the copy before its first push** — the copy carries the original's `sync.json`, so otherwise its push updates the original's site. When two projects in one workspace hold the same site, a push or publish from either is refused until that is done. `uniweb forget --server <url>` removes just one backend's records, such as a scratch server's. A record file's `$uuid` is its own id and stays in both cases. **`push`, `pull` and `publish` go to the backend you are logged in to** — the last `uniweb login --server <url>` — and never to one you are not logged in to. A bare `uniweb login` logs in to https://uniweb.app; for any other backend, name it — logging in is how you switch, and the backend commands take no `--server` of their own. When the project has no site on that backend but has one elsewhere, a push says so before creating a new one.
3001
-
3002
- **`services:` in `site.yml` is where a site says which services it uses** — site search, form
3003
- handling, analytics, an assistant, accounts — one entry per service:
3004
-
3005
- ```yaml
3006
- services:
3007
- search: true # on — your host's, or the built-in index
3008
- submit: false # off
3009
- tracking: https://collector.example.com/events # a provider you bring
3010
- backend: # on, with the service's own settings
3011
- grade: pro
3012
- ```
3013
-
3014
- An entry is `true`, `false`, an address of your own (a string, or `endpoint:` in a map), or a map
3015
- of options; anything else stops the build and the push. ⚠️ `yes`, `no`, `on` and `off` are text to
3016
- YAML, not switches — write `true` or `false`. On a site you push or publish it is also **what you ask your host for**: `true` asks for
3017
- its service, `false` asks it to turn its service off, and an address asks it to leave its own off so
3018
- yours answers. **On a site your host publishes, a service is off unless `services:` asks for it** —
3019
- list the ones the site uses (the templates list theirs). `records: true` asks for your records to be
3020
- delivered live to the published pages. Turn it on before the first publish of a page that shows
3021
- records with a data schema: without it those records never reach the published page, and `publish`
3022
- warns. A static build reads records from files and ignores it. `google: { id: G-XXXXXXXXXX }`
3023
- asks the host to load Google's tag, also ignored by a static build (see Tracking). An entry
3024
- says everything about its service: a setting you remove from it is removed on the next push, and
3025
- removing the entry switches the service off. `uniweb push` and `uniweb publish` send each service
3026
- `site.yml` lists; a service the site has that this copy has never seen (turned on in the app since
3027
- your last pull) is left as it is, and one changed both in the file and on the site since your last
3028
- pull stops the push, naming it — `uniweb pull`, then push. `uniweb pull` writes what the site
3029
- has into `services:` (an off service with no settings only where the file already names it) — pull
3030
- before you edit. A change that needs payment is settled in the app: `publish` opens it. **Everything in an entry but a
3031
- credential is public** — it is built into the site, except `backend`'s settings, which only your host
3032
- reads; a key or token is set in the app. ⛔ The top-level `search:` / `submit:` / `assistant:` /
3033
- `tracking:` / `api:` keys are retired: the build stops on them and says where each one moves. So
3034
- does `api` under `services:` — the site's own backend is the `backend` service — and `$devApi:`,
3035
- which is `$devBackend:`.
3036
-
3037
- **The Cloud also provides a real backend for structured data:** a database for every registered data schema, and a CMS that edits both static page content and dynamic data entities typed by those schemas. That's the piece that makes it viable for teams and client work — the client manages records, not markdown files.
3038
-
3039
- Either side can publish. Nothing about this changes how you build: the same foundation and the same site run under `uniweb dev`, `uniweb export`, or a CI deploy with no account at all.
3040
-
3041
- **Publishing vs registering.** Foundations on Uniweb Cloud live in the catalog as `@org/name@version` — `name` from the foundation's `main.js`. When a foundation powers a single site, **don't run `uniweb register` yourself** — `uniweb publish` from the site directory releases the local foundation to the catalog (when its code changed) and goes live in one step. A registered version is immutable, so when the foundation's code changed under a version already registered, `push` and `publish` release the change under the next version and write it into the foundation's `package.json`, which they commit in a git repository (`--no-release` sends the content without the code). The version it picks is always the next patch: for a change that is not backwards compatible, set a higher minor or major version in the foundation's `package.json` yourself before you push. They stop when the registry holds a version newer than yours, released from another copy: pull that change first, or pass `--bump` to release yours above it. Register deliberately only when the foundation is a product meant for multiple sites; consuming sites then pin `foundation: '@org/name@1.2.3'`. **The catalog is private and access-segregated, not a public package registry** — people see only the foundations licensed to sites they own or edit. The *site* carries the license, and it rides along with site ownership when a developer hands a site to a client. Don't describe publishing as making a foundation publicly discoverable. Schemas can also be registered on their own from a schemas-only package (`@uniweb/schemas`, any `@org/schemas`, or a bare folder of `schemas/*.{yml,json,js}`) — that's how `@std` schemas are published. Auth via `uniweb login` (`uniweb login --server <url> --token <bearer>` without a terminal) or `UNIWEB_TOKEN`; preview with `--dry-run`.
3042
-
3043
- ### Staying current
3044
-
3045
- ```bash
3046
- uniweb status # among its checks: whether a newer Uniweb is out than this project runs
3047
- uniweb -v # CLI version — only a global install also says whether a newer one exists
3048
- uniweb doctor # report drift in this project, changing nothing
3049
- npx uniweb@latest update --dry-run # preview exactly what update would change
3050
- npx uniweb@latest update # apply: align @uniweb/* deps AND refresh AGENTS.md
3051
- ```
3052
-
3053
- When `status` names a newer release, take it: `npx uniweb@latest update`, then build, look at the pages, and commit what the update changed — `status` lists those files until you do. Releases rarely ask anything of a project.
3054
-
3055
- **`npx uniweb@latest update` is the command for bringing a project up to date.** It aligns the project's `@uniweb/*` dependencies *and* this AGENTS.md to the version matrix of the CLI that runs it. Deps and documentation move together — that's the whole point of the verb.
3056
-
3057
- **What the version numbers mean.** A patch brings fixes and features; a minor version is where Uniweb puts breaking changes — `update` lists each package that crosses one, so build and check the project before shipping — and a major is kept for something really big. Dependencies are written as tilde ranges (`~1.0.1`), so `pnpm install` and `pnpm update` never cross a minor on their own. The move from 0.x to 1.0.1 asks nothing of a project that was on the latest 0.x versions — 1.0.1 carried every package's 0.x line over — though `update` marks each package `major · BREAKING`.
3058
-
3059
- > ### ⛔ WRITE `@latest`. A BARE `uniweb update` IS USUALLY A NO-OP, AND IT SAYS SO CONVINCINGLY
3060
- >
3061
- > `update` reconciles this project against **the matrix of the CLI that runs it** — and in a project,
3062
- > `uniweb` resolves to the copy in your own `node_modules`, pinned by your own `package.json`. That
3063
- > copy has no way to know a newer release exists.
3064
- >
3065
- > ⇒ **It reports everything aligned and changes nothing — correctly.** It answered the question it
3066
- > was asked, which is why the output looks like success rather than a mistake. The same applies to
3067
- > `pnpm uniweb update` and to a stale global install.
3068
- >
3069
- > ⭐ **`@latest` is what makes it a question about the newest release** rather than about the one you
3070
- > already have. It also bumps the pin, so the next bare invocation is no longer stale.
3071
-
3072
- > **Don't run `npm update` or `pnpm update` on the `@uniweb/*` packages.** They're a matched set resolved by the CLI's version matrix, not independently versioned libraries you upgrade one at a time. Updating them directly gets you a combination nobody tested, and it won't refresh AGENTS.md — so this guide silently drifts out of sync with the code it describes, which is worse than being out of date, because nothing looks wrong.
3073
-
3074
- Two ordering rules: `update` won't refresh AGENTS.md while declared deps still lag the CLI, or while edited deps haven't been installed — either would put the doc ahead of the code. And updating the CLI itself is your package manager's job (`npm i -g uniweb@latest`, `pnpm add -g uniweb@latest`); `uniweb update` does not do that.
3075
-
3076
- ### `package.json` `uniweb` block
3077
-
3078
- Platform-specific configuration that doesn't belong in npm-standard fields. All fields optional.
3079
-
3080
- | Field | Where used | Default | Purpose |
3081
- |---|---|---|---|
3082
- | `runtimePolicy` | `dist/runtime-pin.json` | unset | Declares how far past the recorded runtime version a host may move a site. |
3083
-
3084
- **The foundation's name is not here — it is `name` in `main.js`** (else `package.json`'s `name`), **and so is the scope it registers under: the scope is part of the name**, `name: '@acme/marketing'`. A scope is a namespace — your personal one, `@<your handle>`, which needs no org, or an org's. A name with no scope has not been registered yet: the first `uniweb register` takes `--scope`, else the workspace you work in — an org's scope, or your personal one; when you belong to orgs and chose no workspace, it asks at a terminal and refuses without one — and writes it into the name; a `--scope` naming another scope than the name's is refused. The foundation's own data schemas register under the same scope (`@/article` → `@acme/article`). ⛔ `uniweb.id` and `uniweb.scope` are no longer read for a foundation: `uniweb register` refuses them and prints the `main.js` line to write instead. (A schemas-only package has no `main.js`, and still records its scope in `uniweb.scope`.)
3085
-
3086
- **Runtime updates — handled for you.** Your foundation's code links against the runtime: it externalizes `react`, `react-dom`, `react-dom/server`, both JSX runtimes and `@uniweb/core`, and the runtime supplies all of them at load time. So a build is bound to *that* React and *that* core API.
3087
-
3088
- You don't declare anything for this. At build time your foundation records the `@uniweb/runtime` version it actually linked against (read from `node_modules`, not chosen) into `dist/runtime-pin.json`, and `uniweb register` sends it with your foundation, so the version you built against travels with it. **Whether two runtime versions are compatible is our determination, not a setting** — you have no way to know whether we changed anything your code can reach, so we don't ask you to guess.
3089
-
3090
- ⚠️ **Nothing acts on the recorded version yet** — today it is stated and carried, not enforced. Don't design around it having an effect.
3091
-
3092
- **The escape hatch,** for the one thing only you can know: if your foundation reaches into undocumented runtime internals, or you have audited it against exactly one runtime build and want no movement at all, set
3093
-
3094
- ```json
3095
- { "uniweb": { "runtimePolicy": "exact" } }
3096
- ```
3097
-
3098
- That freezes sites using your foundation on the recorded version. Only reach for it if one of those two things is actually true — a frozen foundation stops receiving runtime fixes, including security ones. Sites cannot override your choice.
3099
-
3100
- > Older releases documented `auto-patch` and `auto-minor` here as well. They asked you to pick a compatibility rule out of our version numbers, which was never something you were in a position to evaluate — that determination is ours. Both values are still accepted so existing foundations keep working; neither is worth setting.
3101
-
3102
- `@uniweb/runtime` arrives **transitively** through `@uniweb/build`, so your foundation pins a runtime version without declaring one — that's intentional. **Don't add `@uniweb/runtime` to your foundation's dependencies**; to bump the pinned version, bump `@uniweb/build`. If `@uniweb/runtime` isn't resolvable at build time the pin is simply not emitted, and the build still succeeds — nothing in the toolchain requires it.
3103
-
3104
- ### Localization
3105
-
3106
- **Content reaches components already translated.** There is no `t()`, no runtime lookup, no string wrapping — each language is a complete static build with its own HTML, `hreflang` tags, and search index. The default language has no URL prefix (`/about`); others are prefixed (`/es/about`).
3107
-
3108
- **Translations live in `locales/`, a sibling of `pages/` at the site root — never inside `pages/`.** The markdown under `pages/` is one language: the default.
3109
-
3110
- ```yaml
3111
- # site.yml
3112
- defaultLanguage: en
3113
- languages: [en, es, fr] # codes only — a language's name comes from its code;
3114
- # or '*' to auto-discover from the locales/ folder
3115
- publishLanguages: [en, es] # optional — fr stays a dev-previewable draft,
3116
- # excluded from production output entirely
3117
- ```
3118
-
3119
- ```bash
3120
- uniweb build # FIRST — extract scans built content, not source
3121
- uniweb i18n extract # → locales/manifest.json, keyed by 8-char content hash
3122
- uniweb i18n init es fr # → locales/es.json, locales/fr.json, pre-filled with source
3123
- # …translate the values…
3124
- uniweb build # merges translations, emits dist/es/, dist/fr/
3125
- ```
3126
-
3127
- Running `extract` before a build is the usual first mistake — it reads the compiled content, so a stale build yields a stale manifest. After content changes, `uniweb i18n sync` updates the manifest and `init` refreshes the language files; `status` and `audit` report coverage and stale entries.
3128
-
3129
- **A value is inline Markdown.** A sentence's links and bold go into its translation — `"Voir [Rôles](page:docs/roles)."` — or it renders without them, and coverage still counts it; `uniweb i18n status` lists these under *Loses markup*. A **button** — a line that is only a link — is the exception: translate its label alone and it keeps its link and options (`{role=primary}`). Buttons on consecutive lines are one string; give one label per line (`"Créer un groupe\nEn savoir plus"`). The same words are one string wherever they appear: where their places differ — a heading here, a link there — the manifest marks it `markupVaries`, `init` seeds the plain words, and the words alone are what to write: a link or button keeps its own target, and a link written into the value goes to every place the string appears.
3130
-
3131
- **Two mechanisms.** *Hash-based strings* (the default) — `locales/{locale}.json` maps content hash → translation, so structure stays identical across languages. When one source string needs different translations depending on where it appears, the value takes an override form:
3132
-
3133
- ```json
3134
- { "e5f6g7h8": { "default": "Learn More", "overrides": { "/pricing:cta": "See Pricing" } } }
3135
- ```
3136
-
3137
- An override key is the page's route and the section's id (`cta` for `2-cta.md`); a page's own title, label, description and keywords are `/pricing:_meta`, and in `locales/records/` a record is named by its manifest context (`std/article/launch`).
3138
-
3139
- **An entry can be flagged `outdated`:** `{ "default": "Acerca de PandaWatch", "outdated": { "/about:hero": "About PandaWatch" } }`. The source was edited a little, and the old translation stays until someone reviews it, so it still shows, and `uniweb i18n status` lists it. An edit in the Uniweb app does this, and so does one in a file, at `uniweb i18n sync` or at the push. To finish it, write the new translation in the entry: new words end the flag, whatever is left beside them. If the words still hold, make the entry a plain string of them. An edit that shares under half its words with the old text keeps nothing, and neither does a page title, an image's alt text or a data block's string: those show the source until they are translated. **`locales/_kept.json`** holds what the app keeps for a section that no file has a place for. A pull writes it and a push sends it back, so commit it and leave it alone.
3140
-
3141
- *Free-form bodies* — when a language needs different structure, different images, or copy rewritten rather than translated. The file replaces one section's content:
3142
-
3143
- ```
3144
- locales/freeform/es/pages/about/hero.md # by page route
3145
- locales/freeform/es/records/article/x.md # records work too
3146
- ```
3147
-
3148
- These are **body only — no frontmatter**; params and config still come from the source section. `uniweb i18n init-freeform es pages/about hero` creates one pre-filled and records a source hash, so `uniweb i18n status --freeform` can tell you when the original moved on (`update-hash` to acknowledge). `move`, `rename`, and `prune --freeform` keep them aligned when pages get reorganized.
3149
-
3150
- **A tagged data block translates by the shape its key declares** in the component's `meta.js` `data:` — a data schema or an inline field map: its text fields, never an enum, a URL or a `translatable: false` field. A key declared `{}` leaves its blocks to a heuristic that offers any string whose field name and value don't look structural, so a `style: display-black` naming one of your component's looks gets translated too. Declare the shape of every block a translator will see — `{ name: 'string', style: { type: 'string', enum: [...] } }`.
3151
-
3152
- **An image translates by its alt text.** Words alone give it its alt text in that language and keep its file. A translation that is an image also names the file that language shows: `"2d093636": "![La superposition](/docs-media/fr/overview.png)"`. Name it with a `/` path, a file in `public/`, and a build processes it as it does the page's own images; a `./` path has no page's folder to start from, and the build reports it. A caption or a video's `poster` can be given the same way. An image with no alt text has nothing to translate, so give every image one.
3153
-
3154
- **Records translate in the same `extract` run**, into their own manifest at `locales/records/manifest.json` — keyed by the RECORD, so a record translated once is found by every query that returns it. A record whose query has a data schema translates exactly the fields the schema says are text — never an enum, a URL, a date, a number, a file, a reference or a `translatable: false` field — which are the fields a push carries in each language; mark a string that is a code or a key `translatable: false` and no translator is asked for it. An excerpt the build derives is re-derived from each language's body.
3155
-
3156
- **A data schema's own labels are not in `locales/`.** The schema's `label`, `plural`, `description` and its sections' and fields' labels are written once, in its `source_locale`; their other languages go in the schema's `i18n`, keyed by path: `i18n: { fr: { model.label: Séance, section.brief.field.title.label: Titre } }`. A section is named by its full path (`contributions/publications`), and a `fields:` schema's one section is `brief`. See `development/data-schemas.md`.
3157
-
3158
- **Component side.** Nothing to do: `content.title` arrives in the active language. The one thing a foundation builds is a switcher.
3159
-
3160
- ```jsx
3161
- import { useWebsite, Link, getLocaleLabel } from '@uniweb/kit'
3162
-
3163
- function LanguageSwitcher() {
3164
- const { website } = useWebsite()
3165
- if (!website.hasMultipleLocales()) return null
3166
-
3167
- return website.getLocales().map(locale => (
3168
- <Link reload key={locale.code} href={website.getLocaleUrl(locale.code)}>
3169
- {getLocaleLabel(locale)}
3170
- </Link>
3171
- ))
3172
- }
3173
- ```
3174
-
3175
- > **Use `<Link reload>` — not a plain `<a>`, and not `window.location.href`.** `getLocaleUrl()` returns a root-relative path that does **not** include the deployment base path, so under a subdirectory deploy (`base: /docs/` in `site.yml`) a raw href sends the visitor outside the site. `<Link reload>` prepends `website.basePath` and forces the full page load a locale switch requires — an SPA `<Link>` won't do, because the other language is a different build.
3176
- >
3177
- > **A `<select>` or a button calls `website.switchLocale(code)`**, never `window.location.href = …`. It makes the same page load, base path included, and inside a host that switches languages itself, such as an editor's preview, where a page load would leave the preview, it hands the switch to the host. A click on a `<Link reload>` to another language is handed over the same way.
3178
-
3179
- Full model: `development/internationalization.md`. Author's view: `authoring/translating.md`.
3180
-
3181
- ### Migrating from other frameworks
3182
-
3183
- Don't port line-by-line. Study the source, then rebuild from first principles. Other frameworks produce far more components than Uniweb needs — expect consolidation, not 1:1 correspondence.
3184
-
3185
- | React / conventional | Uniweb equivalent |
3186
- |---|---|
3187
- | Props with typed data | Frontmatter params + `meta.js` |
3188
- | Component variants via props | `variant` param; Front Desk pattern for complex routing |
3189
- | Context / ThemeProvider | `theme:` frontmatter + semantic tokens (automatic) |
3190
- | Wrapper/layout components | Section nesting or custom layouts |
3191
- | Prop-drilling visuals into containers | Insets — `![](@Component)` rendered via `<Visual>` |
3192
- | Content in JSX or `.js` data files | Markdown → parser → `content` prop |
3193
- | CSS color tokens / design systems | `theme.yml` → palette shades + semantic tokens |
3194
- | `isDark ? … : …` conditionals | `text-heading` — context classes handle it |
3195
- | Per-component backgrounds | `background:` in frontmatter |
3196
- | Multiple near-identical components | One section type + `variant` param, or Front Desk |
3197
- | i18n wrapping (`t()` / `<Trans>`) | Locale-specific content directories |
3198
-
3199
- **Approach:** scaffold with `--template none` → use named layouts for different page groups → dump legacy components under `components/` (they're not section types; import them from section types during transition) → create section types one at a time.
3200
-
3201
- **It's incremental, not a rewrite.** Level **0** — paste the original as one section type; routing and dev tooling work immediately, and you have a running site. Level **1** — decompose into section types, consolidating duplicates via `variant` params or Front Desk. Level **2** — move content from JSX to markdown, so authors can edit without code. Level **3** — replace hardcoded colors with semantic tokens, so components work in any context. Each level is shippable; stopping at 1 is a legitimate outcome.
3202
-
3203
- **The most common mistake** is recreating source colors as CSS custom properties — that bypasses the token system. Instead: primary color → `colors.primary` in `theme.yml`, neutral tone → `colors.neutral`, context needs → `theme:` frontmatter.
3204
-
3205
- Also: name by purpose, not content (`TheModel` → `SplitContent`, `WorkModes` → `FeatureColumns`), and put UI helpers (buttons, badges, cards) in `components/` with no `meta.js`.
3206
-
3207
- Full guide: `development/converting-existing.md`.
3208
-
3209
- ---
3210
-
3211
- ## Part 6 — Troubleshooting
3212
-
3213
- Most Uniweb failures are **silent** — the build succeeds and the page is wrong. Check these first, because nothing in the terminal will point you at them.
3214
-
3215
- **A red `Component not found: <Type>` box where a section should be** — the `type:` in that section's frontmatter names a section type this foundation doesn't have. `ls <foundation>/sections/` for the real list. The build does not fail on this, so it only surfaces by looking at the page.
3216
-
3217
- **A param has no effect** — it isn't declared in that section type's `meta.js` `params:`. Undeclared frontmatter is passed through and ignored rather than rejected. Read the `meta.js` for the real knobs; if the one you want doesn't exist, exposing it is a foundation change.
3218
-
3219
- **A section doesn't appear at all** — the file is `@`-prefixed (a child section, only rendered via `nest:`), or `_`-prefixed (treated as a draft and skipped), or it's a section type nested below the root of `sections/` without a `meta.js`, which means it was never discovered.
3220
-
3221
- **Content lands in the wrong field** — a heading became a `subtitle` when you wanted an item, or the reverse. That's the step rule (one step smaller and adjacent = the next headline line; two steps, a divider, or any body content first = items). Run `uniweb inspect <path>` rather than re-deriving it.
3222
-
3223
- **A var in frontmatter does nothing** — component vars only apply when declared in that section type's `meta.js` `vars:`. Unknown names are ignored silently.
3224
-
3225
- **A sticky header scrolls away** — it is `sticky top-0` on the component's outermost element, which has no room to move. Make the section sticky instead: `sticky: true` in its type's `meta.js`. A sticky section that still scrolls away sits in a box with `overflow: hidden` — clip with `overflow: clip`. `uniweb dev` names the element in the console.
3226
-
3227
- Loud failures:
3228
-
3229
- **"Could not load foundation"** — check that the site's `package.json` depends on the foundation *by its workspace package name*. For the default layout that's `"src": "file:../src"`; for a co-located project (`docs/src` + `docs/site`) it's `"docs-src": "file:../src"`. The key must match the foundation's `package.json::name`, not the folder it happens to sit in.
3230
-
3231
- **Component not appearing** — verify `meta.js` exists; check for `hidden: true`; rebuild the foundation.
3232
-
3233
- **Styles not applying** — verify `@source` in `styles.css` includes your component paths; `uniweb doctor` names a folder it misses.
3234
-
3235
- **Prerender warnings about hooks** — components with `useState`/`useEffect` show SSG warnings during build in local symlinked mode. Expected and harmless.
3236
-
3237
- **"document is not defined" during build** — your component touches `document`, `window`, or `localStorage` during render rather than inside `useEffect`. **Don't add `typeof document` guards** — use the kit hook instead: dark mode → `useAppearance()`, scroll detection → `useScrolled()`. Kit hooks are SSR-safe by design.
3238
-
3239
- **A modal renders behind the page** — page content or a sidebar paints over your dialog and its backdrop, and raising the z-index changes nothing. Each layout area carries a `view-transition-name`, which makes it a stacking context your `fixed` element cannot escape. Render through `<Overlay>` from `@uniweb/kit` (see Part 4) instead of a bare `fixed inset-0 z-…` div.
3240
-
3241
- **Content not parsing as expected** — `uniweb inspect pages/home/hero.md` (add `--raw` for the ProseMirror AST), or point it at a folder for a whole page.
3242
-
3243
- ---
3244
-
3245
- ## Documentation index
3246
-
3247
- **Index of every page: https://uniweb.io/llms.txt** — start there when you don't know which page you need.
3248
-
3249
- Source repo (public, cloneable): **https://github.com/uniweb/docs** · any page as raw markdown at `https://raw.githubusercontent.com/uniweb/docs/main/{section}/{page}.md`. See *Documentation* in Part 0 for when to fetch versus clone.
3250
-
3251
- | Section | Covers |
3252
- |---------|--------|
3253
- | `architecture/` | Component Content Architecture — the why behind the patterns in this file |
3254
- | `getting-started/` | What is Uniweb, quickstart, templates |
3255
- | `authoring/` | Writing content, site setup, records, theming, translations, predicates |
3256
- | `development/` | Foundations, component patterns, project structures, data, layouts, i18n, migration, schemas |
3257
- | `reference/` | site.yml, page.yml, content structure, meta.js, kit API, navigation, records, queries, data fetching, parametric pages, CLI, deployment |
3258
-
3259
- The by-task table is in Part 0. For CLI flags, prefer `uniweb <command> --help` over this file — it's always current.
3260
-
3261
- ## Notes about this project
3262
-
3263
- Conventions, decisions, where things are — keep them in a file of your own (`NOTES.md`, say). `uniweb update` rewrites this file for each new version, and the one part it keeps is a block between `<!-- project-notes:start -->` and `<!-- project-notes:end -->`, each on a line of its own, which it moves to the end of the file. That block is the place for a line pointing to your notes, or for short notes themselves.
321
+ | write or restructure content, nav, layout files, SEO, math, icons, doc versions | `uniweb guide content` |
322
+ | build a section type, layout or inset | `uniweb guide foundation` |
323
+ | change colors, fonts, light/dark, tokens, `styles.css` | `uniweb guide theme` |
324
+ | start a project, grow the workspace, learn from a template | `uniweb guide start` |
325
+ | work with records, queries, `[slug]` pages, external APIs, schemas, Loom | `uniweb guide data` |
326
+ | add search, forms, tracking, Google Analytics or Tag Manager, an assistant | `uniweb guide services` |
327
+ | the site has accounts or member data (`services.backend`, `@uniweb/api`) | `uniweb guide backend` |
328
+ | add a language | `uniweb guide i18n` |
329
+ | publish, deploy, push/pull, register, CI, workspaces, updates | `uniweb guide ship` |
330
+ | port a React / Next / generated design | `uniweb guide migrate` |
331
+
332
+ **The documentation index is `https://uniweb.io/llms.txt`** — every page with a one-line description and a fetchable link. Go there for anything not answered here and especially to learn whether a feature exists; follow its links rather than constructing them. For several lookups: `git clone --depth 1 https://github.com/uniweb/docs .uniweb-docs` (gitignore it) and grep; bare paths above resolve as index keys, files in the clone, or `https://raw.githubusercontent.com/uniweb/docs/main/{path}`. The docs describe the **latest** release: when `uniweb status` says this project is behind, the fix is `npx uniweb@latest update --yes`, not older docs. Syntax the docs no longer show is listed under *Retired forms* in `uniweb guide ship`. `docs.uniweb.app` is for authors in the visual editor and won't answer framework questions.
333
+
334
+ ## 7. Notes about this project
335
+
336
+ Keep conventions in a file of your own (`NOTES.md`). `uniweb update` rewrites this file and keeps only blocks between a `<!-- project-notes:start -->` line and a `<!-- project-notes:end -->` line: use one to point to that file.