llms.txt
Compare with other sites' llms.txt files →# Olum (olumjs)
> Olum is a small, Vue-like JavaScript framework where components are plain `.html` files with a
> `<script>` (logic) block, an optional scoped `<style>`, and a template using control tags
> (`<if>`, `<else-if>`, `<else>`, `<show>`, `<for>`, `<transition>`). A Node compiler turns each
> `.html` component into a JS module; a tiny browser runtime builds and diff-patches the DOM.
> Ships with a file-based router (`olum-router`) and a zustand-style global store (`olum-store`).
> Scope: prototypes, demos, hackathons, and small apps.
This file is a complete reference for generating correct Olum code. The single design principle:
**is an attribute fundamentally CODE or a STRING?** Native HTML already answers it — `onclick=""`
is code, `class=""` is a string. Code-shaped attributes (`when`, `each`, `key`, `on*`, `html`)
take a JS expression directly inside `""`. Everything else is a literal string with `{expr}` for
dynamic parts. **No naked braces, no colon-bindings, no directives to memorize.**
---
## Project structure
```
src/
├── page.html → route "/" (a folder is a route only if it has page.html)
├── not-found.html → global 404 page (must be at src/ root; lowercase)
├── main.js → OPTIONAL entry. Omit it → router auto-generated from the file tree.
├── sitemap.js → OPTIONAL. Its presence switches on prerendering/SSG (build-time only, NO route).
├── about/page.html → "/about"
├── blog/page.html → "/blog"
├── blog/[slug]/page.html→ "/blog/:slug" (dynamic segment → params().slug)
├── users/[id]/posts/[postId]/page.html → "/users/:id/posts/:postId"
├── (marketing)/pricing/page.html → "/pricing" (parenthesized group dropped from URL)
├── 01-guide/page.html → "/guide" (leading "NN-" prefix stripped; other digits kept: 7guis → /7guis)
├── _drafts/… → NO route (leading underscore = skipped entirely)
├── components/ → NO route (reserved folder; PascalCase component files live here)
└── utils/ → NO route (reserved folder; stores/helpers live here)
```
- Route files: `page.html`, `not-found.html` (exact lowercase, case-sensitive).
- Reusable components: `src/components/AddTodo.html` — PascalCase filenames.
- Static route beats dynamic route on conflict. No catch-all `[...slug]` — each `[param]` = exactly one segment.
- After each route mounts, router fires `window` event `viewLoaded` (useful for scroll restoration/analytics). It fires AFTER the router scrolled to a URL `#id`, so skip your own scroll then: `addEventListener("viewLoaded", () => { if (!location.hash) scrollTo(0, 0) })`.
### Static assets
Files in `public/` are served at the site root. **Always reference with root-absolute URLs starting with `/`**
(templates AND `<style>`): `/assets/logo.svg`, never `assets/logo.svg` (relative resolves against the
current route and 404s in production, because templates/styles are injected at runtime and resolve against
the CURRENT route). The dev server is forgiving here (it strips route segments until a file matches), so a
relative URL *appears* to work in dev — don't trust it. Interpolation composes paths fine, keep the leading
slash: `<span style="background-image: url(/assets/{type}.svg)">`. (Root-absolute stays right even under a
non-default build `base` — the build re-points `src`/`href`/`poster` for you; see Build & Deploy.) `public/index.html` is the app shell;
`public/main.css` is the global stylesheet — both are processed by the build; everything else in `public/` ships
as-is (don't keep scratch files there).
---
## Component file structure
One `.html` file, up to three parts: `<script>` (logic), `<style>` (scoped CSS), and the template (everything else). A **page** component may add a fourth, `<head>` (metadata — see Page metadata & SEO).
```html title="Counter.html"
<script>
const state = { count: 0 };
const inc = () => state.count++;
</script>
<style>
.counter { font-weight: 700; }
</style>
<div class="counter">
Count: {state.count}
<button onclick="inc()">+</button>
</div>
```
- The **filename is the component name** — `CounterCard.html` → `<CounterCard />`. Component tags are **PascalCase**; that's how the compiler distinguishes a component from a plain element.
- `<script>` and `<style>` are both optional. Markup-only files are valid static components.
- `<head>` is **page-only** (`page.html` / `not-found.html`); elsewhere it is ignored with a build warning.
- Every instance renders inside a runtime wrapper `<div>` — that wrapper is `host` (see Lifecycle).
- Import components by their file name (`.html` compiles to `.js`, so imports reference `.js`... but you write the source name):
```html
<script>
import Navbar from "./components/Navbar";
import { formatDate } from "./utils";
</script>
```
---
## Text interpolation
`{expr}` in text is evaluated as JS and **HTML-escaped by default** (XSS-safe).
```html
<p>Hello {state.user.name}</p>
<p>Total: {state.items.length} items</p>
<p>{state.count > 0 ? 'positive' : 'zero'}</p>
```
- `null` / `undefined` render as an empty string.
- No escape for a literal `{` in text — any `{…}` is interpolation. Use `{String.fromCharCode(123)}` or a const holding `"{"`.
---
## Attributes
**String attributes (default):** a literal string; use `{expr}` inside for dynamic parts.
```html
<div class="card {state.active ? 'is-active' : ''}"></div>
<a href="/users/{state.user.id}" title="Open {state.user.name}">Profile</a>
<div style="color:{state.color}; background:{state.bg}; padding:8px;">box</div> <!-- inline style = string + {expr}, kebab-case CSS -->
```
**Code attributes (value is an expression):** `when`, `each`, `key`, `on*`, `html` — the `""` value is JS.
```html
<if when="state.count > 0"> … </if>
<button onclick="inc()">+</button>
```
**Boolean attributes (presence toggle):** when the whole value is a single `{expr}`, the attribute is emitted when truthy, omitted when falsy.
```html
<button disabled="{state.busy}">Save</button>
<input type="checkbox" checked="{state.on}" />
<details open="{state.expanded}">…</details>
```
Recognized: `checked, disabled, selected, readonly, required, hidden, autofocus, multiple, open, loop, muted, controls, autoplay, novalidate, default, defer, ismap, reversed`. Only applies when value is exactly one `{expr}`.
---
## Events
Native `on*` attributes hold **code** (like real HTML). Two forms:
```html
<button onclick="inc()">+</button>
<button onclick="inc(), log()">multi call</button>
<input oninput="(e) => state.text = e.target.value" /> <!-- inline arrow, auto-extracted -->
<button onclick="e => state.n++">no-paren arrow</button>
<input oninput="setValue($event)" /> <!-- $event = the DOM event -->
```
- **No event modifiers.** Do it in the handler: `onsubmit="(e)=> { e.preventDefault(); save() }"`.
- **Several `on*` attributes per element are fine** — each is wired as its own listener (`<input oninput="draft($event)" onblur="save()" />`). Use `onMount` only for listeners on `window`/`document` or ones needing `capture`/`passive`.
- Inside `<for>`, handlers can reference loop variables directly: `<button onclick="remove(item)">`.
- On a **component** tag (any PascalCase tag you import — `<Input/>`, `<TextField/>`, `<Comp/>`), any `on*` name is a **function prop, NOT a DOM event** — and a function prop takes a **NAME only**. Only the capital letter separates the two cases:
```html
<input oninput="state.counter++" /> <!-- ✓ real HTML element: inline code is fine -->
<input oninput="e => console.log(123)" /> <!-- ✓ real HTML element -->
<Input oninput="{handleInput}" /> <!-- ✓ YOUR component: a name -->
<Input oninput="() => console.log(123)" /> <!-- ✗ arrives as a plain string, never runs -->
<Input oninput="{() => console.log(123)}" /> <!-- ✗ arrives as undefined -->
```
- Recognized inline names = the standard DOM `on*` set (`onclick, oninput, onchange, onsubmit, onreset, onformdata, oninvalid, onselect, onsearch, onkeydown, onfocus, onblur, ondragstart…ondrop, onplay, onpause, onloadedmetadata, ontouchmove, …`).
- **NOT recognized inline:** `copy`, `cut`, `paste`, `beforeinput`, `focusin`, `focusout` → `host.querySelector(...).addEventListener(...)` in `onMount`, remove in the cleanup.
**Keyboard:** `keydown` fires first and is the only one you can `preventDefault()` to stop the character; `keyup` last; `keypress` is legacy (misses `Escape`/arrows). Fields: `e.key`, `e.code`, `e.ctrlKey/shiftKey/altKey/metaKey`, `e.repeat`.
```html
<input value="{state.draft}" oninput="(e)=> state.draft = e.target.value" onkeydown="handleKeydown($event)" />
<!-- if (e.key === "Enter") { e.preventDefault(); addTag() } | ctrl+s: e.key === "s" && (e.ctrlKey || e.metaKey) -->
```
**Focus/selection:** `focus`/`blur` do **not** bubble — put them on the field itself (`focusin`/`focusout` bubble but aren't inline). Track "touched" on blur to delay errors. Selected text = `field.value.slice(field.selectionStart, field.selectionEnd)` in `onselect`. Focus a field with `host.querySelector("[name=x]").focus()` (no refs).
**Drag & drop:** `ondragover` **must** `preventDefault()` or the browser refuses the drop; dropped files are `e.dataTransfer.files` (a `FileList`). Reorder = `draggable="true"` per row + move the item in the array; add `key` on the `<for>` so rows keep their DOM.
**Clipboard write** is an API, not an event: `navigator.clipboard.writeText(str)` (returns a promise the browser can reject).
---
## Conditionals — `<if>` / `<else-if>` / `<else>`
`when` is a JS expression. The element is **added/removed** from the DOM.
```html
<if when="state.tab === 'a'"><p>Tab A</p></if>
<else-if when="state.tab === 'b'"><p>Tab B</p></else-if>
<else><p>Fallback</p></else>
```
## Show / Hide — `<show>`
Like `<if>`, but keeps content in the DOM and only toggles visibility (`display: contents` ↔ `none`).
Content nodes are never replaced, so a playing `<video>`, animation, or typed input survives toggling.
```html
<show when="state.visible"><div class="panel">…</div></show>
```
It compiles to one stable wrapper `<div data-o-show>` present in **both** states, so parent CSS with a direct-child
combinator through it (`.parent > .panel`) won't match — target `[data-o-show] > .panel` or drop the `>`.
Don't wrap `<tr>`/`<option>` in `<show>` (its wrapper `<div>` is invalid there) — use `<if>` or a style binding instead.
## Loops — `<for>`
`each` is a JS expression. Three forms:
```html
<for each="fruit of state.fruits"><li>{fruit.name}</li></for> <!-- array: "item of arr" -->
<for each="i of 6"><span>Step {i}</span></for> <!-- numeric range: i goes 1→N (literal number ONLY) -->
<for each="key in state.settings"><div>{key}</div></for> <!-- object keys: "key in obj" -->
```
Index + array params (like `Array.map`), wrap in parens:
```html
<for each="(cat, index, arr) of state.cats"><li>{index+1}/{arr.length}: {cat.name}</li></for>
<for each="(key, index, value) in state.settings"><div>{index}. {key} = {value}</div></for> <!-- value = obj[key] -->
```
**Keyed loops — add `key`** (a JS expr, no braces, unique per item) so items are matched by identity across reorders/removals instead of by position. Needed to keep DOM state (checkboxes, videos, typed text) on the right row:
```html
<for each="todo of state.todos" key="todo.id"><TodoRow todo="{todo}" /></for>
<for each="todo of state.todos" key="todo.id"><li>{todo.text}</li></for>
```
`key` on `<for>` keys both component loops (the instance is reused) and plain-element loops (the repeated root is reused);
it applies to the loop's **direct root only** — inner children are never keyed. `key="{item.id}"` directly on a plain
element does the same thing.
Dynamic count range: `each="i of Array.from({ length: state.n }, (_, k) => k + 1)"` (a literal number is required for the `of N` form).
---
## State & Reactivity
Declare reactive state as a **literal top-level `const state = { ... }`**. Mutating `state` re-renders. Reactivity is **deep** (nested objects, arrays, `Map`, `Set`).
```html
<script>
const state = { count: 0, user: { name: "Ann" } };
const inc = () => state.count++;
const rename = () => (state.user.name = "Bo"); // nested mutation re-renders too
</script>
<p>{state.count} — {state.user.name}</p>
```
- Only `state` is reactive. Plain `const`/`let` are not tracked.
- Deep mutations that re-render: `state.user.name = "Bo"`, `state.todos.push(t)`, `state.todos[0].done = true`, `state.tags.add("x")`.
- Non-plain objects (`Date`, DOM nodes, class instances) are NOT tracked — assign back to a top-level key to re-render.
- Re-assigning the **same reference** (`state.todos = state.todos`) is a no-op. Force a re-render with a fresh value (spread, `map`, `filter`, `slice`).
- `const state = makeState()` is NOT recognized — must be a literal object in the component.
### Rendering & updates (there is no render function — writing to state/store IS the API)
1. A write emits (deep mutations included) → 2. dirty components are **batched per microtask** (`state.a++; state.b++`, or a `splice` shifting 100 rows = ONE pass) → 3. the template renders into a **detached** tree → 4. the patcher diffs it against the live DOM and mutates only what changed.
- **Untouched nodes survive**, and with them everything the browser owns: focus, caret/selection, scroll, playing `<video>`/`<audio>`, running CSS animations, iframes, canvas, uncontrolled input values. Event listeners are kept unless their binding (or a value baked into it, e.g. a loop variable) changed.
- **Only what needs to render, renders.** A write to a state key the **template never reads** doesn't schedule a render at all (so a key used only in handlers/`onMount` is free). Store subscriptions come from *reading* the store during render. If a parent and its child are both dirty in the same tick, only the parent renders (its pass rebuilds the child). Updates for components that left the DOM are discarded.
- **Identity:** component instances have their own; plain elements opt in with `key`. Keyed nodes are **moved** (`moveBefore` where supported), not re-created; unkeyed children are matched positionally with a short insertion/deletion lookahead. A bigger unkeyed reshuffle repaints nodes with a neighbour's data — add `key`.
- **Form controls are never clobbered:** `value`/`checked` are written to a live input only when the **template's** value changed, and the caret is preserved when they are; a `<select>` keeps the user's choice unless the template moves the `selected` option.
- `import { flushUpdates } from "olum"` settles pending re-renders synchronously (idempotent; mostly for tests / imperative DOM reads right after a write). `window.olum.flushUpdates()` is the same call, but the full `window.olum` exists in DEVELOPMENT only — production exposes only a frozen `window.olum = { version, framework }` (for detection tools like Wappalyzer). Never check `window.olum` to detect dev mode.
- If a patch throws, olum logs `patch failed — falling back to full re-render` and rebuilds that component's content (correct, but browser state resets) — that warning is a bug worth reporting.
### Derived values = plain functions (no "computed")
```html
<script>
const state = { count: 1 };
const doubled = () => state.count * 2;
const quadrupled = () => doubled() * 2; // derived can call derived
</script>
<p>{doubled()} {quadrupled()}</p>
```
### Watchers — `const watcher = { key(old, next) {} }`
Fires on **top-level key assignment** only (not nested mutations). Watchers run **synchronously, once per mutation**; re-renders are still batched per microtask.
```html
<script>
const state = { count: 0, log: "—" };
const watcher = { count(old, next) { state.log = `${old} → ${next}`; } };
</script>
```
For a nested change to fire a watcher, assign a fresh value to the key: `state.user = { ...state.user, name: "Bo" }`.
---
## Components & Props
Use a component by its **PascalCase** tag; import it in `<script>`.
```html title="Parent.html"
<script>
import StatusBadge from "./StatusBadge";
const state = { score: 5, name: "Ann" };
</script>
<StatusBadge label="Online" color="#16a34a" />
<CounterCard title="Counter" count="{state.score}" data="{state.user}" greet="Hi {state.name}" />
```
**Prop value rules:**
- `title="Hello"` → string (literal).
- `count="{n + 1}"` → the expression's **real value/type** (number, object, etc.) when the whole value is one `{expr}`.
- `greet="Hi {state.name}"` → interpolated **string**.
- **No spread** (`<Comp {...obj} />`) and **no shorthand** (`<Comp {a} />` / `<Comp a={a} />`). Pass each field: `<Comp a="{obj.a}" />`.
- **Function props travel by NAME** (component tags only — lowercase HTML tags keep normal inline `on*` code). Props are handed over as data, so a function only arrives when the value is a plain name the compiler can resolve: a top-level function of the parent, or a name destructured from `props()`. `onX="(e)=>…"` arrives as a string; `onX="{(e)=>…}"`, `onX="{obj.fn}"` and `onX="{state.fn}"` arrive as `undefined`; `onX="{make(id)}"` passes the call's result. To pre-bind data, pass it as its own prop and let the child call back with it (`<Row row="{row}" onPick="{pick}" />` → child calls `onPick(row.id)`).
- Prop names must be plain identifiers (letters, digits, underscore) — write camelCase (dashes truncate the name on component tags).
**Reading props in the child** — `props()` imported from `olum`, called once at the **top level** of `<script>`:
```html title="StatusBadge.html"
<script>
import { props } from "olum";
const { label, color } = props(); // destructured names stay LIVE
const { size = "md" } = props(); // default when parent omits it
const { theme: t = "dark" } = props(); // alias + default
</script>
<span style="color:{color}">{label}</span>
```
Destructuring from `props()` is a **compiler feature**: each destructured name compiles into a fresh `props().name` read (in templates, methods and handlers alike), so it stays current after the parent re-renders. `{props().label}` is equivalent. Normal scoping applies: a loop variable or function parameter with the same name shadows the prop inside that scope.
**Stays live:** plain names, aliases, defaults, `children`, function props.
**One-time snapshot (NOT live):** `...rest`, nested patterns `{ user: { name } }`, computed keys `{ [key]: v }`, destructures not at the top level of `<script>`, indirect (`const p = props(); const { a } = p`), a default referencing another destructured prop.
**Props are read-only (one-way data flow).** Data flows down via props; changes flow up via **callback props**:
```html title="CounterCard.html"
<!-- parent owns the value + hands down a setter -->
<CounterCard value="{state.score}" onChange="{setScore}" />
<!-- child reads the prop, calls the callback to request a change -->
<script>
import { props } from "olum";
const { value, onChange } = props();
const inc = () => onChange(value + 1);
</script>
```
Assigning to a destructured prop throws (`Assignment to constant variable`); assigning to `props().x` does nothing but log a console warning — never mutate props. A function prop passed the wrong way is not reported by the compiler; the child throws `onX is not a function` when it calls it. On a **component** tag, `on*` names (even `onclick`) are just function props the child chooses when to call — so they follow the NAME-only rule above, and the inline forms allowed on `<button onclick="…">` do not work on `<CustomButton onclick="…">`. A function prop resolves against the component whose template **authored** the tag, so it still arrives when the tag is written inside another component's slot (`<Section><Card onPick="{pick}" /></Section>`).
---
## Slots — `children`
Content between a component's tags is exposed as `children` on `pro