@tschk/moonshine-dom 0.4.4 → 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/README.md CHANGED
@@ -13,6 +13,19 @@ const dispose = render(() => {
13
13
  }, document.getElementById("app")!);
14
14
  ```
15
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
+
16
29
  - `/reactive`: signals, memos, owned computations, cleanup and batching.
17
30
  `on(accessor, callback, { defer: true })` limits an effect or memo to explicit
18
31
  dependencies and skips its first callback. An array of accessors supplies a
@@ -66,7 +79,9 @@ const dispose = render(() => {
66
79
  waves per flush; independent references in one wave are not capped.
67
80
  `ComponentReference<T, readonly [Key, Index]>`
68
81
  preserves typed tuple arguments and requires parts for nonempty tuples;
69
- `ComponentReference<T>` retains the fixed-cell contract. SFC `bind:this` now has bounded scalar/member source acceptance, including empty exports; loop-dependent path extraction remains compiler work.
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.
70
85
  - `/ssr-owner`: lightweight `scopeSSRChild(child)` captures a live owner for the
71
86
  complete serialization of deferred children. It is also exported by `/ssr`.
72
87
  It preserves request context, select state, SVG namespace and text escaping;
@@ -79,6 +94,7 @@ const dispose = render(() => {
79
94
  the scheduling implementation. Ordinary native rendering stays synchronous;
80
95
  the signal kernel has no scheduler dependency.
81
96
  - `/resource`: owned client data fetching, separate from the kernel's resource API.
97
+ - `/resource/ssr`: synchronous server snapshots that never invoke fetchers.
82
98
  - `/control`: keyed `For`/`mapArray`, position-stable `Index`/`indexArray`, and
83
99
  retained `Show` branches with explicit accessors. `Index({ each, children })`
84
100
  calls `children(itemAccessor, indexNumber)` once per position; replacement and
@@ -102,6 +118,15 @@ const dispose = render(() => {
102
118
  Externally captured `scopeSSRChild` values retain their lexical owner and error
103
119
  policy; an error already swallowed there cannot reach this boundary. This is a
104
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.
105
130
  - `/framework-native`: the bundled framework renderer; requires the optional
106
131
  `@tschk/moonshine-framework` peer. Supports Bun, Node and Cloudflare SSR, static-mode rendering and
107
132
  fresh SPA mounts with separate authored client entries.
@@ -179,6 +204,12 @@ The types check component props, children, and known HTML/SVG tag names. Intrins
179
204
  props match `h`'s unrestricted records; attribute names, attribute values, and event
180
205
  parameter types are not checked or inferred.
181
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
+
182
213
  Optional structured state lives on `/store`, using the native reactive graph:
183
214
 
184
215
  ```ts
@@ -235,10 +266,20 @@ Each explicit `refetch` starts a request; calls within one microtask are not
235
266
  coalesced. Fetcher cleanup callbacks retain the resource's owner on refetch.
236
267
 
237
268
  Options support `initialValue` and an informational `name`; other options reject.
238
- This client API does not implement Suspense, transitions, hydration or async SSR,
239
- and is not yet admitted by the Solid compiler bridge. The Solid replacement's
240
- `/solid` export uses this client resource API; the kernel resource API keeps
241
- its existing contract.
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.
242
283
 
243
284
  ### Optional input bindings
244
285
 
@@ -284,8 +325,20 @@ their value once with HTML escaping; nullish/function values omit the attribute.
284
325
  Single selections compare raw values with `===`; multiple arrays use `includes`,
285
326
  matching Svelte 5.57 SSR. All matching options receive `selected`; an unmatched
286
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.
287
334
  These symbols provide SSR output, not hydration or client identity transport.
288
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
+
289
342
  Intentional reference difference: Chromium probes of Svelte 5.46.4 and cached
290
343
  5.57.1 initialize an undefined
291
344
  multiple-select binding to only the first selected scalar. Native bindings adopt
@@ -307,16 +360,24 @@ commit; generic callbacks must manage their own cancellation. `/component` also
307
360
  provides `onComponentReady` during setup, fired once after successful setup with
308
361
  the frame inactive. Failed or already disposed instances do not become ready.
309
362
 
310
- `createInputGroup(kind, read, write)` returns `{ bind(input) }` for radio or
363
+ `createInputGroup(kind, read, write)` returns `{ bind(input, watch?) }` for radio or
311
364
  checkbox groups. Create each token under a live owner, then bind inputs under
