@tschk/moonshine-dom 0.0.0-stage → 0.4.49

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.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 The Software Company of Hong Kong
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,468 @@
1
- # Temporary Holding Version
1
+ # `@tschk/moonshine-dom`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Independent Moonshine browser and server rendering. The only runtime dependency
4
+ is the signal kernel; this package has no React, Solid or parser dependency.
5
+
6
+ ```ts
7
+ import { h, render } from "@tschk/moonshine-dom";
8
+ import { createSignal } from "@tschk/moonshine-dom/reactive";
9
+
10
+ const dispose = render(() => {
11
+ const [count, setCount] = createSignal(0);
12
+ return h("button", { onClick: () => setCount(count() + 1) }, count);
13
+ }, document.getElementById("app")!);
14
+ ```
15
+
16
+ The browser factory `hNS(namespace, tag, props, ...children)` takes an explicit
17
+ namespace URI string. HTML, SVG and MathML literals retain their known element
18
+ types; custom URIs return `Element`. An empty URI creates a null-namespace node.
19
+ Authored `xmlns` stays an ordinary attribute and does not override this choice.
20
+ Pass each child's lexical namespace explicitly when using compiler-owned trees.
21
+ Non-string namespaces fail at the boundary; URI/tag validity follows the browser's
22
+ `createElementNS` behavior.
23
+
24
+ The compiler-facing `hSourceNS(namespace, tag, props, ...children)` also accepts
25
+ runtime namespace values. Nullish values select HTML; other values reach the
26
+ browser unchanged for DOMString conversion and native namespace errors. Ordinary
27
+ `h` keeps its existing string conversion, and `hNS` keeps its string-only guard.
28
+
29
+ - `/reactive`: signals, memos, owned computations, cleanup and batching.
30
+ `on(accessor, callback, { defer: true })` limits an effect or memo to explicit
31
+ dependencies and skips its first callback. An array of accessors supplies a
32
+ tuple of values. The callback receives current inputs, previous inputs and its
33
+ previous result; incidental callback reads do not subscribe. Omit `defer` to
34
+ run on the first evaluation. The same helper is available on `/ssr`.
35
+ - `/html`: opt-in, unsanitized markup. `rawHTML(read, namespace?)` returns an
36
+ accessor of cached nodes for ordinary `h` children; namespace is `html`, `svg`,
37
+ or `mathml`. `htmlContent(element, read)` requires a live owner and controls a
38
+ fresh element's entire sole-child contents (including cleanup); initialize it
39
+ from an `h` ref callback without ordinary children. It preserves contextual
40
+ table/SVG parsing. Identical raw values retain nodes; changed values replace
41
+ them. Both helpers assign directly to `innerHTML`, including TrustedHTML.
42
+ SSR's separate `rawHTML(value)` export from `/ssr` emits unescaped markup.
43
+ These helpers are not sanitizers: inline handlers and other active content
44
+ remain active, although inserted scripts are inert in the browser. Inject only
45
+ trusted content. Injected markup is not compiled into components or bindings;
46
+ this provides no hydration behavior. Default native children remain escaped.
47
+ - `/custom-element`: optional `setCustomElementValue(node, name, value)` preserves
48
+ literal object/function values for registered custom-element setters. Compiler
49
+ effects evaluate expressions before calling it; setters run without tracking or
50
+ an owner. Hyphenated HTML elements only; events use ordinary event listeners.
51
+ Missing setters use string attributes, nullish values remove attributes, and
52
+ unregistered elements receive nonnull objects as properties (upgrade does not
53
+ replay setters). HTML-content/prototype names and style always remain literal
54
+ attributes. This opt-in boundary rejects event names and preserves the ordinary
55
+ `h` contract; it does not supply SSR serialization or hydration.
56
+ - `/component`: per-instance setup scopes, inherited context and an explicit
57
+ component-event listener symbol. Both `h(Component, props)` factories enter an
58
+ attached, untracked scope and preserve live prop descriptors. Context APIs are
59
+ initialization-only; detached control-flow roots inherit context without
60
+ changing their explicit disposal contract. Render roots through `h` to enter
61
+ the component scope. Context-map snapshots do not provide a legacy vnode ABI.
62
+ - `/component-instance`: compiler-facing named exports and captured-path references.
63
+ `exposeComponent(exports)` preserves own descriptors in an opaque instance;
64
+ `componentRef` props carry `{ get, set }`. References publish after setup and
65
+ clear to `null` in a later microtask, only if they still refer to that instance.
66
+ References may opt into `cleanup: "commit"` for Svelte 5.57 teardown timing:
67
+ child and ancestor cleanup can still read the instance, then it clears after
68
+ the complete native cleanup commit and before the outer disposer returns.
69
+ The Svelte lifecycle queue publishes pending references before mount/effect
70
+ callbacks by default. `publication: "post"` requires an active rune scheduler
71
+ and queues publication at the registration point among child lifecycle posts,
72
+ before ancestor posts. Register exposure after child effects/mounts when those
73
+ callbacks must precede publication. SSR creates no reference callbacks. Dynamic paths may supply
74
+ `{ parts: () => tuple, get: (...parts) => value, set: (value, ...parts) => {} }`.
75
+ Only parts are tracked, after setup during reference publication. Path changes
76
+ publish the new target before clearing the old captured target if it still holds
77
+ that instance; disposal clears the last captured path using the chosen timing. Cell
78
+ getters/setters are untracked. Publication drains at most 1,000 successive feedback
79
+ waves per flush; independent references in one wave are not capped.
80
+ `ComponentReference<T, readonly [Key, Index]>`
81
+ preserves typed tuple arguments and requires parts for nonempty tuples;
82
+ `ComponentReference<T>` retains the fixed-cell contract. `enqueueComponentReference`
83
+ schedules owned element/component reference callbacks into the shared flush wave.
84
+ SFC `bind:this` now has bounded scalar/member source acceptance, including empty exports; loop-dependent path extraction remains compiler work.
85
+ - `/ssr-owner`: lightweight `scopeSSRChild(child)` captures a live owner for the
86
+ complete serialization of deferred children. It is also exported by `/ssr`.
87
+ It preserves request context, select state, SVG namespace and text escaping;
88
+ serializing it after owner disposal throws. This entry lets browser provider
89
+ modules support SSR without importing the serializer into browser bundles.
90
+ `isSSRRendering()` detects the synchronous serialization extent, including
91
+ bare callbacks and cleanup; it does not propagate across async continuations.
92
+ - `/render-scheduler`: internal opt-in carrier contract for native render effects,
93
+ structural memos and component/control ownership. The Svelte `/pre` module owns
94
+ the scheduling implementation. Ordinary native rendering stays synchronous;
95
+ the signal kernel has no scheduler dependency.
96
+ - `/resource`: owned client data fetching, separate from the kernel's resource API.
97
+ - `/resource/ssr`: synchronous server snapshots that never invoke fetchers.
98
+ - `/control`: keyed `For`/`mapArray`, position-stable `Index`/`indexArray`, and
99
+ retained `Show` branches with explicit accessors. `Index({ each, children })`
100
+ calls `children(itemAccessor, indexNumber)` once per position; replacement and
101
+ reorder update `itemAccessor()` while preserving that position's DOM and owner.
102
+ Use it for editable primitive lists; keyed `For` follows item identity instead.
103
+ Removed tail positions dispose their owners; appended positions get new owners.
104
+ `Switch({ children: () => matches, fallback })` retains the first truthy
105
+ `Match({ when: accessor, children: valueAccessor => child })`. Conditions are
106
+ checked in order; inactive branches create no contents and selected branches
107
+ retain their owner until selection changes.
108
+ - `/dom` (also the root): direct DOM factories, reactive children/attributes,
109
+ events, refs, form defaults, SVG and bounded style objects.
110
+ - `/ssr`: escaped HTML factories and server lifecycle hooks.
111
+ `boundary(render, fallback)` buffers synchronous serialization, discards failed
112
+ output and internal scopes, then serializes the fallback in a fresh scope.
113
+ Deferred children, arrays, select bookkeeping and SVG context are covered.
114
+ Accepted scopes live until request cleanup; discarded Svelte destruction hooks
115
+ are suppressed. Factories can be created ahead of time and reused: ownership
116
+ and context come from the current serializer. Fallback failures reach an outer
117
+ boundary. Arbitrary state writes and `afterRender` commits are not rolled back.
118
+ Externally captured `scopeSSRChild` values retain their lexical owner and error
119
+ policy; an error already swallowed there cannot reach this boundary. This is a
120
+ native serialization API, with no async, reset, hydration or SFC boundary ABI.
121
+ - `/head`: owned browser head declarations. `head(() => children)` adds only its
122
+ owner's nodes; cleanup removes them. `title(() => text)` updates the document
123
+ title and leaves the last title in place when its owner is disposed.
124
+ - `/head-ssr`: synchronous `renderWithHead(() => child)` returns `{ body, head }`.
125
+ Use this entry's `head` and `title` functions inside that render scope. Ordinary
126
+ meta tags retain declaration order and duplicates. Within a head scope the first
127
+ accepted title wins; later head scopes can override it. Request and boundary
128
+ ownership are preserved. The framework renderer collects component head output
129
+ automatically; component titles override route metadata's fallback title.
130
+ - `/framework-native`: the bundled framework renderer; requires the optional
131
+ `@tschk/moonshine-framework` peer. Supports Bun, Node and Cloudflare SSR, static-mode rendering and
132
+ fresh SPA mounts with separate authored client entries.
133
+ - `/framework-source`: source-file SSR compatibility for Bun/Node, shared by
134
+ the Solid and Svelte replacements. It imports page/layout files on demand;
135
+ deployed bundles use `/framework-native` with their bundled module inventory.
136
+
137
+ If a root callback throws, its owned work is disposed before deferred effects start,
138
+ and the original callback error is rethrown even if cleanup fails.
139
+
140
+ Native SSR layouts initialize around lazy page children, so context providers
141
+ reach their descendants. Explicit `/ssr` `defer(() => child)` retains the live component owner;
142
+ reused factories attach to the current request after that owner is disposed.
143
+ Ordinary accessor children and attributes keep their eager construction snapshot.
144
+
145
+ Source parsing and lowering belong in Crepuscularity. These APIs do not implement
146
+ Solid's compiled instructions. Hydration, islands and async server components
147
+ are unsupported. Raw HTML uses the explicit `/html` entry. Property-only state can use refs. Style objects use
148
+ hyphenated CSS names and explicit units; complex declarations use CSS strings.
149
+ SSR cannot encode distinct live and reset values for a form control. Ambiguous
150
+ SVG tags need an accessor parent context or an explicit namespace.
151
+
152
+ See [the native example](../../examples/native-app/README.md),
153
+ [compiled TSX components](../../examples/native-template/README.md),
154
+ [compiler limits](../compiler/README.md), and [the design](../../DESIGN.md).
155
+ For reproducible scoped comparisons, run `bun scripts/benchmark-reactive.ts`,
156
+ `bun scripts/benchmark-ssr.ts`, or the browser `bun scripts/benchmark-dom.ts` from
157
+ the repository root. Current fixtures have smaller Moonshine bundles but slower
158
+ rendering than Solid; these are not complete framework comparisons.
159
+ For the authored counter comparison against React, run
160
+ `CREPUS_COMPILER=/path/to/crepus bun scripts/benchmark-counter.ts`. It checks
161
+ identical SSR markup and serial DOM commits, reports compressed bundle sizes,
162
+ and records versions and source hashes. Fresh-document startup measures from
163
+ before localhost module fetch through complete DOM commit, with HTTP caching
164
+ disabled, alternating order, five warmups and 25 recorded loads per runtime.
165
+ The browser/process stays warm; document navigation, paint, remote network and
166
+ hydration are excluded. This is one counter workload, not a framework ranking.
167
+ For the exact same authored two-component SFC counter against installed Svelte,
168
+ run `CREPUS_COMPILER=/path/to/crepus bun scripts/benchmark-sfc-counter.ts`.
169
+ It snapshots the compiler and native packages, fingerprints sources/artifacts,
170
+ compares production gzip/Brotli sizes and checks five clicks plus retained child
171
+ identity in Chromium. It also alternates five warmups and 25 fresh-document
172
+ startup samples per framework, plus 625 serial click-to-DOM-commit observations.
173
+ The browser/process stays warm and local responses disable caching. In-page
174
+ clocks exclude RPC time; startup includes localhost module fetch and evaluation.
175
+ Timer resolution can produce zero click medians, which do not mean free work.
176
+ A separate warm Bun process also measures fresh synchronous SSR from those same
177
+ authored components: five discarded warmups, 25 alternating samples of 5,000
178
+ renders, exact repeated markup and visible HTML equality after removing only
179
+ hydration comments. It reports SSR bundle sizes, median/p95 and raw samples in
180
+ the same fingerprinted result. Navigation, paint, cold startup, async data, remote
181
+ network and hydration are excluded. These results cover one workload, not a
182
+ framework ranking.
183
+
184
+ Events accept functions or native listener objects with `handleEvent(event)`.
185
+ Listener objects may include `capture`, `once`, `passive` and `signal` options;
186
+ `this` inside `handleEvent` is the listener object. For example,
187
+ `h("div", { "on:click": { capture: true, handleEvent(event) {} } })` registers
188
+ capture before bubbling handlers. `on:eventName` preserves event name case;
189
+ `onClick` continues to register `click`. Options are captured at registration,
190
+ and owner disposal removes the registered listener. SSR omits event props.
191
+
192
+ DOM lifecycle updates use setters and `batch` from `/reactive`: mount callbacks
193
+ run after the synchronous DOM updates finish. Wrap external kernel signal or store
194
+ writes in this native `batch` too, so newly inserted components mount after commit.
195
+
196
+ For authored TSX source checking, opt in with a declaration file containing
197
+ `import type {} from "@tschk/moonshine-dom/jsx-types";` and TypeScript options
198
+ `"jsx": "preserve", "noEmit": true`. Include that declaration and the source TSX
199
+ in a native-only tsconfig. This supplies no executable JSX runtime: compile source
200
+ with Crepus before running it. Keep React source in a separate config because this
201
+ opt-in namespace describes native components.
202
+
203
+ The types check component props, children, and known HTML/SVG tag names. Intrinsic
204
+ props match `h`'s unrestricted records; attribute names, attribute values, and event
205
+ parameter types are not checked or inferred.
206
+
207
+ `unwrap` on `/store` returns the original store object without subscribing.
208
+ Ordinary object/array containers unwrap embedded proxies in place; frozen
209
+ containers are copied. Mutable object getters are skipped; frozen copies
210
+ evaluate their enumerable getters.
211
+ Raw mutations bypass notifications; opaque instances remain unchanged.
212
+
213
+ Optional structured state lives on `/store`, using the native reactive graph:
214
+
215
+ ```ts
216
+ import { createStore, produce, reconcile } from "@tschk/moonshine-dom/store";
217
+
218
+ const [state, setState] = createStore({ user: { name: "Ada" }, visits: 0 });
219
+ setState("user", "name", "Grace");
220
+ setState(
221
+ produce((draft) => {
222
+ draft.visits++;
223
+ }),
224
+ );
225
+ setState(reconcile({ user: { name: "Lin" }, visits: 3 }));
226
+ ```
227
+
228
+ Property reads, membership checks and key enumeration subscribe independently.
229
+ Public proxies are read-only; setters batch writes through native `/reactive`.
230
+ Path setters support key arrays and array predicates/ranges. Object updates
231
+ shallow-merge; `undefined` deletes a property. `produce` supplies writable drafts;
232
+ `reconcile` replaces snapshots while retaining matching array items by `id`
233
+ (or a supplied key), with `key: null` and `merge` options.
234
+
235
+ Plain objects and arrays retain their input identity. Use setters for tracked
236
+ changes; external mutations of the original object do not notify observers.
237
+ Class instances and other non-plain values are opaque references; their own
238
+ mutations do not notify observers.
239
+ Frozen/nonextensible objects, descriptor/prototype mutation and unsafe prototype
240
+ paths reject explicitly. Deep setter paths have broad TypeScript types. The
241
+ kernel's `createStore` retains its callback-mutation API. The Solid replacement's
242
+ `/store` uses this same native graph; a separately installed Solid runtime does
243
+ not observe it.
244
+
245
+ Client resources use the same native graph:
246
+
247
+ ```ts
248
+ import { createResource } from "@tschk/moonshine-dom/resource";
249
+
250
+ const [user, { mutate, refetch }] = createResource(userId, async (id) =>
251
+ (await fetch(`/api/users/${id}`)).json(),
252
+ );
253
+ // user() reads the value; user.loading, user.error and user.state are reactive.
254
+ // mutate(nextValue) edits locally; refetch(info) fetches the current source again.
255
+ ```
256
+
257
+ Create resources inside an owned root or rendered component. A source accessor
258
+ refetches when its value changes; `false`, `null` and `undefined` disable fetching.
259
+ Fetchers receive the source plus `{ value, refetching }` and may return a value or
260
+ promise. Only the newest request publishes; disposal ignores later results.
261
+ This does not cancel the underlying operation. `mutate` changes only the value;
262
+ an active request may overwrite it. Reads throw terminal fetch errors. The
263
+ `latest` getter retains the previous value while refreshing. State is one of
264
+ `unresolved`, `pending`, `ready`, `refreshing` or `errored`.
265
+ Each explicit `refetch` starts a request; calls within one microtask are not
266
+ coalesced. Fetcher cleanup callbacks retain the resource's owner on refetch.
267
+
268
+ Options support `initialValue` and an informational `name`; other options reject.
269
+ This client API rejects use during native SSR and does not implement Suspense,
270
+ transitions, hydration or async SSR. The local unpublished Solid compiler bridge
271
+ admits it with explicit Solid source provenance. The Solid replacement's `/solid`
272
+ export uses this client resource API; the kernel resource API keeps its contract.
273
+
274
+ `/resource/ssr` provides independent synchronous server resources. Creation needs
275
+ an active native SSR render or server component context. The fetcher never runs;
276
+ use `initialValue` for request-loaded data. State stays `ready` when that option
277
+ is present (including inherited/undefined values), or `unresolved` otherwise.
278
+ Loading is the source's boolean truthiness, so zero/empty string disable it.
279
+ Server `refetch()` re-reads the source and returns loading; server `mutate(value)`
280
+ stores values and functions literally without changing metadata. Reads/actions
281
+ retain plain closure state after render. Only `initialValue`/`name` are supported;
282
+ there is no async SSR, Suspense, hydration or client payload transfer.
283
+
284
+ ### Optional input bindings
285
+
286
+ `@tschk/moonshine-dom/binding` exports `bindValue(element, read, write)`. Call it
287
+ under a live owner after constructing a text/number/range, date, datetime-local,
288
+ month, week, time or color input, or textarea, and
289
+ installing its attributes and user event listeners. It synchronizes parent writes,
290
+ input events and uncancelled form resets, including externally associated forms.
291
+ Undefined/null initial state adopts an existing nonempty DOM value; number/range
292
+ events produce numbers, with empty/invalid numbers producing `undefined`. Other
293
+ accepted types write strings. Browser sanitization stays native: parent model
294
+ values are not replaced by sanitized DOM values, and resets forward raw defaults. Disposal
295
+ removes listeners and suppresses pending reset work. Keep the input type fixed
296
+ for the binding lifetime. Reset synchronization requires a form connected to the
297
+ control's owner document; detached forms are outside this contract. This optional primitive
298
+ does not implement hydration or SFC parsing/lowering.
299
+
300
+ `bindChecked(checkbox, read, write)` uses the same owner/reset contract with the
301
+ `change` event. Nullish initial state adopts `checked` (including false), while
302
+ explicit state overrides `defaultChecked`. Parent writes update checked state;
303
+ uncancelled resets synchronize its default back to state. Install user change
304
+ listeners before the binding. Keep the type fixed to checkbox.
305
+
306
+ `bindSelectValue(select, read, write)` supports single/multiple selects and owns
307
+ its change/reset listeners and option MutationObserver. Single values match by
308
+ `Object.is`; multiple values use array membership. Undefined initial state adopts
309
+ the DOM selection (all selected values as an array for multiple). Explicit null
310
+ selects a typed null option if present, otherwise clears a single select; multiple nullish values preserve selection. Invalid
311
+ nonarray multiple values throw. Option changes reapply the model without writing
312
+ a new model value. Keep `multiple` fixed for the binding lifetime.
313
+
314
+ For typed primitive/object option values, call `setOptionValue(option, value)`
315
+ after constructing each option; identity is preserved in a private WeakMap and
316
+ updates refresh its bound select even when their DOM strings are equal. Ordinary
317
+ `h("option", { value })` retains string semantics. The compiler must emit this
318
+ explicit hook and keep SSR serialization separate; this is not hydration.
319
+
320
+ The SSR factory exports optional `selectBinding` and `optionBinding` symbols for
321
+ compiler-created typed selections: `h("select", { [selectBinding]: { value } },
322
+ h("option", { [optionBinding]: { value: option } }, label))`. These boxes carry
323
+ literal values, including functions, without calling them. Options serialize
324
+ their value once with HTML escaping; nullish/function values omit the attribute.
325
+ Single selections compare raw values with `===`; multiple arrays use `includes`,
326
+ matching Svelte 5.57 SSR. All matching options receive `selected`; an unmatched
327
+ typed selection is allowed. Ordinary string select behavior stays unchanged.
328
+ For compiled source, a select box may also set `preserveSelected: true` to keep
329
+ authored option selection flags alongside binding matches. The optional flag must
330
+ be an own boolean data property; ordinary native boxes retain override behavior.
331
+ With `hSource`, an ordinary option `value` slot preserves attribute placement
332
+ without reading its overridden value/getter. The boxed value still determines
333
+ serialization and comparison identity.
334
+ These symbols provide SSR output, not hydration or client identity transport.
335
+
336
+ Compiler emitters can use `hSourceEntries(tag, entries, ...children)` from `/ssr`
337
+ when ordered source attributes include repeated names. Entries are `[name, value]`
338
+ pairs; function values are lazy readers, evaluated and serialized in entry order.
339
+ The existing source codec, escaping, validation and client-only attribute suppression
340
+ apply. This is attribute serialization; it does not implement group bindings.
341
+
342
+ Intentional reference difference: Chromium probes of Svelte 5.46.4 and cached
343
+ 5.57.1 initialize an undefined
344
+ multiple-select binding to only the first selected scalar. Native bindings adopt
345
+ all selected values as an array, consistent with the multiple-value contract.
346
+ This is a measured difference for those versions, not a claim about all Svelte versions.
347
+
348
+ Native lifecycle adapters can register `onBeforeDispose` and `onAfterDispose`
349
+ from `/reactive`. Before callbacks run parent-first while owned work is live;
350
+ after callbacks run child-first after outer cleanup, DOM removal and the current
351
+ native commit. These are final-disposal hooks, not computation-rerun hooks.
352
+ Disposal drains callbacks, children, cleanups and stops while preserving the first
353
+ error, including reentrant disposal. Before-disposal callbacks may register
354
+ `onAfterDispose` callbacks on their still-live owner; registering another
355
+ `onBeforeDispose` callback during disposal is rejected. Both registrations reject
356
+ ownerless or already disposed scopes.
357
+
358
+ `queuePostCommit` uses the existing native commit queue, or a microtask outside a
359
+ commit; generic callbacks must manage their own cancellation. `/component` also
360
+ provides `onComponentReady` during setup, fired once after successful setup with
361
+ the frame inactive. Failed or already disposed instances do not become ready.
362
+
363
+ `createInputGroup(kind, read, write)` returns `{ bind(input, watch?) }` for radio or
364
+ checkbox groups. Create each token under a live owner, then bind inputs under
365
+ their own live row/component owners after attributes and user change handlers.
366
+ When an optional `watch` callback is passed to `bind(input, watch)`, the member's
367
+ render effect invokes `watch()` before reading the group model so authored dynamic
368
+ `value={expr}` attributes on spread inputs trigger group selection updates.
369
+ Token disposal releases every member; row disposal unregisters only that member.
370
+ The compiler allocates tokens per binding target/component and nested each path;
371
+ there is no global name lookup or runtime ownership guessing. Browser HTML `name`
372
+ grouping still applies independently. Keep input types fixed.
373
+ Use `createInputGroup("mixed", read, write)` when one target intentionally combines
374
+ radio and checkbox members. Selection follows each input's fixed type; checkbox
375
+ writes collect checked values from every member, including radio payloads.
376
+
377
+ `setInputValue(input, value, notify = true)` stores typed group values privately and refreshes
378
+ selection on value changes when `notify` is true. Passing `notify = false` (used by
379
+ bound spread elements) updates the stored and DOM value without immediately
380
+ re-running the group member's checked effect. Ordinary inputs retain string values without this
381
+ hook. Checkbox models must be arrays or nullish; other values reject. Radios use
382
+ `Object.is` on native identities (no Svelte proxy unwrapping); checkbox membership uses array inclusion and change
383
+ collection deduplicates values in current DOM order. Unchecking a duplicate value
384
+ removes that value from the group. Removing a member preserves model state until
385
+ a subsequent change; value changes reapply the model without writing it back.
386
+
387
+ Pinned Svelte 5.46.4 Chromium behavior (also present in 5.57.1 source): group
388
+ undefined state does not adopt checked defaults; radio resets write `null` and
389
+ checkbox resets write `[]`. This differs from standalone `bindChecked` default
390
+ adoption. Native groups follow that protocol, respect cancelled connected-form
391
+ resets and suppress pending work after disposal. No SSR group serialization,
392
+ hydration, cross-component grouping or SFC lowering is claimed by these helpers.
393
+
394
+ New attached scopes reject disposed owners, including work created by post-disposal
395
+ callbacks. Explicit detached roots remain independent and require their own stop.
396
+
397
+ Both `bindSelectValue(select, read, write, equal?)` and
398
+ `createInputGroup(kind, read, write, equal?)` accept an optional final equality
399
+ predicate, defaulting to `Object.is`. It applies only to single selects and radio
400
+ groups; multiple selects and checkbox groups retain array membership semantics.
401
+ This lets compiler adapters normalize their own raw/proxy identities without
402
+ importing a source-language runtime into DOM. Stored values and change payloads
403
+ keep the original typed identity; equality never substitutes a normalized value.
404
+
405
+ Value-binding resets copy raw `defaultValue` into the model before numeric
406
+ conversion. The browser may clamp or sanitize its live value independently: an
407
+ empty range default yields native model `undefined` with a browser value of 50;
408
+ a range default 5 below minimum 10 yields model 5 with browser value 10. Empty
409
+ or invalid numeric defaults remain `undefined`. Svelte's adapter can translate
410
+ empty native numeric values to its version-specific null convention; invalid raw
411
+ numeric defaults still differ from Svelte 5.46.4/5.57.1's NaN conversion.
412
+
413
+ `bindValue` write callbacks may accept optional second argument `reset?: true`.
414
+ Only form-reset writes receive it; normal input and initial adoption call the
415
+ setter with one argument. Compiler adapters can use this metadata to translate
416
+ source-specific numeric reset conventions without adding listeners or changing
417
+ the generic native empty/invalid-to-undefined contract. Existing one-argument
418
+ setters remain compatible.
419
+
420
+ `bindOpen(details, read, write)` controls a details element's `open` property.
421
+ Install it after user `toggle` listeners under a live native owner. Nullish state
422
+ closes the element without adopting its initial DOM state. Native toggle events
423
+ write the boolean property after user listeners; browser coalescing is preserved.
424
+ It has no form-reset behavior. Cleanup removes the binding listener, including
425
+ queued events and retained detached nodes (unlike the audited Svelte 5.57 listener).
426
+ SSR uses the ordinary boolean `open` attribute snapshot. The Svelte `/binding`
427
+ entry re-exports this helper. The unpublished local Crepus compiler now lowers
428
+ bounded authored `bind:open`; see the Svelte adapter's source-support limits.
429
+
430
+ `/store`'s `createMutable(value, { equals })` can select property-write equality.
431
+ The default is strict equality (`===`); the optional comparator receives the
432
+ previous and next values. Nested mutable views and accessor setter receivers
433
+ retain that policy, and raw-object views are cached separately per comparator
434
+ function. The Vue adapter supplies `Object.is` for signed-zero/NaN behavior.
435
+
436
+ ## Optional rotating text
437
+
438
+ `@tschk/moonshine-dom/rotating-text` exports `createRotatingText(phrases, intervalMs)`.
439
+ Its text accessor advances inside a live render owner and stops when that owner
440
+ is disposed. Reduced motion keeps the first phrase; changing the preference
441
+ pauses or resumes rotation. Empty and single-phrase inputs create no timers.
442
+ The helper is separate from the DOM root and signal-only exports.
443
+
444
+ ## Compiler-owned template blocks
445
+
446
+ The `/dom` entry exposes `templateBlock(build)` for compiler-owned node trees.
447
+ It detaches a block before disposal callbacks while preserving its descendant
448
+ DOM for those callbacks; effects, listeners and owned ranges still stop. Pass
449
+ the supplied retention predicate to compiler-created insertion ranges. Nested
450
+ `h()` children and insertion ranges inherit the containing block policy; an
451
+ explicit range predicate overrides it. Cleanup still stops their reactive work
452
+ and listeners.
453
+
454
+ Compiler-owned control ranges can pass an explicit scheduling function to
455
+ `Show`, `For`, `mapArray` (fourth argument), or `indexArray`. Passing `read => read`
456
+ keeps reconciliation inside the containing range pull. The default scheduler and
457
+ `mapArray`'s third deferred-removal argument retain their existing behavior.
458
+
459
+ `setAttributeValue` exposes the existing native attribute setter for typed node
460
+ updates. It does not install event handlers or replace form-binding helpers.
461
+ These primitives do not by themselves implement Svelte directive source syntax.
462
+
463
+ `bindFiles(input, read, write)` on the optional `/binding` entry binds a static
464
+ file input's `FileList`. It requires a live native owner, writes the selected
465
+ list on `change` and after uncancelled connected-form resets, and removes its
466
+ listeners on disposal. A nullish model neither adopts nor clears the input;
467
+ write an empty `FileList` (for example `new DataTransfer().files`) to clear it.
468
+ File contents are not read or uploaded. Browser assignment rules apply.
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-dom",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.49",
4
+ "description": "Independent Moonshine DOM, SSR and reactive rendering",
5
+ "license": "ISC",
6
+ "type": "module",
7
+ "main": "./src/dom.ts",
8
+ "types": "./src/dom.ts",
9
+ "exports": {
10
+ ".": "./src/dom.ts",
11
+ "./dom": "./src/dom.ts",
12
+ "./attributes": "./src/attributes.ts",
13
+ "./reactive": "./src/reactive.ts",
14
+ "./component": "./src/component.ts",
15
+ "./platform": "./src/platform.js",
16
+ "./component-instance": "./src/component-instance.ts",
17
+ "./ssr": "./src/ssr.ts",
18
+ "./control": "./src/control.ts",
19
+ "./store": "./src/store.ts",
20
+ "./resource": "./src/resource.ts",
21
+ "./resource/ssr": "./src/resource-ssr.ts",
22
+ "./framework-native": "./src/framework-native.ts",
23
+ "./framework-source": "./src/framework-source.ts",
24
+ "./jsx-types": {
25
+ "types": "./src/jsx-types.d.ts"
26
+ },
27
+ "./binding": "./src/binding.ts",
28
+ "./custom-element": "./src/custom-element.ts",
29
+ "./ssr-owner": "./src/ssr-owner.ts",
30
+ "./ssr-attempt": "./src/ssr-attempt.ts",
31
+ "./html": "./src/html.ts",
32
+ "./framework-lazy": "./src/framework-lazy.ts",
33
+ "./render-scheduler": "./src/render-scheduler.ts",
34
+ "./rotating-text": "./src/rotating-text.ts",
35
+ "./head": "./src/head.ts",
36
+ "./head-ssr": "./src/head-ssr.ts"
37
+ },
38
+ "files": [
39
+ "src",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "scripts": {
44
+ "format": "bunx prettier --check .",
45
+ "lint": "bunx oxlint .",
46
+ "typecheck": "bunx tsc --noEmit",
47
+ "test": "bun test"
48
+ },
49
+ "dependencies": {
50
+ "@tschk/moonshine": "^0.4.48"
51
+ },
52
+ "peerDependencies": {
53
+ "@tschk/moonshine-framework": "^0.4.48"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "@tschk/moonshine-framework": {
57
+ "optional": true
58
+ }
59
+ },
60
+ "devDependencies": {
61
+ "@types/bun": "1.3.14",
62
+ "typescript": "7.0.2"
63
+ }
64
+ }
@@ -0,0 +1,56 @@
1
+ // https://html.spec.whatwg.org/multipage/indices.html#attributes-3
2
+ const BOOLEAN = /* @__PURE__ */ new Set(
3
+ /* @__PURE__ */ "allowfullscreen alpha async autofocus autoplay checked controls default defer disabled formnovalidate headingreset inert ismap itemscope loop multiple muted nomodule novalidate open playsinline readonly required reversed selected shadowrootclonable shadowrootcustomelementregistry shadowrootdelegatesfocus shadowrootserializable".split(
4
+ " ",
5
+ ),
6
+ );
7
+
8
+ export function attributeValue(
9
+ name: string,
10
+ value: unknown,
11
+ html: boolean,
12
+ ): string | undefined {
13
+ const lower = name.toLowerCase();
14
+ // Hidden also accepts an empty hidden state and the string 'until-found'.
15
+ const boolean = html && (BOOLEAN.has(lower) || lower === "hidden");
16
+ if (value == null || (boolean && !value && value !== "")) return undefined;
17
+ if (html && lower === "translate" && typeof value === "boolean")
18
+ return value ? "yes" : "no";
19
+ return boolean && value === true ? "" : String(value);
20
+ }
21
+
22
+ // Pinned source semantics differ from generic HTML's current standards table.
23
+ const SOURCE_BOOLEAN_ADDITIONS = /* @__PURE__ */ new Set([
24
+ "indeterminate",
25
+ "seamless",
26
+ "webkitdirectory",
27
+ "disablepictureinpicture",
28
+ "disableremoteplayback",
29
+ ]);
30
+ const SOURCE_BOOLEAN_EXCLUSIONS = /* @__PURE__ */ new Set([
31
+ "alpha",
32
+ "headingreset",
33
+ "itemscope",
34
+ "shadowrootclonable",
35
+ "shadowrootcustomelementregistry",
36
+ "shadowrootdelegatesfocus",
37
+ "shadowrootserializable",
38
+ ]);
39
+
40
+ /** Compiler source attributes: literal strings retain their authored fast path. */
41
+ export function sourceAttributeValue(
42
+ name: string,
43
+ value: unknown,
44
+ dynamic: boolean,
45
+ ): string | undefined {
46
+ if (!dynamic && typeof value === "string") return value;
47
+ const boolean =
48
+ (BOOLEAN.has(name) && !SOURCE_BOOLEAN_EXCLUSIONS.has(name)) ||
49
+ SOURCE_BOOLEAN_ADDITIONS.has(name) ||
50
+ (name === "hidden" && value !== "until-found");
51
+ if (value == null || (boolean && !value && value !== "")) return undefined;
52
+ if (boolean) return "";
53
+ if (name === "translate" && typeof value === "boolean")
54
+ return value ? "yes" : "no";
55
+ return String(value);
56
+ }