@hidemikimura/vanji 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ /** Options of the vanji Vite / Rollup plugin. */
2
+ export interface VanjiPluginOptions {
3
+ /** Files to compile. Default: /\.[cm]?[jt]sx?$/ */
4
+ include?: RegExp;
5
+ /** Files to skip. Default: /node_modules/ */
6
+ exclude?: RegExp;
7
+ /** The import name the compiler looks for. Default: '@hidemikimura/vanji' */
8
+ moduleName?: string;
9
+ /**
10
+ * Keep the runtime's long error messages and dev-only checks.
11
+ * Default: on, except in production builds (Vite: `vite build`; Rollup: NODE_ENV=production).
12
+ */
13
+ dev?: boolean;
14
+ }
15
+
16
+ /**
17
+ * A Vite / Rollup plugin object. Typed loosely (the source map is `any`) so it is accepted by Vite's and
18
+ * Rollup's plugin types without this package depending on either.
19
+ */
20
+ export interface VanjiPlugin {
21
+ name: string;
22
+ configResolved(config: { isProduction?: boolean }): void;
23
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the source map type differs per bundler
24
+ transform(code: string, id: string): { code: string; map: any } | null;
25
+ }
26
+
27
+ /** `import vanji from '@hidemikimura/vanji/vite'; export default { plugins: [vanji()] }` */
28
+ export default function vanji(options?: VanjiPluginOptions): VanjiPlugin;
29
+
30
+ /** Runtime source with the DEV flag replaced by `false` (what production builds get). */
31
+ export function withoutDev(code: string): string;
@@ -0,0 +1,35 @@
1
+ // Vite / Rollup plugin. Usage: import vanji from '@hidemikimura/vanji/vite'; export default { plugins: [vanji()] }
2
+ import { fileURLToPath } from 'node:url';
3
+ import { compile } from './index.js';
4
+
5
+ // The runtime's DEV flag (src/dev.js). In production builds every runtime file gets the literal `false`
6
+ // in its place (and loses the import), so any bundler drops the dev-only code while parsing.
7
+ const SRC_DIR = fileURLToPath(new URL('../src/', import.meta.url));
8
+
9
+ /** Runtime source with DEV replaced by `false` (also used by scripts/size.js). */
10
+ export const withoutDev = code =>
11
+ code.replace(/^import \{ DEV \} from '\.\/dev\.js';\n/m, '').replace(/\bDEV\b(?! = )/g, 'false');
12
+
13
+ /**
14
+ * @param {{ include?: RegExp, exclude?: RegExp, moduleName?: string, dev?: boolean }} [options]
15
+ * dev: keep long error messages and dev-only checks. Default: on, except in production builds
16
+ * (Vite: config.isProduction; Rollup: NODE_ENV === 'production').
17
+ */
18
+ export default function vanji({ include = /\.[cm]?[jt]sx?$/, exclude = /node_modules/, moduleName = '@hidemikimura/vanji', dev } = {}) {
19
+ let production = dev === undefined ? process.env.NODE_ENV === 'production' : !dev;
20
+ return {
21
+ name: 'vanji',
22
+ configResolved(config) {
23
+ if (dev === undefined) production = !!config.isProduction;
24
+ },
25
+ transform(code, id) {
26
+ const file = id.split('?')[0];
27
+ if (file.startsWith(SRC_DIR) && file.endsWith('.js')) return production ? { code: withoutDev(code), map: null } : null;
28
+ if (!include.test(file) || exclude.test(file)) return null;
29
+ const out = compile(code, { id: file, moduleName });
30
+ if (!out) return null;
31
+ for (const w of out.warnings) this.warn(`[vanji] ${file}:${w.line}:${w.column} ${w.message}`);
32
+ return { code: out.code, map: out.map };
33
+ },
34
+ };
35
+ }
package/llms.txt ADDED
@@ -0,0 +1,143 @@
1
+ # vanji — complete reference for AI assistants
2
+
3
+ vanji is a tiny UI framework: html`` templates + signals, compiled at build time.
4
+ This file is the whole API. If something is not listed here, it does not exist.
5
+ A Claude Code skill with worked examples ships next to it: skills/vanji (copy it to .claude/skills/).
6
+
7
+ ## Setup (build step is required)
8
+
9
+ npm install @hidemikimura/vanji (and Vite: npm install -D vite)
10
+
11
+ // vite.config.js
12
+ import vanji from '@hidemikimura/vanji/vite';
13
+ export default { plugins: [vanji()] };
14
+
15
+ ## Mental model (3 facts)
16
+
17
+ 1. html`...` returns REAL DOM nodes, created once. There is no re-render and no virtual DOM.
18
+ (With a hole at the root, html`${title()}<p>…</p>`, it returns an array: use it in a hole / each / when / mount.)
19
+ 2. A component is a plain function that returns that node. It runs ONCE.
20
+ 3. THE RULE: a template hole whose expression CALLS A FUNCTION is reactive; anything else is set once.
21
+ Read signals by calling them, as you would anywhere else.
22
+
23
+ const count = signal(0);
24
+ html`<p>${count()}</p>` // reactive: updates when count changes
25
+ html`<p class=${count() > 2 ? 'big' : ''}>` // reactive
26
+ html`<p>${total()}</p>` // reactive, also for signals read inside total()
27
+ html`<p>${'static'} ${someVariable}</p>` // set once (no call)
28
+
29
+ ## Public API (12 exports, all from '@hidemikimura/vanji')
30
+
31
+ signal(v) -> s s() read · s.set(v) · s.update(fn) · s.peek() untracked read
32
+ computed(fn) -> c c() read · c.peek() (lazy, cached, read-only)
33
+ effect(fn) -> stop() runs now + after each change; fn may return a cleanup function
34
+ batch(fn) several writes, one update
35
+ untrack(fn) read without subscribing
36
+ onCleanup(fn) when the current component / effect run / list row is torn down
37
+ onMount(fn) once, after the component's DOM is in the document
38
+ root(fn(dispose)) manual ownership scope (rarely needed)
39
+ html`...` -> Node template
40
+ each(items, row, { key }) keyed list, ONLY directly in a hole: ${each(todos(), t => html`<li>…</li>`, { key: 'id' })}
41
+ when(cond, yes, no?) conditional, ONLY directly in a hole: ${when(open(), html`<dialog>…</dialog>`)}
42
+ mount(Component, el) -> unmount() replaces el's content
43
+
44
+ ## Template syntax
45
+
46
+ <p>${value}</p> text / node / array / null / false (nothing)
47
+ <a href=${url}> attribute null or undefined removes it
48
+ <p class="item ${cls}"> attribute with static text + holes
49
+ <button ?disabled=${flag}> boolean attribute
50
+ <input .value=${text()}> DOM property (a function without a call is passed as the value: .onDone=${callback})
51
+ <button @click=${handler}> event listener (plain addEventListener; never reactive)
52
+ <div ref=${el => (node = el)}> element reference, called once at creation
53
+
54
+ ## Components and composition
55
+
56
+ const Greeting = (name) => html`<h1>Hello ${name()}</h1>`; // a component is a function
57
+ const App = () => html`<main>${Greeting(user)}</main>`; // call it inside a hole
58
+ mount(App, document.getElementById('app'));
59
+
60
+ A component call in a hole runs once; its body is not tracked. Pass a signal (user, not user()) when
61
+ the child must update: Greeting(user) reads user() itself. Greeting(user()) also works but creates the
62
+ whole component again whenever user changes.
63
+
64
+ ## Lists
65
+
66
+ const todos = signal([{ id: 1, title: 'a', done: false }]);
67
+ html`<ul>${each(todos(), t => html`
68
+ <li class=${t.done ? 'done' : ''}>
69
+ <input type="checkbox" .checked=${t.done} @change=${() => toggle(t.id)} />
70
+ ${t.title}
71
+ </li>`, { key: 'id' })}</ul>`
72
+ const toggle = id => todos.update(l => l.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
73
+
74
+ - items are plain objects, updated IMMUTABLY: replace an item object to update its row. The row's DOM is
75
+ kept and only the changed parts are written. Mutating an item (t.done = true) changes nothing on screen.
76
+ - key: a property name ('id') or a function (t => t.id). Without a key, the item itself is the key.
77
+ - row receives (item, index); index is a plain number and stays correct when rows move.
78
+ - Selection is cheap however long the list is: `class=${selected() === row.id ? 'on' : ''}` touches only
79
+ the old and the new row when `selected` changes (when key is that property).
80
+ - A row is created once per key and KEPT while its key stays: a replaced item (or a changed index) only
81
+ updates the parts that use it, so DOM made by the row (an editor created in onMount / ref) survives.
82
+ Read the item inside holes / handlers; a value copied at the top of a block body (const t = r.title)
83
+ stays as it was when the row was created.
84
+ - Exceptions that re-create the row when its item is replaced: a row function passed by name
85
+ (each(items(), Row, …)) or one that destructures its item (({ id }) => …). Write r => Row(r) or r => …r.id.
86
+ - Fastest rows: one root element per row; holes that read item fields directly. Rows with a block body,
87
+ several root nodes, nested templates or components work the same (a little more memory per row).
88
+
89
+ ## Conditionals
90
+
91
+ ${when(open(), html`<dialog>…</dialog>`)} // rebuilds only when open() flips true <-> false
92
+ ${when(user(), html`<p>Hi</p>`, html`<p>Sign in</p>`)}
93
+ ${open() ? html`<b>a</b>` : html`<i>b</i>`} // also valid: rebuilds on every change of open()
94
+
95
+ ## Events
96
+
97
+ @event is a plain addEventListener: native order, stopPropagation and currentTarget behave as in the DOM.
98
+ Inside list rows, every @event is handled by ONE capture listener per event type on the list's parent element
99
+ instead of one per row. Row handlers run from the target outwards, get `this` / e.currentTarget = their
100
+ element, see the row's current item, and run BEFORE the parent's own listeners (so a row's
101
+ e.stopPropagation() stops them). Events that do not bubble (focus, mouseenter, …) reach only the handler on
102
+ their target. Handlers on disabled elements are skipped. A listener you add yourself with addEventListener on
103
+ an element inside a row runs after the row handlers.
104
+
105
+ ## Two-way input
106
+
107
+ const text = signal('');
108
+ html`<input .value=${text()} @input=${e => text.set(e.target.value)}>`
109
+
110
+ ## State updates are immutable
111
+
112
+ todos.update(list => [...list, item]); // correct
113
+ todos().push(item); // WRONG: nothing updates
114
+ user.update(u => ({ ...u, name: 'x' })); // correct
115
+
116
+ ## Rules the compiler enforces (errors include a hint)
117
+
118
+ - Close every non-void element, or write <div />. No implied end tags.
119
+ - No dynamic tag names, no attribute spread, no holes inside <textarea>/<style>/<script>/<title>.
120
+ - <tr> must be inside <tbody>/<thead>/<tfoot>; no block elements inside <p>; no nested <a>/<button>/<form>.
121
+ - No `await` directly inside a hole.
122
+ - @event, .prop, ?bool and ref take exactly one unquoted hole. Event modifiers (@click.once) do not exist.
123
+ - each() and when() only directly as the content of a hole; each takes (items, row, { key }).
124
+
125
+ ## Common mistakes
126
+
127
+ todos().push(x) / t.done = true -> todos.update(l => [...l, x]) / replace the item object
128
+ each(todos, t => t.id, Row) -> each(todos(), Row, { key: 'id' }) (items first, key in options)
129
+ const list = each(…) -> write each(…) directly in the hole
130
+ promise.then(data.set) -> promise.then(v => data.set(v)) (set/update/peek must be called on the signal)
131
+ effect(() => b.set(a() * 2)) -> const b = computed(() => a() * 2) (derive, do not sync signals by hand)
132
+ expecting a component to re-run -> it never does; put changing parts in holes that call signals
133
+ async updates -> none: the DOM is already updated when set() returns
134
+ ${row.label} where label is a signal -> ${row.label()} (in a list row, a function that is not called is read once)
135
+
136
+ ## Whitespace
137
+
138
+ A whitespace run containing a newline is removed next to a tag and becomes one space elsewhere.
139
+ <pre> and <textarea> are untouched.
140
+
141
+ ## Not included (do not invent): JSX, virtual DOM, lifecycle hooks other than onMount/onCleanup,
142
+ context/provide-inject, stores, router, SSR/hydration, custom elements, directives, slots helpers,
143
+ two-way binding sugar, event modifiers.
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@hidemikimura/vanji",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A tiny compile-time UI framework: html`` templates + signals, close to vanilla JS in speed and memory",
5
+ "keywords": [
6
+ "ui",
7
+ "framework",
8
+ "signals",
9
+ "reactive",
10
+ "compiler",
11
+ "vite",
12
+ "html-template",
13
+ "fine-grained"
14
+ ],
15
+ "author": "hidemikimura",
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "sideEffects": false,
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./src/index.d.ts",
25
+ "default": "./src/index.js"
26
+ },
27
+ "./vite": {
28
+ "types": "./compiler/vite.d.ts",
29
+ "default": "./compiler/vite.js"
30
+ },
31
+ "./compiler": {
32
+ "types": "./compiler/index.d.ts",
33
+ "default": "./compiler/index.js"
34
+ },
35
+ "./internal": "./src/internal.js",
36
+ "./llms.txt": "./llms.txt",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "src",
41
+ "compiler",
42
+ "skills",
43
+ "llms.txt",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "test": "node --test test/*.test.js",
52
+ "size": "node scripts/size.js",
53
+ "prepublishOnly": "npm test"
54
+ },
55
+ "dependencies": {
56
+ "acorn": "^8.12.0",
57
+ "magic-string": "^0.30.10"
58
+ },
59
+ "devDependencies": {
60
+ "esbuild": "^0.21.5",
61
+ "jsdom": "^24.1.0"
62
+ }
63
+ }
@@ -0,0 +1,231 @@
1
+ ---
2
+ name: vanji
3
+ description: Build and edit web UIs with vanji (@hidemikimura/vanji), a compile-time html`` + signals framework for Vite. Use this skill whenever a project depends on @hidemikimura/vanji or imports from it, whenever you write or fix html`...` templates, signal(), computed(), each() or when() in such a project, or when the user asks to start a new app "with vanji" / "vanjiで" (vanji でアプリを作って、vanji のコンポーネントを書いて、など). Also use it to debug vanji compile errors ("[vanji] x.js:3:5 …") or UI that does not update.
4
+ ---
5
+
6
+ # Building UIs with vanji
7
+
8
+ vanji compiles `html` tagged templates into direct DOM code at build time. There is no virtual DOM and
9
+ no re-render: a component is a plain function that runs **once** and returns real DOM nodes; signals
10
+ update exactly the parts of the DOM that read them. Almost everything that goes wrong comes from
11
+ expecting React-style re-renders, so keep that model in mind.
12
+
13
+ ## First: read the spec of the installed version
14
+
15
+ The complete, version-matched API is shipped with the package. Read it before writing code, because it
16
+ is short (about 150 lines) and it is the source of truth when this skill and the package disagree:
17
+
18
+ node_modules/@hidemikimura/vanji/llms.txt
19
+
20
+ If the package is not installed yet, set up the project first (below), then read it.
21
+
22
+ ## Setting up a project
23
+
24
+ ```sh
25
+ npm install @hidemikimura/vanji
26
+ npm install -D vite typescript # TypeScript is optional
27
+ ```
28
+
29
+ ```js
30
+ // vite.config.ts (or .js) — the plugin is required: templates are compiled at build time
31
+ import { defineConfig } from 'vite';
32
+ import vanji from '@hidemikimura/vanji/vite';
33
+ export default defineConfig({ plugins: [vanji()] });
34
+ ```
35
+
36
+ ```html
37
+ <!-- index.html -->
38
+ <div id="app"></div>
39
+ <script type="module" src="/src/main.ts"></script>
40
+ ```
41
+
42
+ ```ts
43
+ // src/main.ts
44
+ import { html, signal, mount } from '@hidemikimura/vanji';
45
+
46
+ const App = () => {
47
+ const count = signal(0);
48
+ return html`<button @click=${() => count.update(n => n + 1)}>Clicked ${count()} times</button>`;
49
+ };
50
+ mount(App, document.getElementById('app')!);
51
+ ```
52
+
53
+ Without the plugin, `html` throws "was not compiled" at runtime. In package.json use `"type": "module"`.
54
+
55
+ ## The one rule
56
+
57
+ **A hole (`${…}`) whose expression calls a function is reactive. A hole without a call is set once.**
58
+
59
+ ```ts
60
+ html`<p>${count()}</p>` // updates when count changes
61
+ html`<p class=${done() ? 'done' : ''}>…</p>` // updates
62
+ html`<p>${total()}</p>` // updates, also for signals read inside total()
63
+ html`<p>${title}</p>` // set once (no call)
64
+ html`<input .value=${text()} />` // property, updates
65
+ html`<button ?disabled=${!valid()}>Save</button>` // boolean attribute, updates
66
+ html`<button @click=${save}>Save</button>` // event listener (never reactive)
67
+ ```
68
+
69
+ So: read signals by calling them, inside the hole. Reading a signal *outside* the template
70
+ (`const n = count();` at the top of the component) gives a snapshot that never changes.
71
+
72
+ Dependencies are tracked at runtime, so helper functions are fine: `${format(price())}` or `${label()}`
73
+ where `label = () => user().name.toUpperCase()`.
74
+
75
+ ## Components
76
+
77
+ A component is a function returning `html`. Call it inside a hole. A call to a capitalised function in a
78
+ hole (`${Card(x)}`) runs the component **once**; signals it reads in its body do not rebuild it.
79
+
80
+ ```ts
81
+ const Greeting = (name: () => string) => html`<h1>Hello ${name()}</h1>`;
82
+ const App = () => html`<main>${Greeting(userName)}</main>`; // pass the signal, not userName()
83
+ ```
84
+
85
+ Pass signals (or getter functions) to children that must update. Plain constants are fine as arguments
86
+ (`Column('todo', 'To do')`). Passing a changing value (`Greeting(userName())`) works too, but then the
87
+ whole child is created again whenever the value changes.
88
+
89
+ Derived state: use `computed(() => …)`, not an `effect` that writes another signal. A `computed` created
90
+ inside a component lives as long as the component, so "derive once, read in several holes" is simply:
91
+
92
+ ```ts
93
+ const Column = (id: string) => {
94
+ const mine = computed(() => cards().filter(c => c.column === id)); // filtered once per change
95
+ return html`<section><h2>${mine().length}</h2><ul>${each(mine(), c => html`<li>${c.title}</li>`, { key: 'id' })}</ul></section>`;
96
+ };
97
+ ```
98
+
99
+ `effect` is for side effects (localStorage, document.title, logging); it may return a cleanup function.
100
+ An `effect` at module level (outside any component) is fine and lives for the whole page.
101
+
102
+ State placement: keep state that several components share in module-level signals (`src/store.ts`);
103
+ keep state only one component uses inside that component.
104
+
105
+ `html` is typed as `Renderable` (it can be a node, a fragment or an array). When you need the element
106
+ itself (to hand it to a library), the single-root template returns that element: `html\`<div></div>\` as HTMLElement`.
107
+
108
+ ## State is updated immutably
109
+
110
+ ```ts
111
+ todos.update(list => [...list, newTodo]); // add
112
+ todos.update(list => list.filter(t => t.id !== id)); // remove
113
+ todos.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t))); // change one
114
+ ```
115
+
116
+ `todos().push(x)` or `t.done = true` changes nothing on screen: the signal still holds the same object.
117
+ Keep shared state in module-level signals (for example `src/store.ts`) and import them where needed.
118
+
119
+ ## Lists
120
+
121
+ ```ts
122
+ html`<ul>${each(todos(), t => html`
123
+ <li class=${t.done ? 'done' : ''}>
124
+ <input type="checkbox" .checked=${t.done} @change=${() => toggle(t.id)} />
125
+ ${t.title}
126
+ <button @click=${() => remove(t.id)}>×</button>
127
+ </li>`, { key: 'id' })}</ul>`
128
+ ```
129
+
130
+ - `each(items, row, { key })` must be written **directly** as the content of a hole. The items are any
131
+ expression that calls a function: `todos()`, a computed (`visible()`), or a helper (`byColumn(id)`).
132
+ - The key is a property name or a function (`t => t.id`). It is optional: without it the item itself is
133
+ the key, which is right for lists of strings or numbers (`each(categories(), c => html\`<option>${c}</option>\`)`).
134
+ - A row is kept while its key stays; replacing the item object updates only the parts that changed.
135
+ So DOM created in a row (an editor, a chart) survives updates.
136
+ - Fastest rows: an inline arrow `t => html\`<li>…</li>\`` with **one root element** whose holes read item
137
+ fields directly (`${t.title}`, `class=${t.done ? 'done' : ''}`, `?disabled=${t.column === 'done'}`).
138
+ A hole that calls a function inside a row (`${format(t.price)}`) works but costs one effect per row;
139
+ for long lists prefer reading fields inline. Other shapes (block body, several roots, nested
140
+ templates) also work.
141
+ - Moving an item from one `each` list to another (kanban columns) removes its row from the first list
142
+ and creates a new one in the second; DOM created inside the old row is not carried over.
143
+ - `each` can sit next to static content, for example inside a `<select>` after a fixed
144
+ `<option value="">All</option>`; `.value` on that `<select>` is applied after its options exist.
145
+ - Selection: `class=${selected() === row.id ? 'on' : ''}` touches only two rows when `selected` changes.
146
+ - The second row parameter is the index, a plain number.
147
+ - Write `r => Row(r)`, not `each(items(), Row, …)`, and do not destructure the item (`({ id }) =>`):
148
+ those forms recreate the row whenever its item is replaced.
149
+
150
+ ## Conditionals
151
+
152
+ ```ts
153
+ ${when(loggedIn(), html`<p>Welcome</p>`, html`<button @click=${login}>Sign in</button>`)}
154
+ ${error() ? html`<p class="error">${error()}</p>` : ''}
155
+ ```
156
+
157
+ `when` rebuilds only when the condition flips between truthy and falsy (it must be directly in a hole).
158
+ Its branches are created lazily: a branch is built when it becomes active, and built again after each
159
+ flip. While a branch stays open it is **not** rebuilt, so content that must follow a signal reads it in
160
+ its own holes:
161
+
162
+ ```ts
163
+ // a detail panel that stays open while the selection changes
164
+ ${when(selected(), html`<aside>
165
+ <h2>${selected()?.name}</h2>
166
+ <p>${selected()?.description}</p>
167
+ <button @click=${() => selectedId.set(null)}>×</button>
168
+ </aside>`)}
169
+ ```
170
+
171
+ There is no TypeScript narrowing inside a branch (it is a separate expression), so use `?.` as above, or
172
+ move the content into a component that takes the signal. A ternary rebuilds whenever anything it reads
173
+ changes; both are fine for small content.
174
+
175
+ ## Events and forms
176
+
177
+ `@event=${handler}` is a plain `addEventListener`. There are no modifiers: call `e.preventDefault()`
178
+ yourself. Two-way input is explicit:
179
+
180
+ ```ts
181
+ html`<form @submit=${(e: Event) => { e.preventDefault(); add(); }}>
182
+ <input .value=${text()} @input=${(e: Event) => text.set((e.target as HTMLInputElement).value)} />
183
+ <button ?disabled=${!text().trim()}>Add</button>
184
+ </form>`
185
+ ```
186
+
187
+ Inside list rows, handlers are delegated to the list's parent (capture phase): they run before the
188
+ parent's own listeners, and see the row's current item.
189
+
190
+ ## DOM access, lifecycle, other libraries
191
+
192
+ - `ref=${el => …}` gets the element at creation (before it is in the document).
193
+ - `onMount(fn)` runs after the component's DOM is in the document: create editors, charts, maps there.
194
+ - `onCleanup(fn)` runs when the component / list row / `when` branch is removed: destroy them there.
195
+ - Give a library an empty element and never put template holes inside it; it owns its children.
196
+ - Inside a list row, a row `@keydown` on an ancestor of a third-party widget runs before the widget's
197
+ own handlers (capture). Prefer putting such widgets outside rows, or avoid row events around them.
198
+
199
+ See `references/patterns.md` for full examples (todo app, fetching data, forms, child components,
200
+ third-party editors, testing).
201
+
202
+ ## Other things to know
203
+
204
+ - A template whose root has a hole (`html\`${Header()}<main>…</main>\``) returns an **array**, not a Node.
205
+ Use it in a hole, `each`, `when` or `mount` — not with `appendChild`.
206
+ - No `await` inside a hole: load data in `onMount` / an `effect`, store it in a signal, render the signal.
207
+ - The compiler rejects HTML the browser would rewrite: close every element (`<div />` is allowed), put
208
+ `<tr>` inside `<tbody>`, no block elements inside `<p>`.
209
+ - `s.set` must be called on the signal: `promise.then(v => data.set(v))`, not `.then(data.set)`.
210
+ - There is no JSX, router, context or store library. Use plain modules and signals.
211
+
212
+ ## Common mistakes
213
+
214
+ | Wrong | Right | Why |
215
+ | --- | --- | --- |
216
+ | `const n = count(); html\`${n}\`` | `html\`${count()}\`` | read inside the hole, or it is a snapshot |
217
+ | `todos().push(x)` / `t.done = true` | `todos.update(l => [...l, x])` / replace the item | the signal must get a new object |
218
+ | `each(todos, t => t.id, Row)` | `each(todos(), t => Row(t), { key: 'id' })` | items first, key in options |
219
+ | `const list = each(…)` | write `each(…)` in the hole | it is compiled in place |
220
+ | `effect(() => b.set(a() * 2))` | `const b = computed(() => a() * 2)` | derive instead of syncing |
221
+ | expecting a component to run again | put changing parts in holes that call signals | components run once |
222
+ | `@click.prevent=${f}` | call `e.preventDefault()` in the handler | no modifiers |
223
+ | `${row.label}` with `label` a signal | `${row.label()}` | call it to make it reactive |
224
+
225
+ ## Checking your work
226
+
227
+ 1. `npx vite build` compiles every template. A mistake is reported as
228
+ `[vanji] src/file.ts:12:4 <message>` followed by a `hint:` line; apply the hint.
229
+ 2. Check the behaviour in a browser (`npx vite` / `npx vite preview`), clicking through the flows you
230
+ changed. A part that does not update almost always reads a signal outside a hole, or mutates state.
231
+ 3. For automated tests, Vitest with `environment: 'jsdom'` works with the same plugin in its config.