312
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.
313
369
  Token disposal releases every member; row disposal unregisters only that member.
314
370
  The compiler allocates tokens per binding target/component and nested each path;
315
371
  there is no global name lookup or runtime ownership guessing. Browser HTML `name`
316
372
  grouping still applies independently. Keep input types fixed.
317
-
318
- `setInputValue(input, value)` stores typed group values privately and refreshes
319
- selection on value changes. Ordinary inputs retain string values without this
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
320
381
  hook. Checkbox models must be arrays or nullish; other values reject. Radios use
321
382
  `Object.is` on native identities (no Svelte proxy unwrapping); checkbox membership uses array inclusion and change
322
383
  collection deduplicates values in current DOM order. Unchecking a duplicate value
@@ -363,7 +424,8 @@ write the boolean property after user listeners; browser coalescing is preserved
363
424
  It has no form-reset behavior. Cleanup removes the binding listener, including
364
425
  queued events and retained detached nodes (unlike the audited Svelte 5.57 listener).
365
426
  SSR uses the ordinary boolean `open` attribute snapshot. The Svelte `/binding`
366
- entry re-exports this helper; authored `bind:open` lowering remains pending.
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.
367
429
 
368
430
  `/store`'s `createMutable(value, { equals })` can select property-write equality.
369
431
  The default is strict equality (`===`); the optional comparator receives the
@@ -397,3 +459,10 @@ keeps reconciliation inside the containing range pull. The default scheduler and
397
459
  `setAttributeValue` exposes the existing native attribute setter for typed node
398
460
  updates. It does not install event handlers or replace form-binding helpers.
399
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,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-dom",
3
- "version": "0.4.4",
3
+ "version": "0.4.49",
4
4
  "description": "Independent Moonshine DOM, SSR and reactive rendering",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -9,13 +9,16 @@
9
9
  "exports": {
10
10
  ".": "./src/dom.ts",
11
11
  "./dom": "./src/dom.ts",
12
+ "./attributes": "./src/attributes.ts",
12
13
  "./reactive": "./src/reactive.ts",
13
14
  "./component": "./src/component.ts",
15
+ "./platform": "./src/platform.js",
14
16
  "./component-instance": "./src/component-instance.ts",
15
17
  "./ssr": "./src/ssr.ts",
16
18
  "./control": "./src/control.ts",
17
19
  "./store": "./src/store.ts",
18
20
  "./resource": "./src/resource.ts",
21
+ "./resource/ssr": "./src/resource-ssr.ts",
19
22
  "./framework-native": "./src/framework-native.ts",
20
23
  "./framework-source": "./src/framework-source.ts",
21
24
  "./jsx-types": {
@@ -28,7 +31,9 @@
28
31
  "./html": "./src/html.ts",
29
32
  "./framework-lazy": "./src/framework-lazy.ts",
30
33
  "./render-scheduler": "./src/render-scheduler.ts",
31
- "./rotating-text": "./src/rotating-text.ts"
34
+ "./rotating-text": "./src/rotating-text.ts",
35
+ "./head": "./src/head.ts",
36
+ "./head-ssr": "./src/head-ssr.ts"
32
37
  },
33
38
  "files": [
34
39
  "src",
@@ -42,10 +47,10 @@
42
47
  "test": "bun test"
43
48
  },
44
49
  "dependencies": {
45
- "@tschk/moonshine": "^0.4.4"
50
+ "@tschk/moonshine": "^0.4.48"
46
51
  },
47
52
  "peerDependencies": {
48
- "@tschk/moonshine-framework": "^0.4.4"
53
+ "@tschk/moonshine-framework": "^0.4.48"
49
54
  },
50
55
  "peerDependenciesMeta": {
51
56
  "@tschk/moonshine-framework": {
package/src/attributes.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // https://html.spec.whatwg.org/multipage/indices.html#attributes-3
2
- const BOOLEAN = new Set(
3
- "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(
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
4
  " ",
5
5
  ),
6
6
  );
@@ -18,3 +18,39 @@ export function attributeValue(
18
18
  return value ? "yes" : "no";
19
19
  return boolean && value === true ? "" : String(value);
20
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
+ }
package/src/binding.ts CHANGED
@@ -119,6 +119,31 @@ function listen(
119
119
  });
120
120
  }
