@shadow-js/core 0.1.0 → 1.0.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.
- package/CHANGELOG.md +11 -0
- package/LICENSE +2 -2
- package/README.md +134 -331
- package/dist/dev/action.d.ts +36 -0
- package/dist/dev/action.js +90 -0
- package/dist/dev/action.js.map +1 -0
- package/dist/dev/cache.d.ts +35 -0
- package/dist/dev/cache.js +62 -0
- package/dist/dev/cache.js.map +1 -0
- package/dist/dev/context.d.ts +106 -0
- package/dist/dev/context.js +111 -0
- package/dist/dev/context.js.map +1 -0
- package/dist/dev/effect.d.ts +122 -0
- package/dist/dev/effect.js +111 -0
- package/dist/dev/effect.js.map +1 -0
- package/dist/dev/env.d.ts +29 -0
- package/dist/dev/env.js +31 -0
- package/dist/dev/env.js.map +1 -0
- package/dist/dev/events.d.ts +28 -0
- package/dist/dev/events.js +33 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend/index.d.ts +331 -0
- package/dist/dev/extend/index.js +317 -0
- package/dist/dev/extend/index.js.map +1 -0
- package/dist/dev/external-store.d.ts +60 -0
- package/dist/dev/external-store.js +60 -0
- package/dist/dev/external-store.js.map +1 -0
- package/dist/dev/index.d.ts +29 -0
- package/dist/dev/index.js +26 -0
- package/dist/dev/internal/concurrency.d.ts +213 -0
- package/dist/dev/internal/concurrency.js +632 -0
- package/dist/dev/internal/concurrency.js.map +1 -0
- package/dist/dev/internal/devtools.d.ts +71 -0
- package/dist/dev/internal/devtools.js +77 -0
- package/dist/dev/internal/devtools.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +90 -0
- package/dist/dev/internal/diagnostics.js +102 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/dispose.d.ts +28 -0
- package/dist/dev/internal/dispose.js +49 -0
- package/dist/dev/internal/dispose.js.map +1 -0
- package/dist/dev/internal/flags.js +11 -0
- package/dist/dev/internal/flags.js.map +1 -0
- package/dist/dev/internal/graph.d.ts +233 -0
- package/dist/dev/internal/graph.js +578 -0
- package/dist/dev/internal/graph.js.map +1 -0
- package/dist/dev/internal/hydration-flag.d.ts +33 -0
- package/dist/dev/internal/hydration-flag.js +46 -0
- package/dist/dev/internal/hydration-flag.js.map +1 -0
- package/dist/dev/internal/messages.d.ts +56 -0
- package/dist/dev/internal/messages.js +54 -0
- package/dist/dev/internal/messages.js.map +1 -0
- package/dist/dev/internal/owner.d.ts +142 -0
- package/dist/dev/internal/owner.js +290 -0
- package/dist/dev/internal/owner.js.map +1 -0
- package/dist/dev/internal/queue.js +46 -0
- package/dist/dev/internal/queue.js.map +1 -0
- package/dist/dev/internal/scheduler.d.ts +113 -0
- package/dist/dev/internal/scheduler.js +287 -0
- package/dist/dev/internal/scheduler.js.map +1 -0
- package/dist/dev/internal/state.d.ts +141 -0
- package/dist/dev/internal/state.js +28 -0
- package/dist/dev/internal/state.js.map +1 -0
- package/dist/dev/internal/suspension.d.ts +43 -0
- package/dist/dev/internal/suspension.js +45 -0
- package/dist/dev/internal/suspension.js.map +1 -0
- package/dist/dev/internal/types.d.ts +46 -0
- package/dist/dev/list.d.ts +93 -0
- package/dist/dev/list.js +282 -0
- package/dist/dev/list.js.map +1 -0
- package/dist/dev/memo.d.ts +60 -0
- package/dist/dev/memo.js +41 -0
- package/dist/dev/memo.js.map +1 -0
- package/dist/dev/optimistic.d.ts +26 -0
- package/dist/dev/optimistic.js +45 -0
- package/dist/dev/optimistic.js.map +1 -0
- package/dist/dev/ownership.d.ts +204 -0
- package/dist/dev/ownership.js +261 -0
- package/dist/dev/ownership.js.map +1 -0
- package/dist/dev/props.d.ts +134 -0
- package/dist/dev/props.js +282 -0
- package/dist/dev/props.js.map +1 -0
- package/dist/dev/reaction.d.ts +29 -0
- package/dist/dev/reaction.js +61 -0
- package/dist/dev/reaction.js.map +1 -0
- package/dist/dev/reducer.d.ts +41 -0
- package/dist/dev/reducer.js +39 -0
- package/dist/dev/reducer.js.map +1 -0
- package/dist/dev/refs.d.ts +52 -0
- package/dist/dev/refs.js +58 -0
- package/dist/dev/refs.js.map +1 -0
- package/dist/dev/resource.d.ts +135 -0
- package/dist/dev/resource.js +177 -0
- package/dist/dev/resource.js.map +1 -0
- package/dist/dev/selector.d.ts +34 -0
- package/dist/dev/selector.js +118 -0
- package/dist/dev/selector.js.map +1 -0
- package/dist/dev/signal.d.ts +42 -0
- package/dist/dev/signal.js +39 -0
- package/dist/dev/signal.js.map +1 -0
- package/dist/dev/store/index.d.ts +5 -0
- package/dist/dev/store/index.js +4 -0
- package/dist/dev/store/nodes.js +192 -0
- package/dist/dev/store/nodes.js.map +1 -0
- package/dist/dev/store/proxies.js +160 -0
- package/dist/dev/store/proxies.js.map +1 -0
- package/dist/dev/store/read.d.ts +39 -0
- package/dist/dev/store/read.js +72 -0
- package/dist/dev/store/read.js.map +1 -0
- package/dist/dev/store/reconcile.d.ts +73 -0
- package/dist/dev/store/reconcile.js +186 -0
- package/dist/dev/store/reconcile.js.map +1 -0
- package/dist/dev/store/types.d.ts +106 -0
- package/dist/dev/store/use-store.d.ts +60 -0
- package/dist/dev/store/use-store.js +168 -0
- package/dist/dev/store/use-store.js.map +1 -0
- package/dist/dev/suspense.d.ts +101 -0
- package/dist/dev/suspense.js +45 -0
- package/dist/dev/suspense.js.map +1 -0
- package/dist/dev/transitions.d.ts +77 -0
- package/dist/dev/transitions.js +101 -0
- package/dist/dev/transitions.js.map +1 -0
- package/dist/prod/action.js +2 -0
- package/dist/prod/action.js.map +1 -0
- package/dist/prod/cache.js +2 -0
- package/dist/prod/cache.js.map +1 -0
- package/dist/prod/context.js +2 -0
- package/dist/prod/context.js.map +1 -0
- package/dist/prod/effect.js +2 -0
- package/dist/prod/effect.js.map +1 -0
- package/dist/prod/env.js +2 -0
- package/dist/prod/env.js.map +1 -0
- package/dist/prod/events.js +2 -0
- package/dist/prod/events.js.map +1 -0
- package/dist/prod/extend/index.js +2 -0
- package/dist/prod/extend/index.js.map +1 -0
- package/dist/prod/external-store.js +2 -0
- package/dist/prod/external-store.js.map +1 -0
- package/dist/prod/index.js +1 -0
- package/dist/prod/internal/concurrency.js +2 -0
- package/dist/prod/internal/concurrency.js.map +1 -0
- package/dist/prod/internal/devtools.js +2 -0
- package/dist/prod/internal/devtools.js.map +1 -0
- package/dist/prod/internal/diagnostics.js +2 -0
- package/dist/prod/internal/diagnostics.js.map +1 -0
- package/dist/prod/internal/dispose.js +2 -0
- package/dist/prod/internal/dispose.js.map +1 -0
- package/dist/prod/internal/flags.js +2 -0
- package/dist/prod/internal/flags.js.map +1 -0
- package/dist/prod/internal/graph.js +2 -0
- package/dist/prod/internal/graph.js.map +1 -0
- package/dist/prod/internal/hydration-flag.js +2 -0
- package/dist/prod/internal/hydration-flag.js.map +1 -0
- package/dist/prod/internal/messages.js +2 -0
- package/dist/prod/internal/messages.js.map +1 -0
- package/dist/prod/internal/owner.js +2 -0
- package/dist/prod/internal/owner.js.map +1 -0
- package/dist/prod/internal/queue.js +2 -0
- package/dist/prod/internal/queue.js.map +1 -0
- package/dist/prod/internal/scheduler.js +2 -0
- package/dist/prod/internal/scheduler.js.map +1 -0
- package/dist/prod/internal/state.js +2 -0
- package/dist/prod/internal/state.js.map +1 -0
- package/dist/prod/internal/suspension.js +2 -0
- package/dist/prod/internal/suspension.js.map +1 -0
- package/dist/prod/list.js +2 -0
- package/dist/prod/list.js.map +1 -0
- package/dist/prod/memo.js +2 -0
- package/dist/prod/memo.js.map +1 -0
- package/dist/prod/optimistic.js +2 -0
- package/dist/prod/optimistic.js.map +1 -0
- package/dist/prod/ownership.js +2 -0
- package/dist/prod/ownership.js.map +1 -0
- package/dist/prod/props.js +2 -0
- package/dist/prod/props.js.map +1 -0
- package/dist/prod/reaction.js +2 -0
- package/dist/prod/reaction.js.map +1 -0
- package/dist/prod/reducer.js +2 -0
- package/dist/prod/reducer.js.map +1 -0
- package/dist/prod/refs.js +2 -0
- package/dist/prod/refs.js.map +1 -0
- package/dist/prod/resource.js +2 -0
- package/dist/prod/resource.js.map +1 -0
- package/dist/prod/selector.js +2 -0
- package/dist/prod/selector.js.map +1 -0
- package/dist/prod/signal.js +2 -0
- package/dist/prod/signal.js.map +1 -0
- package/dist/prod/store/index.js +1 -0
- package/dist/prod/store/nodes.js +2 -0
- package/dist/prod/store/nodes.js.map +1 -0
- package/dist/prod/store/proxies.js +2 -0
- package/dist/prod/store/proxies.js.map +1 -0
- package/dist/prod/store/read.js +2 -0
- package/dist/prod/store/read.js.map +1 -0
- package/dist/prod/store/reconcile.js +2 -0
- package/dist/prod/store/reconcile.js.map +1 -0
- package/dist/prod/store/use-store.js +2 -0
- package/dist/prod/store/use-store.js.map +1 -0
- package/dist/prod/suspense.js +2 -0
- package/dist/prod/suspense.js.map +1 -0
- package/dist/prod/transitions.js +2 -0
- package/dist/prod/transitions.js.map +1 -0
- package/dist/server/action.js +2 -0
- package/dist/server/action.js.map +1 -0
- package/dist/server/cache.js +2 -0
- package/dist/server/cache.js.map +1 -0
- package/dist/server/context.js +2 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/effect.js +2 -0
- package/dist/server/effect.js.map +1 -0
- package/dist/server/env.js +2 -0
- package/dist/server/env.js.map +1 -0
- package/dist/server/events.js +2 -0
- package/dist/server/events.js.map +1 -0
- package/dist/server/extend/index.js +2 -0
- package/dist/server/extend/index.js.map +1 -0
- package/dist/server/external-store.js +2 -0
- package/dist/server/external-store.js.map +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/internal/concurrency.js +2 -0
- package/dist/server/internal/concurrency.js.map +1 -0
- package/dist/server/internal/devtools.js +2 -0
- package/dist/server/internal/devtools.js.map +1 -0
- package/dist/server/internal/diagnostics.js +2 -0
- package/dist/server/internal/diagnostics.js.map +1 -0
- package/dist/server/internal/dispose.js +2 -0
- package/dist/server/internal/dispose.js.map +1 -0
- package/dist/server/internal/flags.js +2 -0
- package/dist/server/internal/flags.js.map +1 -0
- package/dist/server/internal/graph.js +2 -0
- package/dist/server/internal/graph.js.map +1 -0
- package/dist/server/internal/hydration-flag.js +2 -0
- package/dist/server/internal/hydration-flag.js.map +1 -0
- package/dist/server/internal/messages.js +2 -0
- package/dist/server/internal/messages.js.map +1 -0
- package/dist/server/internal/owner.js +2 -0
- package/dist/server/internal/owner.js.map +1 -0
- package/dist/server/internal/queue.js +2 -0
- package/dist/server/internal/queue.js.map +1 -0
- package/dist/server/internal/scheduler.js +2 -0
- package/dist/server/internal/scheduler.js.map +1 -0
- package/dist/server/internal/state.js +2 -0
- package/dist/server/internal/state.js.map +1 -0
- package/dist/server/internal/suspension.js +2 -0
- package/dist/server/internal/suspension.js.map +1 -0
- package/dist/server/list.js +2 -0
- package/dist/server/list.js.map +1 -0
- package/dist/server/memo.js +2 -0
- package/dist/server/memo.js.map +1 -0
- package/dist/server/optimistic.js +2 -0
- package/dist/server/optimistic.js.map +1 -0
- package/dist/server/ownership.js +2 -0
- package/dist/server/ownership.js.map +1 -0
- package/dist/server/props.js +2 -0
- package/dist/server/props.js.map +1 -0
- package/dist/server/reaction.js +2 -0
- package/dist/server/reaction.js.map +1 -0
- package/dist/server/reducer.js +2 -0
- package/dist/server/reducer.js.map +1 -0
- package/dist/server/refs.js +2 -0
- package/dist/server/refs.js.map +1 -0
- package/dist/server/resource.js +2 -0
- package/dist/server/resource.js.map +1 -0
- package/dist/server/selector.js +2 -0
- package/dist/server/selector.js.map +1 -0
- package/dist/server/signal.js +2 -0
- package/dist/server/signal.js.map +1 -0
- package/dist/server/store/index.js +1 -0
- package/dist/server/store/nodes.js +2 -0
- package/dist/server/store/nodes.js.map +1 -0
- package/dist/server/store/proxies.js +2 -0
- package/dist/server/store/proxies.js.map +1 -0
- package/dist/server/store/read.js +2 -0
- package/dist/server/store/read.js.map +1 -0
- package/dist/server/store/reconcile.js +2 -0
- package/dist/server/store/reconcile.js.map +1 -0
- package/dist/server/store/use-store.js +2 -0
- package/dist/server/store/use-store.js.map +1 -0
- package/dist/server/suspense.js +2 -0
- package/dist/server/suspense.js.map +1 -0
- package/dist/server/transitions.js +2 -0
- package/dist/server/transitions.js.map +1 -0
- package/dist/server-dev/action.js +90 -0
- package/dist/server-dev/action.js.map +1 -0
- package/dist/server-dev/cache.js +62 -0
- package/dist/server-dev/cache.js.map +1 -0
- package/dist/server-dev/context.js +108 -0
- package/dist/server-dev/context.js.map +1 -0
- package/dist/server-dev/effect.js +56 -0
- package/dist/server-dev/effect.js.map +1 -0
- package/dist/server-dev/env.js +31 -0
- package/dist/server-dev/env.js.map +1 -0
- package/dist/server-dev/events.js +33 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend/index.js +317 -0
- package/dist/server-dev/extend/index.js.map +1 -0
- package/dist/server-dev/external-store.js +46 -0
- package/dist/server-dev/external-store.js.map +1 -0
- package/dist/server-dev/index.js +26 -0
- package/dist/server-dev/internal/concurrency.js +633 -0
- package/dist/server-dev/internal/concurrency.js.map +1 -0
- package/dist/server-dev/internal/devtools.js +77 -0
- package/dist/server-dev/internal/devtools.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +102 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/dispose.js +49 -0
- package/dist/server-dev/internal/dispose.js.map +1 -0
- package/dist/server-dev/internal/flags.js +11 -0
- package/dist/server-dev/internal/flags.js.map +1 -0
- package/dist/server-dev/internal/graph.js +578 -0
- package/dist/server-dev/internal/graph.js.map +1 -0
- package/dist/server-dev/internal/hydration-flag.js +46 -0
- package/dist/server-dev/internal/hydration-flag.js.map +1 -0
- package/dist/server-dev/internal/messages.js +54 -0
- package/dist/server-dev/internal/messages.js.map +1 -0
- package/dist/server-dev/internal/owner.js +290 -0
- package/dist/server-dev/internal/owner.js.map +1 -0
- package/dist/server-dev/internal/queue.js +46 -0
- package/dist/server-dev/internal/queue.js.map +1 -0
- package/dist/server-dev/internal/scheduler.js +287 -0
- package/dist/server-dev/internal/scheduler.js.map +1 -0
- package/dist/server-dev/internal/state.js +28 -0
- package/dist/server-dev/internal/state.js.map +1 -0
- package/dist/server-dev/internal/suspension.js +45 -0
- package/dist/server-dev/internal/suspension.js.map +1 -0
- package/dist/server-dev/list.js +282 -0
- package/dist/server-dev/list.js.map +1 -0
- package/dist/server-dev/memo.js +41 -0
- package/dist/server-dev/memo.js.map +1 -0
- package/dist/server-dev/optimistic.js +45 -0
- package/dist/server-dev/optimistic.js.map +1 -0
- package/dist/server-dev/ownership.js +261 -0
- package/dist/server-dev/ownership.js.map +1 -0
- package/dist/server-dev/props.js +282 -0
- package/dist/server-dev/props.js.map +1 -0
- package/dist/server-dev/reaction.js +61 -0
- package/dist/server-dev/reaction.js.map +1 -0
- package/dist/server-dev/reducer.js +39 -0
- package/dist/server-dev/reducer.js.map +1 -0
- package/dist/server-dev/refs.js +58 -0
- package/dist/server-dev/refs.js.map +1 -0
- package/dist/server-dev/resource.js +176 -0
- package/dist/server-dev/resource.js.map +1 -0
- package/dist/server-dev/selector.js +82 -0
- package/dist/server-dev/selector.js.map +1 -0
- package/dist/server-dev/signal.js +39 -0
- package/dist/server-dev/signal.js.map +1 -0
- package/dist/server-dev/store/index.js +4 -0
- package/dist/server-dev/store/nodes.js +192 -0
- package/dist/server-dev/store/nodes.js.map +1 -0
- package/dist/server-dev/store/proxies.js +160 -0
- package/dist/server-dev/store/proxies.js.map +1 -0
- package/dist/server-dev/store/read.js +72 -0
- package/dist/server-dev/store/read.js.map +1 -0
- package/dist/server-dev/store/reconcile.js +186 -0
- package/dist/server-dev/store/reconcile.js.map +1 -0
- package/dist/server-dev/store/use-store.js +168 -0
- package/dist/server-dev/store/use-store.js.map +1 -0
- package/dist/server-dev/suspense.js +45 -0
- package/dist/server-dev/suspense.js.map +1 -0
- package/dist/server-dev/transitions.js +86 -0
- package/dist/server-dev/transitions.js.map +1 -0
- package/package.json +111 -50
- package/dist/chunk-6Y3CCWOY.js +0 -887
- package/dist/chunk-6Y3CCWOY.js.map +0 -1
- package/dist/chunk-B5FTYDUG.js +0 -3
- package/dist/chunk-B5FTYDUG.js.map +0 -1
- package/dist/index.cjs +0 -2000
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -609
- package/dist/index.d.ts +0 -609
- package/dist/index.js +0 -1094
- package/dist/index.js.map +0 -1
- package/dist/jsx-Bugil6CJ.d.cts +0 -151
- package/dist/jsx-Bugil6CJ.d.ts +0 -151
- package/dist/jsx-dev-runtime.cjs +0 -742
- package/dist/jsx-dev-runtime.cjs.map +0 -1
- package/dist/jsx-dev-runtime.d.cts +0 -2
- package/dist/jsx-dev-runtime.d.ts +0 -2
- package/dist/jsx-dev-runtime.js +0 -4
- package/dist/jsx-dev-runtime.js.map +0 -1
- package/dist/jsx-runtime.cjs +0 -742
- package/dist/jsx-runtime.cjs.map +0 -1
- package/dist/jsx-runtime.d.cts +0 -36
- package/dist/jsx-runtime.d.ts +0 -36
- package/dist/jsx-runtime.js +0 -4
- package/dist/jsx-runtime.js.map +0 -1
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { warn } from "./internal/diagnostics.js";
|
|
2
|
+
import { Owner } from "./internal/owner.js";
|
|
3
|
+
import { readSignal } from "./internal/graph.js";
|
|
4
|
+
import { createRoot, getOwner, onCleanup, runWithOwner, untrack } from "./ownership.js";
|
|
5
|
+
import { disposeTree } from "./internal/dispose.js";
|
|
6
|
+
import { createSignalNode, writeSignal } from "./extend/index.js";
|
|
7
|
+
import { useMemo } from "./memo.js";
|
|
8
|
+
//#region src/list.ts
|
|
9
|
+
/**
|
|
10
|
+
* One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created
|
|
11
|
+
* by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.
|
|
12
|
+
*/
|
|
13
|
+
var Row = class {
|
|
14
|
+
/** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */
|
|
15
|
+
key;
|
|
16
|
+
/** False for a later copy of a key in a keyed list. Such a row is never reused. */
|
|
17
|
+
first;
|
|
18
|
+
/** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */
|
|
19
|
+
item;
|
|
20
|
+
/** Index last written to the row. */
|
|
21
|
+
index;
|
|
22
|
+
value = void 0;
|
|
23
|
+
dispose = noop;
|
|
24
|
+
/** Created by the first `item()` read; null until then. */
|
|
25
|
+
itemNode = null;
|
|
26
|
+
/** Created by the first `index()` read; null until then. */
|
|
27
|
+
indexNode = null;
|
|
28
|
+
constructor(key, first, item, index) {
|
|
29
|
+
this.key = key;
|
|
30
|
+
this.first = first;
|
|
31
|
+
this.item = item;
|
|
32
|
+
this.index = index;
|
|
33
|
+
}
|
|
34
|
+
readItem() {
|
|
35
|
+
this.itemNode ??= createSignalNode(this.item, Object.is);
|
|
36
|
+
return readSignal(this.itemNode);
|
|
37
|
+
}
|
|
38
|
+
readIndex() {
|
|
39
|
+
this.indexNode ??= createSignalNode(this.index, Object.is);
|
|
40
|
+
return readSignal(this.indexNode);
|
|
41
|
+
}
|
|
42
|
+
/** List bookkeeping, not a user write: allowed while the list memo computes. */
|
|
43
|
+
setItem(next) {
|
|
44
|
+
this.item = next;
|
|
45
|
+
if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });
|
|
46
|
+
}
|
|
47
|
+
setIndex(next) {
|
|
48
|
+
this.index = next;
|
|
49
|
+
if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
/** The dispose of a row whose root has not been made yet. */
|
|
53
|
+
function noop() {}
|
|
54
|
+
function mapArray(list, map, options) {
|
|
55
|
+
const keyOf = options?.key;
|
|
56
|
+
return listRows(list, keyOf === void 0 ? {
|
|
57
|
+
keyOf: (item) => item,
|
|
58
|
+
distinct: false
|
|
59
|
+
} : {
|
|
60
|
+
keyOf: (item) => keyOf(item),
|
|
61
|
+
distinct: true
|
|
62
|
+
}, (item, readItem, readIndex) => map(keyOf === void 0 ? item : readItem, readIndex), options?.fallback);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Maps each position of a list to a row. Rows are created and removed only when the length
|
|
66
|
+
* changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.
|
|
67
|
+
*
|
|
68
|
+
* @param list Source list. `null`, `undefined` and `false` are an empty list.
|
|
69
|
+
* @param map Runs once per position, untracked, in the row's own root.
|
|
70
|
+
* @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.
|
|
71
|
+
* @returns Accessor of the mapped rows, in the order of the input.
|
|
72
|
+
* @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several
|
|
73
|
+
* errors at once arrive as one `AggregateError`.
|
|
74
|
+
* @example
|
|
75
|
+
* import { createRoot, indexArray, useSignal } from "@shadow-js/core";
|
|
76
|
+
*
|
|
77
|
+
* createRoot(() => {
|
|
78
|
+
* const [values] = useSignal(["a", "b"]);
|
|
79
|
+
* const cells = indexArray(values, (value, index) => `${index}: ${value()}`);
|
|
80
|
+
* console.log(cells()); // ["0: a", "1: b"]
|
|
81
|
+
* });
|
|
82
|
+
* @see mapArray
|
|
83
|
+
* @since 1.0.0
|
|
84
|
+
*/
|
|
85
|
+
function indexArray(list, map, options) {
|
|
86
|
+
return listRows(list, {
|
|
87
|
+
keyOf: (_item, position) => position,
|
|
88
|
+
distinct: false
|
|
89
|
+
}, (_item, readItem, readIndex) => map(readItem, untrack(readIndex)), options?.fallback);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The shared engine. The memo tracks `list()` and reconciles the previous rows against the new
|
|
93
|
+
* items; each row is a child of a private holder owner, so the memo's own recomputation never
|
|
94
|
+
* disposes rows, and disposing the list's owner disposes the holder with every row in it.
|
|
95
|
+
*/
|
|
96
|
+
function listRows(list, keying, build, fallback) {
|
|
97
|
+
const holder = new Owner(getOwner());
|
|
98
|
+
onCleanup(() => {
|
|
99
|
+
disposeTree(holder);
|
|
100
|
+
});
|
|
101
|
+
let rows = [];
|
|
102
|
+
let emptyFallback;
|
|
103
|
+
return useMemo(() => {
|
|
104
|
+
const source = listItems(list());
|
|
105
|
+
const items = Array.isArray(source) ? Array.prototype.slice.call(source) : source;
|
|
106
|
+
const entries = untrack(() => toEntries(items, keying));
|
|
107
|
+
const reuse = matchRows(rows, entries);
|
|
108
|
+
const created = [];
|
|
109
|
+
const staged = [];
|
|
110
|
+
let nextFallback;
|
|
111
|
+
try {
|
|
112
|
+
entries.forEach((entry, position) => {
|
|
113
|
+
const from = reuse[position] ?? -1;
|
|
114
|
+
const kept = from === -1 ? void 0 : rows[from];
|
|
115
|
+
if (kept !== void 0) {
|
|
116
|
+
staged.push({
|
|
117
|
+
row: kept,
|
|
118
|
+
item: entry.item,
|
|
119
|
+
position,
|
|
120
|
+
fresh: false
|
|
121
|
+
});
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const row = openRow(holder, entry.key, entry.first, entry.item, position, build);
|
|
125
|
+
created.push(row);
|
|
126
|
+
staged.push({
|
|
127
|
+
row,
|
|
128
|
+
item: entry.item,
|
|
129
|
+
position,
|
|
130
|
+
fresh: true
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
if (entries.length === 0 && fallback !== void 0) nextFallback = emptyFallback ?? openFallback(holder, fallback);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
const failures = [];
|
|
136
|
+
for (const row of created) disposeCollecting(row.dispose, failures);
|
|
137
|
+
if (nextFallback !== void 0 && nextFallback !== emptyFallback) disposeCollecting(nextFallback.dispose, failures);
|
|
138
|
+
throw combineFailures(error, failures);
|
|
139
|
+
}
|
|
140
|
+
const failures = [];
|
|
141
|
+
const previousRows = rows;
|
|
142
|
+
const previousFallback = emptyFallback;
|
|
143
|
+
rows = staged.map((stage) => stage.row);
|
|
144
|
+
emptyFallback = nextFallback;
|
|
145
|
+
const kept = new Uint8Array(previousRows.length);
|
|
146
|
+
for (const from of reuse) if (from !== -1) kept[from] = 1;
|
|
147
|
+
previousRows.forEach((row, from) => {
|
|
148
|
+
if (kept[from] !== 1) disposeCollecting(row.dispose, failures);
|
|
149
|
+
});
|
|
150
|
+
if (previousFallback !== void 0 && previousFallback !== nextFallback) disposeCollecting(previousFallback.dispose, failures);
|
|
151
|
+
for (const stage of staged) {
|
|
152
|
+
if (stage.fresh) continue;
|
|
153
|
+
const row = stage.row;
|
|
154
|
+
if (row.index !== stage.position) row.setIndex(stage.position);
|
|
155
|
+
if (!Object.is(row.item, stage.item)) row.setItem(stage.item);
|
|
156
|
+
}
|
|
157
|
+
throwFailures(failures);
|
|
158
|
+
if (nextFallback !== void 0) return [nextFallback.value];
|
|
159
|
+
return rows.map((row) => row.value);
|
|
160
|
+
}, {
|
|
161
|
+
lazy: true,
|
|
162
|
+
allowWrites: true
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** Treats `null`, `undefined` and `false` as an empty list. */
|
|
166
|
+
function listItems(value) {
|
|
167
|
+
return value === null || value === void 0 || value === false ? [] : value;
|
|
168
|
+
}
|
|
169
|
+
/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */
|
|
170
|
+
function toEntries(items, keying) {
|
|
171
|
+
const entries = [];
|
|
172
|
+
const seen = /* @__PURE__ */ new Set();
|
|
173
|
+
let duplicate = false;
|
|
174
|
+
for (const [position, item] of items.entries()) {
|
|
175
|
+
const key = keying.keyOf(item, position);
|
|
176
|
+
let first = true;
|
|
177
|
+
if (keying.distinct) {
|
|
178
|
+
if (seen.has(key)) {
|
|
179
|
+
first = false;
|
|
180
|
+
duplicate = true;
|
|
181
|
+
} else seen.add(key);
|
|
182
|
+
}
|
|
183
|
+
entries.push({
|
|
184
|
+
item,
|
|
185
|
+
key,
|
|
186
|
+
first
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
if (duplicate) warn("EACH_KEY_DUPLICATE");
|
|
190
|
+
return entries;
|
|
191
|
+
}
|
|
192
|
+
/** Keys compare like `Map` keys: `NaN` matches `NaN`. */
|
|
193
|
+
function sameKey(a, b) {
|
|
194
|
+
return a === b || Number.isNaN(a) && Number.isNaN(b);
|
|
195
|
+
}
|
|
196
|
+
function canReuse(row, entry) {
|
|
197
|
+
return row !== void 0 && entry !== void 0 && row.first && entry.first && sameKey(row.key, entry.key);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix
|
|
201
|
+
* and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle
|
|
202
|
+
* is matched through a Map from key to the chain of old positions with that key (earliest first),
|
|
203
|
+
* so the whole pass is linear on average. Iterative throughout.
|
|
204
|
+
*/
|
|
205
|
+
function matchRows(old, next) {
|
|
206
|
+
const m = old.length;
|
|
207
|
+
const n = next.length;
|
|
208
|
+
const reuse = new Int32Array(n).fill(-1);
|
|
209
|
+
let start = 0;
|
|
210
|
+
while (start < m && start < n && canReuse(old[start], next[start])) {
|
|
211
|
+
reuse[start] = start;
|
|
212
|
+
start += 1;
|
|
213
|
+
}
|
|
214
|
+
let oldEnd = m - 1;
|
|
215
|
+
let newEnd = n - 1;
|
|
216
|
+
while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {
|
|
217
|
+
reuse[newEnd] = oldEnd;
|
|
218
|
+
oldEnd -= 1;
|
|
219
|
+
newEnd -= 1;
|
|
220
|
+
}
|
|
221
|
+
if (start > oldEnd || start > newEnd) return reuse;
|
|
222
|
+
const heads = /* @__PURE__ */ new Map();
|
|
223
|
+
const chain = new Int32Array(m).fill(-1);
|
|
224
|
+
for (let i = oldEnd; i >= start; i -= 1) {
|
|
225
|
+
const row = old[i];
|
|
226
|
+
if (row === void 0 || !row.first) continue;
|
|
227
|
+
chain[i] = heads.get(row.key) ?? -1;
|
|
228
|
+
heads.set(row.key, i);
|
|
229
|
+
}
|
|
230
|
+
for (let j = start; j <= newEnd; j += 1) {
|
|
231
|
+
const entry = next[j];
|
|
232
|
+
if (entry === void 0 || !entry.first) continue;
|
|
233
|
+
const head = heads.get(entry.key);
|
|
234
|
+
if (head === void 0 || head === -1) continue;
|
|
235
|
+
reuse[j] = head;
|
|
236
|
+
heads.set(entry.key, chain[head] ?? -1);
|
|
237
|
+
}
|
|
238
|
+
return reuse;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or
|
|
242
|
+
* `index()` during the build sees the final values. The root is detached from the memo on purpose.
|
|
243
|
+
*/
|
|
244
|
+
function openRow(holder, key, first, item, index, build) {
|
|
245
|
+
const row = new Row(key, first, item, index);
|
|
246
|
+
const readItem = () => row.readItem();
|
|
247
|
+
const readIndex = () => row.readIndex();
|
|
248
|
+
runWithOwner(holder, () => createRoot((dispose) => {
|
|
249
|
+
row.dispose = dispose;
|
|
250
|
+
row.value = untrack(() => build(item, readItem, readIndex));
|
|
251
|
+
}));
|
|
252
|
+
return row;
|
|
253
|
+
}
|
|
254
|
+
/** Creates the empty-list row in its own root under the holder. */
|
|
255
|
+
function openFallback(holder, fallback) {
|
|
256
|
+
return runWithOwner(holder, () => createRoot((dispose) => ({
|
|
257
|
+
value: untrack(fallback),
|
|
258
|
+
dispose
|
|
259
|
+
})));
|
|
260
|
+
}
|
|
261
|
+
/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */
|
|
262
|
+
function disposeCollecting(dispose, failures) {
|
|
263
|
+
try {
|
|
264
|
+
dispose();
|
|
265
|
+
} catch (error) {
|
|
266
|
+
failures.push(error);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function combineFailures(primary, failures) {
|
|
270
|
+
if (failures.length === 0) return primary;
|
|
271
|
+
return new AggregateError([primary, ...failures], "Several errors were thrown while mapping a list.");
|
|
272
|
+
}
|
|
273
|
+
/** Rethrows the one disposal failure, or all of them together. */
|
|
274
|
+
function throwFailures(failures) {
|
|
275
|
+
if (failures.length === 0) return;
|
|
276
|
+
if (failures.length === 1) throw failures[0];
|
|
277
|
+
throw new AggregateError(failures, "Several errors were thrown while disposing list rows.");
|
|
278
|
+
}
|
|
279
|
+
//#endregion
|
|
280
|
+
export { indexArray, mapArray };
|
|
281
|
+
|
|
282
|
+
//# sourceMappingURL=list.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"list.js","names":[],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n item: T;\n /** Index last written to the row. */\n index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,IAAM,MAAN,MAAgB;;CAEd;;CAEA;;CAEA;;CAEA;CACA,QAAW,KAAA;CACX,UAAsB;;CAEtB,WAAyC;;CAEzC,YAA+C;CAE/C,YAAY,KAAc,OAAgB,MAAS,OAAe;EAChE,KAAK,MAAM;EACX,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;C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IAAU,KAAK,OAAO,MAAM,KAAK;CACjD,MAAM,iBAAoB,IAAI,SAAS;CACvC,MAAM,kBAA0B,IAAI,UAAU;CAC9C,aAAa,cACX,YAAY,YAAY;EACtB,IAAI,UAAU;EACd,IAAI,QAAQ,cAAc,MAAM,MAAM,UAAU,SAAS,CAAC;CAC5D,CAAC,CACH;CACA,OAAO;AACT;;AAGA,SAAS,aAAgB,QAAe,UAAgC;CACtE,OAAO,aAAa,cAClB,YAAY,aAAa;EAAE,OAAO,QAAQ,QAAQ;EAAG;CAAQ,EAAE,CACjE;AACF;;AAGA,SAAS,kBAAkB,SAAqB,UAA2B;CACzE,IAAI;EACF,QAAQ;CACV,SAAS,OAAO;EACd,SAAS,KAAK,KAAK;CACrB;AACF;AAEA,SAAS,gBAAgB,SAAkB,UAAuC;CAChF,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,OAAO,IAAI,eACT,CAAC,SAAS,GAAG,QAAQ,GACX,kDACZ;AACF;;AAGA,SAAS,cAAc,UAAoC;CACzD,IAAI,SAAS,WAAW,GAAG;CAC3B,IAAI,SAAS,WAAW,GAAG,MAAM,SAAS;CAC1C,MAAM,IAAI,eACR,UAEI,uDAEN;AACF"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createComputation, readComputation } from "./extend/index.js";
|
|
2
|
+
//#region src/memo.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates a cached derivation that recomputes only when a dependency actually changed.
|
|
5
|
+
* Dependencies are discovered on every run, so branches that are not taken are not tracked.
|
|
6
|
+
* A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the
|
|
7
|
+
* error there and keeps its previous value; without a boundary it stores the error and rethrows it
|
|
8
|
+
* to every reader.
|
|
9
|
+
*
|
|
10
|
+
* @param fn Computation; receives the previous value (`undefined` on the first run).
|
|
11
|
+
* @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the
|
|
12
|
+
* defaults.
|
|
13
|
+
* @returns An accessor returning the current, always fresh value.
|
|
14
|
+
* @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it
|
|
15
|
+
* computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last
|
|
16
|
+
* run.
|
|
17
|
+
* @example
|
|
18
|
+
* import { useMemo, useSignal } from "@shadow-js/core";
|
|
19
|
+
*
|
|
20
|
+
* const [count, setCount] = useSignal(2);
|
|
21
|
+
* const doubled = useMemo(() => count() * 2);
|
|
22
|
+
* setCount(5);
|
|
23
|
+
* console.log(doubled()); // 10
|
|
24
|
+
* @see useSignal
|
|
25
|
+
* @since 1.0.0
|
|
26
|
+
*/
|
|
27
|
+
function useMemo(fn, options) {
|
|
28
|
+
const node = createComputation({
|
|
29
|
+
kind: "memo",
|
|
30
|
+
fn,
|
|
31
|
+
equals: options?.equals === void 0 ? Object.is : options.equals,
|
|
32
|
+
lazy: options?.lazy === true,
|
|
33
|
+
allowWrites: options?.allowWrites === true,
|
|
34
|
+
...options?.name === void 0 ? {} : { name: options.name }
|
|
35
|
+
});
|
|
36
|
+
return () => readComputation(node);
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
export { useMemo };
|
|
40
|
+
|
|
41
|
+
//# sourceMappingURL=memo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memo.js","names":[],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: (options?.equals === undefined ? Object.is : options.equals) as Equals<unknown>,\n lazy: options?.lazy === true,\n allowWrites: options?.allowWrites === true,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,QACd,IACA,SACa;CACb,MAAM,OAAO,kBAAkB;EAC7B,MAAM;EACF;EACJ,QAAS,SAAS,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ;EAC7D,MAAM,SAAS,SAAS;EACxB,aAAa,SAAS,gBAAgB;EACtC,GAAI,SAAS,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC9D,CAAC;CACD,aAAa,gBAAmB,IAAI;AACtC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { useSignal } from "./signal.js";
|
|
2
|
+
import { useMemo } from "./memo.js";
|
|
3
|
+
//#region src/optimistic.ts
|
|
4
|
+
/**
|
|
5
|
+
* Optimistic state: shows `reducer` applied over the real value for every action whose
|
|
6
|
+
* `settled` promise is still pending. When the promise settles (either way) the action is
|
|
7
|
+
* dropped and the view falls back to the real source, which is where the confirmed result lives.
|
|
8
|
+
*
|
|
9
|
+
* @param source The authoritative value, tracked.
|
|
10
|
+
* @param reducer Pure function combining the current state with one pending action. It runs for
|
|
11
|
+
* every pending action, in the order they were applied, each time the state recomputes.
|
|
12
|
+
* @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once
|
|
13
|
+
* and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.
|
|
14
|
+
* @example
|
|
15
|
+
* import { useOptimistic, useSignal } from "@shadow-js/core";
|
|
16
|
+
*
|
|
17
|
+
* const [todos, setTodos] = useSignal<string[]>([]);
|
|
18
|
+
* const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);
|
|
19
|
+
* const save = (text: string) =>
|
|
20
|
+
* fetch("/api/todos", { method: "POST", body: text }).then(() => setTodos((l) => [...l, text]));
|
|
21
|
+
* addTodo("milk", save("milk")); // shown() includes "milk" at once
|
|
22
|
+
* @see useAction
|
|
23
|
+
* @since 1.0.0
|
|
24
|
+
*/
|
|
25
|
+
function useOptimistic(source, reducer) {
|
|
26
|
+
const [pending, setPending] = useSignal([]);
|
|
27
|
+
const state = useMemo(() => {
|
|
28
|
+
let current = source();
|
|
29
|
+
for (const entry of pending()) current = reducer(current, entry.action);
|
|
30
|
+
return current;
|
|
31
|
+
});
|
|
32
|
+
const apply = (action, settled) => {
|
|
33
|
+
const entry = { action };
|
|
34
|
+
setPending((list) => [...list, entry]);
|
|
35
|
+
const drop = () => {
|
|
36
|
+
setPending((list) => list.filter((item) => item !== entry));
|
|
37
|
+
};
|
|
38
|
+
settled.then(drop, drop);
|
|
39
|
+
};
|
|
40
|
+
return [state, apply];
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
export { useOptimistic };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=optimistic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"optimistic.js","names":[],"sources":["../../src/optimistic.ts"],"sourcesContent":["import type { Accessor } from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Optimistic state: shows `reducer` applied over the real value for every action whose\n * `settled` promise is still pending. When the promise settles (either way) the action is\n * dropped and the view falls back to the real source, which is where the confirmed result lives.\n *\n * @param source The authoritative value, tracked.\n * @param reducer Pure function combining the current state with one pending action. It runs for\n * every pending action, in the order they were applied, each time the state recomputes.\n * @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once\n * and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.\n * @example\n * import { useOptimistic, useSignal } from \"@shadow-js/core\";\n *\n * const [todos, setTodos] = useSignal<string[]>([]);\n * const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);\n * const save = (text: string) =>\n * fetch(\"/api/todos\", { method: \"POST\", body: text }).then(() => setTodos((l) => [...l, text]));\n * addTodo(\"milk\", save(\"milk\")); // shown() includes \"milk\" at once\n * @see useAction\n * @since 1.0.0\n */\nexport function useOptimistic<T, A>(\n source: Accessor<T>,\n reducer: (state: T, action: A) => T,\n): [Accessor<T>, (action: A, settled: Promise<unknown>) => void] {\n const [pending, setPending] = useSignal<ReadonlyArray<{ action: A }>>([]);\n const state = useMemo(() => {\n let current = source();\n for (const entry of pending()) current = reducer(current, entry.action);\n return current;\n });\n const apply = (action: A, settled: Promise<unknown>): void => {\n const entry = { action };\n setPending((list) => [...list, entry]);\n const drop = (): void => {\n setPending((list) => list.filter((item) => item !== entry));\n };\n settled.then(drop, drop);\n };\n return [state, apply];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,cACd,QACA,SAC+D;CAC/D,MAAM,CAAC,SAAS,cAAc,UAAwC,CAAC,CAAC;CACxE,MAAM,QAAQ,cAAc;EAC1B,IAAI,UAAU,OAAO;EACrB,KAAK,MAAM,SAAS,QAAQ,GAAG,UAAU,QAAQ,SAAS,MAAM,MAAM;EACtE,OAAO;CACT,CAAC;CACD,MAAM,SAAS,QAAW,YAAoC;EAC5D,MAAM,QAAQ,EAAE,OAAO;EACvB,YAAY,SAAS,CAAC,GAAG,MAAM,KAAK,CAAC;EACrC,MAAM,aAAmB;GACvB,YAAY,SAAS,KAAK,QAAQ,SAAS,SAAS,KAAK,CAAC;EAC5D;EACA,QAAQ,KAAK,MAAM,IAAI;CACzB;CACA,OAAO,CAAC,OAAO,KAAK;AACtB"}
|