@shadow-js/core 0.1.0 → 1.0.1
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 +17 -0
- package/LICENSE +2 -2
- package/README.md +134 -331
- package/dist/dev/action.d.ts +34 -0
- package/dist/dev/action.js +89 -0
- package/dist/dev/action.js.map +1 -0
- package/dist/dev/cache.d.ts +33 -0
- package/dist/dev/cache.js +61 -0
- package/dist/dev/cache.js.map +1 -0
- package/dist/dev/context.d.ts +104 -0
- package/dist/dev/context.js +110 -0
- package/dist/dev/context.js.map +1 -0
- package/dist/dev/effect.d.ts +120 -0
- package/dist/dev/effect.js +110 -0
- package/dist/dev/effect.js.map +1 -0
- package/dist/dev/env.d.ts +27 -0
- package/dist/dev/env.js +30 -0
- package/dist/dev/env.js.map +1 -0
- package/dist/dev/events.d.ts +26 -0
- package/dist/dev/events.js +32 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend/index.d.ts +329 -0
- package/dist/dev/extend/index.js +316 -0
- package/dist/dev/extend/index.js.map +1 -0
- package/dist/dev/external-store.d.ts +58 -0
- package/dist/dev/external-store.js +59 -0
- package/dist/dev/external-store.js.map +1 -0
- package/dist/dev/index.d.ts +29 -0
- package/dist/dev/index.js +26 -0
- package/dist/dev/internal/concurrency.d.ts +211 -0
- package/dist/dev/internal/concurrency.js +631 -0
- package/dist/dev/internal/concurrency.js.map +1 -0
- package/dist/dev/internal/devtools.d.ts +69 -0
- package/dist/dev/internal/devtools.js +76 -0
- package/dist/dev/internal/devtools.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +88 -0
- package/dist/dev/internal/diagnostics.js +101 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/dispose.d.ts +26 -0
- package/dist/dev/internal/dispose.js +48 -0
- package/dist/dev/internal/dispose.js.map +1 -0
- package/dist/dev/internal/flags.js +10 -0
- package/dist/dev/internal/flags.js.map +1 -0
- package/dist/dev/internal/graph.d.ts +231 -0
- package/dist/dev/internal/graph.js +577 -0
- package/dist/dev/internal/graph.js.map +1 -0
- package/dist/dev/internal/hydration-flag.d.ts +31 -0
- package/dist/dev/internal/hydration-flag.js +45 -0
- package/dist/dev/internal/hydration-flag.js.map +1 -0
- package/dist/dev/internal/messages.d.ts +54 -0
- package/dist/dev/internal/messages.js +53 -0
- package/dist/dev/internal/messages.js.map +1 -0
- package/dist/dev/internal/owner.d.ts +140 -0
- package/dist/dev/internal/owner.js +289 -0
- package/dist/dev/internal/owner.js.map +1 -0
- package/dist/dev/internal/queue.js +45 -0
- package/dist/dev/internal/queue.js.map +1 -0
- package/dist/dev/internal/scheduler.d.ts +111 -0
- package/dist/dev/internal/scheduler.js +286 -0
- package/dist/dev/internal/scheduler.js.map +1 -0
- package/dist/dev/internal/state.d.ts +139 -0
- package/dist/dev/internal/state.js +27 -0
- package/dist/dev/internal/state.js.map +1 -0
- package/dist/dev/internal/suspension.d.ts +41 -0
- package/dist/dev/internal/suspension.js +44 -0
- package/dist/dev/internal/suspension.js.map +1 -0
- package/dist/dev/internal/types.d.ts +44 -0
- package/dist/dev/list.d.ts +91 -0
- package/dist/dev/list.js +281 -0
- package/dist/dev/list.js.map +1 -0
- package/dist/dev/memo.d.ts +58 -0
- package/dist/dev/memo.js +40 -0
- package/dist/dev/memo.js.map +1 -0
- package/dist/dev/optimistic.d.ts +24 -0
- package/dist/dev/optimistic.js +44 -0
- package/dist/dev/optimistic.js.map +1 -0
- package/dist/dev/ownership.d.ts +202 -0
- package/dist/dev/ownership.js +260 -0
- package/dist/dev/ownership.js.map +1 -0
- package/dist/dev/props.d.ts +132 -0
- package/dist/dev/props.js +281 -0
- package/dist/dev/props.js.map +1 -0
- package/dist/dev/reaction.d.ts +27 -0
- package/dist/dev/reaction.js +60 -0
- package/dist/dev/reaction.js.map +1 -0
- package/dist/dev/reducer.d.ts +39 -0
- package/dist/dev/reducer.js +38 -0
- package/dist/dev/reducer.js.map +1 -0
- package/dist/dev/refs.d.ts +50 -0
- package/dist/dev/refs.js +57 -0
- package/dist/dev/refs.js.map +1 -0
- package/dist/dev/resource.d.ts +133 -0
- package/dist/dev/resource.js +176 -0
- package/dist/dev/resource.js.map +1 -0
- package/dist/dev/selector.d.ts +32 -0
- package/dist/dev/selector.js +117 -0
- package/dist/dev/selector.js.map +1 -0
- package/dist/dev/signal.d.ts +40 -0
- package/dist/dev/signal.js +38 -0
- package/dist/dev/signal.js.map +1 -0
- package/dist/dev/store/index.d.ts +5 -0
- package/dist/dev/store/index.js +4 -0
- package/dist/dev/store/nodes.js +191 -0
- package/dist/dev/store/nodes.js.map +1 -0
- package/dist/dev/store/proxies.js +159 -0
- package/dist/dev/store/proxies.js.map +1 -0
- package/dist/dev/store/read.d.ts +37 -0
- package/dist/dev/store/read.js +71 -0
- package/dist/dev/store/read.js.map +1 -0
- package/dist/dev/store/reconcile.d.ts +71 -0
- package/dist/dev/store/reconcile.js +185 -0
- package/dist/dev/store/reconcile.js.map +1 -0
- package/dist/dev/store/types.d.ts +104 -0
- package/dist/dev/store/use-store.d.ts +58 -0
- package/dist/dev/store/use-store.js +167 -0
- package/dist/dev/store/use-store.js.map +1 -0
- package/dist/dev/suspense.d.ts +99 -0
- package/dist/dev/suspense.js +44 -0
- package/dist/dev/suspense.js.map +1 -0
- package/dist/dev/transitions.d.ts +75 -0
- package/dist/dev/transitions.js +100 -0
- package/dist/dev/transitions.js.map +1 -0
- package/dist/prod/action.js +2 -0
- package/dist/prod/action.js.map +1 -0
- package/dist/prod/cache.js +2 -0
- package/dist/prod/cache.js.map +1 -0
- package/dist/prod/context.js +2 -0
- package/dist/prod/context.js.map +1 -0
- package/dist/prod/effect.js +2 -0
- package/dist/prod/effect.js.map +1 -0
- package/dist/prod/env.js +2 -0
- package/dist/prod/env.js.map +1 -0
- package/dist/prod/events.js +2 -0
- package/dist/prod/events.js.map +1 -0
- package/dist/prod/extend/index.js +2 -0
- package/dist/prod/extend/index.js.map +1 -0
- package/dist/prod/external-store.js +2 -0
- package/dist/prod/external-store.js.map +1 -0
- package/dist/prod/index.js +1 -0
- package/dist/prod/internal/concurrency.js +2 -0
- package/dist/prod/internal/concurrency.js.map +1 -0
- package/dist/prod/internal/devtools.js +2 -0
- package/dist/prod/internal/devtools.js.map +1 -0
- package/dist/prod/internal/diagnostics.js +2 -0
- package/dist/prod/internal/diagnostics.js.map +1 -0
- package/dist/prod/internal/dispose.js +2 -0
- package/dist/prod/internal/dispose.js.map +1 -0
- package/dist/prod/internal/flags.js +2 -0
- package/dist/prod/internal/flags.js.map +1 -0
- package/dist/prod/internal/graph.js +2 -0
- package/dist/prod/internal/graph.js.map +1 -0
- package/dist/prod/internal/hydration-flag.js +2 -0
- package/dist/prod/internal/hydration-flag.js.map +1 -0
- package/dist/prod/internal/messages.js +2 -0
- package/dist/prod/internal/messages.js.map +1 -0
- package/dist/prod/internal/owner.js +2 -0
- package/dist/prod/internal/owner.js.map +1 -0
- package/dist/prod/internal/queue.js +2 -0
- package/dist/prod/internal/queue.js.map +1 -0
- package/dist/prod/internal/scheduler.js +2 -0
- package/dist/prod/internal/scheduler.js.map +1 -0
- package/dist/prod/internal/state.js +2 -0
- package/dist/prod/internal/state.js.map +1 -0
- package/dist/prod/internal/suspension.js +2 -0
- package/dist/prod/internal/suspension.js.map +1 -0
- package/dist/prod/list.js +2 -0
- package/dist/prod/list.js.map +1 -0
- package/dist/prod/memo.js +2 -0
- package/dist/prod/memo.js.map +1 -0
- package/dist/prod/optimistic.js +2 -0
- package/dist/prod/optimistic.js.map +1 -0
- package/dist/prod/ownership.js +2 -0
- package/dist/prod/ownership.js.map +1 -0
- package/dist/prod/props.js +2 -0
- package/dist/prod/props.js.map +1 -0
- package/dist/prod/reaction.js +2 -0
- package/dist/prod/reaction.js.map +1 -0
- package/dist/prod/reducer.js +2 -0
- package/dist/prod/reducer.js.map +1 -0
- package/dist/prod/refs.js +2 -0
- package/dist/prod/refs.js.map +1 -0
- package/dist/prod/resource.js +2 -0
- package/dist/prod/resource.js.map +1 -0
- package/dist/prod/selector.js +2 -0
- package/dist/prod/selector.js.map +1 -0
- package/dist/prod/signal.js +2 -0
- package/dist/prod/signal.js.map +1 -0
- package/dist/prod/store/index.js +1 -0
- package/dist/prod/store/nodes.js +2 -0
- package/dist/prod/store/nodes.js.map +1 -0
- package/dist/prod/store/proxies.js +2 -0
- package/dist/prod/store/proxies.js.map +1 -0
- package/dist/prod/store/read.js +2 -0
- package/dist/prod/store/read.js.map +1 -0
- package/dist/prod/store/reconcile.js +2 -0
- package/dist/prod/store/reconcile.js.map +1 -0
- package/dist/prod/store/use-store.js +2 -0
- package/dist/prod/store/use-store.js.map +1 -0
- package/dist/prod/suspense.js +2 -0
- package/dist/prod/suspense.js.map +1 -0
- package/dist/prod/transitions.js +2 -0
- package/dist/prod/transitions.js.map +1 -0
- package/dist/server/action.js +2 -0
- package/dist/server/action.js.map +1 -0
- package/dist/server/cache.js +2 -0
- package/dist/server/cache.js.map +1 -0
- package/dist/server/context.js +2 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/effect.js +2 -0
- package/dist/server/effect.js.map +1 -0
- package/dist/server/env.js +2 -0
- package/dist/server/env.js.map +1 -0
- package/dist/server/events.js +2 -0
- package/dist/server/events.js.map +1 -0
- package/dist/server/extend/index.js +2 -0
- package/dist/server/extend/index.js.map +1 -0
- package/dist/server/external-store.js +2 -0
- package/dist/server/external-store.js.map +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/internal/concurrency.js +2 -0
- package/dist/server/internal/concurrency.js.map +1 -0
- package/dist/server/internal/devtools.js +2 -0
- package/dist/server/internal/devtools.js.map +1 -0
- package/dist/server/internal/diagnostics.js +2 -0
- package/dist/server/internal/diagnostics.js.map +1 -0
- package/dist/server/internal/dispose.js +2 -0
- package/dist/server/internal/dispose.js.map +1 -0
- package/dist/server/internal/flags.js +2 -0
- package/dist/server/internal/flags.js.map +1 -0
- package/dist/server/internal/graph.js +2 -0
- package/dist/server/internal/graph.js.map +1 -0
- package/dist/server/internal/hydration-flag.js +2 -0
- package/dist/server/internal/hydration-flag.js.map +1 -0
- package/dist/server/internal/messages.js +2 -0
- package/dist/server/internal/messages.js.map +1 -0
- package/dist/server/internal/owner.js +2 -0
- package/dist/server/internal/owner.js.map +1 -0
- package/dist/server/internal/queue.js +2 -0
- package/dist/server/internal/queue.js.map +1 -0
- package/dist/server/internal/scheduler.js +2 -0
- package/dist/server/internal/scheduler.js.map +1 -0
- package/dist/server/internal/state.js +2 -0
- package/dist/server/internal/state.js.map +1 -0
- package/dist/server/internal/suspension.js +2 -0
- package/dist/server/internal/suspension.js.map +1 -0
- package/dist/server/list.js +2 -0
- package/dist/server/list.js.map +1 -0
- package/dist/server/memo.js +2 -0
- package/dist/server/memo.js.map +1 -0
- package/dist/server/optimistic.js +2 -0
- package/dist/server/optimistic.js.map +1 -0
- package/dist/server/ownership.js +2 -0
- package/dist/server/ownership.js.map +1 -0
- package/dist/server/props.js +2 -0
- package/dist/server/props.js.map +1 -0
- package/dist/server/reaction.js +2 -0
- package/dist/server/reaction.js.map +1 -0
- package/dist/server/reducer.js +2 -0
- package/dist/server/reducer.js.map +1 -0
- package/dist/server/refs.js +2 -0
- package/dist/server/refs.js.map +1 -0
- package/dist/server/resource.js +2 -0
- package/dist/server/resource.js.map +1 -0
- package/dist/server/selector.js +2 -0
- package/dist/server/selector.js.map +1 -0
- package/dist/server/signal.js +2 -0
- package/dist/server/signal.js.map +1 -0
- package/dist/server/store/index.js +1 -0
- package/dist/server/store/nodes.js +2 -0
- package/dist/server/store/nodes.js.map +1 -0
- package/dist/server/store/proxies.js +2 -0
- package/dist/server/store/proxies.js.map +1 -0
- package/dist/server/store/read.js +2 -0
- package/dist/server/store/read.js.map +1 -0
- package/dist/server/store/reconcile.js +2 -0
- package/dist/server/store/reconcile.js.map +1 -0
- package/dist/server/store/use-store.js +2 -0
- package/dist/server/store/use-store.js.map +1 -0
- package/dist/server/suspense.js +2 -0
- package/dist/server/suspense.js.map +1 -0
- package/dist/server/transitions.js +2 -0
- package/dist/server/transitions.js.map +1 -0
- package/dist/server-dev/action.js +89 -0
- package/dist/server-dev/action.js.map +1 -0
- package/dist/server-dev/cache.js +61 -0
- package/dist/server-dev/cache.js.map +1 -0
- package/dist/server-dev/context.js +107 -0
- package/dist/server-dev/context.js.map +1 -0
- package/dist/server-dev/effect.js +55 -0
- package/dist/server-dev/effect.js.map +1 -0
- package/dist/server-dev/env.js +30 -0
- package/dist/server-dev/env.js.map +1 -0
- package/dist/server-dev/events.js +32 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend/index.js +316 -0
- package/dist/server-dev/extend/index.js.map +1 -0
- package/dist/server-dev/external-store.js +45 -0
- package/dist/server-dev/external-store.js.map +1 -0
- package/dist/server-dev/index.js +26 -0
- package/dist/server-dev/internal/concurrency.js +632 -0
- package/dist/server-dev/internal/concurrency.js.map +1 -0
- package/dist/server-dev/internal/devtools.js +76 -0
- package/dist/server-dev/internal/devtools.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +101 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/dispose.js +48 -0
- package/dist/server-dev/internal/dispose.js.map +1 -0
- package/dist/server-dev/internal/flags.js +10 -0
- package/dist/server-dev/internal/flags.js.map +1 -0
- package/dist/server-dev/internal/graph.js +577 -0
- package/dist/server-dev/internal/graph.js.map +1 -0
- package/dist/server-dev/internal/hydration-flag.js +45 -0
- package/dist/server-dev/internal/hydration-flag.js.map +1 -0
- package/dist/server-dev/internal/messages.js +53 -0
- package/dist/server-dev/internal/messages.js.map +1 -0
- package/dist/server-dev/internal/owner.js +289 -0
- package/dist/server-dev/internal/owner.js.map +1 -0
- package/dist/server-dev/internal/queue.js +45 -0
- package/dist/server-dev/internal/queue.js.map +1 -0
- package/dist/server-dev/internal/scheduler.js +286 -0
- package/dist/server-dev/internal/scheduler.js.map +1 -0
- package/dist/server-dev/internal/state.js +27 -0
- package/dist/server-dev/internal/state.js.map +1 -0
- package/dist/server-dev/internal/suspension.js +44 -0
- package/dist/server-dev/internal/suspension.js.map +1 -0
- package/dist/server-dev/list.js +281 -0
- package/dist/server-dev/list.js.map +1 -0
- package/dist/server-dev/memo.js +40 -0
- package/dist/server-dev/memo.js.map +1 -0
- package/dist/server-dev/optimistic.js +44 -0
- package/dist/server-dev/optimistic.js.map +1 -0
- package/dist/server-dev/ownership.js +260 -0
- package/dist/server-dev/ownership.js.map +1 -0
- package/dist/server-dev/props.js +281 -0
- package/dist/server-dev/props.js.map +1 -0
- package/dist/server-dev/reaction.js +60 -0
- package/dist/server-dev/reaction.js.map +1 -0
- package/dist/server-dev/reducer.js +38 -0
- package/dist/server-dev/reducer.js.map +1 -0
- package/dist/server-dev/refs.js +57 -0
- package/dist/server-dev/refs.js.map +1 -0
- package/dist/server-dev/resource.js +175 -0
- package/dist/server-dev/resource.js.map +1 -0
- package/dist/server-dev/selector.js +81 -0
- package/dist/server-dev/selector.js.map +1 -0
- package/dist/server-dev/signal.js +38 -0
- package/dist/server-dev/signal.js.map +1 -0
- package/dist/server-dev/store/index.js +4 -0
- package/dist/server-dev/store/nodes.js +191 -0
- package/dist/server-dev/store/nodes.js.map +1 -0
- package/dist/server-dev/store/proxies.js +159 -0
- package/dist/server-dev/store/proxies.js.map +1 -0
- package/dist/server-dev/store/read.js +71 -0
- package/dist/server-dev/store/read.js.map +1 -0
- package/dist/server-dev/store/reconcile.js +185 -0
- package/dist/server-dev/store/reconcile.js.map +1 -0
- package/dist/server-dev/store/use-store.js +167 -0
- package/dist/server-dev/store/use-store.js.map +1 -0
- package/dist/server-dev/suspense.js +44 -0
- package/dist/server-dev/suspense.js.map +1 -0
- package/dist/server-dev/transitions.js +85 -0
- package/dist/server-dev/transitions.js.map +1 -0
- package/package.json +111 -50
- package/dist/chunk-6Y3CCWOY.js +0 -887
- package/dist/chunk-6Y3CCWOY.js.map +0 -1
- package/dist/chunk-B5FTYDUG.js +0 -3
- package/dist/chunk-B5FTYDUG.js.map +0 -1
- package/dist/index.cjs +0 -2000
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -609
- package/dist/index.d.ts +0 -609
- package/dist/index.js +0 -1094
- package/dist/index.js.map +0 -1
- package/dist/jsx-Bugil6CJ.d.cts +0 -151
- package/dist/jsx-Bugil6CJ.d.ts +0 -151
- package/dist/jsx-dev-runtime.cjs +0 -742
- package/dist/jsx-dev-runtime.cjs.map +0 -1
- package/dist/jsx-dev-runtime.d.cts +0 -2
- package/dist/jsx-dev-runtime.d.ts +0 -2
- package/dist/jsx-dev-runtime.js +0 -4
- package/dist/jsx-dev-runtime.js.map +0 -1
- package/dist/jsx-runtime.cjs +0 -742
- package/dist/jsx-runtime.cjs.map +0 -1
- package/dist/jsx-runtime.d.cts +0 -36
- package/dist/jsx-runtime.d.ts +0 -36
- package/dist/jsx-runtime.js +0 -4
- package/dist/jsx-runtime.js.map +0 -1
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A ref object that is also a ref callback: pass it as `ref={r}` (the renderer calls it with the
|
|
3
|
+
* element) and read the element as `r.current`. `undefined` when nothing is attached.
|
|
4
|
+
* @since 1.0.0
|
|
5
|
+
*/
|
|
6
|
+
export interface Ref<T> {
|
|
7
|
+
/** Stores `value` as `current`; `undefined` clears it. The renderer calls it with the element. */
|
|
8
|
+
(value: T | undefined): void;
|
|
9
|
+
/** The value last passed to the ref, or `undefined` when nothing is attached. Not reactive. */
|
|
10
|
+
readonly current: T | undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`
|
|
14
|
+
* clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.
|
|
15
|
+
* @returns A callable ref with a `current` getter, `undefined` until the ref is called.
|
|
16
|
+
* @example
|
|
17
|
+
* import { createRef } from "@shadow-js/core";
|
|
18
|
+
*
|
|
19
|
+
* function SearchBox() {
|
|
20
|
+
* const input = createRef<HTMLInputElement>();
|
|
21
|
+
* return <input ref={input} onKeyDown={() => input.current?.select()} />;
|
|
22
|
+
* }
|
|
23
|
+
* @see useImperativeHandle
|
|
24
|
+
* @since 1.0.0
|
|
25
|
+
*/
|
|
26
|
+
export declare function createRef<T>(): Ref<T>;
|
|
27
|
+
/**
|
|
28
|
+
* Publishes an imperative handle to a ref: `create()` runs once, untracked, and its result is
|
|
29
|
+
* passed to `ref`; when the owner is disposed `ref` receives `undefined`. Components run once, so
|
|
30
|
+
* the handle never needs refreshing: put live state behind accessors inside the handle.
|
|
31
|
+
*
|
|
32
|
+
* A missing `ref` is accepted and `create` does not run, so forwarding an optional ref needs no
|
|
33
|
+
* branch.
|
|
34
|
+
*
|
|
35
|
+
* @param ref The ref callback (a {@link Ref}, or any function of the handle). `null` or `undefined`
|
|
36
|
+
* makes the call a no-op.
|
|
37
|
+
* @param create Builds the handle. Runs once, untracked.
|
|
38
|
+
* @example
|
|
39
|
+
* import { createRef, useImperativeHandle } from "@shadow-js/core";
|
|
40
|
+
*
|
|
41
|
+
* function FancyInput(props: { ref?: (handle: { focus(): void } | undefined) => void }) {
|
|
42
|
+
* const input = createRef<HTMLInputElement>();
|
|
43
|
+
* useImperativeHandle(props.ref, () => ({ focus: () => input.current?.focus() }));
|
|
44
|
+
* return <input ref={input} />;
|
|
45
|
+
* }
|
|
46
|
+
* @see createRef
|
|
47
|
+
* @since 1.0.0
|
|
48
|
+
*/
|
|
49
|
+
export declare function useImperativeHandle<T>(ref: ((value: T | undefined) => void) | null | undefined, create: () => T): void;
|
|
50
|
+
//# sourceMappingURL=refs.d.ts.map
|
package/dist/dev/refs.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { onCleanup, untrack } from "./ownership.js";
|
|
2
|
+
// src/refs.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`
|
|
5
|
+
* clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.
|
|
6
|
+
* @returns A callable ref with a `current` getter, `undefined` until the ref is called.
|
|
7
|
+
* @example
|
|
8
|
+
* import { createRef } from "@shadow-js/core";
|
|
9
|
+
*
|
|
10
|
+
* function SearchBox() {
|
|
11
|
+
* const input = createRef<HTMLInputElement>();
|
|
12
|
+
* return <input ref={input} onKeyDown={() => input.current?.select()} />;
|
|
13
|
+
* }
|
|
14
|
+
* @see useImperativeHandle
|
|
15
|
+
* @since 1.0.0
|
|
16
|
+
*/
|
|
17
|
+
function createRef() {
|
|
18
|
+
let current;
|
|
19
|
+
const ref = ((value) => {
|
|
20
|
+
current = value;
|
|
21
|
+
});
|
|
22
|
+
Object.defineProperty(ref, "current", {
|
|
23
|
+
get: () => current,
|
|
24
|
+
enumerable: true
|
|
25
|
+
});
|
|
26
|
+
return ref;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Publishes an imperative handle to a ref: `create()` runs once, untracked, and its result is
|
|
30
|
+
* passed to `ref`; when the owner is disposed `ref` receives `undefined`. Components run once, so
|
|
31
|
+
* the handle never needs refreshing: put live state behind accessors inside the handle.
|
|
32
|
+
*
|
|
33
|
+
* A missing `ref` is accepted and `create` does not run, so forwarding an optional ref needs no
|
|
34
|
+
* branch.
|
|
35
|
+
*
|
|
36
|
+
* @param ref The ref callback (a {@link Ref}, or any function of the handle). `null` or `undefined`
|
|
37
|
+
* makes the call a no-op.
|
|
38
|
+
* @param create Builds the handle. Runs once, untracked.
|
|
39
|
+
* @example
|
|
40
|
+
* import { createRef, useImperativeHandle } from "@shadow-js/core";
|
|
41
|
+
*
|
|
42
|
+
* function FancyInput(props: { ref?: (handle: { focus(): void } | undefined) => void }) {
|
|
43
|
+
* const input = createRef<HTMLInputElement>();
|
|
44
|
+
* useImperativeHandle(props.ref, () => ({ focus: () => input.current?.focus() }));
|
|
45
|
+
* return <input ref={input} />;
|
|
46
|
+
* }
|
|
47
|
+
* @see createRef
|
|
48
|
+
* @since 1.0.0
|
|
49
|
+
*/
|
|
50
|
+
function useImperativeHandle(ref, create) {
|
|
51
|
+
if (ref === void 0 || ref === null) return;
|
|
52
|
+
ref(untrack(create));
|
|
53
|
+
onCleanup(() => ref(void 0));
|
|
54
|
+
}
|
|
55
|
+
export { createRef, useImperativeHandle };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=refs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refs.js","names":[],"sources":["../../src/refs.ts"],"sourcesContent":["import { onCleanup, untrack } from \"./ownership\";\n\n/**\n * A ref object that is also a ref callback: pass it as `ref={r}` (the renderer calls it with the\n * element) and read the element as `r.current`. `undefined` when nothing is attached.\n * @since 1.0.0\n */\nexport interface Ref<T> {\n /** Stores `value` as `current`; `undefined` clears it. The renderer calls it with the element. */\n (value: T | undefined): void;\n /** The value last passed to the ref, or `undefined` when nothing is attached. Not reactive. */\n readonly current: T | undefined;\n}\n\n/**\n * Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`\n * clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.\n * @returns A callable ref with a `current` getter, `undefined` until the ref is called.\n * @example\n * import { createRef } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * const input = createRef<HTMLInputElement>();\n * return <input ref={input} onKeyDown={() => input.current?.select()} />;\n * }\n * @see useImperativeHandle\n * @since 1.0.0\n */\nexport function createRef<T>(): Ref<T> {\n let current: T | undefined;\n const ref = ((value: T | undefined): void => {\n current = value;\n }) as Ref<T>;\n Object.defineProperty(ref, \"current\", { get: () => current, enumerable: true });\n return ref;\n}\n\n/**\n * Publishes an imperative handle to a ref: `create()` runs once, untracked, and its result is\n * passed to `ref`; when the owner is disposed `ref` receives `undefined`. Components run once, so\n * the handle never needs refreshing: put live state behind accessors inside the handle.\n *\n * A missing `ref` is accepted and `create` does not run, so forwarding an optional ref needs no\n * branch.\n *\n * @param ref The ref callback (a {@link Ref}, or any function of the handle). `null` or `undefined`\n * makes the call a no-op.\n * @param create Builds the handle. Runs once, untracked.\n * @example\n * import { createRef, useImperativeHandle } from \"@shadow-js/core\";\n *\n * function FancyInput(props: { ref?: (handle: { focus(): void } | undefined) => void }) {\n * const input = createRef<HTMLInputElement>();\n * useImperativeHandle(props.ref, () => ({ focus: () => input.current?.focus() }));\n * return <input ref={input} />;\n * }\n * @see createRef\n * @since 1.0.0\n */\nexport function useImperativeHandle<T>(\n ref: ((value: T | undefined) => void) | null | undefined,\n create: () => T,\n): void {\n if (ref === undefined || ref === null) return;\n ref(untrack(create));\n onCleanup(() => ref(undefined));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAgB,YAAuB;CACrC,IAAI;CACJ,MAAM,QAAQ,UAA+B;EAC3C,UAAU;CACZ;CACA,OAAO,eAAe,KAAK,WAAW;EAAE,WAAW;EAAS,YAAY;CAAK,CAAC;CAC9E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,oBACd,KACA,QACM;CACN,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM;CACvC,IAAI,QAAQ,MAAM,CAAC;CACnB,gBAAgB,IAAI,KAAA,CAAS,CAAC;AAChC"}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Accessor } from "./internal/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Where a {@link Resource} is in its life: `"unresolved"` (no value and no fetch, for example while
|
|
4
|
+
* the source is falsy), `"pending"` (the first fetch is in flight), `"ready"` (a value is shown and
|
|
5
|
+
* nothing is in flight), `"refreshing"` (a value is shown while a newer fetch runs) or `"errored"`
|
|
6
|
+
* (the last fetch failed; reading the resource throws).
|
|
7
|
+
* @since 1.0.0
|
|
8
|
+
*/
|
|
9
|
+
export type ResourceState = "unresolved" | "pending" | "ready" | "refreshing" | "errored";
|
|
10
|
+
/** Passed to every fetcher call. @since 1.0.0 */
|
|
11
|
+
export interface ResourceInfo<T = unknown> {
|
|
12
|
+
/** Aborted when a newer fetch starts or the owner is disposed. */
|
|
13
|
+
signal: AbortSignal;
|
|
14
|
+
/** True when this call was started by `refetch()` or a source change after a value existed. */
|
|
15
|
+
refetching: boolean;
|
|
16
|
+
/** The last value, if any. */
|
|
17
|
+
value: T | undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Options of {@link useResource}.
|
|
21
|
+
* @since 1.0.0
|
|
22
|
+
*/
|
|
23
|
+
export interface ResourceOptions<T> {
|
|
24
|
+
/**
|
|
25
|
+
* Value shown before the first fetch settles. With it the resource never reads as `"pending"`: the
|
|
26
|
+
* first fetch still runs, as a refresh (`"refreshing"`, `info.refetching` true), and never
|
|
27
|
+
* suspends. A key that is present with the value `undefined` counts as given.
|
|
28
|
+
* @default No initial value: the first fetch reads as `"pending"` and suspends its readers.
|
|
29
|
+
*/
|
|
30
|
+
initialValue?: T;
|
|
31
|
+
/**
|
|
32
|
+
* The key that matches the value a server render recorded with the resource that hydrates it.
|
|
33
|
+
* Give one when the creation order may differ between server and client.
|
|
34
|
+
* @default undefined (a key is generated from the resource's position in the render)
|
|
35
|
+
*/
|
|
36
|
+
key?: string;
|
|
37
|
+
/**
|
|
38
|
+
* On the server, the streamed response holds its first flush until this resource settles, so its value
|
|
39
|
+
* is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that
|
|
40
|
+
* rejects does not hold the stream: its fallback stays. Only resources created while the shell renders
|
|
41
|
+
* hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers
|
|
42
|
+
* (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no
|
|
43
|
+
* effect there. Matches Solid's option of the same name.
|
|
44
|
+
* @default false
|
|
45
|
+
*/
|
|
46
|
+
deferStream?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Label shown by devtools next to the resource's state changes. It has no effect on caching or on
|
|
49
|
+
* the server key (use `key` for that) and costs nothing in production builds, where devtools reporting
|
|
50
|
+
* is removed.
|
|
51
|
+
* @default undefined (the resource is unnamed)
|
|
52
|
+
*/
|
|
53
|
+
name?: string;
|
|
54
|
+
}
|
|
55
|
+
/** Reactive handle to an asynchronous value. @since 1.0.0 */
|
|
56
|
+
export interface Resource<T> extends Accessor<T | undefined> {
|
|
57
|
+
/** The current {@link ResourceState}. Tracked when read in an effect or memo. */
|
|
58
|
+
readonly state: ResourceState;
|
|
59
|
+
/** True while a fetch is in flight (`"pending"` or `"refreshing"`). Tracked. */
|
|
60
|
+
readonly loading: boolean;
|
|
61
|
+
/** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */
|
|
62
|
+
readonly error: unknown;
|
|
63
|
+
/** The last successfully loaded value; unlike the call form it never throws or suspends. */
|
|
64
|
+
readonly latest: T | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Fetches again (keeping the previous value visible). The promise resolves with the new value,
|
|
67
|
+
* or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never
|
|
68
|
+
* rejects, so a call you do not await is safe.
|
|
69
|
+
*/
|
|
70
|
+
refetch(): Promise<T | undefined>;
|
|
71
|
+
/** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */
|
|
72
|
+
mutate(value: T | ((previous: T | undefined) => T)): T;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Loads data asynchronously and exposes it reactively. Reading it while the first load is pending
|
|
76
|
+
* holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;
|
|
77
|
+
* reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous
|
|
78
|
+
* value visible (`state === "refreshing"`) and never re-suspends.
|
|
79
|
+
*
|
|
80
|
+
* Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever
|
|
81
|
+
* `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.
|
|
82
|
+
*
|
|
83
|
+
* `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the
|
|
84
|
+
* parameter is annotated: `(info: ResourceInfo<User>) => ...`.
|
|
85
|
+
*
|
|
86
|
+
* @param fetcher Called untracked, once at creation (skipped when a server render already provided
|
|
87
|
+
* the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag
|
|
88
|
+
* and the last value; it returns the value or a promise.
|
|
89
|
+
* @param options Initial value, server key and a devtools name. Undefined uses the defaults.
|
|
90
|
+
* @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,
|
|
91
|
+
* `refetch` and `mutate` are on the same function.
|
|
92
|
+
* @throws Nothing itself: a fetcher that throws or rejects makes the resource `"errored"`. Reading
|
|
93
|
+
* the resource then rethrows that error, so the nearest error boundary receives it.
|
|
94
|
+
* @example
|
|
95
|
+
* import { useResource } from "@shadow-js/core";
|
|
96
|
+
*
|
|
97
|
+
* function Clock() {
|
|
98
|
+
* const time = useResource(({ signal }) => fetch("/api/time", { signal }).then((r) => r.text()));
|
|
99
|
+
* return <p>{time.loading ? "Loading..." : time()}</p>;
|
|
100
|
+
* }
|
|
101
|
+
* @see ResourceOptions
|
|
102
|
+
* @see cache
|
|
103
|
+
* @since 1.0.0
|
|
104
|
+
*/
|
|
105
|
+
export declare function useResource<T>(fetcher: (info: ResourceInfo) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
106
|
+
/**
|
|
107
|
+
* Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it
|
|
108
|
+
* changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource
|
|
109
|
+
* stays `"unresolved"` (or keeps its value, `"ready"`). A newer fetch aborts the previous one, whose
|
|
110
|
+
* late result is ignored.
|
|
111
|
+
*
|
|
112
|
+
* @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.
|
|
113
|
+
* @param fetcher Called untracked with the source value and the fetch info.
|
|
114
|
+
* @param options Initial value, server key and a devtools name. Undefined uses the defaults.
|
|
115
|
+
* @returns The resource (see {@link Resource}).
|
|
116
|
+
* @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.
|
|
117
|
+
* @example
|
|
118
|
+
* import { useResource, useSignal } from "@shadow-js/core";
|
|
119
|
+
*
|
|
120
|
+
* function UserCard() {
|
|
121
|
+
* const [id] = useSignal(1);
|
|
122
|
+
* const user = useResource(id, (id, { signal }) =>
|
|
123
|
+
* fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),
|
|
124
|
+
* );
|
|
125
|
+
* return <p>{user()?.name}</p>;
|
|
126
|
+
* }
|
|
127
|
+
* @since 1.0.0
|
|
128
|
+
*/
|
|
129
|
+
export declare function useResource<S, T>(source: Accessor<S | false | null | undefined>, fetcher: (source: S, info: ResourceInfo) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
130
|
+
export declare function useResource<S extends string | number | boolean | bigint | object, T>(source: S, fetcher: (source: S, info: ResourceInfo) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
131
|
+
export declare function useResource<T>(fetcher: (info: ResourceInfo<T>) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
132
|
+
export declare function useResource<S, T>(source: Accessor<S | false | null | undefined>, fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
133
|
+
//# sourceMappingURL=resource.d.ts.map
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { DEVTOOLS_EVENT, report } from "./internal/devtools.js";
|
|
2
|
+
import { readSignal } from "./internal/graph.js";
|
|
3
|
+
import { batch } from "./internal/scheduler.js";
|
|
4
|
+
import { onCleanup, untrack } from "./ownership.js";
|
|
5
|
+
import { useRenderEffect } from "./effect.js";
|
|
6
|
+
import { useContext } from "./context.js";
|
|
7
|
+
import { ResourceCacheContext, SuspenseContext } from "./suspense.js";
|
|
8
|
+
import { holdReader, inTransition } from "./internal/concurrency.js";
|
|
9
|
+
import { createSignalNode, currentListener, currentOwner, writeSignal } from "./extend/index.js";
|
|
10
|
+
// src/resource.ts
|
|
11
|
+
/**
|
|
12
|
+
* A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`
|
|
13
|
+
* false notifies on every write, true only when the value changes.
|
|
14
|
+
*/
|
|
15
|
+
function cell(initial, distinct) {
|
|
16
|
+
const node = createSignalNode(initial, distinct ? Object.is : false);
|
|
17
|
+
return [() => readSignal(node), (next) => {
|
|
18
|
+
writeSignal(node, next, { allowInMemo: true });
|
|
19
|
+
}];
|
|
20
|
+
}
|
|
21
|
+
function isPromiseLike(value) {
|
|
22
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
23
|
+
}
|
|
24
|
+
function useResource(first, second, third) {
|
|
25
|
+
const hasSource = typeof second === "function";
|
|
26
|
+
const source = hasSource ? typeof first === "function" ? first : () => first : () => true;
|
|
27
|
+
const oneShot = first;
|
|
28
|
+
const fetcher = hasSource ? second : (_input, info) => oneShot(info);
|
|
29
|
+
const options = (hasSource ? third : second) ?? {};
|
|
30
|
+
const hasInitial = "initialValue" in options;
|
|
31
|
+
const [value, setValue] = cell(options.initialValue, false);
|
|
32
|
+
const [state, writeState] = cell(hasInitial ? "ready" : "unresolved", true);
|
|
33
|
+
let handle;
|
|
34
|
+
const setState = (next) => {
|
|
35
|
+
writeState(next);
|
|
36
|
+
report(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());
|
|
37
|
+
};
|
|
38
|
+
const [failure, setFailure] = cell(void 0, false);
|
|
39
|
+
const cache = useContext(ResourceCacheContext);
|
|
40
|
+
const cacheKey = cache === null ? void 0 : cache.key(options.key);
|
|
41
|
+
const cached = cache !== null && cacheKey !== void 0 ? cache.read(cacheKey) : void 0;
|
|
42
|
+
let usedCache = false;
|
|
43
|
+
let version = 0;
|
|
44
|
+
let controller;
|
|
45
|
+
let disposed = false;
|
|
46
|
+
let hasValue = hasInitial;
|
|
47
|
+
const holders = /* @__PURE__ */ new Set();
|
|
48
|
+
const release = () => {
|
|
49
|
+
if (holders.size === 0) return;
|
|
50
|
+
const held = [...holders];
|
|
51
|
+
holders.clear();
|
|
52
|
+
for (const tracker of held) tracker.decrement();
|
|
53
|
+
};
|
|
54
|
+
/** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */
|
|
55
|
+
const settle = (id, apply) => {
|
|
56
|
+
if (disposed || id !== version) return false;
|
|
57
|
+
batch(apply);
|
|
58
|
+
release();
|
|
59
|
+
return true;
|
|
60
|
+
};
|
|
61
|
+
/** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */
|
|
62
|
+
const load = (input, refetching) => {
|
|
63
|
+
if (cached !== void 0 && !usedCache && !refetching) {
|
|
64
|
+
usedCache = true;
|
|
65
|
+
hasValue = true;
|
|
66
|
+
batch(() => {
|
|
67
|
+
setValue(cached.value);
|
|
68
|
+
setState("ready");
|
|
69
|
+
});
|
|
70
|
+
return Promise.resolve(cached.value);
|
|
71
|
+
}
|
|
72
|
+
controller?.abort();
|
|
73
|
+
const current = new AbortController();
|
|
74
|
+
controller = current;
|
|
75
|
+
version += 1;
|
|
76
|
+
const id = version;
|
|
77
|
+
batch(() => {
|
|
78
|
+
setState(hasValue ? "refreshing" : "pending");
|
|
79
|
+
setFailure(void 0);
|
|
80
|
+
});
|
|
81
|
+
let output;
|
|
82
|
+
try {
|
|
83
|
+
const joined = refetching || cache === null || cacheKey === void 0 ? void 0 : cache.pending?.(cacheKey);
|
|
84
|
+
output = joined !== void 0 ? joined : untrack(() => fetcher(input, {
|
|
85
|
+
signal: current.signal,
|
|
86
|
+
refetching,
|
|
87
|
+
value: untrack(value)
|
|
88
|
+
}));
|
|
89
|
+
} catch (error) {
|
|
90
|
+
settle(id, () => {
|
|
91
|
+
setFailure(error);
|
|
92
|
+
setState("errored");
|
|
93
|
+
});
|
|
94
|
+
return Promise.resolve(void 0);
|
|
95
|
+
}
|
|
96
|
+
if (isPromiseLike(output)) {
|
|
97
|
+
if (cache !== null && cacheKey !== void 0) cache.track(cacheKey, Promise.resolve(output), { deferStream: options.deferStream });
|
|
98
|
+
return Promise.resolve(output).then((result) => settle(id, () => {
|
|
99
|
+
hasValue = true;
|
|
100
|
+
setValue(result);
|
|
101
|
+
setState("ready");
|
|
102
|
+
}) ? result : void 0, (error) => {
|
|
103
|
+
settle(id, () => {
|
|
104
|
+
setFailure(error);
|
|
105
|
+
setState("errored");
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const immediate = output;
|
|
110
|
+
const applied = settle(id, () => {
|
|
111
|
+
hasValue = true;
|
|
112
|
+
setValue(immediate);
|
|
113
|
+
setState("ready");
|
|
114
|
+
});
|
|
115
|
+
return Promise.resolve(applied ? immediate : void 0);
|
|
116
|
+
};
|
|
117
|
+
const onSource = (input) => {
|
|
118
|
+
if (input === false || input === null || input === void 0) {
|
|
119
|
+
controller?.abort();
|
|
120
|
+
version += 1;
|
|
121
|
+
release();
|
|
122
|
+
setState(hasValue ? "ready" : "unresolved");
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
load(input, hasValue);
|
|
126
|
+
};
|
|
127
|
+
const read = (() => {
|
|
128
|
+
const current = state();
|
|
129
|
+
if (current === "errored") throw failure();
|
|
130
|
+
if (current === "pending") {
|
|
131
|
+
const tracker = useContext(SuspenseContext);
|
|
132
|
+
if (tracker !== null && !holders.has(tracker)) {
|
|
133
|
+
holders.add(tracker);
|
|
134
|
+
tracker.increment();
|
|
135
|
+
}
|
|
136
|
+
if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);
|
|
137
|
+
}
|
|
138
|
+
return value();
|
|
139
|
+
});
|
|
140
|
+
Object.defineProperties(read, {
|
|
141
|
+
state: { get: state },
|
|
142
|
+
loading: { get: () => state() === "pending" || state() === "refreshing" },
|
|
143
|
+
error: { get: failure },
|
|
144
|
+
latest: { get: value },
|
|
145
|
+
refetch: { value: () => {
|
|
146
|
+
const input = untrack(source);
|
|
147
|
+
if (input === false || input === null || input === void 0) return Promise.resolve(void 0);
|
|
148
|
+
return load(input, hasValue);
|
|
149
|
+
} },
|
|
150
|
+
mutate: { value: (next) => {
|
|
151
|
+
let resolved;
|
|
152
|
+
batch(() => {
|
|
153
|
+
resolved = typeof next === "function" ? next(untrack(value)) : next;
|
|
154
|
+
controller?.abort();
|
|
155
|
+
version += 1;
|
|
156
|
+
hasValue = true;
|
|
157
|
+
setValue(resolved);
|
|
158
|
+
setFailure(void 0);
|
|
159
|
+
setState("ready");
|
|
160
|
+
});
|
|
161
|
+
release();
|
|
162
|
+
return resolved;
|
|
163
|
+
} }
|
|
164
|
+
});
|
|
165
|
+
handle = read;
|
|
166
|
+
useRenderEffect(source, onSource);
|
|
167
|
+
onCleanup(() => {
|
|
168
|
+
disposed = true;
|
|
169
|
+
controller?.abort();
|
|
170
|
+
release();
|
|
171
|
+
});
|
|
172
|
+
return read;
|
|
173
|
+
}
|
|
174
|
+
export { useResource };
|
|
175
|
+
|
|
176
|
+
//# sourceMappingURL=resource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource.js","names":[],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\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 * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n batch(apply);\n release();\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? (next as (previous: T | undefined) => T)(untrack(value))\n : next;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n release();\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the
|
|
3
|
+
* current source value. Reading it inside an effect or memo subscribes only to that key's boolean,
|
|
4
|
+
* so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the
|
|
5
|
+
* default equality. A custom `equals` costs one call per registered key per change.
|
|
6
|
+
*
|
|
7
|
+
* The source is tracked by a render-phase effect in the current owner. Create the selector before
|
|
8
|
+
* its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked
|
|
9
|
+
* context reads the source directly and creates no subscription. The default equality is `===`,
|
|
10
|
+
* so `NaN` never matches.
|
|
11
|
+
*
|
|
12
|
+
* @param source The value that selects keys. Tracked.
|
|
13
|
+
* @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.
|
|
14
|
+
* @returns `isSelected(key)`.
|
|
15
|
+
* @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still
|
|
16
|
+
* updated and the error goes to the owner's error handler. In development, a selector created
|
|
17
|
+
* outside any owner warns `NO_OWNER_EFFECT`.
|
|
18
|
+
* @example
|
|
19
|
+
* import { mapArray, useSelector, useSignal } from "@shadow-js/core";
|
|
20
|
+
*
|
|
21
|
+
* function Rows(props: { ids: number[] }) {
|
|
22
|
+
* const [selectedId, setSelectedId] = useSignal(1);
|
|
23
|
+
* const isSelected = useSelector(selectedId);
|
|
24
|
+
* return mapArray(() => props.ids, (id) => (
|
|
25
|
+
* <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>
|
|
26
|
+
* ));
|
|
27
|
+
* }
|
|
28
|
+
* @see mapArray
|
|
29
|
+
* @since 1.0.0
|
|
30
|
+
*/
|
|
31
|
+
export declare function useSelector<T, K = T>(source: () => T, equals?: (key: K, value: T) => boolean): (key: K) => boolean;
|
|
32
|
+
//# sourceMappingURL=selector.d.ts.map
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { track } from "./internal/graph.js";
|
|
2
|
+
import { onCleanup, untrack } from "./ownership.js";
|
|
3
|
+
import { useRenderEffect } from "./effect.js";
|
|
4
|
+
import { isTracking, notify } from "./extend/index.js";
|
|
5
|
+
// src/selector.ts
|
|
6
|
+
/**
|
|
7
|
+
* The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the
|
|
8
|
+
* shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.
|
|
9
|
+
*/
|
|
10
|
+
var Entry = class {
|
|
11
|
+
/** A source with no sources of its own, like a signal. */
|
|
12
|
+
kind = 0;
|
|
13
|
+
observers = null;
|
|
14
|
+
stamp = 0;
|
|
15
|
+
/** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */
|
|
16
|
+
subscribers = 0;
|
|
17
|
+
/** The key this entry answers for. */
|
|
18
|
+
key;
|
|
19
|
+
/** Whether the key matches the selected value. */
|
|
20
|
+
value;
|
|
21
|
+
constructor(key, value) {
|
|
22
|
+
this.key = key;
|
|
23
|
+
this.value = value;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
/** Writes a key's boolean and notifies its readers only when it actually changed. */
|
|
27
|
+
function setEntry(entry, selected) {
|
|
28
|
+
if (entry.value === selected) return;
|
|
29
|
+
entry.value = selected;
|
|
30
|
+
notify(entry);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the
|
|
34
|
+
* current source value. Reading it inside an effect or memo subscribes only to that key's boolean,
|
|
35
|
+
* so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the
|
|
36
|
+
* default equality. A custom `equals` costs one call per registered key per change.
|
|
37
|
+
*
|
|
38
|
+
* The source is tracked by a render-phase effect in the current owner. Create the selector before
|
|
39
|
+
* its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked
|
|
40
|
+
* context reads the source directly and creates no subscription. The default equality is `===`,
|
|
41
|
+
* so `NaN` never matches.
|
|
42
|
+
*
|
|
43
|
+
* @param source The value that selects keys. Tracked.
|
|
44
|
+
* @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.
|
|
45
|
+
* @returns `isSelected(key)`.
|
|
46
|
+
* @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still
|
|
47
|
+
* updated and the error goes to the owner's error handler. In development, a selector created
|
|
48
|
+
* outside any owner warns `NO_OWNER_EFFECT`.
|
|
49
|
+
* @example
|
|
50
|
+
* import { mapArray, useSelector, useSignal } from "@shadow-js/core";
|
|
51
|
+
*
|
|
52
|
+
* function Rows(props: { ids: number[] }) {
|
|
53
|
+
* const [selectedId, setSelectedId] = useSignal(1);
|
|
54
|
+
* const isSelected = useSelector(selectedId);
|
|
55
|
+
* return mapArray(() => props.ids, (id) => (
|
|
56
|
+
* <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>
|
|
57
|
+
* ));
|
|
58
|
+
* }
|
|
59
|
+
* @see mapArray
|
|
60
|
+
* @since 1.0.0
|
|
61
|
+
*/
|
|
62
|
+
function useSelector(source, equals) {
|
|
63
|
+
const entries = /* @__PURE__ */ new Map();
|
|
64
|
+
/** The value the entries were last reconciled against; `null` until the first successful apply. */
|
|
65
|
+
let last = null;
|
|
66
|
+
const matches = (key, value) => equals === void 0 ? key === value : equals(key, value);
|
|
67
|
+
const currentValue = () => last === null ? untrack(source) : last.value;
|
|
68
|
+
const release = (entry) => {
|
|
69
|
+
entry.subscribers -= 1;
|
|
70
|
+
if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);
|
|
71
|
+
};
|
|
72
|
+
const create = (key) => {
|
|
73
|
+
const entry = new Entry(key, matches(key, currentValue()));
|
|
74
|
+
entries.set(key, entry);
|
|
75
|
+
return entry;
|
|
76
|
+
};
|
|
77
|
+
const isSelected = (key) => {
|
|
78
|
+
if (!isTracking()) return matches(key, source());
|
|
79
|
+
const entry = entries.get(key) ?? create(key);
|
|
80
|
+
entry.subscribers += 1;
|
|
81
|
+
onCleanup(() => release(entry));
|
|
82
|
+
track(entry);
|
|
83
|
+
return entry.value;
|
|
84
|
+
};
|
|
85
|
+
useRenderEffect(() => source(), (next) => {
|
|
86
|
+
const previous = last;
|
|
87
|
+
last = { value: next };
|
|
88
|
+
if (previous !== null && equals === void 0) {
|
|
89
|
+
if (previous.value === next) return;
|
|
90
|
+
const before = entries.get(previous.value);
|
|
91
|
+
if (before !== void 0) setEntry(before, before.key === next);
|
|
92
|
+
const after = entries.get(next);
|
|
93
|
+
if (after !== void 0) setEntry(after, after.key === next);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
let failed = false;
|
|
97
|
+
let failure;
|
|
98
|
+
for (const entry of entries.values()) {
|
|
99
|
+
let selected;
|
|
100
|
+
try {
|
|
101
|
+
selected = matches(entry.key, next);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (!failed) {
|
|
104
|
+
failed = true;
|
|
105
|
+
failure = error;
|
|
106
|
+
}
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
setEntry(entry, selected);
|
|
110
|
+
}
|
|
111
|
+
if (failed) throw failure;
|
|
112
|
+
});
|
|
113
|
+
return isSelected;
|
|
114
|
+
}
|
|
115
|
+
export { useSelector };
|
|
116
|
+
|
|
117
|
+
//# sourceMappingURL=selector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"selector.js","names":[],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n readonly key: unknown;\n /** Whether the key matches the selected value. */\n value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n const entry = new Entry(key, matches(key, currentValue()));\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,QAAN,MAAkC;;CAEhC,OAAgB;CAChB,YAAqC;CACrC,QAAQ;;CAER,cAAc;;CAGd;;CAEA;CAEA,YAAY,KAAc,OAAgB;EACxC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;AAGA,SAAS,SAAS,OAAc,UAAyB;CACvD,IAAI,MAAM,UAAU,UAAU;CAC9B,MAAM,QAAQ;CACd,OAAO,KAAK;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,YACd,QACA,QACqB;CACrB,MAAM,0BAAU,IAAI,IAAoB;;CAExC,IAAI,OAAqC;CAEzC,MAAM,WAAW,KAAQ,UACvB,WAAW,KAAA,IAAa,QAAoB,QAAQ,OAAO,KAAK,KAAK;CAEvE,MAAM,qBAAyB,SAAS,OAAO,QAAQ,MAAM,IAAI,KAAK;CAEtE,MAAM,WAAW,UAAuB;EACtC,MAAM,eAAe;EACrB,IAAI,MAAM,gBAAgB,KAAK,QAAQ,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC3F;CAEA,MAAM,UAAU,QAAkB;EAChC,MAAM,QAAQ,IAAI,MAAM,KAAK,QAAQ,KAAK,aAAa,CAAC,CAAC;EACzD,QAAQ,IAAI,KAAK,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAc,QAAoB;EACtC,IAAI,CAAC,WAAW,GAAG,OAAO,QAAQ,KAAK,OAAO,CAAC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,GAAG,KAAK,OAAO,GAAG;EAC5C,MAAM,eAAe;EACrB,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,MAAM,KAAK;EACX,OAAO,MAAM;CACf;CAEA,sBACQ,OAAO,IACZ,SAAS;EACR,MAAM,WAAW;EACjB,OAAO,EAAE,OAAO,KAAK;EACrB,IAAI,aAAa,QAAQ,WAAW,KAAA,GAAW;GAE7C,IAAI,SAAS,UAAU,MAAM;GAC7B,MAAM,SAAS,QAAQ,IAAI,SAAS,KAAK;GACzC,IAAI,WAAW,KAAA,GAAW,SAAS,QAAQ,OAAO,QAAQ,IAAI;GAC9D,MAAM,QAAQ,QAAQ,IAAI,IAAI;GAC9B,IAAI,UAAU,KAAA,GAAW,SAAS,OAAO,MAAM,QAAQ,IAAI;GAC3D;EACF;EAGA,IAAI,SAAS;EACb,IAAI;EACJ,KAAK,MAAM,SAAS,QAAQ,OAAO,GAAG;GACpC,IAAI;GACJ,IAAI;IACF,WAAW,QAAQ,MAAM,KAAU,IAAI;GACzC,SAAS,OAAO;IACd,IAAI,CAAC,QAAQ;KACX,SAAS;KACT,UAAU;IACZ;IACA;GACF;GACA,SAAS,OAAO,QAAQ;EAC1B;EACA,IAAI,QAAQ,MAAM;CACpB,CACF;CAEA,OAAO;AACT"}
|