@verajs/renderer 0.1.4 → 0.2.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.
Files changed (42) hide show
  1. package/README.md +1000 -12
  2. package/dist/development/vera-renderer-hydrate.d.ts +32 -13
  3. package/dist/development/vera-renderer-hydrate.d.ts.map +1 -1
  4. package/dist/development/vera-renderer-hydrate.js +1812 -234
  5. package/dist/development/vera-renderer-hydrate.js.map +1 -1
  6. package/dist/development/vera-renderer-keyed.d.ts +17 -0
  7. package/dist/development/vera-renderer-keyed.d.ts.map +1 -0
  8. package/dist/development/vera-renderer-keyed.js +322 -0
  9. package/dist/development/vera-renderer-keyed.js.map +1 -0
  10. package/dist/development/vera-renderer-profiler.d.ts +57 -17
  11. package/dist/development/vera-renderer-profiler.d.ts.map +1 -1
  12. package/dist/development/vera-renderer-profiler.js +1445 -209
  13. package/dist/development/vera-renderer-profiler.js.map +1 -1
  14. package/dist/development/vera-renderer-slots.d.ts +103 -0
  15. package/dist/development/vera-renderer-slots.d.ts.map +1 -0
  16. package/dist/development/vera-renderer-slots.js +1387 -0
  17. package/dist/development/vera-renderer-slots.js.map +1 -0
  18. package/dist/development/vera-renderer-spread.d.ts +51 -0
  19. package/dist/development/vera-renderer-spread.d.ts.map +1 -0
  20. package/dist/development/vera-renderer-spread.js +499 -0
  21. package/dist/development/vera-renderer-spread.js.map +1 -0
  22. package/dist/development/vera-renderer-tag.d.ts +61 -0
  23. package/dist/development/vera-renderer-tag.d.ts.map +1 -0
  24. package/dist/development/vera-renderer-tag.js +727 -0
  25. package/dist/development/vera-renderer-tag.js.map +1 -0
  26. package/dist/development/vera-renderer.d.ts +41 -16
  27. package/dist/development/vera-renderer.d.ts.map +1 -1
  28. package/dist/development/vera-renderer.js +1375 -200
  29. package/dist/development/vera-renderer.js.map +1 -1
  30. package/dist/vera-renderer-hydrate.min.js +1 -1
  31. package/dist/vera-renderer-hydrate.min.js.map +1 -1
  32. package/dist/vera-renderer-keyed.min.js +2 -0
  33. package/dist/vera-renderer-keyed.min.js.map +1 -0
  34. package/dist/vera-renderer-slots.min.js +2 -0
  35. package/dist/vera-renderer-slots.min.js.map +1 -0
  36. package/dist/vera-renderer-spread.min.js +2 -0
  37. package/dist/vera-renderer-spread.min.js.map +1 -0
  38. package/dist/vera-renderer-tag.min.js +2 -0
  39. package/dist/vera-renderer-tag.min.js.map +1 -0
  40. package/dist/vera-renderer.min.js +1 -1
  41. package/dist/vera-renderer.min.js.map +1 -1
  42. package/package.json +24 -1
package/README.md CHANGED
@@ -1,14 +1,1002 @@
1
1
  # @verajs/renderer
2
2
 
