@hidemikimura/vanji 0.0.0-stage → 0.1.1

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,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.
@@ -0,0 +1,241 @@
1
+ # vanji patterns
2
+
3
+ Complete, working examples. Each one follows the rule: a hole that calls a function is reactive.
4
+
5
+ ## Contents
6
+
7
+ 1. Todo app with filters and localStorage
8
+ 2. Loading data (fetch) with loading / error states
9
+ 3. Forms and validation
10
+ 4. Child components and shared state
11
+ 5. Third-party widgets (editor, chart) in onMount
12
+ 6. Tables with selection and sorting
13
+ 7. Testing with Vitest
14
+
15
+ ## 1. Todo app with filters and localStorage
16
+
17
+ ```ts
18
+ import { html, signal, computed, effect, each, when, mount } from '@hidemikimura/vanji';
19
+
20
+ type Todo = { id: number; title: string; done: boolean };
21
+ type Filter = 'all' | 'active' | 'done';
22
+
23
+ const saved = JSON.parse(localStorage.getItem('todos') ?? '[]') as Todo[];
24
+ const todos = signal<Todo[]>(saved);
25
+ const filter = signal<Filter>('all');
26
+ const text = signal('');
27
+ let nextId = Math.max(0, ...saved.map(t => t.id)) + 1;
28
+
29
+ const visible = computed(() => {
30
+ const f = filter();
31
+ return todos().filter(t => (f === 'all' ? true : f === 'done' ? t.done : !t.done));
32
+ });
33
+ const left = computed(() => todos().filter(t => !t.done).length);
34
+
35
+ effect(() => localStorage.setItem('todos', JSON.stringify(todos()))); // side effect: persist
36
+
37
+ const add = (e: Event) => {
38
+ e.preventDefault();
39
+ const title = text().trim();
40
+ if (!title) return;
41
+ todos.update(l => [...l, { id: nextId++, title, done: false }]);
42
+ text.set('');
43
+ };
44
+ const toggle = (id: number) => todos.update(l => l.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
45
+ const remove = (id: number) => todos.update(l => l.filter(t => t.id !== id));
46
+
47
+ const FilterButton = (f: Filter) =>
48
+ html`<button class=${filter() === f ? 'active' : ''} @click=${() => filter.set(f)}>${f}</button>`;
49
+
50
+ const App = () => html`
51
+ <section>
52
+ <form @submit=${add}>
53
+ <input placeholder="What needs doing?" .value=${text()}
54
+ @input=${(e: Event) => text.set((e.target as HTMLInputElement).value)} />
55
+ </form>
56
+ <ul>${each(visible(), t => html`
57
+ <li class=${t.done ? 'done' : ''}>
58
+ <input type="checkbox" .checked=${t.done} @change=${() => toggle(t.id)} />
59
+ <span>${t.title}</span>
60
+ <button @click=${() => remove(t.id)}>×</button>
61
+ </li>`, { key: 'id' })}</ul>
62
+ <footer>
63
+ <span>${left()} left</span>
64
+ ${FilterButton('all')} ${FilterButton('active')} ${FilterButton('done')}
65
+ ${when(todos().length === 0, html`<p>Nothing to do.</p>`)}
66
+ </footer>
67
+ </section>`;
68
+
69
+ mount(App, document.getElementById('app')!);
70
+ ```
71
+
72
+ Notes: `FilterButton` is called once per button; its `class` hole reads `filter()`, so it updates by
73
+ itself. `visible()` is a computed, so the list only diffs when the todos or the filter change.
74
+
75
+ ## 2. Loading data with loading / error states
76
+
77
+ ```ts
78
+ type User = { id: number; name: string; email: string };
79
+
80
+ const UserList = () => {
81
+ const users = signal<User[]>([]);
82
+ const loading = signal(true);
83
+ const error = signal<string | null>(null);
84
+
85
+ onMount(async () => {
86
+ try {
87
+ const res = await fetch('/api/users');
88
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
89
+ users.set(await res.json());
90
+ } catch (e) {
91
+ error.set(e instanceof Error ? e.message : 'Failed to load');
92
+ } finally {
93
+ loading.set(false);
94
+ }
95
+ });
96
+
97
+ return html`<div>
98
+ ${loading() ? html`<p>Loading…</p>` : ''}
99
+ ${error() ? html`<p class="error">${error()}</p>` : ''}
100
+ <ul>${each(users(), u => html`<li>${u.name} <small>${u.email}</small></li>`, { key: 'id' })}</ul>
101
+ </div>`;
102
+ };
103
+ ```
104
+
105
+ `await` is not allowed inside a hole; do the async work in `onMount` (or an event handler) and set
106
+ signals. To reload when a parameter changes, use an `effect` that reads the parameter signal and starts
107
+ the request; ignore responses that arrive after a newer request started.
108
+
109
+ ## 3. Forms and validation
110
+
111
+ ```ts
112
+ const SignupForm = () => {
113
+ const email = signal('');
114
+ const password = signal('');
115
+ const touched = signal(false);
116
+ const emailError = computed(() => (/^\S+@\S+\.\S+$/.test(email()) ? '' : 'Enter a valid email'));
117
+ const passwordError = computed(() => (password().length >= 8 ? '' : 'At least 8 characters'));
118
+ const valid = computed(() => !emailError() && !passwordError());
119
+ const value = (e: Event) => (e.target as HTMLInputElement).value;
120
+
121
+ const submit = (e: Event) => {
122
+ e.preventDefault();
123
+ touched.set(true);
124
+ if (valid()) console.info('submit', { email: email() });
125
+ };
126
+
127
+ return html`<form @submit=${submit} novalidate>
128
+ <label>Email <input type="email" .value=${email()} @input=${(e: Event) => email.set(value(e))} /></label>
129
+ ${touched() && emailError() ? html`<p class="error">${emailError()}</p>` : ''}
130
+ <label>Password <input type="password" .value=${password()} @input=${(e: Event) => password.set(value(e))} /></label>
131
+ ${touched() && passwordError() ? html`<p class="error">${passwordError()}</p>` : ''}
132
+ <button ?disabled=${touched() && !valid()}>Sign up</button>
133
+ </form>`;
134
+ };
135
+ ```
136
+
137
+ ## 4. Child components and shared state
138
+
139
+ ```ts
140
+ // src/store.ts — shared state lives in modules
141
+ import { signal, computed } from '@hidemikimura/vanji';
142
+ export const cart = signal<{ id: number; name: string; qty: number }[]>([]);
143
+ export const cartCount = computed(() => cart().reduce((n, i) => n + i.qty, 0));
144
+ export const addToCart = (id: number, name: string) =>
145
+ cart.update(l => (l.some(i => i.id === id) ? l.map(i => (i.id === id ? { ...i, qty: i.qty + 1 } : i)) : [...l, { id, name, qty: 1 }]));
146
+
147
+ // src/Header.ts — a child reads shared signals itself
148
+ import { html } from '@hidemikimura/vanji';
149
+ import { cartCount } from './store';
150
+ export const Header = (title: string) => html`<header><h1>${title}</h1><span>Cart: ${cartCount()}</span></header>`;
151
+
152
+ // src/ProductCard.ts — props that change are passed as signals / getters
153
+ export const ProductCard = (p: { id: number; name: string }, onAdd: (id: number, name: string) => void) =>
154
+ html`<article><h2>${p.name}</h2><button @click=${() => onAdd(p.id, p.name)}>Add</button></article>`;
155
+ ```
156
+
157
+ A component runs once. If a prop changes over time, pass the signal (`Header(titleSignal)` and read
158
+ `title()` inside), or a getter (`() => x()`).
159
+
160
+ ## 5. Third-party widgets in onMount
161
+
162
+ ```ts
163
+ import { html, effect, onMount, onCleanup } from '@hidemikimura/vanji';
164
+ import { EditorView, basicSetup } from 'codemirror';
165
+
166
+ export const Editor = (doc: { (): string; set(v: string): void }) => {
167
+ const host = html`<div class="editor"></div>` as HTMLElement; // one root: this is the element; empty: the library owns its children
168
+ let view: EditorView | undefined;
169
+ onMount(() => {
170
+ view = new EditorView({
171
+ doc: doc(),
172
+ parent: host,
173
+ extensions: [basicSetup, EditorView.updateListener.of(u => {
174
+ if (u.docChanged) doc.set(u.state.doc.toString()); // editor -> signal
175
+ })],
176
+ });
177
+ });
178
+ effect(() => { // signal -> editor
179
+ const v = doc();
180
+ if (view && v !== view.state.doc.toString())
181
+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: v } });
182
+ });
183
+ onCleanup(() => view?.destroy());
184
+ return host;
185
+ };
186
+ ```
187
+
188
+ The same pattern fits charts and maps: create in `onMount`, sync with an `effect`, destroy in
189
+ `onCleanup`. Inside list rows the widget survives item updates (rows are kept while their key stays).
190
+
191
+ ## 6. Tables with selection and sorting
192
+
193
+ ```ts
194
+ type Row = { id: number; name: string; score: number };
195
+ const rows = signal<Row[]>([]);
196
+ const selected = signal(0);
197
+ const sortKey = signal<keyof Row>('name');
198
+ const sorted = computed(() => {
199
+ const k = sortKey();
200
+ return rows().slice().sort((a, b) => (a[k] < b[k] ? -1 : a[k] > b[k] ? 1 : 0));
201
+ });
202
+
203
+ const Table = () => html`<table>
204
+ <thead><tr>
205
+ <th @click=${() => sortKey.set('name')}>Name</th>
206
+ <th @click=${() => sortKey.set('score')}>Score</th>
207
+ </tr></thead>
208
+ <tbody>${each(sorted(), r => html`
209
+ <tr class=${selected() === r.id ? 'selected' : ''} @click=${() => selected.set(r.id)}>
210
+ <td>${r.name}</td><td>${r.score}</td>
211
+ </tr>`, { key: 'id' })}</tbody>
212
+ </table>`;
213
+ ```
214
+
215
+ `<tr>` must be inside `<tbody>` / `<thead>`. Sorting creates a new array; rows are moved, not rebuilt.
216
+ The `selected() === r.id` form is optimised to touch only the two affected rows.
217
+
218
+ ## 7. Testing with Vitest
219
+
220
+ ```ts
221
+ // vitest.config.ts
222
+ import { defineConfig } from 'vitest/config';
223
+ import vanji from '@hidemikimura/vanji/vite';
224
+ export default defineConfig({ plugins: [vanji()], test: { environment: 'jsdom' } });
225
+ ```
226
+
227
+ ```ts
228
+ // src/counter.test.ts
229
+ import { test, expect } from 'vitest';
230
+ import { html, signal, mount } from '@hidemikimura/vanji';
231
+
232
+ test('counter increments', () => {
233
+ const count = signal(0);
234
+ const el = document.createElement('div');
235
+ mount(() => html`<button @click=${() => count.update(n => n + 1)}>${count()}</button>`, el);
236
+ el.querySelector('button')!.click();
237
+ expect(el.textContent).toBe('1'); // updates are synchronous
238
+ });
239
+ ```
240
+
241
+ Updates are synchronous, so assertions can run right after `set` / a click without waiting.
package/src/dev.js ADDED
@@ -0,0 +1,3 @@
1
+ // true while developing: long error messages and extra checks. The vanji Vite / Rollup plugin turns it
2
+ // into `false` in production builds (see compiler/vite.js), and the bundler then drops the dev-only code.
3
+ export const DEV = true;