@shadow-js/core 1.0.0 → 1.0.2
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 +19 -0
- package/dist/dev/action.d.ts +0 -2
- package/dist/dev/action.js +1 -2
- package/dist/dev/cache.d.ts +2 -3
- package/dist/dev/cache.js +6 -5
- package/dist/dev/cache.js.map +1 -1
- package/dist/dev/context.d.ts +0 -2
- package/dist/dev/context.js +1 -2
- package/dist/dev/effect.d.ts +0 -2
- package/dist/dev/effect.js +18 -35
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/env.d.ts +0 -2
- package/dist/dev/env.js +1 -2
- package/dist/dev/events.d.ts +0 -2
- package/dist/dev/events.js +1 -2
- package/dist/dev/extend/index.d.ts +7 -8
- package/dist/dev/extend/index.js +8 -9
- package/dist/dev/extend/index.js.map +1 -1
- package/dist/dev/external-store.d.ts +0 -2
- package/dist/dev/external-store.js +9 -5
- package/dist/dev/external-store.js.map +1 -1
- package/dist/dev/internal/concurrency.d.ts +0 -2
- package/dist/dev/internal/concurrency.js +43 -22
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/devtools.d.ts +0 -2
- package/dist/dev/internal/devtools.js +1 -2
- package/dist/dev/internal/diagnostics.d.ts +0 -2
- package/dist/dev/internal/diagnostics.js +1 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/dispose.d.ts +0 -2
- package/dist/dev/internal/dispose.js +1 -2
- package/dist/dev/internal/flags.js +2 -5
- package/dist/dev/internal/flags.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +0 -3
- package/dist/dev/internal/graph.js +21 -39
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/hydration-flag.d.ts +0 -2
- package/dist/dev/internal/hydration-flag.js +1 -2
- package/dist/dev/internal/messages.d.ts +0 -2
- package/dist/dev/internal/messages.js +1 -2
- package/dist/dev/internal/owner.d.ts +7 -7
- package/dist/dev/internal/owner.js +13 -24
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/queue.js +1 -2
- package/dist/dev/internal/scheduler.d.ts +0 -2
- package/dist/dev/internal/scheduler.js +34 -73
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/internal/state.d.ts +0 -2
- package/dist/dev/internal/state.js +1 -2
- package/dist/dev/internal/suspension.d.ts +0 -2
- package/dist/dev/internal/suspension.js +1 -2
- package/dist/dev/internal/types.d.ts +0 -2
- package/dist/dev/list.d.ts +0 -2
- package/dist/dev/list.js +1 -10
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +2 -3
- package/dist/dev/memo.js +5 -6
- package/dist/dev/memo.js.map +1 -1
- package/dist/dev/optimistic.d.ts +0 -2
- package/dist/dev/optimistic.js +1 -2
- package/dist/dev/ownership.d.ts +4 -4
- package/dist/dev/ownership.js +60 -5
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.d.ts +0 -2
- package/dist/dev/props.js +19 -13
- package/dist/dev/props.js.map +1 -1
- package/dist/dev/reaction.d.ts +1 -3
- package/dist/dev/reaction.js +6 -3
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.d.ts +0 -2
- package/dist/dev/reducer.js +2 -3
- package/dist/dev/reducer.js.map +1 -1
- package/dist/dev/refs.d.ts +0 -2
- package/dist/dev/refs.js +1 -2
- package/dist/dev/resource.d.ts +0 -2
- package/dist/dev/resource.js +22 -14
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.d.ts +0 -2
- package/dist/dev/selector.js +2 -7
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +3 -4
- package/dist/dev/signal.js +1 -2
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +7 -2
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/proxies.js +1 -2
- package/dist/dev/store/read.d.ts +0 -2
- package/dist/dev/store/read.js +1 -2
- package/dist/dev/store/reconcile.d.ts +0 -2
- package/dist/dev/store/reconcile.js +1 -2
- package/dist/dev/store/types.d.ts +0 -2
- package/dist/dev/store/use-store.d.ts +5 -2
- package/dist/dev/store/use-store.js +1 -2
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/suspense.d.ts +0 -2
- package/dist/dev/suspense.js +1 -2
- package/dist/dev/transitions.d.ts +0 -2
- package/dist/dev/transitions.js +2 -3
- package/dist/dev/transitions.js.map +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/cache.js.map +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/extend/index.js.map +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/external-store.js.map +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/flags.js +1 -1
- package/dist/prod/internal/flags.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/owner.js +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/memo.js +1 -1
- package/dist/prod/memo.js.map +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js.map +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/reaction.js.map +1 -1
- package/dist/prod/reducer.js +1 -1
- package/dist/prod/reducer.js.map +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/selector.js.map +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/prod/transitions.js.map +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/cache.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/extend/index.js.map +1 -1
- package/dist/server/external-store.js.map +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/flags.js +1 -1
- package/dist/server/internal/flags.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/owner.js +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/memo.js +1 -1
- package/dist/server/memo.js.map +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js.map +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/reaction.js.map +1 -1
- package/dist/server/reducer.js +1 -1
- package/dist/server/reducer.js.map +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/selector.js.map +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js.map +1 -1
- package/dist/server-dev/action.js +1 -2
- package/dist/server-dev/cache.js +6 -5
- package/dist/server-dev/cache.js.map +1 -1
- package/dist/server-dev/context.js +1 -2
- package/dist/server-dev/effect.js +1 -2
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/env.js +1 -2
- package/dist/server-dev/events.js +1 -2
- package/dist/server-dev/extend/index.js +8 -9
- package/dist/server-dev/extend/index.js.map +1 -1
- package/dist/server-dev/external-store.js +1 -2
- package/dist/server-dev/external-store.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +43 -22
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/devtools.js +1 -2
- package/dist/server-dev/internal/diagnostics.js +1 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +1 -2
- package/dist/server-dev/internal/flags.js +2 -5
- package/dist/server-dev/internal/flags.js.map +1 -1
- package/dist/server-dev/internal/graph.js +21 -39
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/hydration-flag.js +1 -2
- package/dist/server-dev/internal/messages.js +1 -2
- package/dist/server-dev/internal/owner.js +13 -24
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/queue.js +1 -2
- package/dist/server-dev/internal/scheduler.js +34 -73
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/internal/state.js +1 -2
- package/dist/server-dev/internal/suspension.js +1 -2
- package/dist/server-dev/list.js +1 -10
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/memo.js +5 -6
- package/dist/server-dev/memo.js.map +1 -1
- package/dist/server-dev/optimistic.js +1 -2
- package/dist/server-dev/ownership.js +60 -5
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +19 -13
- package/dist/server-dev/props.js.map +1 -1
- package/dist/server-dev/reaction.js +6 -3
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/reducer.js +2 -3
- package/dist/server-dev/reducer.js.map +1 -1
- package/dist/server-dev/refs.js +1 -2
- package/dist/server-dev/resource.js +22 -14
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js +2 -7
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/signal.js +1 -2
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +7 -2
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/proxies.js +1 -2
- package/dist/server-dev/store/read.js +1 -2
- package/dist/server-dev/store/reconcile.js +1 -2
- package/dist/server-dev/store/use-store.js +1 -2
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/suspense.js +1 -2
- package/dist/server-dev/transitions.js +1 -2
- package/dist/server-dev/transitions.js.map +1 -1
- package/package.json +2 -1
package/dist/dev/ownership.js
CHANGED
|
@@ -2,7 +2,56 @@ import { ShadowError, warn } from "./internal/diagnostics.js";
|
|
|
2
2
|
import { Owner, addCleanup, handleError } from "./internal/owner.js";
|
|
3
3
|
import { disposeTree } from "./internal/dispose.js";
|
|
4
4
|
import { currentOwner, runInScope } from "./extend/index.js";
|
|
5
|
-
|
|
5
|
+
// src/ownership.ts
|
|
6
|
+
/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */
|
|
7
|
+
const REGISTRY_KEY = "shadow-js.core.instances";
|
|
8
|
+
/**
|
|
9
|
+
* The most copies the registry lists. Real programs have one, a misconfigured one two or three; the
|
|
10
|
+
* limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.
|
|
11
|
+
*/
|
|
12
|
+
const MAX_LISTED_COPIES = 8;
|
|
13
|
+
/**
|
|
14
|
+
* The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:
|
|
15
|
+
* the server build and the client build are different files by design, and tests that render on the server
|
|
16
|
+
* and hydrate in one process load one of each, so only copies of the same build count as duplicates.
|
|
17
|
+
*/
|
|
18
|
+
const COPY = { server: false };
|
|
19
|
+
/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */
|
|
20
|
+
function copyRegistry() {
|
|
21
|
+
const found = globalThis[Symbol.for(REGISTRY_KEY)];
|
|
22
|
+
return found instanceof Map ? found : void 0;
|
|
23
|
+
}
|
|
24
|
+
/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */
|
|
25
|
+
function releaseRoot() {
|
|
26
|
+
const registry = copyRegistry();
|
|
27
|
+
const live = registry?.get(COPY);
|
|
28
|
+
if (registry === void 0 || live === void 0) return;
|
|
29
|
+
if (live > 1) registry.set(COPY, live - 1);
|
|
30
|
+
else registry.delete(COPY);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the
|
|
34
|
+
* live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has
|
|
35
|
+
* live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies
|
|
36
|
+
* that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only
|
|
37
|
+
* behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one
|
|
38
|
+
* shared function, so a root costs no closure: rows of a list make a root each.
|
|
39
|
+
*/
|
|
40
|
+
function listRoot(root) {
|
|
41
|
+
let registry = copyRegistry();
|
|
42
|
+
if (registry === void 0) {
|
|
43
|
+
registry = /* @__PURE__ */ new Map();
|
|
44
|
+
globalThis[Symbol.for(REGISTRY_KEY)] = registry;
|
|
45
|
+
}
|
|
46
|
+
const listed = registry.has(COPY);
|
|
47
|
+
for (const copy of registry.keys()) if (copy !== COPY && copy.server === COPY.server) {
|
|
48
|
+
warn("DUPLICATE_CORE");
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
if (!listed && registry.size >= MAX_LISTED_COPIES) return;
|
|
52
|
+
registry.set(COPY, (registry.get(COPY) ?? 0) + 1);
|
|
53
|
+
addCleanup(root, releaseRoot);
|
|
54
|
+
}
|
|
6
55
|
/**
|
|
7
56
|
* Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an
|
|
8
57
|
* effect or a memo to read a value without re-running when that value changes. The current owner
|
|
@@ -30,14 +79,16 @@ function untrack(fn) {
|
|
|
30
79
|
* Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is
|
|
31
80
|
* disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use
|
|
32
81
|
* it for code that runs outside a component, such as an app entry point, a test or a module that
|
|
33
|
-
* owns long-lived effects.
|
|
82
|
+
* owns long-lived effects. Development builds also use the root to find a second copy of core: a root
|
|
83
|
+
* created while a root of another copy is alive warns `DUPLICATE_CORE` once.
|
|
34
84
|
*
|
|
35
85
|
* @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.
|
|
36
86
|
* @param options `detached` keeps the root out of the current owner. Undefined uses the default
|
|
37
87
|
* (attached).
|
|
38
88
|
* @returns Whatever `fn` returns.
|
|
39
89
|
* @throws Rethrows any error thrown by `fn`, after the root and everything created in it are
|
|
40
|
-
* disposed.
|
|
90
|
+
* disposed. When a cleanup of the root throws as well, both errors are thrown together as an
|
|
91
|
+
* `AggregateError` (the body's first), so the body's error is never replaced.
|
|
41
92
|
* @example
|
|
42
93
|
* import { createRoot, useEffect, useSignal } from "@shadow-js/core";
|
|
43
94
|
*
|
|
@@ -56,13 +107,18 @@ function createRoot(fn, options) {
|
|
|
56
107
|
const current = currentOwner();
|
|
57
108
|
const root = new Owner(detached ? null : current);
|
|
58
109
|
if (detached) root.context = current === null ? null : current.context;
|
|
110
|
+
listRoot(root);
|
|
59
111
|
try {
|
|
60
112
|
return runInScope({
|
|
61
113
|
owner: root,
|
|
62
114
|
listener: null
|
|
63
115
|
}, () => fn(() => disposeTree(root)));
|
|
64
116
|
} catch (error) {
|
|
65
|
-
|
|
117
|
+
try {
|
|
118
|
+
disposeTree(root);
|
|
119
|
+
} catch (cleanupError) {
|
|
120
|
+
throw new AggregateError([error, cleanupError], "The root body threw and so did its disposal.");
|
|
121
|
+
}
|
|
66
122
|
throw error;
|
|
67
123
|
}
|
|
68
124
|
}
|
|
@@ -255,7 +311,6 @@ function useId() {
|
|
|
255
311
|
owner.idCount += 1;
|
|
256
312
|
return `s${path.join("-")}_${sequence}`;
|
|
257
313
|
}
|
|
258
|
-
//#endregion
|
|
259
314
|
export { catchError, createRoot, getOwner, onCleanup, onError, runWithOwner, untrack, useId };
|
|
260
315
|
|
|
261
316
|
//# sourceMappingURL=ownership.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownership.js","names":["disposeOwner"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n disposeOwner(root);\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,QAAW,IAAgB;CACzC,OAAO,WAAW,EAAE,UAAU,KAAK,GAAG,EAAE;AAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,WAAc,IAAgC,SAA0B;CACtF,MAAM,WAAW,SAAS,aAAa;CACvC,MAAM,UAAU,aAAa;CAC7B,MAAM,OAAO,IAAI,MAAM,WAAW,OAAO,OAAO;CAChD,IAAI,UAAU,KAAK,UAAU,YAAY,OAAO,OAAO,QAAQ;CAC/D,IAAI;EACF,OAAO,WAAW;GAAE,OAAO;GAAM,UAAU;EAAK,SAAS,SAASA,YAAa,IAAI,CAAC,CAAC;CACvF,SAAS,OAAO;EACd,YAAa,IAAI;EACjB,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,WAAyB;CACvC,OAAO,aAAa;AACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,aAAgB,OAAqB,IAAgB;CACnE,IAAI,SAAS;CACb,IAAI,QAAQ,UAAU;EACpB,KAAK,yBAAyB;EAC9B,SAAS;CACX;CACA,OAAO,WAAW;EAAE,OAAO;EAAQ,UAAU;CAAK,GAAG,EAAE;AACzD;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,IAAmB;CAC3C,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM;EAClB,KAAK,kBAAkB;EACvB;CACF;CACA,WAAW,OAAO,EAAE;AACtB;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,QAAQ,SAA6B;CACnD,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM;EAClB,KAAK,gBAAgB;EACrB;CACF;CACA,IAAI,MAAM,kBAAkB,MAAM,MAAM,gBAAgB,CAAC,OAAO;MAC3D,MAAM,cAAc,KAAK,OAAO;AACvC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,WAAc,IAAa,SAAsC;CAC/E,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;CACtC,MAAM,gBAAgB,CAAC,OAAO;CAC9B,IAAI;EACF,OAAO,aAAa,OAAO,EAAE;CAC/B,SAAS,OAAO;EACP,YAAiB,OAAO,KAAK;EAApC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAAgB;CAC9B,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM,MAAM,IAAI,YAAY,aAAa;CAIvD,KAAK,IAAI,OAAqB,OAAO,SAAS,MAAM,OAAO,KAAK,QAAQ;EACtE,IAAI,KAAK,aAAa,KAAA,GAAW;EACjC,MAAM,SAAS,KAAK;EACpB,KAAK,WAAW;EAChB,OAAO,IAAI,KAAK,WAAW;CAC7B;CACA,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,OAAqB,OAAO,SAAS,MAAM,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK,KAAK;CAC5F,KAAK,QAAQ;CACb,MAAM,WAAW,MAAM;CACvB,MAAM,WAAW;CACjB,OAAO,IAAI,KAAK,KAAK,GAAG,EAAE,GAAG;AAC/B"}
|
|
1
|
+
{"version":3,"file":"ownership.js","names":["disposeOwner"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */\nconst REGISTRY_KEY = \"shadow-js.core.instances\";\n\n/**\n * The most copies the registry lists. Real programs have one, a misconfigured one two or three; the\n * limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.\n */\nconst MAX_LISTED_COPIES = 8;\n\n/**\n * The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:\n * the server build and the client build are different files by design, and tests that render on the server\n * and hydrate in one process load one of each, so only copies of the same build count as duplicates.\n */\nconst COPY: { readonly server: boolean } = { server: __SERVER__ };\n\n/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */\nfunction copyRegistry(): Map<{ readonly server: boolean }, number> | undefined {\n const found = (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)];\n return found instanceof Map ? found : undefined;\n}\n\n/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */\nfunction releaseRoot(): void {\n const registry = copyRegistry();\n const live = registry?.get(COPY);\n if (registry === undefined || live === undefined) return;\n if (live > 1) registry.set(COPY, live - 1);\n else registry.delete(COPY);\n}\n\n/**\n * Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the\n * live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has\n * live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies\n * that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only\n * behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one\n * shared function, so a root costs no closure: rows of a list make a root each.\n */\nfunction listRoot(root: Owner): void {\n let registry = copyRegistry();\n if (registry === undefined) {\n registry = new Map();\n (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)] = registry;\n }\n const listed = registry.has(COPY);\n for (const copy of registry.keys()) {\n if (copy !== COPY && copy.server === COPY.server) {\n warn(\"DUPLICATE_CORE\");\n break;\n }\n }\n // A copy past the limit is not listed; the warning above has been given by then.\n if (!listed && registry.size >= MAX_LISTED_COPIES) return;\n registry.set(COPY, (registry.get(COPY) ?? 0) + 1);\n addCleanup(root, releaseRoot);\n}\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects. Development builds also use the root to find a second copy of core: a root\n * created while a root of another copy is alive warns `DUPLICATE_CORE` once.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed. When a cleanup of the root throws as well, both errors are thrown together as an\n * `AggregateError` (the body's first), so the body's error is never replaced.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n if (__DEV__) listRoot(root);\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n try {\n disposeOwner(root);\n } catch (cleanupError) {\n // The body's error says what went wrong; a cleanup error must not replace it.\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"The root body threw and so did its disposal.\" : \"SHADOW_ROOT_ERRORS\",\n );\n }\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,eAAe;;;;;AAMrB,MAAM,oBAAoB;;;;;;AAO1B,MAAM,OAAqC,EAAE,QAAA,MAAmB;;AAGhE,SAAS,eAAsE;CAC7E,MAAM,QAAS,WAA0C,OAAO,IAAI,YAAY;CAChF,OAAO,iBAAiB,MAAM,QAAQ,KAAA;AACxC;;AAGA,SAAS,cAAoB;CAC3B,MAAM,WAAW,aAAa;CAC9B,MAAM,OAAO,UAAU,IAAI,IAAI;CAC/B,IAAI,aAAa,KAAA,KAAa,SAAS,KAAA,GAAW;CAClD,IAAI,OAAO,GAAG,SAAS,IAAI,MAAM,OAAO,CAAC;MACpC,SAAS,OAAO,IAAI;AAC3B;;;;;;;;;AAUA,SAAS,SAAS,MAAmB;CACnC,IAAI,WAAW,aAAa;CAC5B,IAAI,aAAa,KAAA,GAAW;EAC1B,2BAAW,IAAI,IAAI;EACnB,WAA2C,OAAO,IAAI,YAAY,KAAK;CACzE;CACA,MAAM,SAAS,SAAS,IAAI,IAAI;CAChC,KAAK,MAAM,QAAQ,SAAS,KAAK,GAC/B,IAAI,SAAS,QAAQ,KAAK,WAAW,KAAK,QAAQ;EAChD,KAAK,gBAAgB;EACrB;CACF;CAGF,IAAI,CAAC,UAAU,SAAS,QAAQ,mBAAmB;CACnD,SAAS,IAAI,OAAO,SAAS,IAAI,IAAI,KAAK,KAAK,CAAC;CAChD,WAAW,MAAM,WAAW;AAC9B;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,QAAW,IAAgB;CACzC,OAAO,WAAW,EAAE,UAAU,KAAK,GAAG,EAAE;AAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,WAAc,IAAgC,SAA0B;CACtF,MAAM,WAAW,S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AO,aAAa,OAAO,EAAE;CAC/B,SAAS,OAAO;EACP,YAAiB,OAAO,KAAK;EAApC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAAgB;CAC9B,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM,MAAM,IAAI,YAAY,aAAa;CAIvD,KAAK,IAAI,OAAqB,OAAO,SAAS,MAAM,OAAO,KAAK,QAAQ;EACtE,IAAI,KAAK,aAAa,KAAA,GAAW;EACjC,MAAM,SAAS,KAAK;EACpB,KAAK,WAAW;EAChB,OAAO,IAAI,KAAK,WAAW;CAC7B;CACA,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,OAAqB,OAAO,SAAS,MAAM,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK,KAAK;CAC5F,KAAK,QAAQ;CACb,MAAM,WAAW,MAAM;CACvB,MAAM,WAAW;CACjB,OAAO,IAAI,KAAK,KAAK,GAAG,EAAE,GAAG;AAC/B"}
|
package/dist/dev/props.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/props.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* A value accepted by {@link mergeProps}: an object, a function that returns one (called at every
|
|
4
3
|
* read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type
|
|
@@ -129,6 +128,5 @@ export declare function splitProps<T extends object, const K extends readonly (r
|
|
|
129
128
|
* @since 1.0.0
|
|
130
129
|
*/
|
|
131
130
|
export declare function children(fn: () => unknown): ResolvedChildren;
|
|
132
|
-
//#endregion
|
|
133
131
|
export {};
|
|
134
132
|
//# sourceMappingURL=props.d.ts.map
|
package/dist/dev/props.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { untrack } from "./ownership.js";
|
|
2
2
|
import { useMemo } from "./memo.js";
|
|
3
|
-
|
|
3
|
+
// src/props.ts
|
|
4
4
|
/**
|
|
5
5
|
* Keys that never take part in a merge or a split. Reading them through a props object that came
|
|
6
6
|
* from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.
|
|
@@ -74,17 +74,19 @@ function mergedKeys(objects) {
|
|
|
74
74
|
return keys;
|
|
75
75
|
}
|
|
76
76
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
77
|
+
* The cache of the live views: `readDepth` counts how deep the live reads are running and
|
|
78
|
+
* `readStates` holds the state each live view computed during the outermost read. A view's traps
|
|
79
|
+
* read the views beneath them, and those read the views beneath them: without a cache every trap
|
|
80
|
+
* recomputes each level below, and a few nested components (a chain of `{...props}` forwards) take
|
|
81
|
+
* exponential time. Within one outermost read a view's state is computed once, so a read costs time
|
|
82
|
+
* linear in the number of views. The cache is dropped when that read returns, so each read still
|
|
83
|
+
* sees the current values.
|
|
84
|
+
*
|
|
85
|
+
* These two are module-level scratch state (R-CODE-4, the scratch-array class), and not registers
|
|
86
|
+
* of `internal/state.ts`: this file may import only the public extension API (EXT-01), which has no
|
|
87
|
+
* place for them, and a new public export for two private counters is not worth it. They are safe
|
|
88
|
+
* because every write is undone in `finally` (`duringRead`), so a getter that throws leaves depth 0
|
|
89
|
+
* and an empty map, and because the map holds a view only while one outermost read is running.
|
|
88
90
|
*/
|
|
89
91
|
let readDepth = 0;
|
|
90
92
|
const readStates = /* @__PURE__ */ new Map();
|
|
@@ -104,6 +106,11 @@ function duringRead(run) {
|
|
|
104
106
|
if (readDepth === 0) readStates.clear();
|
|
105
107
|
}
|
|
106
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so
|
|
111
|
+
* a function source is called once per access. The target is an ordinary object, so prototype
|
|
112
|
+
* lookups keep their usual meaning, and every write is refused because props are read-only.
|
|
113
|
+
*/
|
|
107
114
|
function liveView(load) {
|
|
108
115
|
const target = {};
|
|
109
116
|
return new Proxy(target, {
|
|
@@ -276,7 +283,6 @@ function children(fn) {
|
|
|
276
283
|
}
|
|
277
284
|
});
|
|
278
285
|
}
|
|
279
|
-
//#endregion
|
|
280
286
|
export { children, mergeProps, splitProps };
|
|
281
287
|
|
|
282
288
|
//# sourceMappingURL=props.js.map
|
package/dist/dev/props.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"props.js","names":[],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\n/**\n * How deep the live reads are running, and the state each live view computed during the outermost\n * read. A view's traps read the views beneath it, and those read the views beneath them: without a\n * cache every trap recomputes each level below, and a few nested components (a chain of `{...props}`\n * forwards) take exponential time. Within one outermost read a view's state is computed once, so a\n * read costs time linear in the number of views. The cache is dropped when that read returns, so each\n * read still sees the current values.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new Typ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,IAAI,MAAM,IAAI;IACtB,IAAI,QAAQ;IACZ,QAAQ,IAAI;IACZ,WAAW;GACb,OAAO;IACL,OAAO,IAAI;IACX,KAAK,OAAO,IAAI,KAAK;GACvB;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,SAAS,IAAqC;CAC5D,MAAM,OAAO,cAAc,gBAAgB,EAAE,GAAG,EAAE,aAAa,KAAK,CAAC;CACrE,MAAM,iBAA0B;EAC9B,MAAM,SAAS,KAAK;EACpB,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;EACvC,OAAO,OAAO,WAAW,IAAI,KAAA,IAAY;CAC3C;CACA,OAAO,OAAO,OAAO,UAAU;EAC7B,eAA0B,CAAC,GAAG,KAAK,CAAC;EACpC,aAAqB,KAAK,CAAC,CAAC;EAC5B,MAAS,OACP,KAAK,CAAC,CAAC,KAAK,MAAM,UAAU,cAAc,GAAG,MAAM,KAAK,CAAC,CAAC;EAC5D,UAAU,OAAqD;GAC7D,KAAK,CAAC,CAAC,SAAS,MAAM,UAAU;IAC9B,cAAc,GAAG,MAAM,KAAK,CAAC;GAC/B,CAAC;EACH;EACA,YAAqB;GACnB,MAAM,SAAS,KAAK;GACpB,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,UAEJ,mDAAmD,OAAO,QAEhE;GAEF,OAAO,OAAO;EAChB;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"props.js","names":[],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * The cache of the live views: `readDepth` counts how deep the live reads are running and\n * `readStates` holds the state each live view computed during the outermost read. A view's traps\n * read the views beneath them, and those read the views beneath them: without a cache every trap\n * recomputes each level below, and a few nested components (a chain of `{...props}` forwards) take\n * exponential time. Within one outermost read a view's state is computed once, so a read costs time\n * linear in the number of views. The cache is dropped when that read returns, so each read still\n * sees the current values.\n *\n * These two are module-level scratch state (R-CODE-4, the scratch-array class), and not registers\n * of `internal/state.ts`: this file may import only the public extension API (EXT-01), which has no\n * place for them, and a new public export for two private counters is not worth it. They are safe\n * because every write is undone in `finally` (`duringRead`), so a getter that throws leaves depth 0\n * and an empty map, and because the map holds a view only while one outermost read is running.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n : \"SHADOW_CHILDREN_ONLY\",\n );\n }\n return leaves[0];\n },\n });\n}\n"],"mappings":";;;;;;;AAOA,MAAM,8BAAwC,IAAI,IAAiB;CACjE;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAM,gCAAgB,IAAI,QAAgB;;AAG1C,MAAM,sBAAsB;;AAgF5B,SAAS,cAAc,OAAmD;CACxE,OAAO,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU;AAC5D;;AAGA,SAAS,kBAAkB,QAAuB;CAChD,OAAO,QAAQ,QAAQ,MAAM,CAA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AAW,IAAI,KAAA,IAAY;CAC3C;CACA,OAAO,OAAO,OAAO,UAAU;EAC7B,eAA0B,CAAC,GAAG,KAAK,CAAC;EACpC,aAAqB,KAAK,CAAC,CAAC;EAC5B,MAAS,OACP,KAAK,CAAC,CAAC,KAAK,MAAM,UAAU,cAAc,GAAG,MAAM,KAAK,CAAC,CAAC;EAC5D,UAAU,OAAqD;GAC7D,KAAK,CAAC,CAAC,SAAS,MAAM,UAAU;IAC9B,cAAc,GAAG,MAAM,KAAK,CAAC;GAC/B,CAAC;EACH;EACA,YAAqB;GACnB,MAAM,SAAS,KAAK;GACpB,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,UAEJ,mDAAmD,OAAO,QAEhE;GAEF,OAAO,OAAO;EAChB;CACF,CAAC;AACH"}
|
package/dist/dev/reaction.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/reaction.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`
|
|
4
3
|
* returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.
|
|
@@ -10,7 +9,7 @@
|
|
|
10
9
|
*
|
|
11
10
|
* @param onInvalidate Called once, untracked, after a change of a tracked read.
|
|
12
11
|
* @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the
|
|
13
|
-
* owner that called `useReaction`, so it stops when that owner is disposed.
|
|
12
|
+
* owner that called `useReaction`, so it stops when that owner is disposed; calling `track` after that does nothing.
|
|
14
13
|
* @example
|
|
15
14
|
* import { useReaction, useSignal } from "@shadow-js/core";
|
|
16
15
|
*
|
|
@@ -25,5 +24,4 @@
|
|
|
25
24
|
* @since 1.0.0
|
|
26
25
|
*/
|
|
27
26
|
export declare function useReaction(onInvalidate: () => void): (track: () => void) => void;
|
|
28
|
-
//#endregion
|
|
29
27
|
//# sourceMappingURL=reaction.d.ts.map
|
package/dist/dev/reaction.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { untrack } from "./ownership.js";
|
|
2
2
|
import { disposeTree } from "./internal/dispose.js";
|
|
3
3
|
import { createComputation, createOwner, currentOwner, runInScope } from "./extend/index.js";
|
|
4
|
-
|
|
4
|
+
// src/reaction.ts
|
|
5
5
|
/**
|
|
6
6
|
* Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`
|
|
7
7
|
* returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.
|
|
@@ -13,7 +13,7 @@ import { createComputation, createOwner, currentOwner, runInScope } from "./exte
|
|
|
13
13
|
*
|
|
14
14
|
* @param onInvalidate Called once, untracked, after a change of a tracked read.
|
|
15
15
|
* @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the
|
|
16
|
-
* owner that called `useReaction`, so it stops when that owner is disposed.
|
|
16
|
+
* owner that called `useReaction`, so it stops when that owner is disposed; calling `track` after that does nothing.
|
|
17
17
|
* @example
|
|
18
18
|
* import { useReaction, useSignal } from "@shadow-js/core";
|
|
19
19
|
*
|
|
@@ -32,6 +32,10 @@ function useReaction(onInvalidate) {
|
|
|
32
32
|
let scope = null;
|
|
33
33
|
return (track) => {
|
|
34
34
|
if (scope !== null) disposeTree(scope);
|
|
35
|
+
if (owner?.disposed === true) {
|
|
36
|
+
scope = null;
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
35
39
|
const next = createOwner(owner);
|
|
36
40
|
scope = next;
|
|
37
41
|
let tracking = true;
|
|
@@ -55,7 +59,6 @@ function useReaction(onInvalidate) {
|
|
|
55
59
|
});
|
|
56
60
|
};
|
|
57
61
|
}
|
|
58
|
-
//#endregion
|
|
59
62
|
export { useReaction };
|
|
60
63
|
|
|
61
64
|
//# sourceMappingURL=reaction.js.map
|
package/dist/dev/reaction.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reaction.js","names":[],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,YAAY,cAAuD;CACjF,MAAM,QAAQ,aAAa;CAC3B,IAAI,QAAsB;CAC1B,QAAQ,UAA4B;EAClC,IAAI,UAAU,MAAM,YAAa,KAAK;
|
|
1
|
+
{"version":3,"file":"reaction.js","names":[],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed; calling `track` after that does nothing.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n // The owner is gone: a scope made now would hang on it and never be disposed.\n if (owner?.disposed === true) {\n scope = null;\n return;\n }\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,YAAY,cAAuD;CACjF,MAAM,QAAQ,aAAa;CAC3B,IAAI,QAAsB;CAC1B,QAAQ,UAA4B;EAClC,IAAI,UAAU,MAAM,YAAa,KAAK;EAEtC,IAAI,OAAO,aAAa,MAAM;GAC5B,QAAQ;GACR;EACF;EACA,MAAM,OAAO,YAAY,KAAK;EAC9B,QAAQ;EACR,IAAI,WAAW;EACf,WAAW;GAAE,OAAO;GAAM,UAAU;EAAK,SAAS;GAChD,kBAAkB;IAChB,MAAM;IACN,QAAQ;IACR,OAAO;IACP,UAAU;KACR,IAAI,UAAU;MACZ,WAAW;MACX,MAAM;MACN;KACF;KACA,QAAQ,YAAY;IAEtB;GACF,CAAC;EACH,CAAC;CACH;AACF"}
|
package/dist/dev/reducer.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Accessor, Equals } from "./internal/types.js";
|
|
2
|
-
//#region src/reducer.d.ts
|
|
3
2
|
/** Options of {@link useReducer}. @since 1.0.0 */
|
|
4
3
|
export interface ReducerOptions {
|
|
5
4
|
/**
|
|
@@ -37,5 +36,4 @@ export interface ReducerOptions {
|
|
|
37
36
|
* @since 1.0.0
|
|
38
37
|
*/
|
|
39
38
|
export declare function useReducer<S, A>(reducer: (state: S, action: A) => S, initialState: S, options?: ReducerOptions): [Accessor<S>, (action: A) => void];
|
|
40
|
-
//#endregion
|
|
41
39
|
//# sourceMappingURL=reducer.d.ts.map
|
package/dist/dev/reducer.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useSignal } from "./signal.js";
|
|
2
|
-
|
|
2
|
+
// src/reducer.ts
|
|
3
3
|
/**
|
|
4
4
|
* A state cell whose writes go through a reducer: `dispatch(action)` stores
|
|
5
5
|
* `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,
|
|
@@ -26,14 +26,13 @@ import { useSignal } from "./signal.js";
|
|
|
26
26
|
function useReducer(reducer, initialState, options) {
|
|
27
27
|
const [state, setState] = useSignal(initialState, {
|
|
28
28
|
equals: options?.equals ?? Object.is,
|
|
29
|
-
|
|
29
|
+
name: options?.name
|
|
30
30
|
});
|
|
31
31
|
const dispatch = (action) => {
|
|
32
32
|
setState((previous) => reducer(previous, action));
|
|
33
33
|
};
|
|
34
34
|
return [state, dispatch];
|
|
35
35
|
}
|
|
36
|
-
//#endregion
|
|
37
36
|
export { useReducer };
|
|
38
37
|
|
|
39
38
|
//# sourceMappingURL=reducer.js.map
|
package/dist/dev/reducer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reducer.js","names":[],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n
|
|
1
|
+
{"version":3,"file":"reducer.js","names":[],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n name: options?.name,\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,WACd,SACA,cACA,SACoC;CACpC,MAAM,CAAC,OAAO,YAAY,UAAa,cAAc;EACnD,QAAS,SAAS,UAAU,OAAO;EACnC,MAAM,SAAS;CACjB,CAAC;CACD,MAAM,YAAY,WAAoB;EACpC,UAAU,aAAa,QAAQ,UAAU,MAAM,CAAC;CAClD;CACA,OAAO,CAAC,OAAO,QAAQ;AACzB"}
|
package/dist/dev/refs.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/refs.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* A ref object that is also a ref callback: pass it as `ref={r}` (the renderer calls it with the
|
|
4
3
|
* element) and read the element as `r.current`. `undefined` when nothing is attached.
|
|
@@ -48,5 +47,4 @@ export declare function createRef<T>(): Ref<T>;
|
|
|
48
47
|
* @since 1.0.0
|
|
49
48
|
*/
|
|
50
49
|
export declare function useImperativeHandle<T>(ref: ((value: T | undefined) => void) | null | undefined, create: () => T): void;
|
|
51
|
-
//#endregion
|
|
52
50
|
//# sourceMappingURL=refs.d.ts.map
|
package/dist/dev/refs.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { onCleanup, untrack } from "./ownership.js";
|
|
2
|
-
|
|
2
|
+
// src/refs.ts
|
|
3
3
|
/**
|
|
4
4
|
* Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`
|
|
5
5
|
* clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.
|
|
@@ -52,7 +52,6 @@ function useImperativeHandle(ref, create) {
|
|
|
52
52
|
ref(untrack(create));
|
|
53
53
|
onCleanup(() => ref(void 0));
|
|
54
54
|
}
|
|
55
|
-
//#endregion
|
|
56
55
|
export { createRef, useImperativeHandle };
|
|
57
56
|
|
|
58
57
|
//# sourceMappingURL=refs.js.map
|
package/dist/dev/resource.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Accessor } from "./internal/types.js";
|
|
2
|
-
//#region src/resource.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Where a {@link Resource} is in its life: `"unresolved"` (no value and no fetch, for example while
|
|
5
4
|
* the source is falsy), `"pending"` (the first fetch is in flight), `"ready"` (a value is shown and
|
|
@@ -131,5 +130,4 @@ export declare function useResource<S, T>(source: Accessor<S | false | null | un
|
|
|
131
130
|
export declare function useResource<S extends string | number | boolean | bigint | object, T>(source: S, fetcher: (source: S, info: ResourceInfo) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
132
131
|
export declare function useResource<T>(fetcher: (info: ResourceInfo<T>) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
133
132
|
export declare function useResource<S, T>(source: Accessor<S | false | null | undefined>, fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
134
|
-
//#endregion
|
|
135
133
|
//# sourceMappingURL=resource.d.ts.map
|
package/dist/dev/resource.js
CHANGED
|
@@ -7,7 +7,7 @@ import { useContext } from "./context.js";
|
|
|
7
7
|
import { ResourceCacheContext, SuspenseContext } from "./suspense.js";
|
|
8
8
|
import { holdReader, inTransition } from "./internal/concurrency.js";
|
|
9
9
|
import { createSignalNode, currentListener, currentOwner, writeSignal } from "./extend/index.js";
|
|
10
|
-
|
|
10
|
+
// src/resource.ts
|
|
11
11
|
/**
|
|
12
12
|
* A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`
|
|
13
13
|
* false notifies on every write, true only when the value changes.
|
|
@@ -54,8 +54,11 @@ function useResource(first, second, third) {
|
|
|
54
54
|
/** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */
|
|
55
55
|
const settle = (id, apply) => {
|
|
56
56
|
if (disposed || id !== version) return false;
|
|
57
|
-
|
|
58
|
-
|
|
57
|
+
try {
|
|
58
|
+
batch(apply);
|
|
59
|
+
} finally {
|
|
60
|
+
release();
|
|
61
|
+
}
|
|
59
62
|
return true;
|
|
60
63
|
};
|
|
61
64
|
/** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */
|
|
@@ -143,22 +146,28 @@ function useResource(first, second, third) {
|
|
|
143
146
|
error: { get: failure },
|
|
144
147
|
latest: { get: value },
|
|
145
148
|
refetch: { value: () => {
|
|
149
|
+
if (disposed) return Promise.resolve(void 0);
|
|
146
150
|
const input = untrack(source);
|
|
147
151
|
if (input === false || input === null || input === void 0) return Promise.resolve(void 0);
|
|
148
152
|
return load(input, hasValue);
|
|
149
153
|
} },
|
|
150
154
|
mutate: { value: (next) => {
|
|
151
155
|
let resolved;
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
156
|
+
let changed = false;
|
|
157
|
+
try {
|
|
158
|
+
batch(() => {
|
|
159
|
+
resolved = typeof next === "function" ? untrack(() => next(value())) : next;
|
|
160
|
+
changed = true;
|
|
161
|
+
controller?.abort();
|
|
162
|
+
version += 1;
|
|
163
|
+
hasValue = true;
|
|
164
|
+
setValue(resolved);
|
|
165
|
+
setFailure(void 0);
|
|
166
|
+
setState("ready");
|
|
167
|
+
});
|
|
168
|
+
} finally {
|
|
169
|
+
if (changed) release();
|
|
170
|
+
}
|
|
162
171
|
return resolved;
|
|
163
172
|
} }
|
|
164
173
|
});
|
|
@@ -171,7 +180,6 @@ function useResource(first, second, third) {
|
|
|
171
180
|
});
|
|
172
181
|
return read;
|
|
173
182
|
}
|
|
174
|
-
//#endregion
|
|
175
183
|
export { useResource };
|
|
176
184
|
|
|
177
185
|
//# sourceMappingURL=resource.js.map
|