3
- A keyed, template-identity renderer (<!--size:renderer.gzip-->3.54 KB<!--/size:renderer.gzip--> gzip): tagged templates, `.prop`/`?bool`/`@event`
4
- and React-style `onClick` bindings, element refs, `keyed()` lists, `hold()` DOM preservation.
5
- `@verajs/renderer/hydrate` is a drop-in superset whose first render ADOPTS server-rendered DOM —
6
- markerless hydration (no framework comments in server HTML). SSR apps import from `/hydrate`;
7
- everyone else pays zero hydration bytes.
8
-
9
- `@verajs/renderer/profiler` is a development-only entry that reports how many templates were
10
- committed in place versus torn down and rebuilt, naming the template pairs that churn and where.
11
- `showProfiler()` puts the same information in a live panel in the corner of the page. It costs
12
- production nothing — the instrumentation is removed by the build, not merely unused.
13
-
14
- Wire once: `setRenderer(render)` from `@verajs/core`.
3
+ The DOM renderer for VeraJS — <!--size:renderer.gzip-->4.38 KB<!--/size:renderer.gzip--> gzipped,
4
+ no dependencies, no build step required.
5
+
6
+ Tagged templates parse once and clone; every render after the first walks only the value slots, so
7
+ updates touch the DOM and nothing else. Lists are keyed by value, not by directive. Server-rendered
8
+ pages hydrate through a separate entry that non-SSR apps never download.
9
+
10
+ ```sh
11
+ npm i @verajs/core @verajs/renderer
12
+ ```
13
+
14
+ ## Quick start
15
+
16
+ `wire([renderer])` is the only wiring. Core's `html` tag already produces the shape this accepts, so
17
+ there is no second call to make.
18
+
19
+ <!-- recipe -->
20
+ ```js
21
+ import { init, createStore, render, wire, html } from '@verajs/core';
22
+ import { renderer } from '@verajs/renderer';
23
+
24
+ wire([renderer]);
25
+
26
+ customElements.define(
27
+ 'click-counter',
28
+ class extends HTMLElement {
29
+ connectedCallback() {
30
+ init(this, { mode: 'open' });
31
+ const state = createStore({ count: 0 });
32
+ render(() => html`<button @click=${() => state.count++}>Clicked ${state.count} times</button>`);
33
+ }
34
+ }
35
+ );
36
+
37
+ document.body.append(document.createElement('click-counter'));
38
+ ```
39
+
40
+ Without it, core has no renderer at all: `render()` warns once in development and puts
41
+ nothing on the page. `@event`, `.prop` and `?bool` bindings are the first things to go missing.
42
+
43
+ ### `renderInto(result, container)`
44
+
45
+ The same write, called directly — no reactivity, no lifecycle, no custom element. `wire([renderer])`
46
+ registers exactly this function, so a component's `render()` ends up here; calling it yourself is how
47
+ you draw into a plain node, which is the incremental-adoption path and the way to test a template
48
+ without spinning up an element.
49
+
50
+ ```js
51
+ import { renderInto } from '@verajs/renderer';
52
+ import { html } from '@verajs/core';
53
+
54
+ renderInto(html`<p>${count}</p>`, document.querySelector('#app'));
55
+ ```
56
+
57
+ It **owns its own range and nothing else**: the first call anchors a root part at a marker it
58
+ appends, later calls with the same container reuse that part and walk only the value slots, and
59
+ whatever was already in the container stays. It is not reactive — call it again to update, or use a
60
+ component and let a store do it.
61
+
62
+ It was named `render` until 0.2.0, which collided with core's `render` — a different function, with
63
+ a different arity, that declares a *reactive* template and commits a component's setup. Both are
64
+ public and both are documented, so a reader who knew one misread the other.
65
+
66
+ ## Bindings
67
+
68
+ | Written | Means |
69
+ | --- | --- |
70
+ | `<p>${value}</p>` | child content — see [Values](#values) |
71
+ | `<p title=${value}>` | attribute. `null`/`undefined` **remove** it |
72
+ | `<p class="a ${b} ${c}">` | attribute built from several expressions and the static text between them |
73
+ | `<x-item .item=${value}>` | property assignment, uncoerced — objects, arrays, functions |
74
+ | `<p ?hidden=${value}>` | boolean attribute, present when truthy |
75
+ | `<input !checked=${value}>` | property written from the **live DOM** rather than from what the binding last wrote — see below |
76
+ | `<button @click=${fn}>` | event listener. An object with a `handleEvent` method works too — `addEventListener` takes both |
77
+ | `<button onClick=${fn}>` | the same thing, React-style. Strictly `on` + a capital — a template-written `onclick` stays a plain attribute (yours, greppable); **spread refuses it** (see the spread section's security note) |
78
+ | `<input ${fn}>` | element ref: a function is called with the element |
79
+ | `<input ${obj}>` | element ref: an object gets the element assigned to `.value`, so core's `ref()` works here |
80
+ | `<input ${spread(props)}>` | names resolved at runtime — see [`/spread`](#verajsrendererspread) |
81
+
82
+ A ref runs once per **distinct value**, not once per render.
83
+
84
+ **A ref is released when its subtree is rendered away, and not when its component is removed from
85
+ the document.** Toggling `${show ? html`<i ${box}>` : 'gone'}` sets `box.value` back to `null` (and
86
+ calls a function ref with `null`); removing the whole component leaves `box.value` pointing at the
87
+ element, now detached. That is deliberate rather than an oversight: here a disconnect is not a
88
+ destruction — moving a node between parents fires one, and the component re-renders on reconnect —
89
+ so releasing would blank every ref for the frame it takes a move to complete. Guard with
90
+ `box.value?.isConnected` if you need to know, and note that a ref created inside the component (the
91
+ way every example writes it) becomes garbage along with it either way.
92
+
93
+ An event handler is called with the element as `this`, and the listener is registered once — swapping
94
+ the handler across renders never touches the DOM, so there is no add/remove churn and no way to end
95
+ up with two. `undefined`, `null` and `false` all mean *no handler*, so `@click=${enabled && onClick}`
96
+ binds conditionally without a ternary. Anything else that cannot listen — a string, a number, an
97
+ object with no `handleEvent` — is inert, and **development names it at the binding**: a listener is
98
+ only ever called when a user clicks, so left unchecked the mistake surfaces at a point where nothing
99
+ on the stack says where the value came from.
100
+
101
+ ### `!name` — a live property
102
+
103
+ Every other binding skips a write when the value matches what it last wrote. That is what keeps a
104
+ field someone has typed into, and it is exactly wrong for a control whose DOM state changes as a
105
+ **side effect of interacting with a sibling**:
106
+
107
+ ```js
108
+ html`<input type="radio" name="pick" !checked=${state.picked === 'one'} />
109
+ <input type="radio" name="pick" !checked=${state.picked === 'two'} />`
110
+ ```
111
+
112
+ Clicking the second radio unchecks the first *in the DOM*, with no event on it. With `.checked` the
113
+ first binding still says `true`, still matches what it committed, and never writes again — the model
114
+ and the page diverge and no amount of re-rendering reconciles them. A `<select>`'s options are the
115
+ same shape.
116
+
117
+ It is deliberately narrow, and it is a **property** binding only:
118
+
119
+ - **Not for text inputs.** Bind those with `.value` and let a person's typing stand. `!value` exists
120
+ and is authoritative, which is precisely why it is not the default.
121
+ - **Not offered for attributes or booleans.** Nothing changes those behind the renderer's back, so
122
+ there is nothing to re-read.
123
+ - **It yields during hydration.** A click that happened before the bundle landed had no handler to
124
+ report it, so adoption records the value without writing; live semantics resume on the first
125
+ state-driven render.
126
+
127
+ `spread({ '!checked': … })` means the same thing, and `@verajs/ssr` serializes it exactly as
128
+ `.checked` — a server has nothing to re-read.
129
+
130
+ Bindings inside comments are not supported — the value is consumed and ignored. A **dynamic tag
131
+ name** is a binding a template cannot express either, and has its own entry:
132
+ [`/tag`](#verajsrenderertag).
133
+
134
+ ## Values
135
+
136
+ What a child position does with each kind of value. These match lit-html exactly, `null` and
137
+ `undefined` included.
138
+
139
+ | Value | Renders |
140
+ | --- | --- |
141
+ | string, number, `true`, `false`, `0` | as text — `${cond && 'x'}` puts the word `false` on the page |
142
+ | `null`, `undefined` | nothing |
143
+ | a template result | the template, updated in place while its shape holds |
144
+ | an array or iterable | each entry in order; key them with `keyed()` |
145
+ | a DOM node or fragment | itself, moved into place |
146
+ | anything else | `String(value)` |
147
+
148
+ Strings render as **text**, always. There is no path by which an interpolated value becomes markup
149
+ — see [Trusted HTML](#trusted-html-and-why-there-is-no-unsafehtml).
150
+
151
+ A DOM node renders as itself, which is how a template holds something another library owns:
152
+
153
+ ```js
154
+ const chart = document.createElement('canvas');
155
+ new Chart(chart, config);
156
+
157
+ renderInto(html`<figure>${chart}<figcaption>${title}</figcaption></figure>`, host);
158
+ ```
159
+
160
+ ## Lists — `keyed()`
161
+
162
+ ```js
163
+ import { renderInto } from '@verajs/renderer';
164
+ import { keyed } from '@verajs/renderer/keyed';
165
+
166
+ renderInto(html`<ul>${rows.map((row) => keyed(row.id, html`<li>${row.label}</li>`))}</ul>`, host);
167
+ ```
168
+
169
+ `keyed(key, result)` tags a result with its identity, so a reorder **moves** the existing elements
170
+ instead of rebuilding them — focus, scroll position, form state and running animations all survive.
171
+ It is its own entry because most apps never reorder a list, and the algorithm that makes reordering
172
+ cheap is <!--size:keyed.gzip-->923 B<!--/size:keyed.gzip--> gzipped they would otherwise carry. Importing `keyed` is the whole installation:
173
+ nothing registers, and there is no `wire()` call — the marker stamps each result with the strategy
174
+ that understands it, so a list always names its own reconciler and two strategies cannot disagree
175
+ about one. Lit splits `repeat` out for the same reason; the difference is that this one arrives on
176
+ the values rather than through a directive protocol.
177
+
178
+ **Keep it on the same version as `@verajs/renderer`.** It reaches the renderer through a handful of
179
+ two-character members that are exempt from property mangling, and nothing checks that both sides
180
+ agree about them — a `keyed` bundle paired with a different renderer release fails at runtime rather
181
+ than at install. Both ship from this package and bump together, so a single version range covers it;
182
+ the trap is pinning one and floating the other. `@verajs/renderer/spread` carries the same rule for
183
+ the same reason.
184
+
185
+ **It is additive, not a substitute.** Unlike `/hydrate` and `/profiler`, this entry imports nothing
186
+ at all — it reaches whatever renderer is present through a handful of mangling-exempt members — so
187
+ it is safe alongside any of them, `/hydrate` included.
188
+
189
+ **A list is keyed because `keyed()` marked it, not because its results have a `key` property.**
190
+ Setting `.key` by hand no longer makes a list keyed — the marker is what carries the algorithm, so
191
+ it is what the renderer looks for, on the client and when adopting server markup alike.
192
+
193
+ **Key every item in a list, or none of them.** A list is keyed when its first item is, and an
194
+ unkeyed item in a keyed list has no identity to match on.
195
+
196
+ An unkeyed list is not wrong — it updates each position in place, which is exactly right for a list
197
+ whose order never changes.
198
+
199
+ ## Preserving DOM — `hold()`
200
+
201
+ ```js
202
+ renderInto(html`<div>${hold(editing ? editor(state) : viewer(state))}</div>`, host);
203
+ ```
204
+
205
+ `hold(result)` parks the DOM it replaces instead of destroying it, keyed by template identity, and
206
+ brings it back when that template returns. lit calls this `cache`. What survives is everything no
207
+ attribute records: what the user typed, a checkbox or radio the user set, a `<select>`'s chosen
208
+ option, a `<details>` left open, a media element's playback position — and the nodes themselves, so
209
+ the element that had focus is the same element when it comes back.
210
+
211
+ **A scroll offset does not survive, and cannot.** Every engine resets `scrollTop` to zero the moment
212
+ an element leaves the document — measured on Chromium, Firefox and WebKit, which report `0` while
213
+ parked, `0` on return, and `0` even for a node moved directly between two attached parents. Nothing an
214
+ applier does with the nodes can hold it, and lit's `cache()` cannot either. If a scroll position
215
+ matters, read it before the toggle and restore it after.
216
+
217
+ Anything that is not a template passes straight through — there is nothing to park for a string, a list, `null` or `false` — so `hold(editing && editor())` is safe to write.
218
+
219
+ It only re-adopts a template it has seen at **that same call site** — two `hold()` calls in
220
+ different templates are two different templates, and neither adopts the other's DOM. The other
221
+ direction is also safe, and reads less obviously from "call site": every keyed **row** of a list
222
+ shares one call site, and each still holds its own state — the cache rides the row's own part, so
223
+ two rows toggling through the same `hold` never adopt each other's parked DOM, including through a
224
+ reorder while one is parked. Measured, and pinned in the combination matrix.
225
+
226
+ **It keeps every shape it has parked, for as long as the part lives.** That is the point — a tab
227
+ strip of twelve panels holds twelve, and each comes back exactly as it was left — but it is a cache
228
+ with no eviction, so `hold` over an unbounded set of templates retains an unbounded amount of DOM.
229
+ Verified: fifty distinct shapes cycled through one `hold` and the first still re-adopted its own
230
+ nodes. lit's `cache()` behaves the same way, and for the same reason — evicting would silently throw
231
+ away the state the applier exists to preserve, which is worse than holding it. Use `hold` for a
232
+ set you can name, and let an unbounded one rebuild.
233
+
234
+ ## Write stable shapes
235
+
236
+ Rendering the same elements every pass and toggling `hidden` is faster than swapping one subtree for
237
+ another. Template identity holds, so values update in place rather than the subtree being torn down
238
+ and rebuilt. Both forms are correct; this one is cheaper.
239
+
240
+ ```js
241
+ // fragile — two sibling parts, each swapping between a template and ''
242
+ html`<section>
243
+ ${items.length === 0 ? html`<p>empty</p>` : html`<ul>${rows}</ul>`}
244
+ ${busy ? html`<p>loading</p>` : ''}
245
+ </section>`;
246
+
247
+ // preferred — one shape, visibility toggled
248
+ html`<section>
249
+ <p ?hidden=${items.length > 0}>empty</p>
250
+ <ul ?hidden=${items.length === 0}>${rows}</ul>
251
+ <p ?hidden=${!busy}>loading</p>
252
+ </section>`;
253
+ ```
254
+
255
+ [`/profiler`](#verajsrendererprofiler) exists to make the difference visible: it counts templates
256
+ committed in place against templates that replaced a different template.
257
+
258
+ ## Entries
259
+
260
+ | Import | What it adds | Ships in production |
261
+ | --- | --- | --- |
262
+ | `@verajs/renderer` | the renderer | yes |
263
+ | `@verajs/renderer/hydrate` | a superset whose first render adopts server-rendered DOM | yes |
264
+ | `@verajs/renderer/keyed` | `keyed(key, result)` — keyed list reconciliation | yes |
265
+ | `@verajs/renderer/spread` | `spread(props)` — binding names resolved at runtime | yes |
266
+ | `@verajs/renderer/tag` | `` tag`h1` `` — an element whose tag name is decided at runtime | yes |
267
+ | `@verajs/renderer/slots` | `slots` (wire it) + `slotted(host, name?)` — light-DOM `<slot>` distribution | yes |
268
+ | `@verajs/renderer/profiler` | a superset that measures template churn | no — development only |
269
+
270
+ `/hydrate` and `/profiler` each re-export the whole public API, so they are drop-in replacements for
271
+ the base import. **Never mix two of them in one app** — that loads two renderers with two template
272
+ caches.
273
+
274
+ **Which means an app can have one of them, not both — so a hydrating app cannot be profiled.** They
275
+ each bundle their own renderer with its own instrumentation hook, so profiling while rendering
276
+ through `/hydrate` observes an instance nothing renders into: measured, three renders reported zero
277
+ frames while the page updated correctly. `formatReport` says so when it observed nothing, because a
278
+ zero report is otherwise indistinguishable from an app with nothing to optimise.
279
+
280
+ ## `@verajs/renderer/slots` — light-DOM slots
281
+
282
+ Native `<slot>` needs a shadow root. This entry teaches the renderer to distribute a light-DOM
283
+ component's own children into the `<slot name="…">` positions of its template, so **one component
284
+ works in both modes** — users write `<div slot="title">` exactly as they would against shadow DOM.
285
+
286
+ Given this markup:
287
+
288
+ ```html
289
+ <my-card>
290
+ <h2 slot="header">Hello</h2>
291
+ Body text goes to the default slot.
292
+ </my-card>
293
+ ```
294
+
295
+ <!-- recipe -->
296
+ ```js
297
+ import { init, render, wire, html } from '@verajs/core';
298
+ import { renderer } from '@verajs/renderer';
299
+ import { slots, slotted } from '@verajs/renderer/slots';
300
+
301
+ wire([renderer, slots]);
302
+
303
+ customElements.define(
304
+ 'my-card',
305
+ class extends HTMLElement {
306
+ connectedCallback() {
307
+ init(this); // LIGHT DOM — no shadow options
308
+ render(
309
+ () => html`<article>
310
+ <header><slot name="header" @slotchange=${(e) => this.onHeader(e.target)}>Untitled</slot></header>
311
+ <main><slot>Nothing here yet.</slot></main>
312
+ </article>`
313
+ );
314
+ }
315
+ /** Written exactly as it would be against a shadow root, and it runs in both. */
316
+ onHeader(slot) {
317
+ console.log('header is now:', slot.assignedElements().map((el) => el.textContent));
318
+ }
319
+ }
320
+ );
321
+
322
+ const card = document.createElement('my-card');
323
+ card.innerHTML = '<h2 slot="header">Hello</h2>Body text goes to the default slot.';
324
+ document.body.append(card);
325
+
326
+ await new Promise((resolve) => requestAnimationFrame(resolve));
327
+ console.log(card.querySelector('header').textContent); // "Hello"
328
+ console.log(card.querySelector('main').textContent); // "Body text goes to the default slot."
329
+ console.log(slotted(card, 'header').length); // 1
330
+ ```
331
+
332
+ `slots` is the insert descriptor you wire; that is all a consumer touches.
333
+
334
+ > **Wire the renderer as a MODULE — `wire([renderer, slots])` — not as a bare function.** Both
335
+ > spellings register a renderer, and only the module form runs the descriptor's `connect()`, which
336
+ > is how the renderer receives the app's insert registry and therefore how it finds this seam at
337
+ > all. `wire({ on: 'render', fn: renderInto, priority: 50 })` leaves that registry unset, so every
338
+ > `<slot>` renders its fallback and nothing says why. (That spelling is documented for wiring a
339
+ > DIFFERENT renderer — lit-html — where there is no seam to find.) The assignment follows
340
+ the platform's own rules — elements to the slot their `slot` attribute names, text to the default
341
+ slot, fallback shown only while a slot is unassigned and restored when it empties, direct children
342
+ only. Live: appending, removing, or re-slotting children redistributes automatically, with one documented
343
+ divergence — see **Late children** below. Re-renders leave slotted nodes in place, identity intact, so focus and input values
344
+ survive; SSR emits already-distributed markup and hydration adopts it.
345
+
346
+ **A `<slot>` inside another slot's fallback works**, and takes over at the moment that fallback
347
+ becomes visible — the same thing the platform does, verified by layout on three engines. Slots are
348
+ handed over in document order, so a slot's nested slots are taken over first, while they still have
349
+ a parent to anchor into.
350
+
351
+ **`::slotted()` is shadow-only and deliberately not translated.** In light DOM the slotted content
352
+ is in the same tree, so an ordinary descendant selector reaches it — and reaches deeper than
353
+ `::slotted()` can, which only ever matched top-level assigned nodes. Measured on three engines, the
354
+ two are exactly complementary: neither spelling reaches across. A component that renders both ways
355
+ writes both, `::slotted(img), [part="body"] img`, exactly as `:host, :scope` was needed before
356
+ `:host` became translatable.
357
+
358
+ The asymmetry with `:host` is the reason one is translated and this is not. `:host` styles the
359
+ component ITSELF and nothing else can supply it, so a component from npm that uses it is visibly
360
+ broken in light mode. `::slotted()` styles the USER'S content, which in light DOM the page author
361
+ can already reach — so the failure is a missing default rather than a broken component, and making
362
+ it work would mean writing framework attributes into the user's own markup.
363
+
364
+ ### Late children
365
+
366
+ **A node added AFTER the first render joins its slot with full native semantics** — bare text and
367
+ attribute-less elements included, in document order, exactly as a shadow root would assign them.
368
+ The renderer stamps everything it emits at a light host's top level with a hidden, non-enumerable
369
+ property, so an unstamped node there is knowably the user's; `slot=""`/`slot="name"` still route,
370
+ they are simply no longer required.
371
+
372
+ This used to be the feature's one documented divergence, and the rule existed because a light
373
+ host's children after the first render are also the component's own rendered output, with nothing
374
+ in the DOM to tell them apart. Ownership is written down now rather than inferred from position,
375
+ so the ambiguity — and the rule — are gone. Two things remain worth knowing: whitespace appended
376
+ to a light host suppresses the default fallback, which is parity (a shadow root does the same), and
377
+ re-slotting a node (`slot="a"` → `"b"`) rejoins in light-tree order rather than arrival order.
378
+ Every position you can reach orders exactly as the platform does — what light has fewer of is
379
+ positions you can name, since a distributed child is no longer a direct child of the host.
380
+
381
+ **Cloning a RENDERED light component does not work, and cannot.** `cloneNode(true)` copies a
382
+ light host's children — which after a render are the component's own output with the user's slotted
383
+ nodes already distributed into it. The clone then captures all of that as its slot content, so its
384
+ rendered tree ends up nested inside its own default slot. A shadow component clones cleanly for the
385
+ opposite reason: `cloneNode` does not copy a shadow root, so the clone re-renders and its light
386
+ children are still just its light children.
387
+
388
+ Nothing can detect this — the ambiguity is the same one behind the late-children rule above, and
389
+ the original user content was consumed at the first render, so there is nothing to recover. **To
390
+ duplicate a component, clone the SOURCE markup and let the copy render itself**, rather than cloning
391
+ a live instance. This matters most to anything that duplicates components as an operation: an editor
392
+ canvas, a repeater, a drag-to-copy.
393
+
394
+ **`slotted(host, name?)`** is the component-internal accessor — what the user assigned to a slot,
395
+ answered identically in shadow mode (native assignment) and light mode (the capture map). Omit
396
+ `name` for the default slot. Component authors reach for this; app users do not.
397
+
398
+ ### The `<slot>` element is still the component's handle on the slot
399
+
400
+ A slot is not only a position, and a component that keeps up with what it was given binds to the
401
+ element itself. All of that means here what it means in a shadow root:
402
+
403
+ ```js
404
+ render(() => html`<header>
405
+ <slot name=${section} &ref=${(el) => (this.slot = el)}
406
+ @slotchange=${(e) => wire(e.target.assignedElements())}>Nothing yet</slot>
407
+ </header>`);
408
+ ```
409
+
410
+ - **`@slotchange`** fires on first assignment and on every change after it — and only then, so a
411
+ child added without a `slot` attribute fires nothing. The sequence and each event's
412
+ `assignedNodes()` are asserted against real shadow DOM, which is the oracle for this. It fires
413
+ for a slot whose rendering is currently displaced too (assignment is independent of rendering),
414
+ exactly as native does for a slot that is not on screen.
415
+ - **`node.assignedSlot` answers `null` — ask the slot, not the node.** The reverse lookup is a
416
+ platform accessor tied to real shadow assignment, and overriding it on YOUR nodes is an intrusion
417
+ this module refuses. The forward reads carry the same fact: `slot.assignedNodes().includes(node)`
418
+ through a `&ref`, or `slotted(host, name)` from outside.
419
+ - **Bind `slotchange` directly — it does not bubble to the host.** In a shadow root one listener on
420
+ the root hears every slot by bubbling; here the slot handles are deliberately out of the document,
421
+ so there is no tree for the event to climb and `host.addEventListener('slotchange', …)` hears
422
+ silence. Use `@slotchange` on each slot, which also hands you the right `event.target`. (The same
423
+ boundary as `querySelector('slot')`: fewer places to listen, not fewer events.)
424
+ - **`assignedNodes(options)` / `assignedElements(options)`** answer from the live assignment,
425
+ through `event.target` or a `&ref`. With nothing assigned, `{ flatten: true }` gives the fallback
426
+ actually on screen — slottables only, so a comment you wrote into fallback content is not in it,
427
+ and a nested slot flattens through to whatever it is showing, both as the platform does.
428
+ - **Use `child.before(node)` / `child.after(node)`, never `host.insertBefore(node, child)`.** A light
429
+ host's children are physically moved into the slot they are assigned to, so a child you appended
430
+ and kept a reference to is no longer a *direct* child of the host — and `insertBefore` throws
431
+ `NotFoundError` when its reference node is not a child of the node it is called on. In a shadow
432
+ root the same line works, because there nothing moves. `before()`/`after()` route through the
433
+ node's own current parent, so they are correct in both modes, and the content lands in the order
434
+ you asked for. This is the sharpest difference between the two modes and the easiest to hit.
435
+ - **A displaced node is *disconnected* here; native slotting never disconnects it.** Shadow
436
+ distribution is virtual — a slottable no slot names stays in the light tree, connected, merely
437
+ unrendered. Light slots park it physically, so a custom element inside displaced content runs its
438
+ `disconnectedCallback` (and a Vera component's effect cleanups) on the way out, and
439
+ `connectedCallback` again when its slot returns — with its element identity, stores and typed-in
440
+ state intact, and reactivity re-established by the re-init. Component authors already handle this
441
+ pair for any `appendChild` move; the difference is only *when* it happens: a component that
442
+ pauses a video on disconnect pauses while displaced here and keeps playing in a shadow root.
443
+ The slot element is deliberately not in your DOM (see below), so it is unreachable by selector and
444
+ reports `isConnected === false`. It is a live API object, not a position in the tree.
445
+ - **`name` can be a binding.** `<slot name=${section}>` routes by the name it actually has, and
446
+ re-routes if it changes between renders.
447
+
448
+ ### Keeping the `<slot>` in the tree — a strategy you can own
449
+
450
+ Every boundary above has one cause: the shipped strategy removes the `<slot>` element so your
451
+ markup stays exactly what you wrote. The seam it registers through is public, single-registrant,
452
+ and takes whole strategies — so if you would rather have the *shadow tree's own structure* (the
453
+ slot element present, selectable, `:first-child`-countable, made layout-invisible by the same
454
+ `display: contents` the UA stylesheet gives real slots), you can wire a strategy that keeps it.
455
+ This one is complete enough to run — and it runs, in CI, as written:
456
+
457
+ <!-- recipe -->
458
+ ```js
459
+ import { init, render, wire, html } from '@verajs/core';
460
+ import { renderer } from '@verajs/renderer';
461
+
462
+ /** Distribution that KEEPS the <slot>: content moves INSIDE it, fallback shows when it is empty. */
463
+ const slotsInTree = {
464
+ name: 'my-app/slots-in-tree',
465
+ on: 'slot',
466
+ priority: 50,
467
+ fn(slot, root, name) {
468
+ if (root.nodeType !== 1) return null; // a shadow root keeps native slotting
469
+ const host = root;
470
+ const fallback = [...slot.childNodes];
471
+ const isMine = (n) =>
472
+ n.nodeType === 1 ? (n.getAttribute('slot') ?? '') === name
473
+ : name === '' && n.nodeType === 3 && n.data.trim() !== '';
474
+ let shown = -1;
475
+ const fill = () => {
476
+ for (const n of [...host.childNodes]) if (isMine(n)) slot.append(n);
477
+ const assigned = [...slot.childNodes].filter((n) => !fallback.includes(n));
478
+ for (const n of fallback) (assigned.length ? n.remove() : slot.append(n));
479
+ observer.takeRecords(); // our own moves are not the user's
480
+ if (assigned.length !== shown) {
481
+ shown = assigned.length;
482
+ slot.dispatchEvent(new Event('slotchange', { bubbles: true })); // real ancestors — it CLIMBS
483
+ }
484
+ };
485
+ const observer = new MutationObserver(fill);
486
+ fill();
487
+ observer.observe(host, { childList: true, subtree: true });
488
+ return { _$park$: () => { observer.disconnect(); for (const n of [...slot.childNodes]) if (!fallback.includes(n)) host.append(n); } };
489
+ },
490
+ };
491
+
492
+ wire([renderer, slotsInTree]);
493
+ document.head.insertAdjacentHTML('beforeend', '<style>slot{display:contents}</style>');
494
+
495
+ customElements.define('tree-card', class extends HTMLElement {
496
+ connectedCallback() {
497
+ init(this);
498
+ render(() => html`<article><slot name="header">Untitled</slot></article>`);
499
+ }
500
+ });
501
+
502
+ const card = document.createElement('tree-card');
503
+ card.innerHTML = '<h2 slot="header">Hello</h2>';
504
+ document.body.append(card);
505
+ await new Promise((resolve) => requestAnimationFrame(resolve));
506
+
507
+ /** Every documented boundary of the shipped strategy, working: */
508
+ let heard = 0;
509
+ card.addEventListener('slotchange', () => heard++); // a HOST-level listener — bubbling exists here
510
+ if (!card.querySelector('slot')) throw new Error('querySelector finds the slot');
511
+ if (card.querySelector('h2').parentElement.localName !== 'slot') throw new Error('reverse lookup');
512
+ card.querySelector('h2').remove();
513
+ await new Promise((resolve) => setTimeout(resolve, 0));
514
+ if (card.querySelector('article').textContent !== 'Untitled') throw new Error('fallback returns');
515
+ if (heard !== 1) throw new Error('slotchange bubbled to the host');
516
+ ```
517
+
518
+ The trade is the one the platform itself makes: this is the shadow tree's structure, so the
519
+ `<slot>` now appears in your host's serialized markup (as it appears in a `shadowRoot`'s), your
520
+ component CSS can select it — and structural selectors written against the template see it as the
521
+ child it is, because selectors follow the tree, not layout. Wire it *instead of* `slots` — the
522
+ seam is single-registrant, and wiring both says so in development, by name.
523
+
524
+ What this recipe deliberately does not do is the audited module's territory: light-tree ordering
525
+ under re-slots and prepends, duplicate-name handover, nested slots in fallbacks, dynamic
526
+ `name=${…}`, SSR and hydration. It is a starting point you own, not a drop-in peer — the measured
527
+ design for a full sibling lives with the maintainers.
528
+
529
+ **The one thing a light-DOM slot cannot carry is presentation** — `class`, `style`, `id` and other
530
+ plain attributes. A light host has no second tree, so the slot element is not rendered and there is
531
+ nothing for them to apply to, while in a shadow root they do apply. Put them on a real element
532
+ around the slot. Development builds say so, naming the attribute, rather than leaving it to be
533
+ found.
534
+
535
+ Additive like `keyed`/`spread`: it imports no renderer and reaches the one present through the wired
536
+ seam, so it is safe beside any renderer entry on a CDN page. The entry is
537
+ **<!--size:slots.gzip-->3.35 KB<!--/size:slots.gzip-->** gzipped and only apps importing it pay;
538
+ `@verajs/renderer` itself carries just the seam that records where a template's slots are. It is
539
+ also Node-safe — it imports nothing and touches no global document — so a universal app can wire it
540
+ on both sides.
541
+
542
+ ## `@verajs/renderer/hydrate`
543
+
544
+ <!-- recipe -->
545
+ ```js
546
+ import { renderer } from '@verajs/renderer/hydrate'; // instead of '@verajs/renderer'
547
+ ```
548
+
549
+ Same name, same `wire([renderer])`, different entry — this one's `renderer` binds the adopting
550
+ render below, so swapping the import (or the importmap target) really is the only change.
551
+
552
+ The first render into a container that already has children **adopts** them as server output of the
553
+ same template: node identity is preserved, listeners attach, and updates mutate the adopted nodes.
554
+ Hydration here is **markerless** — server HTML carries no framework comments, and the client repairs
555
+ its own anchors into the adopted DOM.
556
+
557
+ Any disagreement with the server markup clears the container (keeping `<style data-vm-sheet="styles">` tags)
558
+ and renders fresh, so correctness never depends on the server output being right. A DOM node at a
559
+ child position is the one thing the server cannot have rendered; it is inserted without giving up
560
+ adoption of everything around it.
561
+
562
+ **A fallback warns in development, naming the first place the two renders disagreed** — *"expected
563
+ `<p>` and found `<div>`"*, *"`<ul>` contains `<li>`, which the template does not describe"*. The page
564
+ is correct either way, which is the point of the fallback and also why it needs saying: that
565
+ container's markup was just thrown away, and with nothing observable to notice, the only symptom is
566
+ a first paint that is slower than the one you paid a server render for. An attribute that disagrees
567
+ is simply re-set during adoption and is not a fallback at all.
568
+
569
+ **A fallback costs one container, not the page.** Adoption is decided per container, so components
570
+ hydrating into their own roots are independent: one that disagrees rebuilds and warns, and every
571
+ other one keeps the server's nodes. Measured in `tests/hydrate-mismatch.test.mjs` — three containers,
572
+ one mismatch, one warning, two adoptions. Worth stating because the warning used to imply otherwise
573
+ and sent the reader hunting for a page-wide cause.
574
+
575
+ **Comments are outside the comparison, in both directions** — a comment in your template is not
576
+ required in the server markup, and one in the server markup that your template does not have is not
577
+ a disagreement. A comment renders nothing, so neither direction changes what a reader sees; matching
578
+ on them would only cost every commented template its adoption.
579
+
580
+ On a CDN page, point the import map's `@verajs/renderer` at `vera-renderer-hydrate.min.js` and
581
+ nothing else changes. Apps that never hydrate download none of this.
582
+
583
+ ### Importing this in Node
584
+
585
+ **`@verajs/renderer` needs a DOM to be imported at all**, not merely to render. It captures
586
+ `document` at module scope and builds two shared `TreeWalker`s there, which is what saves an
587
+ allocation per instance — so `import '@verajs/renderer'` on a server throws
588
+ `ReferenceError: document is not defined` before any of your code runs. The same is true of
589
+ `/hydrate` and `/profiler`, and of `@verajs/jsx/standalone`, which contains a renderer.
590
+
591
+ This is worth stating because [`@verajs/router`](../router#node-and-ssr) documents the opposite
592
+ about itself, and the asymmetry is easy to read the wrong way. The rest of the family is Node-safe:
593
+ `@verajs/core`, `@verajs/inserts`, `@verajs/store` and `/collections`, `@verajs/router`,
594
+ `@verajs/styles`, `@verajs/autoloader`, `@verajs/jsx` (the transform), `@verajs/ssr` — **and
595
+ `@verajs/renderer/keyed`, `/spread` and `/tag`**, which hold no DOM of their own even though their
596
+ parent entry does.
597
+
598
+ In a universal app, hand the renderer in rather than importing it in shared code — which is what
599
+ `examples/kitchen-sink/wiring.js` does, taking it as a parameter so the server can pass `null`.
600
+ `tests/node-import-safety.test.mjs` holds both halves of that list.
601
+
602
+ ## `@verajs/renderer/spread`
603
+
604
+ Spread a props object onto an element, with names resolved at runtime.
605
+
606
+ <!-- recipe -->
607
+ ```js
608
+ import { init, createStore, render, wire, html } from '@verajs/core';
609
+ import { renderer } from '@verajs/renderer';
610
+ import { spread } from '@verajs/renderer/spread';
611
+
612
+ wire([renderer]);
613
+
614
+ customElements.define(
615
+ 'x-field',
616
+ class extends HTMLElement {
617
+ connectedCallback() {
618
+ init(this, { mode: 'open' });
619
+ const state = createStore({ disabled: false });
620
+ const props = {
621
+ id: 'email', // attribute
622
+ placeholder: 'you@example.com', // "
623
+ '.value': '', // property
624
+ '?disabled': state.disabled, // boolean attribute
625
+ onInput: (e) => console.log(e.target.value), // event — @input works too
626
+ };
627
+ render(() => html`<input ${spread(props)} />`);
628
+ }
629
+ }
630
+ );
631
+
632
+ document.body.append(document.createElement('x-field'));
633
+ ```
634
+
635
+ Keys carry the same sigils as written bindings, so a spread key and a written binding mean the same
636
+ thing — `.value`, `?disabled`, `@click`, `onClick`, and `&ref` for an element ref.
637
+
638
+ **A key that cannot be written into markup is skipped**, with a warning in development. That is any
639
+ name holding whitespace, a quote, `<`, `>`, `/`, `=`, a backtick or a control character. Engines are
640
+ more permissive than markup — measured across Chromium, Firefox and WebKit, `setAttribute` accepts
641
+ `"`, `'` and `<` — but a name that binds in the browser and cannot survive server rendering is worse
642
+ than one that works nowhere, so both sides apply the same rule. Skipped rather than thrown: the keys
643
+ are runtime data, and one bad name in a props bag should not cost the render.
644
+
645
+ Several spreads on one element are supported — each element position owns its own keys, so
646
+ `<div ${spread(a)} ${spread(b)}>` works and neither releases the other's bindings.
647
+
648
+ Keys are strings carrying sigils, so TypeScript cannot check them against the element's attributes.
649
+ That is a genuine step down from written bindings, and the trade for names that are not known until
650
+ runtime.
651
+
652
+ ### Removing a key
653
+
654
+ A key that disappears between renders **restores what the element held before the binding existed**.
655
+
656
+ ```js
657
+ renderInto(html`<input type="text" ${spread({ type: 'number' })} />`, host); // type="number"
658
+ renderInto(html`<input type="text" ${spread({})} />`, host); // type="text" again
659
+ ```
660
+
661
+ Not removed — *restored*. The usual framing, "what value means absent", has no answer for a
662
+ property: `delete` cannot remove a prototype accessor, and assigning `undefined` puts the literal
663
+ string `"undefined"` into a form field. Asked as "undo what this binding did" it is well defined for
664
+ every kind, because it reads the element's own pristine state — `""` for `input.value`, `undefined`
665
+ for a custom element's property.
666
+
667
+ **On a hydrated page it restores the server's value**, because that is genuinely what was there
668
+ before the binding: the server rendered this same spread, and a spread key *replaces* a static
669
+ attribute in server markup exactly as it overwrites one on the client. The original is gone by
670
+ construction, so bind `null` when you mean removal:
671
+
672
+ ```js
673
+ renderInto(html`<input ${spread({ id: null })} />`, host); // removes, on either path
674
+ ```
675
+
676
+ One residue worth knowing: `.value`, `.checked` and `.selected` are mirrored to attributes
677
+ server-side so hydration can read them back, and releasing the property does not clear that
678
+ attribute. The property is correct either way; the attribute lingers as the field's *default* value.
679
+
680
+ A released event binding stops dispatching; the listener itself stays registered, which is how
681
+ written `@event` bindings behave too.
682
+
683
+ ### What it costs, and why it is a separate entry
684
+
685
+ `@verajs/renderer` grows **5 B** gzipped for the protocol this uses, whether or not you import it —
686
+ measured 2026-08-27 by deleting the `_$apply$` branch and rebuilding, as a **difference** rather than
687
+ a pair of totals — the totals move with every change to this package and the difference does not,
688
+ which is the mistake this line already made once. `llms.txt` and this file disagreed about the figure
689
+ for a while, at 16 B and 8 B respectively, and both were wrong. Nothing regenerates it, so it is
690
+ dated; re-measure the same way if it matters.
691
+ The entry itself is **<!--size:spread.gzip-->1.28 KB<!--/size:spread.gzip-->** gzipped, and only apps
692
+ that import it pay for that.
693
+
694
+ Runtime is at parity with writing the bindings out: both do one comparison per binding per render,
695
+ and the spread does one part-dispatch where five written bindings do five.
696
+
697
+ Template renderers bake attribute names into the template at parse time. That is what makes them
698
+ small and fast, and it is why neither this renderer nor lit-html has spread built in —
699
+ [lit's spread PR](https://github.com/lit/lit/pull/1960) has been an open draft since 2021.
700
+
701
+ The renderer itself holds only a protocol: a value at element position carrying `_$apply$` applies
702
+ itself. Everything else lives in this entry, which imports nothing — not even from the renderer — so
703
+ it loads alongside any renderer that honours the protocol, including your own.
704
+
705
+ ## `@verajs/renderer/profiler`
706
+
707
+ <!-- recipe -->
708
+ ```js
709
+ import { renderInto, profile, formatReport } from '@verajs/renderer/profiler';
710
+
711
+ /** `profile` awaits an async driver — driving an app means awaiting frames, and the render
712
+ scheduler is `requestAnimationFrame`, so nothing commits inside one synchronous turn. */
713
+ const { report } = await profile(async () => { /* click around, await frames */ });
714
+ console.log(formatReport(report));
715
+ // 39 updated in place, 2 created, 19 rebuilt (32% of commits)
716
+ // Template identity churn — these were torn down, not updated:
717
+ // 10x at body > main#app > ul.todo-list
718
+ // <li class="done"><s>${…}</s></li>
719
+ // -> <li><label><input type="checkbox">${…}</label></li>
720
+ ```
721
+
722
+ `showProfiler()` puts the same numbers in a live panel in the corner of the page and returns a
723
+ function that removes it. The panel is plain DOM in a shadow root — it never renders itself through
724
+ the renderer, so it does not appear in its own measurements.
725
+
726
+ **Calling it again replaces the panel rather than adding one**, and a second call's `options` take
727
+ effect. That matters because the natural way to use this is a console — `showProfiler()`, look,
728
+ `showProfiler()` again — where the first return value is already gone: two panels would sit on top of
729
+ each other in the same corner, and the second one's teardown would stop profiling for the first,
730
+ which kept repainting a frozen report.
731
+
732
+ Full API: `startProfiling()`, `stopProfiling()`, `getReport()`, `isProfiling()`, `profile(fn)`,
733
+ `formatReport(report)`, `showProfiler(options?)`.
734
+
735
+ This costs production nothing, and there is nothing to strip: the instrumentation sits behind a
736
+ `__DEV__` constant the build folds to `false`, so `vera-renderer.min.js` is byte-identical whether
737
+ or not this entry exists.
738
+
739
+ ## Trusted HTML, and why there is no `unsafeHTML`
740
+
741
+ Every interpolated value is escaped at the render boundary. There is no `unsafeHTML` and there will
742
+ not be one: shipping a sanctioned opt-out puts an XSS sink in the public API, where it reads as
743
+ blessed in tutorials and in review.
744
+
745
+ Trusted markup goes through a property binding, so you write the sink yourself:
746
+
747
+ ```js
748
+ renderInto(html`<div .innerHTML=${trustedMarkup}></div>`, host);
749
+ ```
750
+
751
+ Greppable, obviously yours, reviewable as the security decision it is. Sanitize first
752
+ (`DOMPurify.sanitize`) unless the markup is genuinely your own, and put it on an element whose
753
+ children nothing else binds — the renderer owns the content of elements it renders into.
754
+
755
+ **Security: spread refuses the injection sinks.** The `.innerHTML` posture above rests on the
756
+ template spelling being greppable, obviously yours, and reviewable — three properties a spread key
757
+ does not have, because spread names arrive at runtime inside a props object that is often built
758
+ from data. So `spread()` refuses `.innerHTML`/`!outerHTML` property keys, the `srcdoc` attribute,
759
+ and any inline-handler attribute name (`onclick` and friends, any casing — `on` + Capital with a
760
+ function remains the documented event spelling and still works), on the client AND in the SSR
761
+ serializer alike. Development builds name each refused key and the sanctioned template spelling.
762
+ If you genuinely need one of these dynamically, write the binding in the template where a reviewer
763
+ can see it.
764
+
765
+ ## `@verajs/renderer/tag`
766
+
767
+ An element whose **tag name** is decided at runtime — a heading whose level comes from data, a
768
+ component that renders `<a>` or `<button>`.
769
+
770
+ ```js
771
+ import { html, tag } from '@verajs/renderer/tag';
772
+
773
+ const HEADING = { 1: tag`h1`, 2: tag`h2`, 3: tag`h3` };
774
+
775
+ const H = HEADING[state.level];
776
+ renderInto(html`<${H} class="title">${state.text}</${H}>`, host);
777
+ ```
778
+
779
+ A template renderer bakes tag names into its statics — that is what template identity *is*, and
780
+ what every fast path here depends on. So a runtime tag cannot be a binding: it is spliced into the
781
+ statics before the renderer sees the template. Downstream nothing changes. The renderer,
782
+ `@verajs/ssr` and hydration all receive an ordinary template and are unaware this entry exists.
783
+
784
+ Note the `html` import: in a template containing a tag, use the one from here rather than core's.
785
+
786
+ ### In JSX
787
+
788
+ **A tag is also a component.** A capitalized JSX tag compiles to `H({…})`, and a tag *is* that
789
+ function, so the same value works in both notations with no compiler change and no new syntax —
790
+ `<{expr}>` is not valid JSX or TSX, and inventing it would break `tsc`, Prettier and every editor.
791
+
792
+ ```jsx
793
+ const H = HEADING[state.level];
794
+ return <H className="title" hidden={state.muted}>{state.text}</H>;
795
+ ```
796
+
797
+ React's names are mapped here exactly as the compiler maps them on a written element, so `<H
798
+ className="t" hidden={false}>` and `<h1 className="t" hidden={false}>` mean the same thing. That is
799
+ a correctness matter, not an ergonomic one: passed through raw, `hidden={false}` becomes the
800
+ attribute `hidden="false"` and any value at all applies it.
801
+
802
+ `ref` is mapped too — `<H ref={r}>` binds exactly as `<h1 ref={r}>` does. `key` never reaches the
803
+ component: `@verajs/jsx` consumes it into `keyed(…)` for both spellings, and a hand-written
804
+ `H({ key })` drops it and says so in development, because a key marks a template for reconciliation
805
+ and this call *returns* one rather than being one.
806
+
807
+ **`dangerouslySetInnerHTML` is the one React name a tag cannot honour, and that is a security
808
+ property rather than a gap.** A tag reaches its element through `/spread`, whose names are only
809
+ known at runtime — which is exactly what makes that sink unreviewable — so `/spread` refuses
810
+ `.innerHTML` outright. Write the element directly, with the value sanitized first:
811
+
812
+ ```js
813
+ renderInto(html`<${H} .innerHTML=${trusted}>`, host);
814
+ ```
815
+
816
+ `tests/jsx-component-equivalence.test.mjs` drives every one of these both ways, compiled and
817
+ rendered, and compares the DOM — because the name-level pin that preceded it passed for the entire
818
+ life of three defects.
819
+
820
+ ### What to know
821
+
822
+ - **A string can never become a tag.** Only another tag may be interpolated, so the set of tags an
823
+ app can produce is fixed by its source. That is what keeps a tag out of reach of a request — the
824
+ same reasoning as there being no `unsafeHTML` — and it is what bounds the cache below.
825
+ - **Each tag is its own template.** Switching tags rebuilds the subtree, which is correct: the
826
+ element genuinely changed. Within a tag it updates in place like anything else.
827
+ - **The cache is per call site.** Spliced statics hang off the call site's own `strings` array, so
828
+ two template literals in the source are two entries however identical they look. Right for real
829
+ code, where a template lives at one place in a render function — and the thing that catches people
830
+ writing tests for it.
831
+ - HTML only. There is no `svg`/`mathml` equivalent yet.
832
+
833
+ <!--size:tag.gzip-->1.94 KB<!--/size:tag.gzip--> gzipped, which includes `/spread` — the factory
834
+ needs it to apply props whose names it cannot know. Additive, like `/spread` and unlike the other
835
+ entries: it inlines no renderer internals, so it is safe alongside any of them.
836
+
837
+ This entry also exports `jsxName` and `BOOLEAN_ATTRIBUTES`, **which are not API for applications.**
838
+ They are the table this entry uses to map React's names, and `@verajs/jsx` carries its own copy
839
+ deliberately — the two are build-time and runtime, and a shared package would be a dependency where
840
+ a test does the job. `tests/jsx-name-mapping.test.mjs` asserts the two agree on every key, and it can
841
+ only do that against the built artifact, which is why they are exported at all. Read them if you are
842
+ writing something that has to agree with both; do not build on them.
843
+
844
+ ## Extending it — `_$apply$` and `_$child$`
845
+
846
+ The renderer holds no directive system. It holds a **protocol**, at the two positions worth
847
+ extending, and everything built on it is an ordinary package the renderer knows nothing about —
848
+ `@verajs/renderer/spread` is the proof, at 5 B of protocol in this bundle and its own weight only
849
+ for apps that import it.
850
+
851
+ | position | brand | called as |
852
+ | --- | --- | --- |
853
+ | element — `<div ${value}>` | `_$apply$` | `value._$apply$(element, part)` |
854
+ | child — `<div>${value}</div>` | `_$child$` | `value._$child$(part, previous)` |
855
+
856
+ A child-position value carrying `_$child$` applies itself. It is handed the part and whatever it
857
+ returned last time **at that part**, and calls `part._$commit$(value)` to render content. That is
858
+ the whole surface: `until()` is nine lines against it.
859
+
860
+ ```js
861
+ /** Hoisted — the applier's identity is its own continuity key. */
862
+ function applyUntil(part, previous) {
863
+ if (previous && previous.promise === this.promise) return previous;
864
+ if (previous) previous.live = false;
865
+ const state = { promise: this.promise, live: true };
866
+ part._$commit$(this.placeholder);
867
+ this.promise.then((value) => { if (state.live) part._$commit$(value); });
868
+ return state;
869
+ }
870
+ const until = (promise, placeholder) => ({ _$child$: applyUntil, promise, placeholder });
871
+
872
+ renderInto(html`<p>${until(fetchUser(), html`<em>loading…</em>`)}</p>`, host);
873
+ ```
874
+
875
+ Three rules, each of which is a real trap:
876
+
877
+ - **Hoist the applier.** Written as an object-literal method it is a new function per call, so the
878
+ part can never recognise it and `previous` is always `undefined`. Its identity is what keeps two
879
+ appliers at one part from reading each other's state.
880
+ - **Continuity lives in the return value**, not in an applier instance. That is what makes this a
881
+ protocol rather than a framework — no base class, no `directive()` factory, no lifecycle.
882
+ - **Teardown is opt-in, on the applier.** `applyThing._$detach$ = (previous) => …` is called with
883
+ whatever the applier last returned, when the subtree holding it is removed — replaced, dropped
884
+ from a keyed list, or shrunk out of an unkeyed one. Declaring it is what arms the walk; an applier
885
+ that does not declare it costs nothing, and neither does an app with no such applier anywhere.
886
+
887
+ It **notifies, it does not defer**. The nodes are already going. To hold content on screen while it
888
+ animates out, do not remove it: an applier owns what it commits, so it can simply not commit the
889
+ removal until it is ready — see *Deferring a removal* below.
890
+ - **Why declaring `_$detach$` is what arms it:** `_clear` bulk-removes DOM — when the part owns
891
+ its parent, one `parent.textContent = ''`, which is what makes clearing a 1 000-row table ~5 ms
892
+ against lit-html's ~22 ms. Notifying nested appliers means walking the part tree on removal,
893
+ which is exactly the per-node work that fast path exists to skip — so the walk runs only once
894
+ something, anywhere, has declared teardown, and an app with none pays nothing.
895
+
896
+ ### Deferring a removal
897
+
898
+ An applier owns the content it commits, so an exit animation needs nothing from the renderer — it
899
+ just does not commit the removal until the animation has finished:
900
+
901
+ ```js
902
+ function applyTransition(part, previous) {
903
+ const next = this.value;
904
+ const state = previous ?? { shown: undefined, timer: null };
905
+ if (next != null) { part._$commit$(next); state.shown = next; return state; }
906
+ if (state.shown != null && state.timer === null)
907
+ state.timer = setTimeout(() => { state.timer = null; part._$commit$(null); }, 300);
908
+ return state;
909
+ }
910
+ const transition = (value) => ({ _$child$: applyTransition, value });
911
+ ```
912
+
913
+ This works for a child position and for a whole list committed as one value. It does **not** work for
914
+ one row inside a keyed list: that row's removal is decided by the reconciler, and nothing inside it
915
+ is asked.
916
+
917
+ Both names survive minification by construction: the renderer mangles `/^_[a-z]/`, and `_$…$` does
918
+ not match it. `tests/minification-contracts.test.mjs` holds that.
919
+
920
+ The check costs the hot path nothing: it sits after the template branch, and a template — the
921
+ common object at a child position — returns before ever reading it, so only arrays, nodes and
922
+ appliers pay a property read. Measured with no runtime difference distinguishable from noise.
923
+
924
+ The whole protocol is **116 B gzipped** — the check, the two fields holding an applier's state and
925
+ whose it is, the save/restore in `_$commit$` that stops an applier's own rendering from destroying
926
+ its continuity, and the `_$detach$` call. It was 94 B before teardown existed.
927
+
928
+ ## Animating things in and out
929
+
930
+ There is no transition component, and none is needed — but the shapes are worth knowing, because
931
+ one of the obvious ones does not work in every engine.
932
+
933
+ **Fading on `?hidden`.** The framework's own advice is to prefer a stable shape with `?hidden=${…}`
934
+ over swapping subtrees, and that is also what makes an exit transition possible: the element is
935
+ still there to animate.
936
+
937
+ ```css
938
+ .fade { opacity: 1; transition: opacity 200ms; }
939
+ .fade[hidden] { display: block; opacity: 0; pointer-events: none; }
940
+ ```
941
+
942
+ The `display: block` is load-bearing — it overrides the user agent's `[hidden] { display: none }`,
943
+ which would otherwise remove the element from rendering instantly with nothing to fade.
944
+
945
+ **Do not reach for `transition-behavior: allow-discrete` on `display` for this.** Measured
946
+ 2026-08-24 across all three engines, transitioning `display` with `allow-discrete`: Chromium and
947
+ WebKit fade correctly, **Firefox jumps straight to `display: none`** and no transition runs. All
948
+ three report `CSS.supports('transition-behavior', 'allow-discrete')` as `true`, so the feature test
949
+ does not tell you. The opacity-only shape above behaves identically in all three.
950
+
951
+ **Animating a removal**, where the element really does leave the render, is the browser's job:
952
+
953
+ ```js
954
+ const flushSync = (fn) => {
955
+ const previous = setRenderScheduler((run) => run());
956
+ try { fn(); } finally { setRenderScheduler(previous); }
957
+ };
958
+
959
+ document.startViewTransition(() => flushSync(() => { state.rows = next; }));
960
+ ```
961
+
962
+ The View Transitions API snapshots the DOM around the callback and cross-fades, so a row that
963
+ disappears fades out and the rows below animate up. `startViewTransition` is present in Chromium,
964
+ Firefox and WebKit. Two things it needs: the state change must happen **inside** the callback —
965
+ which is what `flushSync` is for, since a render deferred to the next frame lands after the snapshot
966
+ — and each row needs its own `view-transition-name`, or the whole page cross-fades as one image.
967
+
968
+ **Or keep it in state.** Mark the row `leaving`, animate, then drop it. Vue's `<Transition>` is
969
+ sugar over exactly this, and it is the only one of the three that gives you a completion callback.
970
+
971
+ ## Absent on purpose
972
+
973
+ Directives other renderers ship, and what replaces them here.
974
+
975
+ | Elsewhere | Here |
976
+ | --- | --- |
977
+ | `repeat()` | `keyed()` |
978
+ | `cache()` | `hold()` |
979
+ | `ref()` | an element-position expression, `<input ${myRef}>` |
980
+ | `ifDefined()` | built in — `null`/`undefined` remove an attribute |
981
+ | `classMap()` / `styleMap()` | build the string: `class="base ${extra}"` |
982
+ | `guard()` | reactivity already skips unchanged work |
983
+ | `until()`, `asyncReplace()` | render a loading state and re-render from an effect — or nine lines against [`_$child$`](#extending-it--apply-and-child) |
984
+ | `unsafeHTML()` | `.innerHTML=${trusted}`, above |
985
+ | `literal()` / `static-html` | [`/tag`](#verajsrenderertag) — and a tag doubles as a JSX component |
986
+ | `live()` | [`!name`](#name--a-live-property) — a sigil, for the case that needs it |
987
+
988
+ ## Types
989
+
990
+ `TemplateResult` is exported for annotating what a template function returns. The rest of the
991
+ surface is inferred.
992
+
993
+ ## For AI assistants — and anyone who wants the whole API on one page
994
+
995
+ The repository root's [`llms.txt`](../../llms.txt) is the complete, hand-maintained API
996
+ reference for every package, written to be pasted into a model's context window: full export
997
+ tables, the buildless CDN and JSX recipes, semantics that differ from other frameworks, and the
998
+ mistakes that come up most. Its recipes are executed by the test suite, so they stay honest.
999
+
1000
+ ## License
1001
+
1002
+ MIT