@shadow-js/core 1.0.1 → 1.0.3
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 +23 -0
- package/dist/dev/action.js +11 -7
- package/dist/dev/action.js.map +1 -1
- package/dist/dev/cache.d.ts +2 -1
- package/dist/dev/cache.js +5 -3
- package/dist/dev/cache.js.map +1 -1
- package/dist/dev/effect.js +17 -33
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/extend/index.d.ts +7 -6
- package/dist/dev/extend/index.js +7 -7
- package/dist/dev/extend/index.js.map +1 -1
- package/dist/dev/external-store.js +8 -3
- package/dist/dev/external-store.js.map +1 -1
- package/dist/dev/internal/concurrency.js +56 -30
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/diagnostics.js +0 -2
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/dispose.js +1 -1
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/flags.js +1 -3
- package/dist/dev/internal/flags.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +1 -2
- package/dist/dev/internal/graph.js +47 -69
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/owner.d.ts +9 -6
- package/dist/dev/internal/owner.js +22 -30
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/scheduler.js +44 -73
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/list.js +4 -12
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +2 -1
- package/dist/dev/memo.js +4 -4
- package/dist/dev/memo.js.map +1 -1
- package/dist/dev/ownership.d.ts +4 -2
- package/dist/dev/ownership.js +59 -3
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.js +18 -11
- package/dist/dev/props.js.map +1 -1
- package/dist/dev/reaction.d.ts +1 -1
- package/dist/dev/reaction.js +5 -1
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.js +1 -1
- package/dist/dev/reducer.js.map +1 -1
- package/dist/dev/resource.js +24 -15
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.js +1 -5
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +3 -2
- package/dist/dev/signal.js +3 -3
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +10 -4
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/use-store.d.ts +5 -0
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/transitions.js +1 -1
- package/dist/dev/transitions.js.map +1 -1
- package/dist/prod/action.js +1 -1
- package/dist/prod/action.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/dispose.js +1 -1
- package/dist/prod/internal/dispose.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 +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/action.js +1 -1
- package/dist/server/action.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/dispose.js +1 -1
- package/dist/server/internal/dispose.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 +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 +11 -7
- package/dist/server-dev/action.js.map +1 -1
- package/dist/server-dev/cache.js +5 -3
- package/dist/server-dev/cache.js.map +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/extend/index.js +7 -7
- package/dist/server-dev/extend/index.js.map +1 -1
- package/dist/server-dev/external-store.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +56 -30
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +0 -2
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +1 -1
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/flags.js +1 -3
- package/dist/server-dev/internal/flags.js.map +1 -1
- package/dist/server-dev/internal/graph.js +47 -69
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/owner.js +22 -30
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +44 -73
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/list.js +4 -12
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/memo.js +4 -4
- package/dist/server-dev/memo.js.map +1 -1
- package/dist/server-dev/ownership.js +59 -3
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +18 -11
- package/dist/server-dev/props.js.map +1 -1
- package/dist/server-dev/reaction.js +5 -1
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/reducer.js +1 -1
- package/dist/server-dev/reducer.js.map +1 -1
- package/dist/server-dev/resource.js +24 -15
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js +1 -5
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/signal.js +3 -3
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +10 -4
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/transitions.js.map +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.3
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- A queued effect now brings its stale owners up to date first and is skipped when they dispose it, so a child effect never runs against state its parent was about to discard (also in the transition lane).
|
|
8
|
+
- A disposal nested in a cleanup no longer flushes effects while the outer tree is half torn down.
|
|
9
|
+
- When a cleanup throws as a memo or effect re-runs, the older cleanups still run, the node still re-runs, and the error is thrown once afterward (an `AggregateError` for several); cleanups run as a disposal, so a memo's own cleanup may write a signal in development too.
|
|
10
|
+
- `pauseOwner` pauses every node before running any cleanup, runs cleanups children first, and rethrows once at the end.
|
|
11
|
+
- `useAction` sends the error of a stale dispatch to the owner's error handler, and `dispatch` no longer throws synchronously when the owner has no handler (the error is reported with `reportError`).
|
|
12
|
+
|
|
13
|
+
## 1.0.2
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- A computation that disposed its own owner while running no longer leaves graph edges for the signals it read afterward.
|
|
18
|
+
- `resource.refetch()` on a disposed resource starts no fetch, and a Suspense boundary is released even when the flush after a resource settles (or after `mutate()`) throws.
|
|
19
|
+
- The updater of `resource.mutate()`, the `equals` of `useSelector`, the function behind `cache()` and the `subscribe` function of `useExternalStore` run untracked.
|
|
20
|
+
- `useExternalStore` unsubscribes when its first `getSnapshot()` after subscribing throws, `useReaction`'s `track()` does nothing once its owner is disposed, and a throwing cleanup of a `createRoot` no longer replaces the error its body threw (both are thrown in an `AggregateError`).
|
|
21
|
+
- A store no longer keeps one tracking signal per key it ever read in a tracked context: once an object has collected a few hundred of them, the ones nothing observes are dropped, and a key read again gets a fresh one that reflects the current value (`store.byId[id]` with churning ids no longer grows without bound).
|
|
22
|
+
- Transitions started while a Suspense hold is engaged share one promise instead of adding a waiter each, and the list of suspended memos and effects lists a node once and drops the disposed ones.
|
|
23
|
+
- The `equals` of a memo and of a signal runs untracked, so what it reads is not a dependency of the reader that pulled the memo or of the computation that writes.
|
|
24
|
+
- `DUPLICATE_CORE` is raised now: in development builds `createRoot` lists its copy of core in a registry at `globalThis[Symbol.for("shadow-js.core.instances")]` (at most 8 copies, each with its number of live roots, removed with its last root) and warns once when a root is created while another copy of the same build (client or server) has live roots. Copies that never overlap, such as separate test files, do not warn.
|
|
25
|
+
|
|
3
26
|
## 1.0.1
|
|
4
27
|
|
|
5
28
|
### Changed
|
package/dist/dev/action.js
CHANGED
|
@@ -55,20 +55,24 @@ function useAction(action, initialState) {
|
|
|
55
55
|
});
|
|
56
56
|
};
|
|
57
57
|
const fail = (error) => {
|
|
58
|
-
if (id
|
|
59
|
-
setPending(false);
|
|
58
|
+
if (id === latest) setPending(false);
|
|
60
59
|
if (owner === null) throw error;
|
|
61
|
-
|
|
60
|
+
try {
|
|
61
|
+
handleError(error, owner);
|
|
62
|
+
} catch (uncaught) {
|
|
63
|
+
if (typeof reportError === "function") reportError(uncaught);
|
|
64
|
+
else queueMicrotask(() => Promise.reject(uncaught));
|
|
65
|
+
}
|
|
62
66
|
};
|
|
63
67
|
let result;
|
|
64
68
|
try {
|
|
65
69
|
result = untrack(() => action(previous, ...args));
|
|
66
70
|
} catch (error) {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
71
|
+
try {
|
|
72
|
+
fail(error);
|
|
73
|
+
} catch (thrown) {
|
|
74
|
+
return Promise.reject(thrown);
|
|
70
75
|
}
|
|
71
|
-
fail(error);
|
|
72
76
|
return Promise.resolve();
|
|
73
77
|
}
|
|
74
78
|
if (!isPromiseLike(result)) {
|
package/dist/dev/action.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action.js","names":[],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id
|
|
1
|
+
{"version":3,"file":"action.js","names":[],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n // A stale dispatch changes no state, but its error is still the owner's to hear.\n if (id === latest) setPending(false);\n if (owner === null) throw error;\n try {\n handleError(error, owner);\n } catch (uncaught) {\n // No handler took it: report it, as documented, instead of throwing out of dispatch.\n if (typeof reportError === \"function\") reportError(uncaught);\n else queueMicrotask(() => Promise.reject(uncaught));\n }\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n try {\n fail(error);\n } catch (thrown) {\n // Without an owner the returned promise carries the error.\n return Promise.reject(thrown);\n }\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":";;;;;;AAIA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,UACd,QACA,cAC2F;CAC3F,MAAM,QAAQ,aAAa;CAC3B,MAAM,CAAC,OAAO,YAAY,UAAa,YAAY;CACnD,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,SAAS;CAEb,MAAM,YAAY,GAAG,SAA2B;EAC9C,UAAU;EACV,MAAM,KAAK;EACX,MAAM,WAAW,QAAQ,KAAK;EAC9B,MAAM,UAAU,UAAmB;GACjC,IAAI,OAAO,QAAQ;GACnB,YAAY;IACV,eAAe,KAAK;IACpB,WAAW,KAAK;GAClB,CAAC;EACH;EACA,MAAM,QAAQ,UAAyB;GAErC,IAAI,OAAO,QAAQ,WAAW,KAAK;GACnC,IAAI,UAAU,MAAM,MAAM;GAC1B,IAAI;IACF,YAAY,OAAO,KAAK;GAC1B,SAAS,UAAU;IAEjB,IAAI,OAAO,gBAAgB,YAAY,YAAY,QAAQ;SACtD,qBAAqB,QAAQ,OAAO,QAAQ,CAAC;GACpD;EACF;EACA,IAAI;EACJ,IAAI;GACF,SAAS,cAAc,OAAO,UAAU,GAAG,IAAI,CAAC;EAClD,SAAS,OAAO;GACd,IAAI;IACF,KAAK,KAAK;GACZ,SAAS,QAAQ;IAEf,OAAO,QAAQ,OAAO,MAAM;GAC9B;GACA,OAAO,QAAQ,QAAQ;EACzB;EACA,IAAI,CAAC,cAAiB,MAAM,GAAG;GAC7B,OAAO,MAAM;GACb,OAAO,QAAQ,QAAQ;EACzB;EACA,WAAW,IAAI;EACf,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,KAAK,QAAQ,IAAI;CAClD;CACA,OAAO;EAAC;EAAO;EAAU;CAAO;AAClC"}
|
package/dist/dev/cache.d.ts
CHANGED
|
@@ -10,7 +10,8 @@ export interface CacheOptions {
|
|
|
10
10
|
* Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
|
|
11
11
|
* arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
|
|
12
12
|
* position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
|
|
13
|
-
* A call that throws is not kept.
|
|
13
|
+
* A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what
|
|
14
|
+
* it reads. Outside any owner nothing is scoped, so `fn` runs every time.
|
|
14
15
|
*
|
|
15
16
|
* Use it to share one data fetch between components rendered in the same request.
|
|
16
17
|
*
|
package/dist/dev/cache.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { untrack } from "./ownership.js";
|
|
1
2
|
import { currentOwner } from "./extend/index.js";
|
|
2
3
|
// src/cache.ts
|
|
3
4
|
function sameArgs(a, b) {
|
|
@@ -15,7 +16,8 @@ function rootOf(owner) {
|
|
|
15
16
|
* Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
|
|
16
17
|
* arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
|
|
17
18
|
* position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
|
|
18
|
-
* A call that throws is not kept.
|
|
19
|
+
* A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what
|
|
20
|
+
* it reads. Outside any owner nothing is scoped, so `fn` runs every time.
|
|
19
21
|
*
|
|
20
22
|
* Use it to share one data fetch between components rendered in the same request.
|
|
21
23
|
*
|
|
@@ -40,14 +42,14 @@ function cache(fn, options) {
|
|
|
40
42
|
const scopes = /* @__PURE__ */ new WeakMap();
|
|
41
43
|
return (...args) => {
|
|
42
44
|
const root = rootOf(currentOwner());
|
|
43
|
-
if (root === null) return fn(...args);
|
|
45
|
+
if (root === null) return untrack(() => fn(...args));
|
|
44
46
|
let entries = scopes.get(root);
|
|
45
47
|
if (entries === void 0) {
|
|
46
48
|
entries = [];
|
|
47
49
|
scopes.set(root, entries);
|
|
48
50
|
}
|
|
49
51
|
for (const entry of entries) if (sameArgs(entry.args, args)) return entry.value;
|
|
50
|
-
const value = fn(...args);
|
|
52
|
+
const value = untrack(() => fn(...args));
|
|
51
53
|
entries.push({
|
|
52
54
|
args,
|
|
53
55
|
value
|
package/dist/dev/cache.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.js","names":[],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return fn(...args);\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = fn(...args);\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cache.js","names":[],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what\n * it reads. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return untrack(() => fn(...args));\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = untrack(() => fn(...args));\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":";;;AAiBA,SAAS,SAAS,GAAuB,GAAgC;CACvE,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GACjC,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO;CAErC,OAAO;AACT;;AAGA,SAAS,OAAO,OAAmC;CACjD,IAAI,OAAO;CACX,OAAO,SAAS,QAAQ,KAAK,WAAW,MAAM,OAAO,KAAK;CAC1D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,MACd,IACA,SACmB;CACnB,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WACE,yCACZ;CAEF,MAAM,yBAAS,IAAI,QAAwB;CAC3C,QAAQ,GAAG,SAAe;EACxB,MAAM,OAAO,OAAO,aAAa,CAAC;EAClC,IAAI,SAAS,MAAM,OAAO,cAAc,GAAG,GAAG,IAAI,CAAC;EACnD,IAAI,UAAU,OAAO,IAAI,IAAI;EAC7B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,CAAC;GACX,OAAO,IAAI,MAAM,OAAO;EAC1B;EACA,KAAK,MAAM,SAAS,SAClB,IAAI,SAAS,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM;EAE/C,MAAM,QAAQ,cAAc,GAAG,GAAG,IAAI,CAAC;EACvC,QAAQ,KAAK;GAAE;GAAM;EAAM,CAAC;EAC5B,IAAI,QAAQ,SAAS,OAAO,QAAQ,MAAM;EAC1C,OAAO;CACT;AACF"}
|
package/dist/dev/effect.js
CHANGED
|
@@ -2,53 +2,37 @@ import { warn } from "./internal/diagnostics.js";
|
|
|
2
2
|
import { untrack } from "./ownership.js";
|
|
3
3
|
import { createComputation, currentOwner } from "./extend/index.js";
|
|
4
4
|
// src/effect.ts
|
|
5
|
-
/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */
|
|
6
|
-
const HELD = Symbol("held");
|
|
7
|
-
/** The nearest gate above the current owner (see `Owner.gate`), or null. */
|
|
8
|
-
function nearestGate() {
|
|
9
|
-
for (let owner = currentOwner(); owner !== null; owner = owner.parent) if (owner.gate !== null) return owner.gate;
|
|
10
|
-
return null;
|
|
11
|
-
}
|
|
12
5
|
function createEffect(fnIn, applyIn, render, deferIn, name) {
|
|
13
6
|
if (currentOwner() === null) warn("NO_OWNER_EFFECT");
|
|
14
7
|
let fn = fnIn;
|
|
15
8
|
let apply = applyIn;
|
|
16
9
|
let defer = deferIn;
|
|
17
|
-
const gate = render ? null :
|
|
10
|
+
const gate = render ? null : currentOwner()?.gate ?? null;
|
|
18
11
|
if (gate !== null) {
|
|
19
12
|
let opened = false;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
13
|
+
let closed = false;
|
|
14
|
+
const innerFn = fn;
|
|
15
|
+
const innerApply = apply;
|
|
16
|
+
let skipFirst = defer;
|
|
17
|
+
defer = false;
|
|
18
|
+
fn = (previous) => {
|
|
19
|
+
closed = !opened && gate();
|
|
20
|
+
opened ||= !closed;
|
|
21
|
+
return closed ? void 0 : innerFn(previous);
|
|
22
|
+
};
|
|
23
|
+
if (innerApply !== null) apply = (value, previous) => {
|
|
24
|
+
if (closed) return void 0;
|
|
25
|
+
if (!skipFirst) return innerApply(value, previous);
|
|
26
|
+
skipFirst = false;
|
|
25
27
|
};
|
|
26
|
-
if (apply === null) {
|
|
27
|
-
const inner = fn;
|
|
28
|
-
fn = (previous) => held() ? void 0 : inner(previous);
|
|
29
|
-
} else {
|
|
30
|
-
const innerFn = fn;
|
|
31
|
-
const innerApply = apply;
|
|
32
|
-
let skipFirst = defer;
|
|
33
|
-
defer = false;
|
|
34
|
-
fn = (previous) => held() ? HELD : innerFn(previous);
|
|
35
|
-
apply = (value, previous) => {
|
|
36
|
-
if (value === HELD) return void 0;
|
|
37
|
-
if (skipFirst) {
|
|
38
|
-
skipFirst = false;
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
return innerApply(value, previous === HELD ? void 0 : previous);
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
28
|
}
|
|
45
29
|
createComputation({
|
|
46
30
|
kind: "effect",
|
|
47
31
|
fn,
|
|
48
32
|
render,
|
|
49
33
|
defer,
|
|
50
|
-
|
|
51
|
-
|
|
34
|
+
apply: apply ?? void 0,
|
|
35
|
+
name
|
|
52
36
|
});
|
|
53
37
|
}
|
|
54
38
|
function useEffect(first, second, third) {
|
package/dist/dev/effect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\
|
|
1
|
+
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (__DEV__ && currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : (currentOwner()?.gate ?? null);\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect. `closed` is what the latest run of `fn`\n // found: `apply` runs right after it, and does nothing for a run that was held.\n let opened = false;\n let closed = false;\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => {\n closed = !opened && gate();\n opened ||= !closed;\n return closed ? undefined : innerFn(previous);\n };\n if (innerApply !== null) {\n apply = (value, previous) => {\n if (closed) return undefined;\n if (!skipFirst) return innerApply(value, previous);\n skipFirst = false;\n return undefined;\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n apply: apply ?? undefined,\n name,\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":";;;;AA4BA,SAAS,aACP,MACA,SACA,QACA,SACA,MACM;CAGN,IAAe,aAAa,MAAM,MAAM,KAAK,iBAAiB;CAC9D,IAAI,KAAK;CACT,IAAI,QAAQ;CACZ,IAAI,QAAQ;CACZ,MAAM,OAAO,SAAS,OAAQ,aAAa,CAAC,EAAE,QAAQ;CACtD,IAAI,SAAS,MAAM;EAIjB,IAAI,SAAS;EACb,IAAI,SAAS;EACb,MAAM,UAAU;EAChB,MAAM,aAAa;EAEnB,IAAI,YAAY;EAChB,QAAQ;EACR,MAAM,aAAa;GACjB,SAAS,CAAC,UAAU,KAAK;GACzB,WAAW,CAAC;GACZ,OAAO,SAAS,KAAA,IAAY,QAAQ,QAAQ;EAC9C;EACA,IAAI,eAAe,MACjB,SAAS,OAAO,aAAa;GAC3B,IAAI,QAAQ,OAAO,KAAA;GACnB,IAAI,CAAC,WAAW,OAAO,WAAW,OAAO,QAAQ;GACjD,YAAY;EAEd;CAEJ;CACA,kBAAkB;EAChB,MAAM;EACN;EACA;EACA;EACA,OAAO,SAAS,KAAA;EAChB;CACF,CAAC;AACH;AA0DA,SAAgB,UACd,OACA,QACA,OACM;CACN,IAAI,OAAO,WAAW,YACpB,aACE,OACA,QACA,OACA,OAAO,UAAU,MACjB,OAAO,IACT;MACK;EACL,IAAI,MAAM,QAAQ,MAAM,GAAG,KAAK,qBAAqB;EACrD,aAAa,OAAO,MAAM,OAAO,OAAQ,QAAsC,IAAI;CACrF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBACd,SACA,OACM;CACN,aACE,SACC,SAAS,MACV,MACA,OACA,KAAA,CACF;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,IAAgC;CACtD,mBAAmB,QAAQ,EAAE,GAAG,MAAM,OAAO,OAAO,SAAS;AAC/D"}
|
|
@@ -111,7 +111,8 @@ export declare function runInScope<T>(scope: {
|
|
|
111
111
|
*
|
|
112
112
|
* @param value Initial value.
|
|
113
113
|
* @param equals Decides whether a write is a change: readers are notified only when it returns
|
|
114
|
-
* `false`. `false` notifies on every write.
|
|
114
|
+
* `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's
|
|
115
|
+
* own `equals`), so what it reads is not a dependency of the writer or the reader.
|
|
115
116
|
* @param name Label shown by devtools. Undefined leaves the signal unnamed.
|
|
116
117
|
* @returns The signal node. It has no owner: it lives as long as something references it.
|
|
117
118
|
* @example
|
|
@@ -198,12 +199,12 @@ export interface ComputationOptions {
|
|
|
198
199
|
* returns `false`, and `false` always propagates. Ignored for effects.
|
|
199
200
|
* @default Object.is
|
|
200
201
|
*/
|
|
201
|
-
equals?: Equals<unknown
|
|
202
|
+
equals?: Equals<unknown> | undefined;
|
|
202
203
|
/**
|
|
203
204
|
* Label shown by devtools and diagnostics.
|
|
204
205
|
* @default undefined (the node is unnamed)
|
|
205
206
|
*/
|
|
206
|
-
name?: string;
|
|
207
|
+
name?: string | undefined;
|
|
207
208
|
/**
|
|
208
209
|
* Effects: run in the render phase, synchronously at creation and before user effects in each
|
|
209
210
|
* flush. Ignored for memos.
|
|
@@ -219,19 +220,19 @@ export interface ComputationOptions {
|
|
|
219
220
|
* Memos: do not compute until the first read.
|
|
220
221
|
* @default false (the memo computes once at creation)
|
|
221
222
|
*/
|
|
222
|
-
lazy?: boolean;
|
|
223
|
+
lazy?: boolean | undefined;
|
|
223
224
|
/**
|
|
224
225
|
* Memos that run component setup (such as a hot-reload wrapper): writing signals inside is
|
|
225
226
|
* legitimate there, so the dev-mode write guard stays off.
|
|
226
227
|
* @default false
|
|
227
228
|
*/
|
|
228
|
-
allowWrites?: boolean;
|
|
229
|
+
allowWrites?: boolean | undefined;
|
|
229
230
|
/**
|
|
230
231
|
* Effects: second stage, run untracked with the value `fn` computed and the previous one. It may
|
|
231
232
|
* return a cleanup function.
|
|
232
233
|
* @default undefined (`fn` is the whole effect)
|
|
233
234
|
*/
|
|
234
|
-
apply?: (value: never, previous: never) => unknown;
|
|
235
|
+
apply?: ((value: never, previous: never) => unknown) | undefined;
|
|
235
236
|
/**
|
|
236
237
|
* Owner to attach to. `null` creates a node that no owner disposes.
|
|
237
238
|
* @default the current owner
|
package/dist/dev/extend/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { ShadowError, resetWarningDedupe, setWarningListener, warn } from "../in
|
|
|
4
4
|
import { rt } from "../internal/state.js";
|
|
5
5
|
import { Owner, addCleanup, handleError } from "../internal/owner.js";
|
|
6
6
|
import { enqueue } from "../internal/queue.js";
|
|
7
|
-
import { Computation, Signal, hasObservers, markObservers, observersOf, readMemo, readSignal, recompute, sourcesOf, track, updateIfNecessary } from "../internal/graph.js";
|
|
7
|
+
import { Computation, Signal, hasObservers, isEqual, markObservers, observersOf, readMemo, readSignal, recompute, sourcesOf, track, updateIfNecessary } from "../internal/graph.js";
|
|
8
8
|
import { batch, flush, flushSync, group, schedule } from "../internal/scheduler.js";
|
|
9
9
|
import { runWithContext } from "../context.js";
|
|
10
10
|
import { disposeTree } from "../internal/dispose.js";
|
|
@@ -141,7 +141,8 @@ function runInScope(scope, fn) {
|
|
|
141
141
|
*
|
|
142
142
|
* @param value Initial value.
|
|
143
143
|
* @param equals Decides whether a write is a change: readers are notified only when it returns
|
|
144
|
-
* `false`. `false` notifies on every write.
|
|
144
|
+
* `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's
|
|
145
|
+
* own `equals`), so what it reads is not a dependency of the writer or the reader.
|
|
145
146
|
* @param name Label shown by devtools. Undefined leaves the signal unnamed.
|
|
146
147
|
* @returns The signal node. It has no owner: it lives as long as something references it.
|
|
147
148
|
* @example
|
|
@@ -181,7 +182,7 @@ function createSignalNode(value, equals, name) {
|
|
|
181
182
|
function writeSignal(signal, next, options) {
|
|
182
183
|
if (options?.allowInMemo !== true && isComputingMemo()) throw new ShadowError("WRITE_IN_MEMO");
|
|
183
184
|
const equals = signal.equals;
|
|
184
|
-
if (equals !== false && equals
|
|
185
|
+
if (equals !== false && isEqual(equals, signal.value, next)) return false;
|
|
185
186
|
signal.value = next;
|
|
186
187
|
report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));
|
|
187
188
|
notify(signal);
|
|
@@ -233,13 +234,12 @@ function notify(source) {
|
|
|
233
234
|
*/
|
|
234
235
|
function createComputation(options) {
|
|
235
236
|
const owner = options.owner === void 0 ? rt.owner : options.owner;
|
|
236
|
-
|
|
237
|
-
|
|
237
|
+
const memo = options.kind === "memo";
|
|
238
|
+
const node = new Computation(owner, memo ? 1 : 2, memo ? 32 | (options.allowWrites === true ? 256 : 0) : (options.render === true ? 16 : 0) | (options.defer === true ? 64 : 0) | (options.lane === true ? 512 : 0), options.fn, memo ? options.equals ?? Object.is : false, options.name);
|
|
239
|
+
if (memo) {
|
|
238
240
|
if (options.lazy !== true) updateIfNecessary(node);
|
|
239
241
|
return node;
|
|
240
242
|
}
|
|
241
|
-
const flags = (options.render === true ? 16 : 0) | (options.defer === true ? 64 : 0) | (options.lane === true ? 512 : 0);
|
|
242
|
-
const node = new Computation(owner, 2, flags, options.fn, false, options.name);
|
|
243
243
|
node.apply = options.apply ?? null;
|
|
244
244
|
if (options.render === true) recompute(node);
|
|
245
245
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["OwnerClass"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && equals(signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: (value: never, previous: never) => unknown;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n if (options.kind === \"memo\") {\n const node = new Computation(\n owner,\n KIND_MEMO,\n FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0),\n options.fn,\n options.equals ?? Object.is,\n options.name,\n );\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n const flags =\n (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0);\n const node = new Computation(owner, KIND_EFFECT, flags, options.fn, false, options.name);\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,SAAgB,eAA6B;CAC3C,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAsC;CACpD,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;AAiBA,SAAgB,aAAsB;CACpC,OAAO,GAAG,aAAa;AACzB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAA2B;CACzC,OACE,GAAG,cAAc,KACjB,GAAG,YAAY,QACf,GAAG,QAAQ,SAAA,MACV,GAAG,QAAQ,QAAA,SAA+B;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,WACd,OACA,IACG;CACH,MAAM,QAAQ,GAAG;CACjB,MAAM,WAAW,GAAG;CACpB,IAAI;EACF,MAAM,YAAY,MAAM;EACxB,IAAI,cAAc,KAAA,GAAW,GAAG,QAAQ;EACxC,MAAM,eAAe,MAAM;EAC3B,IAAI,iBAAiB,KAAA,GAAW,GAAG,WAAW;EAC9C,OAAO,GAAG;CACZ,UAAU;EACR,GAAG,QAAQ;EACX,GAAG,WAAW;CAChB;AACF;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,iBAAoB,OAAU,QAAmB,MAA0B;CACzF,OAAO,IAAI,OAAU,OAAO,QAAQ,IAAI;AAC1C;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,YAAe,QAAmB,MAAS,SAAiC;CAC1F,IAAe,SAAS,gBAAgB,QAAQ,gBAAgB,GAC9D,MAAM,IAAI,YAAY,eAAe;CAEvC,MAAM,SAAS,OAAO;CACtB,IAAI,WAAW,SAAS,OAAO,OAAO,OAAO,IAAI,GAAG,OAAO;CAC3D,OAAO,QAAQ;CAEb,OAAO,eAAe,gBAAgB,QAAQ,MAAM,GAAG,SAAS,YAAY,MAAM,CAAC;CAErF,OAAO,MAAM;CACb,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAAO,QAAsB;CAC3C,IAAI,CAAC,aAAa,MAAM,GAAG;CAC3B,cAAc,MAAM;CACpB,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,QAAQ,QAAQ,UAAU,KAAA,IAAY,GAAG,QAAQ,QAAQ;CAC/D,IAAI,QAAQ,SAAS,QAAQ;EAC3B,MAAM,OAAO,IAAI,YACf,OAAA,GAAA,MAEe,QAAQ,gBAAgB,OAAA,MAA2B,IAClE,QAAQ,IACR,QAAQ,UAAU,OAAO,IACzB,QAAQ,IACV;EACA,IAAI,QAAQ,SAAS,MAAM,kBAAkB,IAAI;EACjD,OAAO;CACT;CACA,MAAM,SACH,QAAQ,WAAW,OAAA,KAAqB,MACxC,QAAQ,UAAU,OAAA,KAAoB,MACtC,QAAQ,SAAS,OAAA,MAAmB;CACvC,MAAM,OAAO,IAAI,YAAY,OAAA,GAAoB,OAAO,QAAQ,IAAI,OAAO,QAAQ,IAAI;CACvF,KAAK,QAAQ,QAAQ,SAAS;CAC9B,IAAI,QAAQ,WAAW,MAGrB,UAAU,IAAI;MACT;EACL,QAAQ,IAAI;EACZ,SAAS;CACX;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAmB,MAAsB;CACvD,OAAO,SAAY,IAAI;AACzB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,MAAyB;CAC/C,kBAAkB,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,QAA8B;CACxD,OAAO,IAAIA,MAAW,WAAW,KAAA,IAAY,GAAG,QAAQ,MAAM;AAChE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["OwnerClass"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n isEqual,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write. It runs untracked (from `writeSignal`, and from a memo's\n * own `equals`), so what it reads is not a dependency of the writer or the reader.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && isEqual(equals, signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown> | undefined;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string | undefined;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean | undefined;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean | undefined;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: ((value: never, previous: never) => unknown) | undefined;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n const memo = options.kind === \"memo\";\n const node = new Computation(\n owner,\n memo ? KIND_MEMO : KIND_EFFECT,\n memo\n ? FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0)\n : (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0),\n options.fn,\n memo ? (options.equals ?? Object.is) : false,\n options.name,\n );\n if (memo) {\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,SAAgB,eAA6B;CAC3C,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAsC;CACpD,OAAO,GAAG;AACZ;;;;;;;;;;;;;;;;AAiBA,SAAgB,aAAsB;CACpC,OAAO,GAAG,aAAa;AACzB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAA2B;CACzC,OACE,GAAG,cAAc,KACjB,GAAG,YAAY,QACf,GAAG,QAAQ,SAAA,MACV,GAAG,QAAQ,QAAA,SAA+B;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,WACd,OACA,IACG;CACH,MAAM,QAAQ,GAAG;CACjB,MAAM,WAAW,GAAG;CACpB,IAAI;EACF,MAAM,YAAY,MAAM;EACxB,IAAI,cAAc,KAAA,GAAW,GAAG,QAAQ;EACxC,MAAM,eAAe,MAAM;EAC3B,IAAI,iBAAiB,KAAA,GAAW,GAAG,WAAW;EAC9C,OAAO,GAAG;CACZ,UAAU;EACR,GAAG,QAAQ;EACX,GAAG,WAAW;CAChB;AACF;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAoB,OAAU,QAAmB,MAA0B;CACzF,OAAO,IAAI,OAAU,OAAO,QAAQ,IAAI;AAC1C;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,YAAe,QAAmB,MAAS,SAAiC;CAC1F,IAAe,SAAS,gBAAgB,QAAQ,gBAAgB,GAC9D,MAAM,IAAI,YAAY,eAAe;CAEvC,MAAM,SAAS,OAAO;CACtB,IAAI,WAAW,SAAS,QAAQ,QAAQ,OAAO,OAAO,IAAI,GAAG,OAAO;CACpE,OAAO,QAAQ;CAEb,OAAO,eAAe,gBAAgB,QAAQ,MAAM,GAAG,SAAS,YAAY,MAAM,CAAC;CAErF,OAAO,MAAM;CACb,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAAO,QAAsB;CAC3C,IAAI,CAAC,aAAa,MAAM,GAAG;CAC3B,cAAc,MAAM;CACpB,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,QAAQ,QAAQ,UAAU,KAAA,IAAY,GAAG,QAAQ,QAAQ;CAC/D,MAAM,OAAO,QAAQ,SAAS;CAC9B,MAAM,OAAO,IAAI,YACf,OACA,OAAA,IAAA,GACA,OAAA,MACmB,QAAQ,gBAAgB,OAAA,MAA2B,MACjE,QAAQ,WAAW,OAAA,KAAqB,MACtC,QAAQ,UAAU,OAAA,KAAoB,MACtC,QAAQ,SAAS,OAAA,MAAmB,IAC3C,QAAQ,IACR,OAAQ,QAAQ,UAAU,OAAO,KAAM,OACvC,QAAQ,IACV;CACA,IAAI,MAAM;EACR,IAAI,QAAQ,SAAS,MAAM,kBAAkB,IAAI;EACjD,OAAO;CACT;CACA,KAAK,QAAQ,QAAQ,SAAS;CAC9B,IAAI,QAAQ,WAAW,MAGrB,UAAU,IAAI;MACT;EACL,QAAQ,IAAI;EACZ,SAAS;CACX;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAmB,MAAsB;CACvD,OAAO,SAAY,IAAI;AACzB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,MAAyB;CAC/C,kBAAkB,IAAI;AACxB;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,QAA8B;CACxD,OAAO,IAAIA,MAAW,WAAW,KAAA,IAAY,GAAG,QAAQ,MAAM;AAChE"}
|
|
@@ -41,15 +41,20 @@ function useExternalStore(subscribe, getSnapshot, options) {
|
|
|
41
41
|
const first = isHydrating() && options?.getServerSnapshot !== void 0 ? options.getServerSnapshot : getSnapshot;
|
|
42
42
|
const [value, setValue] = useSignal(untrack(first), {
|
|
43
43
|
equals: options?.equals ?? Object.is,
|
|
44
|
-
|
|
44
|
+
name: options?.name
|
|
45
45
|
});
|
|
46
46
|
const sync = () => {
|
|
47
47
|
const next = untrack(getSnapshot);
|
|
48
48
|
setValue(() => next);
|
|
49
49
|
};
|
|
50
50
|
useEffect(() => {
|
|
51
|
-
const unsubscribe = subscribe(sync);
|
|
52
|
-
|
|
51
|
+
const unsubscribe = untrack(() => subscribe(sync));
|
|
52
|
+
try {
|
|
53
|
+
sync();
|
|
54
|
+
} catch (error) {
|
|
55
|
+
unsubscribe();
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
53
58
|
return unsubscribe;
|
|
54
59
|
});
|
|
55
60
|
return value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store.js","names":[],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n
|
|
1
|
+
{"version":3,"file":"external-store.js","names":[],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n const sync = (): void => {\n const next = untrack(getSnapshot);\n setValue(() => next);\n };\n useEffect(() => {\n // `subscribe` is a user callback: what it reads must not re-run (and re-subscribe) this effect.\n const unsubscribe = untrack(() => subscribe(sync));\n try {\n // Catch up with changes made between the first read and the subscription.\n sync();\n } catch (error) {\n // The effect fails, so no cleanup is registered: release the subscription here.\n unsubscribe();\n throw error;\n }\n return unsubscribe;\n });\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,SAAgB,iBACd,WACA,aACA,SACa;CAOb,MAAM,QACJ,YAAY,KAAK,SAAS,sBAAsB,KAAA,IAC5C,QAAQ,oBACR;CACN,MAAM,CAAC,OAAO,YAAY,UAAa,QAAQ,KAAK,GAAG;EACrD,QAAQ,SAAS,UAAU,OAAO;EAClC,MAAM,SAAS;CACjB,CAAC;CACD,MAAM,aAAmB;EACvB,MAAM,OAAO,QAAQ,WAAW;EAChC,eAAe,IAAI;CACrB;CACA,gBAAgB;EAEd,MAAM,cAAc,cAAc,UAAU,IAAI,CAAC;EACjD,IAAI;GAEF,KAAK;EACP,SAAS,OAAO;GAEd,YAAY;GACZ,MAAM;EACR;EACA,OAAO;CACT,CAAC;CACD,OAAO;AACT"}
|