` as tall as the window (a three.js script) or fills the
element it is in (React Three Fiber): give it the size the page wants.
- Light strengths are not on the same scale as three.js's. Look at the picture and adjust.
- A statement kept as a comment in a ported scene names something that is not in it (an object
made in a loop, a raycaster, a material's setting): write it as a `
` of ``, as
`on:click` on the mesh, or as a prop bound to a `state` (the `clarity-gl` skill).
From Vue or Svelte, and for what the tool leaves: port the behaviour, not the lines. Read the
component, list its state, what is derived from it, what happens on each event and what it
fetches; then write that as a `.clarity` component.
| In React | In Vue | In Svelte 5 | In Clarity |
|---|---|---|---|
| `const [n, setN] = useState(0)` | `const n = ref(0)` | `let n = $state(0)` | `state n = 0`, then `n = n + 1` |
| `useMemo(() => a * 2, [a])` | `computed(() => a.value * 2)` | `$derived(a * 2)` | `computed twice = a * 2` |
| `useEffect(() => { … }, [a])` | `watch(a, …)` | `$effect(() => { … })` | `effect on (a) { … }`, or `effect { … }` to follow whatever it reads |
| `useEffect(() => { start(); return stop }, [])` | `onMounted` / `onUnmounted` | `onMount` | `onMount { … }` and `onCleanup { … }` |
| `useRef()` on an element | `ref` + `ref="el"` | `bind:this` | `ref el`, then ` ` |
| `props.title` | `defineProps` | `$props()` | `component Card(title)` |
| `{ ok && …
}` | `v-if` | `{#if ok}` | `… ` |
| `{ ok ? : }` | `v-if` / `v-else` | `{:else}` | ` ` |
| `items.map((it) => … )` | `v-for` | `{#each items as it (it.id)}` | `{ item.name }
` |
| `onClick={() => save(id)}` | `@click="save(id)"` | `onclick={() => save(id)}` | `on:click={ save(id) }` |
| `value={v} onChange={e => setV(e.target.value)}` | `v-model="v"` | `bind:value={v}` | `bind:value={ v }` |
| `className={cx("btn", on && "on")}` | `:class="{ on }"` | `class:on` | `class={ ["btn", on && "on"] }` or `class={ { on } }` |
| `children` | ` ` | `{@render children()}` | ` ` |
| context | `provide` / `inject` | `setContext` | `createContext`, ``, `useContext(C)` |
| an error boundary class | `onErrorCaptured` | `` | `… ` |
| `createPortal` | `` | — | `… ` |
| React Query / SWR | Pinia Colada | — | `createQuery`, `createMutation` |
| Zustand / Redux | Pinia | stores | `createStore` |
| React Router | Vue Router | SvelteKit routes | files under `pages/`, ` `, `navigate()` |
| Next.js server actions | Nuxt server routes | form actions | `defineServerAction`, `useServerAction` |
| React Three Fiber + three.js | TresJS | Threlte | `` and `` from `@clarity-js/gl` (the `clarity-gl` skill); from React Three Fiber and three.js, `npx @clarity-js/port` writes them |
What does not carry over:
- **No hooks rules, no dependency arrays to keep right.** `computed` and `effect { }` follow
what they read.
- **No `key` prop on elements**: the key is on ``.
- **A handler is a statement, not a function you must wrap**: `on:click={ n++ }`. Passing a
function (`on:click={ save }`) works too and gets the event.
- **Component libraries do not come along.** For buttons, fields, dialogs, tabs, menus, toasts
and tables use `@clarity-js/ui` (`references/language.md` §21); rewrite what else the page uses;
wrap a DOM library (a chart, a map) with `ref`, `onMount` and `onCleanup`.
- **TypeScript comes along where the project is TypeScript** (a `tsconfig.json`, and `typescript`
installed; `references/language.md` §22): a props interface becomes the parameters' types
(`component Card(title: string, tone?: Tone)`), `useState(null)` becomes
`state row: Row | null = null`, a typed handler a typed `action`. In a JavaScript project leave
the types out, or keep them in `.ts` modules beside the component.
After porting: give the component an `ai:` contract. It is the one thing the original could not say.
---
# Clarity.js — LLM Context File (llms.txt)
> Single-file, complete reference for writing **`.clarity`** components correctly from scratch.
> Package: `@ozsarman/clarityjs` v1.5.0 (sections 12 to 23 list what is new in 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 1.0, 1.1, 1.2, 1.3, 1.4 and 1.5). AI-native, permission-aware frontend framework + DSL.
> If you read only this file, you can write valid Clarity. Do not invent APIs not listed here.
> The app around the components (routes, data from a server, server rendering, forms, tests) and a
> porting table from React, Vue and Svelte are in the `clarity` skill: this file plus those, as one
> file, is https://clarity-js.com/clarity-skill.txt (in an installed project:
> `node_modules/@ozsarman/clarityjs/skills/clarity/`).
---
## 0. What Clarity is (one paragraph)
Clarity is a compiled UI framework. You write `.clarity` files in a small DSL; the compiler turns
them into plain JavaScript that drives the DOM with fine-grained **signals** (no virtual DOM, no
diffing). Its signature feature: components declare, at the source level, what AI agents may **read**,
**act on**, and **never touch** (`ai:readable` / `ai:actionable` / `ai:forbidden`). Reactivity model is
signal-based like Solid/Svelte 5: `state` is a writable signal, `computed` is a derived signal, and the
DOM updates surgically when signals change.
---
## 1. File type & compiling
- Extension: **`.clarity`**
- Compile programmatically:
```js
import { compile } from '@ozsarman/clarityjs';
const { code, map, dts, ast, tokens } = compile(source, { filename: 'X.clarity', types: true });
// code = JS string. Pass { types:true } to also get a .d.ts (dts).
```
- Compile via CLI: `clarity build File.clarity` (or `clarity build dir/` for a whole folder).
- Vite plugin: `import clarity from '@ozsarman/clarityjs/vite'`.
- Runtime primitives (if you ever need them in raw JS): `signal, computed, effect, batch, mount, h`
exported from `@ozsarman/clarityjs`.
---
## 2. Component anatomy (THE most important section)
A file is zero or more `import`s followed by one or more `component` blocks.
```clarity
component Name(propA, propB) { // props are declared as parameters, passed as named attributes
// ── declarations (any order, but all BEFORE render) ──
state count = 0 // writable reactive signal
async state users = [] // auto-creates usersLoading + usersError signals
computed doubled = count * 2 // derived signal, auto-tracks deps
ref inputEl // signal(null), auto-bound to a DOM node via ref={inputEl}
const TAX = 0.2 // 0.10: plain JS declarations (const/let/function/class) are locals
function fmt(n) { return n.toFixed(2) }
action increment(by) { count = count + (by ?? 1) } // a named handler: on:click={ increment() }; also what an agent may invoke
ai:readable = [count, doubled] // state an AI agent may READ
ai:actionable = [increment] // handlers/actions an AI agent may INVOKE
ai:forbidden = [secretToken] // state an AI agent must NEVER see
effect on (count) { // re-runs ONLY when a listed dep changes (body reads are untracked)
console.log("count is", count)
}
effect { document.title = `${count}` } // 0.10: auto-tracking effect — re-runs when anything it reads changes
onMount { // runs once after the component (incl. / content) is in the document
// start timers, fetch, init 3rd-party libs here
// 0.10: `return () => …` registers a cleanup
}
onCleanup { // runs on unmount — clear timers, destroy libs here
// teardown
}
style { // component-scoped CSS (multiple style{} blocks allowed)
.name-box { padding: 12px; }
}
render { // REQUIRED. Exactly one root expression of JSX-like markup.
{ count }
}
}
```
### Declaration reference
| Declaration | Syntax | Notes |
|---|---|---|
| State | `state x = expr` | Writable signal. Read/assign as a plain variable: `x`, `x = x + 1`. |
| Async state | `async state x = []` | ALSO creates `xLoading` (bool, starts true) and `xError` (string, starts "") — assign them yourself in fetch `.then/.catch`. |
| Computed | `computed y = expr` | Read-only derived signal. Auto-tracks any signals used in `expr`. Never assign to it. |
| Ref | `ref el` | Creates `signal(null)`. Bind with ` `. Then use `el.focus()`, `el.value`, `el.scrollIntoView()`, `el.getContext('2d')`, etc. |
| Effect | `effect on (a, b) { ... }` | Re-runs only when a listed dep changes; reads inside the body do not subscribe. |
| Auto effect | `effect { ... }` | **0.10.** Re-runs whenever any signal it reads changes. |
| JS declarations | `const x = …` / `let t = null` / `function f() {}` | **0.10.** Plain locals in the component body (not reactive). Use `let timer` for interval handles. |
| Action | `action name(a, b) { ... }` / `action async name() { ... }` | Component function; AI-callable when listed in `ai:actionable` (actions are always callable by `act()`). |
| onMount | `onMount { ... }` | After insertion into DOM. Use for fetch, timers, canvas/chart libs. |
| onCleanup | `onCleanup { ... }` | On unmount. Pair every timer/listener/lib instance created in onMount with teardown here. |
| AI readable | `ai:readable = [a, b]` | List of state signals exposed to AI agents (read). |
| AI actionable | `ai:actionable = [fn1, fn2]` | List of actions/handlers an AI agent may call. |
| AI forbidden | `ai:forbidden = [secret]` | Never exposed to AI. Highest priority — overrides readable. |
| Style | `style { ...css... }` | Scoped to the component. You may have several `style{}` blocks. |
| Server | `server { ... }` | Advanced: server-only code block. Not needed for client components. |
| Render | `render { }` | Required; the template. One root element. |
---
## 3. Template (JSX-like) syntax
Inside `render { ... }`:
- **Interpolation**: `{ expr }` — any JavaScript expression (parsed by acorn): `{ user.name }`, `{ a + b }`,
`{ ok ? "Y" : "N" }`, template literals, `{ u?.name ?? "anon" }`, `{ s.replace(/-/g, " ") }`,
`{ Math.max(...xs) }`, `{ typeof v }`. `null`/`undefined` render nothing; a DOM Node is inserted.
Invalid JS is a compile error with line/col (never silently `null`).
- **Text vs expression**: bare text is literal; wrap dynamic values in `{ }`. Both `Label` and
`{ "Label" }` work. Text may contain apostrophes, URLs and HTML entities (`Don't`, `https://x`,
`©`, `•`). `{/* comment */}` and `` render nothing.
- **Whitespace**: HTML-like. Runs collapse to one space; indentation-only text between tags is
dropped; a single space between `{ a }` and an inline element on the same line is kept.
- **Attributes**: `class="..."`, `id="..."`, `type="range"`, etc. Dynamic attr via `{ }`:
`style={ \`width:${pct}%\` }` or `style={ { width: pct + "%" } }`, `disabled={ isBusy }`,
`class={ ["btn", active && "on"] }` / `class={ { on: active } }`. `null`/`false` removes an attribute;
`value`/`checked` are set as DOM properties; `href`/`src` with `javascript:` URLs are blanked.
Void elements need no `/>` (` `, ` `); mismatched closing tags are compile errors.
- **SVG**: `` subtrees (and SVG-only component roots like ``) are created in the SVG
namespace; `` switches back to HTML.
- **Two-way binding**: `bind:value={x}` on inputs/selects/range/checkbox. Updates `x` on user input.
- **Events**: `on:click={ stmt }`, `on:input={ text = e.target.value }` (`e` is the event),
`on:click={ (e) => save(e) }` or `on:click={ save }` (function values/references are called with
the event — **0.10**). Modifiers: `.prevent .stop .self .enter .escape .space .tab .up .down`.
- **Multiple statements in one handler are separated by COMMAS** (not semicolons):
`on:click={ count = count + 1, log = "clicked" }`
- **Conditionals**: ` ...markup... ...otherwise... `
(`cond=` is accepted too). The branch is re-created only when the condition's truthiness flips;
everything inside it (effects, nested components, their onCleanup) is disposed when it goes away.
- **Lists**: ` ...markup using item...
`
- The loop variable is **`item`** (rename with `as="todo"`); `index="i"` exposes the row index (**0.10**).
- `key` names the unique field (`key="id"`, `key="user.id"`) or is an expression (`key={item.id}`);
without it rows are keyed by item identity. Rows are moved, not re-created, and a row whose key
is unchanged updates in place. `items={ todos.filter(t => !t.done) }` works.
- Example:
```clarity
{ item.text }
```
- **Children / composition**: define a slot with ` ` in the child component; pass markup
between tags when using it. A component that wraps one element takes the caller's other
attributes with a rest parameter and hands them on: `component Chip(tone, ...rest)` +
`` (1.3, section 21).
- **Using child components**: ` ` — props map to params by NAME
(`component Badge(label, color)`), passed as attributes. Dynamic prop: `value={count}` (passed
live); a derived expression `value={count * 2}` is passed as a computed — the child always reads
the current value.
- **Other built-ins**: `… ` (error boundary), `… ` + `useContext(C)` (survives later ``/`` re-renders),
`… `, ` `, ``,
` ` (pushState, `aria-current="page"` when active).
---
## 4. Reactivity rules (avoid the common traps)
- `state` and `computed` are read like plain variables in expressions; the compiler tracks them.
Scoping is real JS scoping: a local/param with the same name shadows the state.
- Assign to `state` to update: `count = count + 1`, `count++`, `count *= 2`, `name ??= "x"` all work.
- Calling methods on a state value works: `chart && chart.update()`, `stops.forEach(f => f())`.
- The explicit signal API is also allowed: `count.get()`, `count.set(v)`, `count.update(fn)`,
`count.peek()` (`m.get(k)` / `m.set(k, v)` on a Map held in state still call the Map).
- `state c = someProp` copies the prop's current value.
- **Arrays and objects in `state` can be changed in place (0.11) or replaced.** Both update the view:
- in place: `cards.push(newCard)`, `cards.splice(i, 1)`, `cards[i].col = "done"`, `user.name = n`,
`m.set(k, v)`, `tags.add(t)`, `delete cfg.k`, `pos.x++`. Inside ``, `item.done = true`
updates the row and the list's source state.
- replaced: `cards = [...cards, newCard]`, `cards = cards.filter(c => c.id !== id)`,
`cards = cards.map(c => c.id === id ? { ...c, col: "done" } : c)`
- The compiler sees a change where the state's name starts the chain (`cards[i].col = …`). A change
made through another reference (a helper in a plain `.js` module that was handed the array) is
not seen: assign the result back (`cards = sort(cards)`).
- Never assign to a `computed`.
- In `effect on (...)`, list the signals you depend on inside the parentheses (or use `effect { }`).
- Updates are glitch-free: an effect never sees a stale computed and runs once per change.
---
## 5. AI permission directives (the differentiator)
```clarity
ai:readable = [name, email, role] // agent may read these
ai:actionable = [promote, resetLog] // agent may call these actions
ai:forbidden = [balance, apiToken] // agent may NEVER read these (wins over readable)
```
These compile into runtime metadata so an AI runtime bridge can introspect a component
(`aiQuery(element)`) and is prevented from reading forbidden fields or calling non-actionable code.
- Several `ai:*` lines of the same kind are merged.
- `ai:readable = [user.name]` exposes only that field (never the whole `user`).
- A name that is both readable and forbidden (or a readable object containing a forbidden path)
is a **compile error**. Computeds derived from forbidden state are forbidden too.
- Inside agent calls (`act()`), forbidden state cannot be read or written — also after an
`await` in an async action. The app's own rendering is never blocked by an agent action.
- `read()` and `snapshot()` return copies, so an agent cannot change state by mutating a value
it read.
- **0.13: `ai:actionable` is the whole list.** `act()` runs only what is listed there. An
`action` that is not listed is the page's own: calling it through the contract throws, runs
nothing, and leaves an `unknown_action` entry (`reason: 'not in ai:actionable'`) in the audit
trail. A component with no `ai:actionable` line offers agents no actions. List every action an
agent may call.
Audit helpers exported from the package: `getAIAuditLog()`, `clearAIAuditLog()`, `onAIAction(cb)`.
---
## 6. Complete worked example (copy this mental model)
```clarity
component Counter(start) {
state count = start
computed parity = count % 2 === 0 ? "even" : "odd"
ai:readable = [count, parity]
ai:actionable = [increment, reset]
action increment() { count = count + 1 }
action reset() { count = start }
style {
.counter { display:flex; gap:8px; align-items:center; }
.val { font-size:2rem; font-weight:700; }
}
render {
{ "−" }
{ count }
{ "+" }
Reset
{ parity }
10 }>
{ "High!" }
}
}
```
Wrapping a canvas-based 3rd-party library (e.g. Chart.js) — the lifecycle pattern:
```clarity
component LineChart(series) {
ref canvasEl
state chart = null
onMount {
chart = new Chart(canvasEl, { type: "line", data: series })
}
effect on (series) {
chart && (chart.data = series, chart.update())
}
onCleanup {
chart && chart.destroy()
}
render {
}
}
```
---
## 7. Type story
- **A component may be written in TypeScript** (1.4): typed parameters, state, computed, refs and
actions, interfaces in the file, and `clarity check` checks the types of the whole project,
components included. Section 22 has all of it. It is on where the project is TypeScript (a
`tsconfig.json`, and `typescript` installed); anywhere else a component is JavaScript.
- The compiler can emit a `.d.ts` per file: `compile(src, { types: true }).dts`, or `clarity types File.clarity`.
- In a JavaScript project nothing is asked of you: write no types.
---
## 8. Gotchas checklist (read before you write)
1. Multiple statements in an event handler use **commas**, not semicolons.
2. `` lives inside ``: `…… `.
3. List loop variable is **`item`** (or `as="name"`); use `index="i"` for the index.
4. `render` takes **one** root element.
5. Arrays/objects in `state` update the view when changed in place (`list.push(x)`, `obj.k = v`) or
replaced. A change made by code outside the component (a helper in a `.js` module) must be assigned back.
6. Props are **positional params** on `component Name(a, b)`, passed as **named attributes**.
7. `async state x` gives you `xLoading` and `xError` for free — use them, don't redeclare.
8. Pair `onMount` resource creation with `onCleanup` teardown (timers, listeners, lib instances).
9. `ref` gives a real DOM node after mount; access it in handlers/onMount, not at top level.
10. Don't assign to `computed`.
## 9. Reserved words (0.10 — only at the start of a component-body declaration)
DSL keywords (`state`, `computed`, `effect`, `render`, `action`, `ai`, `style`, `server`, `ref`,
`onMount`, `onCleanup`, `beforeMount`, `data`, …) are only special where a component-body
declaration starts. Everywhere else — props, variables, parameters, object keys, member names —
they are ordinary JavaScript identifiers: `component C(data)`, `const state = …`, `obj.data` all
work. Computed keys `{ [expr]: v }` work too (all of modern JS is supported inside `{ }` and in
action / effect / lifecycle bodies).
**3rd-party libraries (Chart.js, etc.) now work inline** — `data:` config keys and `.data`
access compile directly:
```clarity
component LineChart(series) {
ref el
state chart = null
onMount { chart = new Chart(el, { type: "line", data: { datasets: [] } }) }
effect on (series) { if (chart) { chart.data = series; chart.update() } }
onCleanup { if (chart) chart.destroy() }
render { }
}
```
(A plain-JS adapter module is still a fine pattern for large lib configs, but no longer required.)
## 10. Compiler quirks — FIXED in v0.8.1
The patterns that previously needed workarounds now compile correctly:
- ✅ **Bare `return`** (`if (x) return`) — emits valid JS. Use it freely.
- ✅ **Object-literal arrow bodies** — `arr.map(e => ({ ...e, k: v }))` compiles to a correct
parenthesised object (object spread `...e` is supported).
- ✅ **Boolean attributes** — `disabled={ !ok }`, `checked={x}` toggle the attribute's presence
(falsy → removed), so the element actually enables/disables.
- ✅ **Props inside a child `computed`** — `component Spark(series){ computed pts = series.map(…) }`
now unwraps the prop signal automatically, same as local state.
- ✅ **AI contracts without `onMount`** — a component declaring `ai:readable/forbidden` with no
`onMount` is still found by `aiDiscover()`.
Remaining nit: declare interval handles — `let timer = null` (0.10) or `state timer = 0` — rather than
assigning an undeclared `timer` (an undeclared assignment throws in a strict module).
## 11. 0.10 compiler notes
- Embedded JavaScript is parsed with acorn; expression nodes in `compile().ast` are ESTree
(`BinaryExpression`, `ConditionalExpression`, …).
- `import X from "…"`, `import { a as b } from "…"`, `import * as ns from "…"` all work.
- Scoped `style { }` rules also match the component root (`.card` on the root element) and the
scope class includes a hash of the file path (`_c-Card-1a2b3c`); `@keyframes` are untouched.
```
## 12. New in 0.12
**Frame clock** (`@ozsarman/clarityjs/game-loop`):
```clarity
import { frame, clock } from '@ozsarman/clarityjs/game-loop'
component Mover() {
state x = 0
onMount { frame((dt) => { x += 60 * dt }) } // one shared rAF loop; stops on unmount
render { { "→" }
}
}
// clock.pause() · clock.resume() · clock.step(1/60) · clock.advance(seconds) · clock.timeScale = 0.5
```
**Input** (`@ozsarman/clarityjs/input`): `const input = createInput()` (in a component body; disposed
on unmount) → `input.axis('x')` / `input.axis('y')` computed -1…1 (arrows, WASD, left stick, on-screen
joystick), `input.key('Space')` computed boolean, `input.onPress('KeyP', fn)`, `input.joystick(el)`,
`input.pointer`, `input.gamepads`. Read inside `frame()` with `.peek()`.
**3D** (`@clarity-js/gl`: Clarity's own WebGL2 renderer, no dependencies, no three.js): components `Scene`, `Mesh`,
`Group`, `Primitive`, `AmbientLight`, `HemisphereLight`, `DirectionalLight`, `PointLight`, `SpotLight`
(`target`, `angle` in degrees to the cone's edge, `penumbra`). Up to eight lamps (point and spot). A lamp with `castShadow`
throws shadows in ``: up to six cones, or one point light.
More surfaces (each only in a page that uses it): `physical(lights, { clearcoat, clearcoatRoughness, sheen, sheenRoughness, iridescence, iridescenceIOR, iridescenceThickness /* nm */, anisotropy, anisotropyRotation, … })`,
`toon(lights, { steps, rim, rimWidth })`, `matcap(lights, { matcap })`, `normalMaterial(lights)`; a `` takes a maker:
` `. `wires(shape, angle)` → a geometry of lines (a wireframe; with an angle, an outline).
```clarity
import { Scene, Mesh, DirectionalLight } from '@clarity-js/gl'
component World() {
state enemies = [{ id: 1, x: 0, z: 0 }]
render {
}
}
```
- Every prop may be reactive; `position`/`rotation`/`scale` take `[x, y, z]`; `rotation-y={ a }` sets one axis
(rotation is `[pitch, heading, roll]` in radians).
- `geometry`: box sphere icosahedron octahedron plane ground cylinder cone torus (or a triangle list, or a
`Geometry`) + `args`; `material`: `standard` (lit, default), `basic` (its own colour) or one you made with
`material({ vertex, fragment, uniforms })`; material props: `color emissive emissiveIntensity roughness
metalness flatShading receiveShadow opacity`. Colours are hex strings (`"#ff6347"`), not CSS names.
- `` props: `camera { fov, near, far, position, lookAt }`, `background`, `fog { color, near, far, density }`,
`shadows`, `antialias`, `dpr`, `frameloop` (`auto` | `always` | `demand`), `effects` (a lens that draws the
picture itself: bloom, grading), `onCreated={ (api) => … }` → `api.camera`, `api.scene`, `api.lights`,
`api.renderer`, `api.stats`, `api.invalidate()`, `api.screenshot()`.
- To move many objects per frame, keep positions in state and replace list items immutably
(`enemies = enemies.map(e => ({ ...e, x: e.x + dt }))`), or use `ref` + mutate the `Node` inside `frame()`
(`node.position[0] += dt`): the scene draws while frame callbacks run.
- More shapes (plain triangle lists; pass them as `geometry={ capsule(0.4, 1.2) }`, they are not names for `geometry="…"`):
`capsule(radius, height)`, `ring(inner, outer)`, `disc(radius)` (upright, facing +z), `tube(pointsOrCurve, radius)`,
`torusKnot()`, `tetrahedron(r)`, `icosahedron(r)`, `dodecahedron(r)`, `polygon(outline, holes)`, `extrude(outline, depth, { holes })`.
Curves: `catmullRom(points, { closed })`, `bezier(a, b, c, d?)`, `polyline(points)`, `path(...curves)` → `curve.at(t)`,
`curve.along(u)` (even speed), `curve.tangent(t)`, `curve.length`, `curve.points(n)`.
- Lines with a width: ` ` (CSS pixels; `worldUnits` for
the scene's units; `points={ wires(box(1, 1, 1), 1) }` for a shape's edges). `mode: 'lines'` geometry is always one pixel wide.
` ` faces the eye (`attenuate={ false }`: size is a part of the picture's height).
`` draws one child by distance, finest first. `clip(material, [[0, -1, 0, 1.2]])` cuts a surface open
(keeps x·px + y·py + z·pz + d ≥ 0; give the material `side: 'double'`): ` clip(standard(lights, p), planes) } />`.
- Many copies of one shape (a geometry with an `instanceMatrix` attribute of 16 numbers a copy, and `instances`): put ` `
in the scene and only the copies that can be seen are drawn. With `` a compute pass decides (outside the
view, or hidden behind the scene's solid meshes) and nothing comes back to the page; with WebGL2 only what is outside the view is
left out. By hand: `const hides = occluders(renderer), cull = cullCopies(renderer, node)`; before each picture
`hides.draw(root, camera); cull.update(camera, hides)`; `await cull.drawn()` is how many were drawn.
- A very large mesh (hundreds of thousands of triangles: a scan, a terrain, a statue): `const data = buildClusters(trianglesOrGeometry)`
once (about a second per 150,000 triangles; plain typed arrays, can be made in a worker or a build), then
` `. It is drawn with as many triangles as the picture needs (clusters with
coarser clusters over them, no holes); with `` a compute pass chooses, with WebGL2 the page does.
`error` is the pixels of difference allowed. Corners are welded: no hard edges, no UV pictures (colour by corner); one material.
By hand: `createVirtual(renderer, data, material)`, `.update(camera)` before each picture, `.drawn()`.
Streaming: `packClusters(data)` → one file (Uint8Array, coarsest first; write it in a build step); in the page `const data = await loadClusters('/rock.clusters')`
(head + first page now, the rest by HTTP byte range as the eye needs it; whole surface at every moment); `data.stream` → { loaded, pages, bytes, total, idle, whole() }.
- Mirrors that show the scene itself: ` ` inside `` looks at the scene
from that point (once, and whenever `refresh` changes) and makes it the surroundings of all lit materials (metal mirrors it, rough
metal blurs it, matte surfaces are lit by it). Not per frame. By hand: `reflectionProbe(lights, { position }).capture(renderer, scene)`.
- A light with an area (a glowing rectangle: a window, a screen, a light box): ` `
inside ``; it faces `target` and glows to that side only. `intensity` is the light its face shows. Lights standard/textured/physical
surfaces, up to 4; it draws nothing itself (put a `basic` plane there to see it). Soft shadows (sharp where things touch, wider with distance and the light's size): ` ` (import `areaShadows`; meshes cast with `castShadow`). By hand: `areaLight(lights, { … })` → `.set()`, `.corners()`, `.dispose()`; `areaShadows(lights, renderer, root, { which: [panel], size, bias, samples })` before drawing.
- A video on a surface: `const film = videoTexture(videoElement, { onFrame: () => api.invalidate('video') })`, then `map={ film }`;
`film.dispose()` when done. The video must be started by the page (muted, after a click).
- Glass that bends what is behind it: `glass(material, { ior: 1.5, thickness: 0.4, tint: '#d8f0ff', frost: 0 })` on a material (dark colour,
low roughness, low opacity: the material is the glass's own surface) and `refraction()` among the lens passes (after `transparency()`).
One bend, screen-space: glass behind glass is not seen; without the pass the material is drawn as it is.
- See-through things that overlap or cross (glass in glass, many drifting shards): put `transparency()` first in `createLens({ passes })`.
It draws every mesh whose material blends (`opacity < 1`, alpha pictures, text, sprites) so that the picture is the same whatever order
they come in (weighted sums; one surface alone is unchanged, overlapping colours are mixed by nearness). Nothing else to change.
`transparency({ range: 20 })`: about how far from the camera the see-through part reaches. Additive meshes are left as they are.
- Light that bounces (dynamic global illumination, one bounce, nothing baked): two more passes for `createLens({ passes })`.
`bounce({ radius = 1.5, strength = 1, samples = 16, scale = 0.5, bias, most, only })` reads the picture and its depth: lit surfaces light
what is beside them, in the same frame, any material; nothing from what is off screen or hidden.
`const probes = lightProbes({ bounds: { min, max }, grid: [4, 2, 4], perFrame: 1, size: 16, strength, sky, only })`: a grid of points that
keep the light arriving from six sides; `perFrame` of them are redrawn each frame (six small scene draws each), all on the first
picture and after `probes.refresh()`; also carries what is behind the camera; walls hold it back. `further: 0.5` → more than one bounce
(the probes see each other's light; the share a surface sends on; settles at 1 / (1 − further) × the first bounce in a closed room). Put them before
`ambientOcclusion()`. The added light takes the hue of the pixel it lands on (no albedo is known): lower `strength` for dark scenes.
- A lens: ``.
Passes run in the order given. `ambientOcclusion({ radius, strength, bias, samples, scale, only })`;
`depthOfField({ focus, aperture, most, samples })` (focus: distance from the camera; aperture/most: parts of the
picture's height); `outline({ of, colour, width, hidden, hiddenColour, fill })` (of: a Node, an array or Set of
Nodes, or a signal/function giving one; a node stands for all under it); `reflections({ of, strength, fresnel, roughness, reach, thickness, steps, fade })` (screen-space reflections on the named surfaces, or on all when `of` is not given; fresnel 0.04 = water, 1 = mirror; only what is in the picture is mirrored); `motionBlur({ strength, most, samples })` (camera movement only); `fxaa()`; `grade({ brightness, contrast,
saturation, tint, lut, strength })` with `cubeLUT(text)` / `loadLUT('/x.cube' | strip picture)`. Numbers and
colours may be signals or functions (read for every picture). Your own: `lensPass(fragment, { uniforms, stage:
'light' | 'screen', depth, update })`: the shader reads `tColor` (and, with `depth: true` and `${LENS_DEPTH}` pasted in,
`viewZ(uv)` = minus the distance and `viewAt(uv)`). Do not hand-write an AO/DOF/outline/FXAA/LUT pass: use these.
- By hand, shader and all: `new Node(geometry, material)`, `new Geometry({ attributes, index, instances })`,
`createLights()`, the `LIGHTS` GLSL chunk, `createPass` / `createBloom`; put the result in the scene with
` ` or ``.
- Models: ` ` inside ``, or by hand
`const model = await loadGLTF(url, { lights }); root.add(model.scene); const anim = createAnimator(model); anim.play('Run'); frame((dt) => anim.update(dt))`.
glTF 2.0 (`.glb` / `.gltf`): meshes, materials with their pictures (`textured()`: `map`, `normalMap`, `surfaceMap`, `emissiveMap`, `occlusionMap`; a `Texture` takes `anisotropy` 1 … 16), skins (`Skin`, bones in every lit
material and in the shadow pass), animations of position / rotation / scale with fades between clips. `model.bounds`,
`model.names`, `model.find(name)`. Morph targets: `model.morphs` (names), `model.morph('smile', 0.8)`, clips of weights;
`blendShapes(geometry, weights)`. `model.cameras`, `model.lights` (KHR_lights_punctual): data with their nodes. Read too: models packed by meshoptimizer
(gltfpack: EXT_/KHR_meshopt_compression, KHR_mesh_quantization), KHR_texture_transform, the numbers of clearcoat / sheen / iridescence /
anisotropy (→ `physical()`), KHR_materials_transmission + ior + volume (→ glass, shown bent by the `refraction()` lens pass), and
EXT_mesh_gpu_instancing (one draw call). Pictures in KTX2 files (KHR_texture_basisu): call `useKTX2()` once first (UASTC and ETC1S both read). Meshes packed by Draco (KHR_draco_mesh_compression) are read too: own decoder, fetched only when a model needs it, nothing to set up.
- KTX2 pictures: `const t = await loadKTX2(url, { renderer })` → a Texture (`map={ t }`). Read: levels plain or squeezed with Zstandard / zlib; R8, RG8, RGB8,
RGBA8 (colours or numbers), RGBA16F / 32F on every GPU; BC1, BC3, BC7, ETC2, ASTC 4×4 kept packed where the GPU reads them; Basis Universal, both kinds, opened to
RGBA8 pixels (UASTC: `decodeUASTC(blocks, w, h)`; ETC1S / BasisLZ: `decodeETC1S(books, colour, second, w, h)`); kept packed instead where `renderer`'s GPU reads the kind and the levels are in the file: UASTC as ASTC 4×4 blocks (`packUASTC`, 1/4 the memory, exact) or, where it reads BC7 and not ASTC (desktops), as BC7 blocks (`bc7UASTC`, 1/4, near not exact: about 47–52 dB), ETC1S colours as ETC1 blocks where it reads ETC2 (`packETC1S`, 1/8, exact; with alpha ETC2 RGBA blocks, 1/4, alpha near) or, where it reads BC and not ETC2 (desktops), as BC1 blocks (`bcETC1S`, 1/8, near: about 42–58 dB; with alpha BC3, 1/4); two numbers ('rg') are opened; `{ pixels: true }` always opens. `textureSupport(renderer)` → { bc, etc, astc, bc7 }. NOT read: BC4, BC5, ASTC in other block sizes, cube maps, texture video: refused by name. `useKTX2()` once → models read their
KTX2 pictures. `parseKTX2(bytes)` header only; `readKTX2(bytes)` levels; `openKTX2(bytes)` → { width, height, format, data }; `unzstd(bytes)`.
- Other formats, same result as `loadGLTF` (` ` shows it): `await loadOBJ(url, { lights })` (fetches its .mtl and pictures
from beside it; `mtl: text | false`, `material`, `bumpIsNormal`, `model.missing`), `await loadSTL(url, { lights, color, roughness, metalness, smooth: 30, up: 'z' })`,
`await loadPLY(url, { lights, pointSize })` (corners' colours kept; no faces → a cloud of points), `await loadDRC(url, { lights, pointSize })` (a Draco .drc on its own: a mesh, or a point cloud told in order; own decoder, fetched on first call; k-d tree clouds refused by name). Readers alone, no GPU: `parseOBJ(text)`,
`parseMTL(text)`, `parseSTL(bytes)`, `parsePLY(bytes)`. In a `` pass `lights: api.lights`.
- Building 3D with an agent: the repository's `skills/` folder is a pack of seven Agent Skills for this renderer
(`clarity-gl`, `-shaders`, `-vfx`, `-models`, `-game`, `-polish`) with ready recipes (particles, lightning,
flames, ripples, an HDR lens, shake and hit-stop, shader chunks, model building, seeded random, Web Audio
sound, a template game, a stepped-screenshot script). `npx skills add https://gitlab.com/ozsarman/clarity.js`.
## 13. New in 0.13
**The simulation kit** (`@ozsarman/clarityjs/sim`): the rules of a game apart from its page — plain
numbers, seeded chance, no DOM. The same seed plays the same game in the browser, in a Node test
and under `clarity balance`.
```js
import { createSim, createRng, runSim, balance } from '@ozsarman/clarityjs/sim'
export const createGarden = ({ seed = 1 } = {}) => createSim({
seed,
setup: ({ rng }) => ({ water: 3, plants: [], rain: rng.range(4, 9) }), // the state: plain data
step(s, dt, { rng, emit }) { s.rain -= dt; if (s.rain <= 0) { s.water++; s.rain = rng.range(4, 9); emit({ type: 'rain' }) } },
actions: { plant(s, { emit }, x) { if (s.water > 0) { s.water--; s.plants.push({ x, size: 0 }) } } },
report: (s) => ({ water: s.water, plants: s.plants.length }), // what is shown and read
})
export const advise = (report, t) => (report.water > 0 ? { act: 'plant', x: report.plants } : null) // a player, for tests
```
- `sim.step(dt)`, `sim.report()`, `sim.plant(2)` / `sim.act('plant', 2)`, `sim.events`, `sim.on(fn)`, `sim.log`,
`sim.snapshot()` / `sim.restore(snap)`, `sim.rng`, `sim.t`. Rule functions: `setup(ctx)`,
`step(state, dt, ctx)`, `action(state, ctx, ...args)`, `report(state, ctx)`; `ctx = { rng, seed, t, emit }`.
- `createRng(seed)`: `rng()`, `.range(a, b)`, `.int(n)` / `.int(a, b)`, `.chance(p)`, `.pick(list)`, `.shuffle(list)`,
`.sign()`, `.fork(label)`, `.state`. Never use `Math.random()` in rules.
- In a page: `const sim = createGarden({ seed })`, then `frame((dt) => { sim.step(dt); view = sim.report() })`;
actions of the component call the simulation's.
- `runSim(make, { seed, seconds, dt, policy, every, until })` plays one game with no page;
`balance(make, { seeds: 24, … })` plays one a seed and returns how many reached the end and in what time.
- CLI: `clarity balance rules.js --seeds 24 --seconds 120 --until "grown >= 5" [--measure a,b] [--min-rate 1] [--json]`.
The module exports `createSim` (or a default) and may export `advise` and `done(report)`.
A simulation is anything with `step(dt)` and `report()`; one written by hand works too.
**`ai:actionable` is the whole list** (see section 5). **`@clarity-js/gl`** ships types (`index.d.ts`) and
recovers by itself when the WebGL context is lost and given back (`renderer.onRestore(fn)`).
**Hydration**: `hydrateRoot(container, App, props, { onMismatch })` returns `{ unmount, mismatches, restored }`;
differences are reported with paths; typed input and focus survive. Server: `renderToString(App)` disposes
everything the render created. Pages router: `await Routes.preload(url)` before rendering on the server
and before `hydrateRoot` on the client.
**Router a11y**: after navigation focus moves to `[data-route-focus]` / `main h1` / `h1` / `main` and the page
is announced (`createRouter({ focus, announce })`). **Reduced motion**: `reducedMotion` signal,
`setReducedMotion(bool|null)`; `` skips animations while it is on.
**Browser entry**: bundlers load `src/browser.js` (no Node-only SSG/ISR), so importing
`@ozsarman/clarityjs` in client code never pulls in `node:fs`.
## 14. New in 0.14
**Pointer events on meshes, picking, an orbit control** (`@clarity-js/gl`). A scene hears the pointer when it is
given `events={ pointerEvents }`; then meshes and groups take `on:click`, `on:dblclick`, `on:contextmenu`,
`on:pointerdown`, `on:pointerup`, `on:pointermove`, `on:pointerover`, `on:pointerout`.
```clarity
import { Scene, Mesh, Group, Orbit, pointerEvents } from '@clarity-js/gl'
```
- In a handler: `e.object` (the node it is on), `e.target` (the mesh hit), `e.point`, `e.normal`, `e.distance`,
`e.nativeEvent`, `e.stopPropagation()`. Several statements in one `on:` handler are joined with commas.
- The nearest mesh under the pointer is the target even with no handler (a wall hides a button), unless it is
`pickable={ false }`. The event rises through parents. over/out go to the nearest listening node and do not rise.
- By hand: `raycast(root, origin, direction)` → `[{ node, point, normal, distance, triangle }]` nearest first, with
`camera.ray(x, y)`; `node.on = { click(e) {} }`; `createOrbit(camera, canvas, options)` + `orbit.update(dt)`.
- Editing in the scene: ` ` draws arrows,
rings or sticks on the node `of` holds (e.g. `e.object` from a click) and moves/turns/scales it under the pointer; a camera control
beside it stays still while a part is held. ` …meshes… ` is a group dragged
by any of its meshes. Helpers: ` `, ` `, ` `, ` `,
`boundsOf(node)` → `{ min, max }`. By hand: `createHandle(camera, canvas, lights, options)` + `handle.update()` each frame, `drag(camera, canvas, node, options)`.
- Other cameras, as children of ``: ` ` (no perspective; `height` = half the picture's height in units, or none to
follow the zoom of an ``/`` beside it); ` y } lock />` (W A S D, drag
or locked mouse to look, Shift runs, left half of a touch screen is a stick); ` ` (moves the way it looks, Space/E up,
Q/C down); ` ` (drag slides the ground under the pointer, wheel zooms to the
pointer, right-drag turns). By hand: `orthographic(camera, { height })`, `createWalk|createFly|createMap(camera, canvas, options)`
+ `.update(dt)`.
With `events`, the scene api has `pick(clientX, clientY)`.
- Not picked: copies drawn by instancing, lines, points.
**One quality dial**: `const quality = createQuality()` (`'low' | 'medium' | 'high'`), ``.
Resolution, shadows, the shadow map and the lens follow its level; `quality.use('steps')` is a computed for
anything else (a prop, or a shader uniform), `quality.set('low')` / `lower()` / `raise()` move it, and while
`auto` is on it steps down when pictures come slower than `fps`. `levels: { low: { fish: 40 }, high: { fish: 400 } }`
adds your own keys.
**Uniforms that follow state**: a uniform may be `{ value }`, a signal or computed, or a function:
`material({ …, uniforms: { uHeat: heat, uTime: () => clock.elapsed } })`; in markup,
` `. A change asks for one new picture.
**Recording and replay** (`@ozsarman/clarityjs/replay`). A tape is plain JSON.
```js
import { recordSim, replaySim, recordPage, replayPage } from '@ozsarman/clarityjs/replay'
const rec = recordSim(sim); /* …play… */ const tape = rec.stop()
const again = replaySim(createGarden, tape) // throws if it does not end where the recording did
// a game that reads createInput() in frame(): the clock's frames and every change of input
clock.pause(); const rec2 = recordPage({ input }); clock.resume(); /* … */ const tape2 = rec2.stop()
await replayPage(tape2, { input, speed: 1 }) // on a page in the same state; speed 0: all at once
```
- Exact when time comes from the clock and chance from `createRng(seed)`. `Math.random()` and `Date.now()` are not on the tape.
- `rec.note('start', level)` puts something of your own on a page tape; `replayPage(tape, { on: { start: (level) => … } })` hands it back.
- Input: `input.press(code)`, `input.release(code)`, `input.listen(fn)`, `input.feed(kind, …)`, `input.mute(on)`. `clock.elapsed` can be set.
**Golden frames** (`@ozsarman/clarityjs/golden`, Node): `matchGolden(file.png, frame, { threshold, tolerance })` compares
a frame with the picture kept in `file` (the first run, or `CLARITY_UPDATE_GOLDEN=1`, writes it; a failure leaves
`.actual.png` and `.diff.png`). `compareFrames(a, b, options)`, `encodePNG`, `decodePNG`. In the page:
`packFrame(readFrame(sceneApi))` from `@clarity-js/gl`, at a moment fixed with `clock.pause()` and `clock.step()`.
**Hot reload** (Vite plugin, dev only). An edited `.clarity` component is mounted again with the state it had
(an edited child is passed up to the file that holds the root). An edited shader is swapped into the running
scene with no re-mount: a `.glsl` / `.vert` / `.frag` file (imported, it is its text) or a text exported from a
module that marks its shaders with `/* glsl */`; one that does not compile is refused and the old one keeps drawing.
## 15. New in 0.15
Everything here is in `@clarity-js/gl` unless a line says otherwise. A scene that does not use a
feature does not carry its code.
**A world of blocks** (voxels):
```clarity
import { Scene, Voxels, DirectionalLight, createVoxels, pointerEvents } from '@clarity-js/gl'
component Field() {
const world = createVoxels({ blocks: { grass: "#5b8c3a", stone: "#8a8a8a", water: { color: "#3b82f6", opacity: 0.6 } } })
onMount { world.fill([-8, 0, -8], [7, 0, 7], "grass") }
render {
}
}
```
Also `world.set(x, y, z, name)`, `world.get(x, y, z)`, `world.pick(origin, direction)`. A changed block re-meshes its own chunk only. `world.move(position, half, delta)` slides a box through it
(`{ position, hit, grounded }`); `save()` / `load()`; `loadVox(url)` reads MagicaVoxel.
**Cloud, smoke, fire**: ` `.
`makeVolume(size, (x, y, z) => density)` makes one; `loadVDB(url, { grid, heat })` reads an OpenVDB file.
**Gaussian splats**: ` ` (3DGS `.ply`, `.splat`), beside meshes.
**Upscaling**: `` draws small and shows sharp;
`upscaler({ mode: "temporal", scale: 0.5 })`. A quality level may say `upscale: 'spatial' | 'temporal' | 'off'`.
It takes the place of `effects`.
**Light from the surroundings**: ` `
or ` `. Every lit material mirrors it and is lit
by it; `metalness` and `roughness` decide how.
**Particles on the GPU**:
```clarity
{ burst = p } } />
```
`rate={ 0 }` and `burst.emit(40)` for a burst; `burst.node.position = [x, y, z]` moves where it happens. Also
`drag`, `turbulence`, `floor` + `bounce`, `stretch`, `blend="alpha"`, `emitting`, and
`force="vel += (uTarget - pos) * 6.0 * dt;"` with `uniforms={ { uTarget: { value: [0, 2, 0] } } }`.
**Words in the scene**: ` `, or the words
as content: `GAME OVER `. Any CSS font (`font`, `weight`); `maxWidth`,
`align`, `anchorX`, `anchorY`. Score and lives belong in the page's HTML; `` is for words in the world.
**Accessible 3D**: `` and a
`label` on a mesh. With `on:click` it is a button (Tab, Enter, Space, a screen reader); alone it is read as a
picture. `role`, `focusable`, `aria={ { valuenow: v } }`, `on:focus`, `on:blur`, `on:keydown`, `on:keyup`.
`describeView(sceneApiOrElement).text` says what is in the picture in words.
**Sound** (`@clarity-js/audio`, a package of its own, no dependencies):
```clarity
import { audio, sfx } from '@clarity-js/audio'
component Sounds() {
state volume = 0.8
const coin = audio.sound(sfx.coin()) // from numbers; also jump, laser, hit, explosion, powerup, hurt, blip, step
const jump = audio.sound("/sfx/jump.ogg") // a file: loads in the background
const theme = audio.music("/music/theme.ogg")
effect { audio.volume = volume }
onMount { theme.play({ fade: 1 }) }
render {
Coin
Jump
Mute
}
}
```
Also `audio.bus("music").volume = 0.4`, `tune("C5 E5 G5")`. Sound waits for the first touch of the page by itself. `audio.heard("coin")` counts plays, for tests.
A recipe: `{ wave, freq: [from, to], time, attack, release, volume, steps, filter, layers }`.
**More input** (`@ozsarman/clarityjs/input`): `input.touches` (every finger down), `input.pinch`
(`{ active, scale, rotation, x, y }`), `createTilt(input).enable()` from a tap (tilt joins `input.axis("x")` / `"y"`),
`vibrate(40)`.
**A game from one command**: `npm create clarity@latest my-game -- --game`. Rules in `src/rules.js`
(`createSim`, with `advise` and `done`), the page in `src/Game.clarity`, `npm test`, `npm run balance`.
The page copies `game.report()` into state each frame and turns `game.events` into sounds and bursts.
**Agents from outside the page** (MCP): in `main.js`,
`import { connectAgent } from '@ozsarman/clarityjs/agent'` and `connectAgent({ view: () => describeView(sceneEl) })`.
It does nothing until the page is opened with `?agent`. `npx clarity mcp --open http://localhost:5173` is the MCP
server (stdio): tools `clarity_games`, `clarity_read`, `clarity_act`, `clarity_clock`, `clarity_wait`,
`clarity_view`, `clarity_screenshot`. An agent gets what `ai:readable` and `ai:actionable` allow. An action should
show its effect at once (copy the report into state inside the action), because an agent may be holding the clock.
**For a whole game**, follow `skills/clarity-game/SKILL.md`: design on one page, rules first, balance by
playing many seeds (`scripts/playtest.mjs`), a replay as a test, then feel, then look.
## 16. New in 0.16
All in `@clarity-js/gl`. WebGL2 stays the default: a scene that asks for none of this is what it was.
**WebGPU, with WebGL2 underneath.** The same scene, the same GLSL shaders:
```clarity
import { Scene, webgpu } from '@clarity-js/gl'
…
```
`defaultBackend(webgpu)` once does it for every ``; `backend={ false }` keeps one on WebGL2.
`scene.backend` is `'webgl2'` or `'webgpu'`. By hand: `const renderer = await createGPURenderer(canvas)` from
`@clarity-js/gl/webgpu` returns what `createRenderer()` returns (plus `renderer.device`); call
`renderer.flush()` after drawing a picture (`` does). Do NOT write WGSL: write GLSL ES 3.00 as always,
the package translates it (`translate({ vertex, fragment, defines })` shows the result). Not understood by the
translator: `switch`, uniform blocks, arrays of samplers, integer textures. Do not use `renderer.gl` in code
meant for both (it is null on WebGPU): use `readPixels(renderer)`, `renderer.floatTargets`, `readAttribute(renderer, geometry, name)`.
**Compute.** One GLSL step for every element of a set, kept on the GPU (compute pass on WebGPU, transform
feedback on WebGL2):
```js
const flock = compute(renderer, {
count: 4000,
state: { position: { size: 3, data: (i) => [i, 0, 0] }, velocity: { size: 3 } },
uniforms: { uDt },
step: `uniform float uDt;
void main() { // position, velocity: this element; index, count; at_position(j): any other
vec3 d = at_position((index + 1) % count) - position;
velocity += d * uDt; position += velocity * uDt;
}`,
})
scene.add(flock.node({ attributes: { corner: { data: quad, size: 2 } }, count: 6 }, material)) // drawn once an element
frame((dt) => { uDt.value = dt; flock.run() })
```
`flock.points(material)`, `await flock.read('position')`, `flock.write('position', data)`, `flock.dispose()`.
In the drawing shader the state arrives as attributes named as in `state` (`in vec3 position;`), or renamed with
a third argument: `flock.node(geometry, material, { position: 'aPos' })`.
**The asset step of the build** (`vite.config.js`: `import assets from '@clarity-js/gl/assets'`, `plugins: [clarity(), assets()]`):
```js
import ship from './ship.glb' // packed in a build; ship.url, ship.clips.Fly, ship.nodes.Hull (typed: ship.d.glb.ts is written beside it)
import wall from './wall.png?texture' // packed for the GPU (BC and ETC2); ?texture&linear for normals/roughness
// or loadGLTF(ship)
const map = await loadTexture(wall) // a Texture: the packed kind this GPU reads, or the PNG
```
tsconfig: `"allowArbitraryExtensions": true`, `"types": ["@clarity-js/gl/assets/client"]`. Without a bundler:
`packModel(bytes)`, `packTexture(pngBytes)`, `modelTypes(info, file)` from `@clarity-js/gl/assets` (Node).
**3D islands.** A picture from the server, the scene when it comes into view:
```clarity
import { Island } from '@clarity-js/gl/island'
import('./Reef.clarity') } away="unmount" />
```
`when`: `visible` (default) | `idle` | `load` | `click` | `never`; `props` go to the component; the element has
`data-island="still | loading | live | failed"`. Import `Island` from `@clarity-js/gl/island`, not from
`@clarity-js/gl`, so the page's own code has no renderer in it. Make the picture with `saveStill(scene)`.
## 17. New in 0.17
All in `@clarity-js/gl`.
**What is not in the picture is not drawn.** Nothing to write: a `` off the screen is left out, in the
shadow pass too. It is tested only where its bounds can be trusted (the package's materials, no bones, no
instancing). For a vertex shader of your own, instanced copies or a skinned mesh, say where it can be:
`geometry.bounds = { center: [0, 2, 0], radius: 40 }` (or `node.bounds`); `node.cull = false` always draws.
`camera.sees(node)` is the test; `renderer.stats.culled` counts.
**Instances are picked one by one.** `raycast()` hits carry `instance`, pointer events `e.instance`. Copies are
found through the geometry's `instanceMatrix` attribute (size 16, instanced), which `standard()` and `basic()`
read; a shader that places copies its own way sets `geometry.placeCopy = (i, m) => { …16 numbers into m… }`.
**Clips mixed by weight, and a state machine.**
```js
anim.mix({ Walk: 1 - pace, Run: pace }, { sync: true }) // call every frame; with { fade: 0.3 } it fades there instead
const gait = createStateMachine(anim, {
start: 'idle',
states: { idle: 'Idle', move: { mix: (p) => ({ Walk: 1 - p.speed, Run: p.speed }) }, jump: { clip: 'Jump', loop: false, then: 'move' } },
moves: [{ from: 'idle', to: 'move', when: (p) => p.speed > 0.05 }, { from: 'move', to: 'idle', when: (p) => p.speed <= 0.05 },
{ from: ['idle', 'move'], to: 'jump', when: (p) => p.jump }],
params: { speed: 0, jump: false },
})
frame((dt) => { gait.params.speed = pace; gait.update(dt) }) // update() moves the animator: do not call anim.update() too
```
Markup: ` `, or
` createStateMachine(animator, { … }) } params={ { speed: pace, jump } } />`.
**The sun's shadow near and far.** `` (`import { cascaded } from '@clarity-js/gl'`)
with ` `: 2 to 4 shadow maps that follow the
camera. Both are needed: the module on the scene, the number on the light. Without them the one map covers
`shadowCameraSize` round `target`.
In a shader of your own `sunShadow(P, N)` is called as before; do not read `uSunVP` yourself (it is an array now).
## 18. New in 1.0
**The API is frozen.** From 1.0 the packages follow semantic versioning. Every exported name of
`@ozsarman/clarityjs`, `@clarity-js/gl` and `@clarity-js/audio` is on record in `api/surface.json`;
`node scripts/api-surface.mjs` compares the source with it. Names that begin with `_` are internal: do not
use them. `STABILITY.md` says what is promised. `setAIStrictActions()` is gone (it did nothing since 0.13).
**Why was this frame drawn?** A `` draws only when something asks. Its handle (`onCreated`) says who:
```js
api.why // ['mesh "ship": position', 'frame() callbacks are running']
api.invalidate('the tide turned') // ask for a picture and say who asks (the word shows up in api.why)
const stop = api.watch((f) => { f.frame; f.why; f.dt; f.calls; f.triangles; f.culled }) // every picture
```
A scene that never rests has the same asker in every frame: a `frame()` callback left running, a signal
that changes every frame bound to a prop, `frameloop="always"`. The devtools (`initDevtools()` from
`@ozsarman/clarityjs/devtools`) have a **3D** tab that shows this for every scene on the page.
**WebXR.** A scene goes into a headset when it is given the module:
```
import { Scene, Mesh, XRController, immersive } from '@clarity-js/gl'
component Room() {
let scene = null
render {
Enter VR
{ scene = api } }>
}
}
```
- `scene.xr.supported(mode)` → Promise; `enter(mode, { features, scale, space })` must be called
from a click; `exit()`; `presenting` is a signal; `mode` is `'immersive-vr'` or `'immersive-ar'`.
- Units are metres. The player stands under the scene's camera unless you say where:
`scene.xr.place([x, 0, z], turn)`. `scene.xr.origin` is a `Node` (the floor under the player): move it
to move the player.
- A controller's trigger is `on:click` on the mesh it points at; pointing is `onPointerOver` /
`onPointerOut`. The event has `e.controller` (`hand`, `grip`, `ray`, `hit`). No `events={ pointerEvents }`
is needed in the headset (it is still needed for a mouse on the page).
- ``: its children follow that hand and are not
drawn outside a headset. `scene.xr.controller('right').source.gamepad` has buttons and sticks.
- ``: a hand the headset sees
itself (no controller). Drawn joint by joint; with `joint`, its children ride on that joint. It asks for
hand tracking itself. `scene.xr.controller('left')` also has `tracked` (signal), `joints` (25 × 16 numbers,
in `JOINTS`' order), `radii`, `joint(name)` (a Node), `pinch` (0 … 1), `pinching` (signal).
- ` ` (AR): the room the headset knows (WebXR plane + mesh detection) as nodes under the
player's origin; `hides`: real walls/tables hide what is behind them (depth only, drawn first); `light`: scene lights follow the device's light estimate.
By hand `xrRoom(scene.xr, { hides, material, lights, onAdd, onChange, onRemove, onLight })` → `{ parts, find(label), stop() }`; `planeGeometry(polygon)`;
`scene.xr.onFrame((frame, space) => …)`. NOT yet tried in a real headset; depth sensing is not read.
- `` (AR): its children (or a ring)
sit on the floor, table or wall found. `onSelect(e)`: `e.position`, `e.quaternion`, `e.matrix`, and
`e.anchor()` → `{ node, anchored, remove() }`: put what you place under `node`. Without the component:
`scene.xr.hitTest({ from })` → `{ node, found, anchor(), stop() }`; `scene.xr.onSelect(fn)`; `scene.xr.want(feature)`.
- `effects` (a lens) is used in VR, once for each eye; not in AR. `createLens({ bloom, exposure, vignette,
grain, samples, tone, passes })` is a ready lens for ``, in a headset or on a page.
- In the headset `frame()` callbacks run on the headset's beat (`clock.drive`), and the camera is the head.
- AR: the background is not drawn; give the scene nothing that hides the room. A scene with `xr` is drawn
with WebGL2 (`defaultBackend()` is not followed). `` is drawn with
WebGPU, in the headset too, only where the browser has `XRGPUBinding` (experimental in 2026); WebGL2 otherwise.
- Tests: `tests/runtime/xr-fake.js` is a headset that is not there (`installFakeXR(globalThis)`).
**Shadows.** Cascades blend into each other near their edges; nothing to write.
---
## 19. New in 1.1
**The linter reads a file as the compiler does.** The compiler stops at what is not Clarity; it lets
through what is Clarity and almost surely a mistake. `clarity check` and `clarity lint` now find those,
with the line and column where each starts and ends:
```
npx clarity check src/App.clarity # one file: the compiler and the linter together (do this after every change)
npx clarity lint . # every .clarity file of the project (node_modules and dist are left alone)
npx clarity lint . --fix # also apply the repairs that cannot change the program
npx clarity lint . --format json # for tools (compact: one line per finding)
npx clarity format . # whitespace only; a file that would compile differently is left as it was
```
Errors (the command fails): `syntax`, `compile`, `render-required`, `no-duplicate-declaration`,
`no-assign-computed` (a computed is assigned), `bind-target` (`bind:` given a computed or an action),
`unknown-event-modifier` (`on:click.prevnt`: it would be ignored and the handler would run every time),
`list-requires-items`, `when-requires-test`, `else-outside-when`, `ai-unknown-target` (an `ai:` list names
something the component does not declare), `effect-unknown-dep`.
Warnings: `no-undef` (a name or a component tag that is not declared, imported or a global; it says the
name that was probably meant), `no-unused-state`, `no-unused-computed`, `no-unused-ref`, `no-unused-import`,
`no-unused-prop`, `component-name-pascal`, `no-assign-in-expression` (`onClose={ open = false }` assigns
while the template is drawn: write `onClose={ () => { open = false } }`), `missing-cleanup` (a
`setInterval`, a listener on `window` or an observer that nothing in the component stops),
`duplicate-attribute`, `img-alt`. Off until asked for: `list-key`, `no-unused-action`.
Levels are set in `.clarity-lint.json` at the root of the project: `{ "rules": { "img-alt": "error",
"no-unused-prop": "off" } }` (`"error"`, `"warn"`, `"off"`).
**In the editor.** VS Code: the *Clarity.js* extension (errors and warnings as you type, completion, hover
that says whether an agent may read or call a name, go to definition, outline, formatting, quick fixes).
Other editors: `npm i -g @clarity-js/language-server`, started as `clarity-language-server --stdio`.
ESLint: `eslint-plugin-clarity` (`export default [...clarity.configs.recommended]`) puts the same
findings into ESLint's report. All of them ask the same two modules:
```js
import { lintCode, formatCode, RULES } from '@ozsarman/clarityjs/linter'
import { diagnose, complete, hover, definition, symbols, codeActions } from '@ozsarman/clarityjs/language'
lintCode(source) // { issues: [{ severity, rule, message, line, column, endLine, endColumn, fix, suggest }], errorCount, warningCount }
formatCode(source) // the tidied text
complete(source, { line: 12, column: 9 }) // what could be written there: [{ label, kind, detail, documentation, snippet }]
hover(source, { line: 12, column: 9 }) // { contents (Markdown), line, column, endColumn } or null
```
Lines and columns count from 1. These functions take the text of a file and answer; they read no files,
and everything but `lintCode` / `diagnose` also works on a file that does not compile yet.
## 20. New in 1.2: webpack and Rollup
A `.clarity` file is compiled by the bundler. Vite is the default (`@ozsarman/clarityjs/vite`).
Since 1.2 webpack 5 and Rollup have plugins that do the whole job, and all three stand on one
core, `@ozsarman/clarityjs/bundler`, so a component compiles to the same module in each.
```js
// rollup.config.js npm i -D rollup rollup-plugin-clarity
import clarity from 'rollup-plugin-clarity'
export default {
input: 'src/main.js',
output: { dir: 'dist', format: 'es' },
plugins: [clarity({ css: 'inject', scanPages: false })],
}
```
Rollup options: `css` `'inject'` (default: each component adds its own `