121
121
 
122
+ /** FileList binding; nullish models leave the browser's current selection intact. */
123
+ export function bindFiles(
124
+ element: HTMLInputElement,
125
+ read: () => FileList | null | undefined,
126
+ write: (value: FileList | null) => void,
127
+ ): void {
128
+ const owner = getOwner();
129
+ if (!owner || owner.disposed)
130
+ throw new Error("Files bindings require a live native owner");
131
+ if (
132
+ !(element instanceof HTMLInputElement) ||
133
+ element.type !== "file" ||
134
+ typeof read !== "function" ||
135
+ typeof write !== "function"
136
+ )
137
+ throw new TypeError(
138
+ "Files bindings require a file input and getter/setter functions",
139
+ );
140
+ listen(element, "change", () => untrack(() => write(element.files)));
141
+ createRenderEffect(() => {
142
+ const files = read();
143
+ if (files != null) element.files = files;
144
+ });
145
+ }
146
+
122
147
  /** Checkbox checked binding; call after attributes and user change listeners. */
123
148
  export function bindChecked(
124
149
  element: HTMLInputElement,
@@ -161,7 +186,7 @@ export function setOptionValue(
161
186
  const select = option.closest("select");
162
187
  if (select) untrack(() => selectUpdates.get(select)?.());
163
188
  }
164
- function optionValue(option: HTMLOptionElement): unknown {
189
+ export function optionValue(option: HTMLOptionElement): unknown {
165
190
  return optionValues.has(option) ? optionValues.get(option) : option.value;
166
191
  }
167
192
 
@@ -260,13 +285,17 @@ const inputUpdates = /* @__PURE__ */ new WeakMap<
260
285
  >();
261
286
 
262
287
  /** Compiler hook for typed radio/checkbox values; ordinary DOM values stay strings. */
263
- export function setInputValue(input: HTMLInputElement, value: unknown): void {
288
+ export function setInputValue(
289
+ input: HTMLInputElement,
290
+ value: unknown,
291
+ notify = true,
292
+ ): void {
264
293
  if (!(input instanceof HTMLInputElement))
265
294
  throw new TypeError("Input values require an input element");
266
295
  const text = value == null ? "" : String(value);
267
296
  inputValues.set(input, value);
268
297
  input.value = text;
269
- untrack(() => inputUpdates.get(input)?.());
298
+ if (notify) untrack(() => inputUpdates.get(input)?.());
270
299
  }
271
300
  function inputValue(input: HTMLInputElement): unknown {
272
301
  return inputValues.has(input) ? inputValues.get(input) : input.value;
@@ -274,17 +303,24 @@ function inputValue(input: HTMLInputElement): unknown {
274
303
 
275
304
  /** One explicit token per compiler binding target; never inferred from HTML names. */
276
305
  export function createInputGroup(
277
- kind: "radio" | "checkbox",
306
+ kind: "radio" | "checkbox" | "mixed",
278
307
  read: () => unknown,
279
308
  write: (value: unknown) => void,
280
309
  equal: (left: unknown, right: unknown) => boolean = Object.is,
281
- ): { bind(input: HTMLInputElement): void } {
310
+ ): { bind(input: HTMLInputElement, watch?: () => unknown): void } {
282
311
  const owner = getOwner();
283
312
  if (!owner || owner.disposed || owner.disposing)
284
313
  throw new Error("Input groups require a live native owner");
285
- if (kind !== "radio" && kind !== "checkbox")
286
- throw new TypeError("Input groups support radio or checkbox inputs only");
287
- type Member = { input: HTMLInputElement; stop: () => void };
314
+ if (kind !== "radio" && kind !== "checkbox" && kind !== "mixed")
315
+ throw new TypeError(
316
+ "Input groups support radio, checkbox or mixed inputs only",
317
+ );
318
+ type Member = {
319
+ input: HTMLInputElement;
320
+ checkbox: boolean;
321
+ watch: (() => unknown) | undefined;
322
+ stop: () => void;
323
+ };
288
324
  const members = new Set<Member>();
289
325
  let active = true;
290
326
  function release(member: Member): void {
@@ -308,8 +344,9 @@ export function createInputGroup(
308
344
  });
309
345
  function apply(member: Member): void {
310
346
  if (!active || !members.has(member)) return;
347
+ member.watch?.();
311
348
  const value = read();
312
- if (kind === "checkbox") {
349
+ if (member.checkbox) {
313
350
  if (value != null && !Array.isArray(value))
314
351
  throw new TypeError(
315
352
  "Checkbox groups require an array or nullish value",
@@ -321,17 +358,30 @@ export function createInputGroup(
321
358
  } else member.input.checked = equal(inputValue(member.input), value);
322
359
  }
323
360
  return {
324
- bind(input) {
361
+ bind(input, watch) {
325
362
  const current = getOwner();
326
363
  if (!active || !current || current.disposed || current.disposing)
327
364
  throw new Error(
328
365
  "Input group members require a live group and native owner",
329
366
  );
330
- if (!(input instanceof HTMLInputElement) || input.type !== kind)
331
- throw new TypeError(`Input group requires ${kind} inputs`);
367
+ if (
368
+ !(input instanceof HTMLInputElement) ||
369
+ (kind === "mixed"
370
+ ? input.type !== "radio" && input.type !== "checkbox"
371
+ : input.type !== kind)
372
+ )
373
+ throw new TypeError(
374
+ kind === "mixed"
375
+ ? "Input group requires radio or checkbox inputs"
376
+ : `Input group requires ${kind} inputs`,
377
+ );
378
+ if (watch !== undefined && typeof watch !== "function")
379
+ throw new TypeError("Input group value watch must be a function");
332
380
  if (inputUpdates.has(input))
333
381
  throw new Error("Input already belongs to a group");
334
- const member: Member = { input, stop: () => {} };
382
+ const checkbox =
383
+ kind === "checkbox" || (kind === "mixed" && input.type === "checkbox");
384
+ const member: Member = { input, checkbox, watch, stop: () => {} };
335
385
  onCleanup(() => release(member));
336
386
  try {
337
387
  createRoot((stop) => {
@@ -341,8 +391,8 @@ export function createInputGroup(
341
391
  listen(input, "change", (reset) =>
342
392
  untrack(() => {
343
393
  if (!active || !members.has(member)) return;
344
- if (reset) write(kind === "checkbox" ? [] : null);
345
- else if (kind === "radio") write(inputValue(input));
394
+ if (reset) write(checkbox ? [] : null);
395
+ else if (!checkbox) write(inputValue(input));
346
396
  else {
347
397
  const ordered = [...members].toSorted((a, b) => {
348
398
  const position = a.input.compareDocumentPosition(b.input);
@@ -158,7 +158,8 @@ export function exposeComponent<T extends object>(exports: T): T {
158
158
  return instance;
159
159
  }
160
160
 
161
- function enqueuePublication(publish: () => void): void {
161
+ /** Schedule an owned reference publisher for the next microtask or explicit flush. */
162
+ export function enqueueComponentReference(publish: () => void): void {
162
163
  publications.add(publish);
163
164
  if (!scheduled && !flushing) {
164
165
  scheduled = true;
@@ -280,7 +281,7 @@ export function bindOwnedReference<T extends object>(
280
281
  }
281
282
 
282
283
  function publisher(publication?: "post"): (fn: () => void) => void {
283
- if (publication !== "post") return enqueuePublication;
284
+ if (publication !== "post") return enqueueComponentReference;
284
285
  const scheduler = getRenderScheduler();
285
286
  if (!scheduler)
286
287
  throw new Error(
package/src/component.ts CHANGED
@@ -160,6 +160,17 @@ function withConsumer<T>(
160
160
  const context = owner.context,
161
161
  active = frame.active,
162
162
  wasDisposed = owner.disposed;
163
+ if (!cleanup && active && context?.get(componentKey) === frame) {
164
+ try {
165
+ return fn();
166
+ } finally {
167
+ frame.active = active;
168
+ owner.context =
169
+ owner.disposed && !wasDisposed && !context.has(cleanupComputationKey)
170
+ ? undefined
171
+ : context;
172
+ }
173
+ }
163
174
  owner.context = new Map(context);
164
175
  owner.context.set(componentKey, frame);
165
176
  if (cleanup) owner.context.set(cleanupComputationKey, true);
package/src/control.ts CHANGED
@@ -66,42 +66,112 @@ function disposeAll(entries: Iterable<{ dispose: () => void }>): void {
66
66
  if (failed) throw failure;
67
67
  }
68
68
 
69
- /** Optional deferRemoved takes ownership of removed roots; throwing falls back to disposal. */
70
- export function mapArray<T, U>(
69
+ /** Deferred removals transfer root ownership; immediate fallbacks own one empty branch per read. */
70
+ export function mapArray<T, U, F = never>(
71
71
  list: Accessor<readonly T[]>,
72
72
  map: (item: T, index: Accessor<number>) => U,
73
73
  deferRemoved?: (dispose: () => void) => void,
74
- schedule: (read: () => U[]) => Accessor<U[]> = createRenderMemo,
75
- ): Accessor<U[]> {
74
+ schedule: (
75
+ read: () => U[] | NoInfer<F>,
76
+ ) => Accessor<U[] | NoInfer<F>> = createRenderMemo,
77
+ removalOrder: "after-map" | "before-map" = "after-map",
78
+ fallback?: () => F,
79
+ ): Accessor<U[] | NoInfer<F>> {
80
+ if (deferRemoved && removalOrder === "before-map")
81
+ throw new TypeError("Removal before mapping cannot be deferred");
82
+ if (deferRemoved && fallback)
83
+ throw new TypeError("Owned fallback removal cannot be deferred");
76
84
  const owner = getRenderScheduler()
77
85
  ? createComponentScope(() => getOwner()!)
78
86
  : undefined;
79
87
  let entries: Entry<T, U>[] = [];
88
+ let fallbackRoot: ReturnType<typeof owned<F>> | undefined;
80
89
  let disposed = false;
81
90
  onCleanup(() => {
82
91
  disposed = true;
83
- const previous = entries;
92
+ const previous = entries,
93
+ previousFallback = fallbackRoot;
84
94
  entries = [];
85
- disposeAll(previous);
95
+ fallbackRoot = undefined;
96
+ disposeAll(previousFallback ? [...previous, previousFallback] : previous);
86
97
  });
87
98
  return schedule(() => {
88
99
  const items = list();
100
+ const mappedLength =
101
+ removalOrder === "before-map" ? items.length : undefined;
102
+ const previousFallback = fallbackRoot;
103
+ fallbackRoot = undefined;
104
+ previousFallback?.dispose();
105
+ if (fallback && (mappedLength ?? items.length) === 0) {
106
+ const previous = entries;
107
+ entries = [];
108
+ disposeAll(previous);
109
+ if (disposed) return [];
110
+ const root = owned(fallback, undefined, owner);
111
+ if (disposed) {
112
+ root.dispose();
113
+ return [];
114
+ }
115
+ fallbackRoot = root;
116
+ return root.value;
117
+ }
89
118
  const available = new Map<T, Entry<T, U>[]>();
90
- for (let i = entries.length - 1; i >= 0; i--) {
119
+ let retainedPlan: Array<Entry<T, U> | undefined> | undefined;
120
+ let start = 0,
121
+ end = entries.length - 1,
122
+ newEnd = 0;
123
+ if (removalOrder === "before-map") {
124
+ newEnd = mappedLength! - 1;
125
+ retainedPlan = [];
126
+ while (
127
+ start <= Math.min(end, newEnd) &&
128
+ entries[start]!.item === items[start]
129
+ ) {
130
+ retainedPlan[start] = entries[start];
131
+ start++;
132
+ }
133
+ while (
134
+ end >= start &&
135
+ newEnd >= start &&
136
+ entries[end]!.item === items[newEnd]
137
+ ) {
138
+ retainedPlan[newEnd--] = entries[end--];
139
+ }
140
+ }
141
+ for (let i = end; i >= start; i--) {
91
142
  const entry = entries[i]!;
92
143
  const bucket = available.get(entry.item);
93
144
  if (bucket) bucket.push(entry);
94
145
  else available.set(entry.item, [entry]);
95
146
  }
147
+ if (retainedPlan) {
148
+ for (let position = start; position <= newEnd; position++)
149
+ retainedPlan[position] = available.get(items[position]!)?.pop();
150
+ const retained = new Set(retainedPlan);
151
+ const previous = entries;
152
+ entries = [];
153
+ const removed: Entry<T, U>[] = [];
154
+ for (const entry of previous)
155
+ (retained.has(entry) ? entries : removed).push(entry);
156
+ // Keep only live survivors if cleanup throws or a replacement mapper fails.
157
+ disposeAll(removed);
158
+ }
96
159
  const created: Entry<T, U>[] = [];
97
160
  let next: Entry<T, U>[];
98
161
  try {
99
162
  next = [];
100
- for (let position = 0; position < items.length; position++) {
163
+ for (
164
+ let position = 0;
165
+ position < (mappedLength ?? items.length);
166
+ position++
167
+ ) {
101
168
  if (disposed) break;
102
169
  const item = items[position]!;
103
- const retained = available.get(item)?.pop();
170
+ const retained = retainedPlan
171
+ ? retainedPlan[position]
172
+ : available.get(item)?.pop();
104
173
  if (retained) {
174
+ if (retainedPlan) retained.index(position);
105
175
  next.push(retained);
106
176
  continue;
107
177
  }
@@ -156,12 +226,16 @@ export function mapArray<T, U>(
156
226
  });
157
227
  }
158
228
 
159
- /** Retain each position while its item accessor follows the current list value. */
160
- export function indexArray<T, U>(
229
+ /** Retain positions; before-map publishes item values before creating later slots. */
230
+ export function indexArray<T, U, F = never>(
161
231
  list: Accessor<readonly T[]>,
162
232
  map: (item: Accessor<T>, index: number) => U,
163
- schedule: (read: () => U[]) => Accessor<U[]> = createRenderMemo,
164
- ): Accessor<U[]> {
233
+ schedule: (
234
+ read: () => U[] | NoInfer<F>,
235
+ ) => Accessor<U[] | NoInfer<F>> = createRenderMemo,
236
+ updateOrder: "after-map" | "before-map" = "after-map",
237
+ fallback?: () => F,
238
+ ): Accessor<U[] | NoInfer<F>> {
165
239
  const owner = getRenderScheduler()
166
240
  ? createComponentScope(() => getOwner()!)
167
241
  : undefined;
@@ -171,19 +245,46 @@ export function indexArray<T, U>(
171
245
  write: Setter<T>;
172
246
  scope?: Owner;
173
247
  }> = [];
248
+ let fallbackRoot: ReturnType<typeof owned<F>> | undefined;
174
249
  let disposed = false;
175
250
  onCleanup(() => {
176
251
  disposed = true;
177
- const previous = entries;
252
+ const previous = entries,
253
+ previousFallback = fallbackRoot;
178
254
  entries = [];
179
- disposeAll(previous);
255
+ fallbackRoot = undefined;
256
+ disposeAll(previousFallback ? [...previous, previousFallback] : previous);
180
257
  });
181
258
  return schedule(() => {
182
259
  const items = list();
183
- const next = entries.slice(0, items.length);
260
+ const mappedLength =
261
+ updateOrder === "before-map" ? items.length : undefined;
262
+ const previousFallback = fallbackRoot;
263
+ fallbackRoot = undefined;
264
+ previousFallback?.dispose();
265
+ if (fallback && (mappedLength ?? items.length) === 0) {
266
+ const previous = entries;
267
+ entries = [];
268
+ disposeAll(previous);
269
+ if (disposed) return [];
270
+ const root = owned(fallback, undefined, owner);
271
+ if (disposed) {
272
+ root.dispose();
273
+ return [];
274
+ }
275
+ fallbackRoot = root;
276
+ return root.value;
277
+ }
278
+ const next = entries.slice(0, mappedLength ?? items.length);
279
+ if (mappedLength !== undefined)
280
+ next.forEach((entry, index) => entry.write(() => items[index]!));
184
281
  const created: typeof entries = [];
185
282
  try {
186
- for (let index = next.length; index < items.length; index++) {
283
+ for (
284
+ let index = next.length;
285
+ index < (mappedLength ?? items.length);
286
+ index++
287
+ ) {
187
288
  if (disposed) break;
188
289
  const [item, write] = createSignal<T>(items[index]!);
189
290
  const entry = {
@@ -205,10 +306,11 @@ export function indexArray<T, U>(
205
306
  disposeAll(created);
206
307
  return [];
207
308
  }
208
- const removed = entries.slice(items.length);
309
+ const removed = entries.slice(mappedLength ?? items.length);
209
310
  entries = next;
210
311
  batch(() => {
211
- next.forEach((entry, index) => entry.write(() => items[index]!));
312
+ if (mappedLength === undefined)
313
+ next.forEach((entry, index) => entry.write(() => items[index]!));
212
314
  disposeAll(removed);
213
315
  });
214
316
  return disposed ? [] : next.map((entry) => entry.value);