@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 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":";;;AAuCA,MAAM,wBAAwC,IAAI,QAAQ;;;;;;;;;AAU1D,SAAgB,OAAO,QAA2C;CAChE,OAAO,MAAM,IAAI,MAAM;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,UAAa,MAAS,SAA2C;CAC/E,MAAM,OAAsB;EAC1B;EACA,KAAK,SAAS,OAAO;EACrB,OAAO,SAAS,UAAU;CAC5B;CACA,MAAM,mBAAkC;EACtC,MAAM,IAAI,UAEJ,gEAEN;CACF;CACA,MAAM,IAAI,YAAY,IAAI;CAC1B,OAAO;AACT;;AAQA,SAAS,WAAW,MAAe,KAAqD;CACtF,IAAI,CAAC,YAAY,IAAI,GAAG,OAAO,KAAA;CAC/B,IAAI,OAAO,QAAQ,YAAY,OAAO,IAAI,IAAI;CAC9C,OAAO,OAAO,OAAO,MAAM,GAAG,IAAI,QAAQ,IAAI,MAAM,GAAG,IAAI,KAAA;AAC7D;;AAGA,SAAS,SAAS,GAAW,GAAoB;CAC/C,OAAO,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAA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AAQ,QAAQ,aAAa;EACnC,IAAI,UAAU,IAAI;GAChB,OAAO,KAAK,IAAI;GAChB;EACF;EACA,MAAM,WAAW,SAAS;EAC1B,IAAI,YAAY,QAAQ,KAAK,YAAY,IAAI,KAAK,SAAS,UAAU,IAAI,GAAG;GAC1E,IAAI,aAAa,MAAM,QAAQ,UAAU,IAAI;GAC7C,OAAO,KAAK,QAAQ;EACtB,OACE,OAAO,KAAK,IAAI;CAEpB;CACA,IAAI,KAAK,OACF;OAAA,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GACpD,IAAI,KAAK,WAAW,MAAM,OAAO,KAAK,SAAS,MAAM;CAAA;CAIzD,KAAK,IAAI,WAAW,GAAG,WAAW,OAAO,QAAQ,YAAY,GAC3D,SAAS,QAAQ,OAAO,QAAQ,GAAG,OAAO,SAAS;CAErD,IAAI,KAAK,SAAS,OAAO,QAAQ,SAAS,QAAQ,UAAU,OAAO,MAAM;AAC3E;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,QAAW,QAAgD;CACzE,OAAO;AACT"}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { DEVTOOLS_EVENT, report } from "../internal/devtools.js";
|
|
2
|
+
import { ShadowError } from "../internal/diagnostics.js";
|
|
3
|
+
import { group } from "../internal/scheduler.js";
|
|
4
|
+
import { untrack } from "../ownership.js";
|
|
5
|
+
import { useSignal } from "../signal.js";
|
|
6
|
+
import { currentOwner, isComputingMemo } from "../extend/index.js";
|
|
7
|
+
import { isReservedKey, isWrappable, unwrapValue } from "./nodes.js";
|
|
8
|
+
import { snapshot } from "./read.js";
|
|
9
|
+
import { applyReconcile, reconcile, specOf } from "./reconcile.js";
|
|
10
|
+
import { Transaction, draftOf, readProxyOf } from "./proxies.js";
|
|
11
|
+
// src/store/use-store.ts
|
|
12
|
+
function isPlainObject(value) {
|
|
13
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
14
|
+
const prototype = Object.getPrototypeOf(value);
|
|
15
|
+
return prototype === Object.prototype || prototype === null;
|
|
16
|
+
}
|
|
17
|
+
function rangeKeys(range, length) {
|
|
18
|
+
const from = range.from ?? 0;
|
|
19
|
+
const to = range.to ?? length - 1;
|
|
20
|
+
const by = range.by ?? 1;
|
|
21
|
+
if (!Number.isFinite(by) || by === 0) throw new TypeError("ShadowStore: a range needs a non-zero `by`");
|
|
22
|
+
const keys = [];
|
|
23
|
+
for (let i = from; by > 0 ? i <= to : i >= to; i += by) {
|
|
24
|
+
keys.push(i);
|
|
25
|
+
if (keys.length > length + 1) break;
|
|
26
|
+
}
|
|
27
|
+
return keys;
|
|
28
|
+
}
|
|
29
|
+
/** The keys one path step addresses on `target` (a draft). */
|
|
30
|
+
function stepKeys(target, step, label) {
|
|
31
|
+
const keys = [];
|
|
32
|
+
if (Array.isArray(target)) {
|
|
33
|
+
if (typeof step === "number") keys.push(step);
|
|
34
|
+
else if (typeof step === "function") {
|
|
35
|
+
const filter = step;
|
|
36
|
+
for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);
|
|
37
|
+
} else if (Array.isArray(step)) keys.push(...step);
|
|
38
|
+
else if (typeof step === "object" && step !== null) keys.push(...rangeKeys(step, target.length));
|
|
39
|
+
else throw new TypeError(`ShadowStore${label}: bad path step for an array`);
|
|
40
|
+
} else if (typeof step === "string" || typeof step === "number") keys.push(step);
|
|
41
|
+
else if (Array.isArray(step)) keys.push(...step);
|
|
42
|
+
else throw new TypeError(`ShadowStore${label}: bad path step for an object`);
|
|
43
|
+
for (const key of keys) if (typeof key === "string" && isReservedKey(key)) throw new TypeError(`ShadowStore${label}: the key "${key}" cannot be used in a path`);
|
|
44
|
+
return keys;
|
|
45
|
+
}
|
|
46
|
+
/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */
|
|
47
|
+
function applyPath(root, path, label) {
|
|
48
|
+
const value = path[path.length - 1];
|
|
49
|
+
const steps = path.slice(0, -1);
|
|
50
|
+
const walk = (target, depth) => {
|
|
51
|
+
for (const key of stepKeys(target, steps[depth], label)) {
|
|
52
|
+
const holder = target;
|
|
53
|
+
if (depth === steps.length - 1) {
|
|
54
|
+
const previous = holder[key];
|
|
55
|
+
const spec = typeof value === "function" ? specOf(value) : void 0;
|
|
56
|
+
if (spec !== void 0) {
|
|
57
|
+
if (isWrappable(previous)) applyReconcile(unwrapValue(previous), spec, label);
|
|
58
|
+
else holder[key] = spec.next;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const next = typeof value === "function" ? value(previous) : value;
|
|
62
|
+
if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) mergeInto(previous, next, label);
|
|
63
|
+
else holder[key] = next;
|
|
64
|
+
} else {
|
|
65
|
+
const child = holder[key];
|
|
66
|
+
if (!isWrappable(child)) throw new TypeError(`ShadowStore${label}: the path goes through a value that is not an object`);
|
|
67
|
+
walk(child, depth + 1);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
walk(root, 0);
|
|
72
|
+
}
|
|
73
|
+
function mergeInto(target, source, label) {
|
|
74
|
+
for (const key of Object.keys(source)) {
|
|
75
|
+
if (isReservedKey(key)) throw new TypeError(`ShadowStore${label}: the key "${key}" cannot be assigned`);
|
|
76
|
+
target[key] = source[key];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)
|
|
81
|
+
* in production, where `__DEV__` is false.
|
|
82
|
+
*/
|
|
83
|
+
const storeHandles = /* @__PURE__ */ new WeakMap();
|
|
84
|
+
function createDeepStore(initial, label) {
|
|
85
|
+
const root = unwrapValue(initial);
|
|
86
|
+
const store = readProxyOf(root);
|
|
87
|
+
const apply = (...args) => {
|
|
88
|
+
if (isComputingMemo()) throw new ShadowError("WRITE_IN_MEMO");
|
|
89
|
+
if (args.length === 0) throw new TypeError(`ShadowStore${label}: setStore() needs an argument`);
|
|
90
|
+
const first = args[0];
|
|
91
|
+
group(() => untrack(() => {
|
|
92
|
+
if (args.length > 1) {
|
|
93
|
+
const tx = new Transaction(label);
|
|
94
|
+
try {
|
|
95
|
+
applyPath(draftOf(root, tx), args, label);
|
|
96
|
+
} finally {
|
|
97
|
+
tx.open = false;
|
|
98
|
+
}
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (typeof first === "function") {
|
|
102
|
+
const spec = specOf(first);
|
|
103
|
+
if (spec !== void 0) {
|
|
104
|
+
applyReconcile(root, spec, label);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const tx = new Transaction(label);
|
|
108
|
+
let result;
|
|
109
|
+
try {
|
|
110
|
+
result = first(draftOf(root, tx));
|
|
111
|
+
} finally {
|
|
112
|
+
tx.open = false;
|
|
113
|
+
}
|
|
114
|
+
if (result !== void 0) replaceWith(root, result, label);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
replaceWith(root, first, label);
|
|
118
|
+
}));
|
|
119
|
+
};
|
|
120
|
+
const setStore = apply;
|
|
121
|
+
{
|
|
122
|
+
const handle = {
|
|
123
|
+
name: label === "" ? "store" : label.replace(/^ \((.*)\)$/, "$1"),
|
|
124
|
+
snapshot: () => snapshot(store),
|
|
125
|
+
set: (path, value) => {
|
|
126
|
+
apply(...path, value);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
const anchored = storeHandles.get(root);
|
|
130
|
+
if (anchored === void 0) storeHandles.set(root, [handle]);
|
|
131
|
+
else anchored.push(handle);
|
|
132
|
+
report(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());
|
|
133
|
+
}
|
|
134
|
+
return [store, setStore];
|
|
135
|
+
}
|
|
136
|
+
/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */
|
|
137
|
+
function replaceWith(root, value, label) {
|
|
138
|
+
if (Array.isArray(root)) {
|
|
139
|
+
if (!Array.isArray(value)) throw new TypeError(`ShadowStore${label}: an array store is updated with an array or a function`);
|
|
140
|
+
const spec = specOf(reconcile(value));
|
|
141
|
+
if (spec !== void 0) applyReconcile(root, spec, label);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (!isPlainObject(value)) throw new TypeError(`ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`);
|
|
145
|
+
const tx = new Transaction(label);
|
|
146
|
+
try {
|
|
147
|
+
mergeInto(draftOf(root, tx), value, label);
|
|
148
|
+
} finally {
|
|
149
|
+
tx.open = false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function useStore(initial, options) {
|
|
153
|
+
const label = options?.name === void 0 ? "" : ` (${options.name})`;
|
|
154
|
+
const root = unwrapValue(initial);
|
|
155
|
+
if (isWrappable(root)) return createDeepStore(root, label);
|
|
156
|
+
const [read, write] = useSignal(wrapCell(initial), options?.name === void 0 ? void 0 : { name: options.name });
|
|
157
|
+
const set = (next) => write(typeof next === "function" ? (previous) => wrapCell(next(previous)) : wrapCell(next));
|
|
158
|
+
return [read, set];
|
|
159
|
+
}
|
|
160
|
+
/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */
|
|
161
|
+
function wrapCell(value) {
|
|
162
|
+
const raw = unwrapValue(value);
|
|
163
|
+
return isWrappable(raw) ? readProxyOf(raw) : value;
|
|
164
|
+
}
|
|
165
|
+
export { useStore };
|
|
166
|
+
|
|
167
|
+
//# sourceMappingURL=use-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-store.js","names":[],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,UAAU,OAAoD,QAA0B;CAC/F,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,KAAK,MAAM,MAAM,SAAS;CAChC,MAAM,KAAK,MAAM,MAAM;CACvB,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,OAAO,GACjC,MAAM,IAAI,UACE,4CACZ;CACF,MAAM,OAA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F,MAAM,KAAK,IAAI,YAAY,KAAK;CAChC,IAAI;EACF,UAAU,QAAQ,MAAM,EAAE,GAA8B,OAAO,KAAK;CACtE,UAAU;EACR,GAAG,OAAO;CACZ;AACF;AA+CA,SAAgB,SAAS,SAAkB,SAAiC;CAC1E,MAAM,QAAQ,SAAS,SAAS,KAAA,IAAY,KAAK,KAAK,QAAQ,KAAK;CACnE,MAAM,OAAO,YAAY,OAAO;CAChC,IAAI,YAAY,IAAI,GAAG,OAAO,gBAAgB,MAAM,KAAK;CAGzD,MAAM,CAAC,MAAM,SAAS,UACpB,SAAS,OAAO,GAChB,SAAS,SAAS,KAAA,IAAY,KAAA,IAAY,EAAE,MAAM,QAAQ,KAAK,CACjE;CACA,MAAM,OAAO,SACX,MACE,OAAO,SAAS,cACX,aAAsB,SAAU,KAAwC,QAAQ,CAAC,IAClF,SAAS,IAAI,CACnB;CACF,OAAO,CAAC,MAAM,GAAG;AACnB;;AAGA,SAAS,SAAS,OAAyB;CACzC,MAAM,MAAM,YAAY,KAAK;CAC7B,OAAO,YAAY,GAAG,IAAI,YAAY,GAAG,IAAI;AAC/C"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createContext } from "./context.js";
|
|
2
|
+
// src/suspense.ts
|
|
3
|
+
/**
|
|
4
|
+
* The context through which an asynchronous source finds the nearest `<Suspense>` boundary. Each
|
|
5
|
+
* boundary provides its {@link SuspenseTracker}; the value is `null` outside any boundary. Read it
|
|
6
|
+
* when building a data primitive that should hold the boundary while it loads, as `useResource`
|
|
7
|
+
* does.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* import { SuspenseContext, useContext } from "@shadow-js/core";
|
|
11
|
+
*
|
|
12
|
+
* function useLoadingHold(promise: Promise<unknown>): void {
|
|
13
|
+
* const tracker = useContext(SuspenseContext); // null outside any <Suspense>
|
|
14
|
+
* if (tracker === null) return;
|
|
15
|
+
* tracker.increment(); // the boundary shows its fallback
|
|
16
|
+
* promise.finally(() => tracker.decrement());
|
|
17
|
+
* }
|
|
18
|
+
* @see useResource
|
|
19
|
+
* @since 1.0.0
|
|
20
|
+
*/
|
|
21
|
+
const SuspenseContext = /* @__PURE__ */ createContext(null, { name: "Suspense" });
|
|
22
|
+
/**
|
|
23
|
+
* The context through which `useResource` reaches the renderer's {@link ResourceCache}. Server
|
|
24
|
+
* renderers and hydration provide it; the value is `null` when resources should always fetch. Only
|
|
25
|
+
* a custom renderer needs to provide it.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* import { type ResourceCache, ResourceCacheContext } from "@shadow-js/core";
|
|
29
|
+
*
|
|
30
|
+
* const values = new Map<string, unknown>();
|
|
31
|
+
* let created = 0;
|
|
32
|
+
* const cache: ResourceCache = {
|
|
33
|
+
* key: (explicit) => explicit ?? `resource-${created++}`,
|
|
34
|
+
* read: (key) => (values.has(key) ? { value: values.get(key) } : undefined),
|
|
35
|
+
* track: (key, promise) => void promise.then((value) => values.set(key, value)),
|
|
36
|
+
* };
|
|
37
|
+
* const page = <ResourceCacheContext value={cache}><p>Loading data</p></ResourceCacheContext>;
|
|
38
|
+
* @see useResource
|
|
39
|
+
* @since 1.0.0
|
|
40
|
+
*/
|
|
41
|
+
const ResourceCacheContext = /* @__PURE__ */ createContext(null, { name: "ResourceCache" });
|
|
42
|
+
export { ResourceCacheContext, SuspenseContext };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=suspense.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"suspense.js","names":[],"sources":["../../src/suspense.ts"],"sourcesContent":["import { type Context, createContext } from \"./context\";\n\n/**\n * Counter protocol between asynchronous sources and the nearest `<Suspense>` boundary.\n * A source calls `increment()` when it starts blocking its readers and `decrement()` exactly once\n * when it settles.\n * @since 1.0.0\n */\nexport interface SuspenseTracker {\n /**\n * Records one more pending source. The boundary shows its fallback while the count is above\n * zero; call it once per source, the first time a reader sees that source pending.\n */\n increment(): void;\n /**\n * Records that one pending source settled (with a value or an error). Call it exactly once per\n * `increment()`; when the count returns to zero the boundary shows its content again.\n */\n decrement(): void;\n /**\n * Called when a transition reads pending data in this boundary. Returns true when the boundary keeps\n * its content meanwhile: the reader then throws the suspension and keeps its previous value until\n * the boundary releases it. Returns false (or is absent) to show the fallback as usual.\n * @default undefined (the boundary never holds its content: the fallback shows as usual)\n */\n hold?(): boolean;\n}\n\n/**\n * The context through which an asynchronous source finds the nearest `<Suspense>` boundary. Each\n * boundary provides its {@link SuspenseTracker}; the value is `null` outside any boundary. Read it\n * when building a data primitive that should hold the boundary while it loads, as `useResource`\n * does.\n *\n * @example\n * import { SuspenseContext, useContext } from \"@shadow-js/core\";\n *\n * function useLoadingHold(promise: Promise<unknown>): void {\n * const tracker = useContext(SuspenseContext); // null outside any <Suspense>\n * if (tracker === null) return;\n * tracker.increment(); // the boundary shows its fallback\n * promise.finally(() => tracker.decrement());\n * }\n * @see useResource\n * @since 1.0.0\n */\nexport const SuspenseContext: Context<SuspenseTracker | null> =\n /* @__PURE__ */ createContext<SuspenseTracker | null>(null, { name: \"Suspense\" });\n\n/**\n * Bridge between resources and the server/hydration runtime. During server rendering it collects\n * in-flight fetches and replays finished ones on the next pass; during hydration it serves the\n * values the server already fetched, so the client does not fetch them again.\n * @since 1.0.0\n */\nexport interface ResourceCache {\n /**\n * Deterministic key for a resource created at this point of the render. `explicit` is the\n * resource's `key` option, or `undefined` when it has none.\n */\n key(explicit: string | undefined): string;\n /** A cached value, wrapped so that `undefined` values are representable. */\n read(key: string): { value: unknown } | undefined;\n /**\n * A fetch started; the cache stores its value under `key` when it resolves. `options.deferStream` is\n * true for a resource that holds the first streamed flush (see `ResourceOptions.deferStream`).\n */\n track(key: string, promise: Promise<unknown>, options?: ResourceTrackOptions): void;\n /**\n * The fetch an earlier pass of the same render started for `key` and that has not settled, when there\n * is one. A resource that finds it waits for that fetch instead of starting another, so a pass that\n * renders again does not fetch twice. Optional: a cache that does not keep earlier fetches omits it.\n */\n pending?(key: string): Promise<unknown> | undefined;\n}\n\n/** What {@link ResourceCache.track} is told about a fetch. @since 1.0.0 */\nexport interface ResourceTrackOptions {\n /** True when the resource was created with `deferStream: true`. */\n readonly deferStream?: boolean | undefined;\n}\n\n/**\n * The context through which `useResource` reaches the renderer's {@link ResourceCache}. Server\n * renderers and hydration provide it; the value is `null` when resources should always fetch. Only\n * a custom renderer needs to provide it.\n *\n * @example\n * import { type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\n *\n * const values = new Map<string, unknown>();\n * let created = 0;\n * const cache: ResourceCache = {\n * key: (explicit) => explicit ?? `resource-${created++}`,\n * read: (key) => (values.has(key) ? { value: values.get(key) } : undefined),\n * track: (key, promise) => void promise.then((value) => values.set(key, value)),\n * };\n * const page = <ResourceCacheContext value={cache}><p>Loading data</p></ResourceCacheContext>;\n * @see useResource\n * @since 1.0.0\n */\nexport const ResourceCacheContext: Context<ResourceCache | null> =\n /* @__PURE__ */ createContext<ResourceCache | null>(null, { name: \"ResourceCache\" });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,kBACK,8BAAsC,MAAM,EAAE,MAAM,WAAW,CAAC;;;;;;;;;;;;;;;;;;;;AAsDlF,MAAa,uBACK,8BAAoC,MAAM,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { untrack } from "./ownership.js";
|
|
2
|
+
import { useSignal } from "./signal.js";
|
|
3
|
+
import { startTransition } from "./internal/concurrency.js";
|
|
4
|
+
// src/transitions.ts
|
|
5
|
+
/**
|
|
6
|
+
* Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:
|
|
7
|
+
* `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense
|
|
8
|
+
* boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.
|
|
9
|
+
*
|
|
10
|
+
* Use it for updates that may be slow to show (navigating to a page that loads data): the previous
|
|
11
|
+
* screen stays until the new one is ready, and the input stays responsive meanwhile.
|
|
12
|
+
*
|
|
13
|
+
* @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that
|
|
14
|
+
* resolves when the transition has been applied. On the server `start` runs `fn` at once.
|
|
15
|
+
* @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing
|
|
16
|
+
* `isPending` when no other transition of this hook is running.
|
|
17
|
+
* @example
|
|
18
|
+
* import { useSignal, useTransition } from "@shadow-js/core";
|
|
19
|
+
*
|
|
20
|
+
* function Tabs() {
|
|
21
|
+
* const [page, setPage] = useSignal("home");
|
|
22
|
+
* const [pending, start] = useTransition();
|
|
23
|
+
* return (
|
|
24
|
+
* <button disabled={pending()} onClick={() => start(() => setPage("reports"))}>
|
|
25
|
+
* {page() === "reports" ? "Reports" : "Open reports"}
|
|
26
|
+
* </button>
|
|
27
|
+
* );
|
|
28
|
+
* }
|
|
29
|
+
* @see startTransition
|
|
30
|
+
* @see useDeferredValue
|
|
31
|
+
* @since 1.0.0
|
|
32
|
+
*/
|
|
33
|
+
function useTransition() {
|
|
34
|
+
const [pending, setPending] = useSignal(false);
|
|
35
|
+
let running = 0;
|
|
36
|
+
const start = (fn) => {
|
|
37
|
+
running += 1;
|
|
38
|
+
untrack(() => setPending(true));
|
|
39
|
+
let applied;
|
|
40
|
+
try {
|
|
41
|
+
applied = startTransition(fn);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
running -= 1;
|
|
44
|
+
if (running === 0) untrack(() => setPending(false));
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
return applied.then(() => {
|
|
48
|
+
running -= 1;
|
|
49
|
+
if (running === 0) untrack(() => setPending(false));
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
return [pending, start];
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Returns a value that follows `source` in the transition lane: it keeps the previous value while
|
|
56
|
+
* urgent updates run, and takes the new value when the lane applies it. Reads of the source are
|
|
57
|
+
* unaffected. On the server it returns the source itself (there is no lane).
|
|
58
|
+
*
|
|
59
|
+
* @param source The value to follow. Tracked by a watcher that runs in the transition lane.
|
|
60
|
+
* @param options Equality and a devtools name. Undefined uses the defaults.
|
|
61
|
+
* @returns An accessor of the deferred value. It starts as the source's current value.
|
|
62
|
+
* @example
|
|
63
|
+
* import { useDeferredValue, useMemo, useSignal } from "@shadow-js/core";
|
|
64
|
+
*
|
|
65
|
+
* const names = ["Ada", "Grace", "Linus"];
|
|
66
|
+
* function Search() {
|
|
67
|
+
* const [query, setQuery] = useSignal("");
|
|
68
|
+
* const deferredQuery = useDeferredValue(query);
|
|
69
|
+
* const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));
|
|
70
|
+
* return (
|
|
71
|
+
* <label>
|
|
72
|
+
* <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />
|
|
73
|
+
* {results().join(", ")}
|
|
74
|
+
* </label>
|
|
75
|
+
* );
|
|
76
|
+
* }
|
|
77
|
+
* @see useTransition
|
|
78
|
+
* @since 1.0.0
|
|
79
|
+
*/
|
|
80
|
+
function useDeferredValue(source, options) {
|
|
81
|
+
return source;
|
|
82
|
+
}
|
|
83
|
+
export { useDeferredValue, useTransition };
|
|
84
|
+
|
|
85
|
+
//# sourceMappingURL=transitions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transitions.js","names":[],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,gBAAwE;CACtF,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,UAAU;CACd,MAAM,SAAS,OAAkC;EAC/C,WAAW;EAEX,cAAc,WAAW,IAAI,CAAC;EAC9B,IAAI;EACJ,IAAI;GACF,UAAU,gBAAgB,EAAE;EAC9B,SAAS,OAAO;GACd,WAAW;GACX,IAAI,YAAY,GAAG,cAAc,WAAW,KAAK,CAAC;GAClD,MAAM;EACR;EACA,OAAO,QAAQ,WAAW;GACxB,WAAW;GACX,IAAI,YAAY,GAAG,cAAc,WAAW,KAAK,CAAC;EACpD,CAAC;CACH;CACA,OAAO,CAAC,SAAS,KAAK;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBACd,QACA,SACa;CACG,OAAO;AAkBzB"}
|
package/package.json
CHANGED
|
@@ -1,66 +1,127 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shadow-js/core",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "
|
|
5
|
-
"author": "Jehaad AL-Johani",
|
|
6
|
-
"homepage": "https://github.com/shadowjs-dev/shadow#readme",
|
|
7
|
-
"repository": {
|
|
8
|
-
"type": "git",
|
|
9
|
-
"url": "https://github.com/shadowjs-dev/shadow.git",
|
|
10
|
-
"directory": "packages/core"
|
|
11
|
-
},
|
|
12
|
-
"bugs": {
|
|
13
|
-
"url": "https://github.com/shadowjs-dev/shadow/issues"
|
|
14
|
-
},
|
|
15
|
-
"keywords": [
|
|
16
|
-
"shadowjs",
|
|
17
|
-
"jsx",
|
|
18
|
-
"framework",
|
|
19
|
-
"reactivity",
|
|
20
|
-
"dom"
|
|
21
|
-
],
|
|
22
|
-
"engines": {
|
|
23
|
-
"node": ">=20"
|
|
24
|
-
},
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Signals, stores, memos and effects that update exactly what changed",
|
|
25
5
|
"license": "MIT",
|
|
26
6
|
"type": "module",
|
|
27
7
|
"sideEffects": false,
|
|
28
|
-
"
|
|
29
|
-
|
|
30
|
-
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=22.12.0"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"README.md",
|
|
14
|
+
"CHANGELOG.md"
|
|
15
|
+
],
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public",
|
|
18
|
+
"provenance": true
|
|
19
|
+
},
|
|
31
20
|
"exports": {
|
|
32
21
|
".": {
|
|
33
|
-
"types": "./dist/index.d.ts",
|
|
34
|
-
"
|
|
35
|
-
|
|
22
|
+
"types": "./dist/dev/index.d.ts",
|
|
23
|
+
"browser": {
|
|
24
|
+
"development": "./dist/dev/index.js",
|
|
25
|
+
"default": "./dist/prod/index.js"
|
|
26
|
+
},
|
|
27
|
+
"node": {
|
|
28
|
+
"development": "./dist/server-dev/index.js",
|
|
29
|
+
"default": "./dist/server/index.js"
|
|
30
|
+
},
|
|
31
|
+
"worker": {
|
|
32
|
+
"development": "./dist/server-dev/index.js",
|
|
33
|
+
"default": "./dist/server/index.js"
|
|
34
|
+
},
|
|
35
|
+
"deno": {
|
|
36
|
+
"development": "./dist/server-dev/index.js",
|
|
37
|
+
"default": "./dist/server/index.js"
|
|
38
|
+
},
|
|
39
|
+
"bun": {
|
|
40
|
+
"development": "./dist/server-dev/index.js",
|
|
41
|
+
"default": "./dist/server/index.js"
|
|
42
|
+
},
|
|
43
|
+
"development": "./dist/dev/index.js",
|
|
44
|
+
"default": "./dist/prod/index.js"
|
|
36
45
|
},
|
|
37
|
-
"./
|
|
38
|
-
"types": "./dist/
|
|
39
|
-
"
|
|
40
|
-
|
|
46
|
+
"./store": {
|
|
47
|
+
"types": "./dist/dev/store/index.d.ts",
|
|
48
|
+
"browser": {
|
|
49
|
+
"development": "./dist/dev/store/index.js",
|
|
50
|
+
"default": "./dist/prod/store/index.js"
|
|
51
|
+
},
|
|
52
|
+
"node": {
|
|
53
|
+
"development": "./dist/server-dev/store/index.js",
|
|
54
|
+
"default": "./dist/server/store/index.js"
|
|
55
|
+
},
|
|
56
|
+
"worker": {
|
|
57
|
+
"development": "./dist/server-dev/store/index.js",
|
|
58
|
+
"default": "./dist/server/store/index.js"
|
|
59
|
+
},
|
|
60
|
+
"deno": {
|
|
61
|
+
"development": "./dist/server-dev/store/index.js",
|
|
62
|
+
"default": "./dist/server/store/index.js"
|
|
63
|
+
},
|
|
64
|
+
"bun": {
|
|
65
|
+
"development": "./dist/server-dev/store/index.js",
|
|
66
|
+
"default": "./dist/server/store/index.js"
|
|
67
|
+
},
|
|
68
|
+
"development": "./dist/dev/store/index.js",
|
|
69
|
+
"default": "./dist/prod/store/index.js"
|
|
41
70
|
},
|
|
42
|
-
"./
|
|
43
|
-
|
|
44
|
-
"
|
|
45
|
-
"
|
|
71
|
+
"./package.json": "./package.json",
|
|
72
|
+
"./extend": {
|
|
73
|
+
"types": "./dist/dev/extend/index.d.ts",
|
|
74
|
+
"browser": {
|
|
75
|
+
"development": "./dist/dev/extend/index.js",
|
|
76
|
+
"default": "./dist/prod/extend/index.js"
|
|
77
|
+
},
|
|
78
|
+
"node": {
|
|
79
|
+
"development": "./dist/server-dev/extend/index.js",
|
|
80
|
+
"default": "./dist/server/extend/index.js"
|
|
81
|
+
},
|
|
82
|
+
"worker": {
|
|
83
|
+
"development": "./dist/server-dev/extend/index.js",
|
|
84
|
+
"default": "./dist/server/extend/index.js"
|
|
85
|
+
},
|
|
86
|
+
"deno": {
|
|
87
|
+
"development": "./dist/server-dev/extend/index.js",
|
|
88
|
+
"default": "./dist/server/extend/index.js"
|
|
89
|
+
},
|
|
90
|
+
"bun": {
|
|
91
|
+
"development": "./dist/server-dev/extend/index.js",
|
|
92
|
+
"default": "./dist/server/extend/index.js"
|
|
93
|
+
},
|
|
94
|
+
"development": "./dist/dev/extend/index.js",
|
|
95
|
+
"default": "./dist/prod/extend/index.js"
|
|
46
96
|
}
|
|
47
97
|
},
|
|
48
|
-
"files": [
|
|
49
|
-
"dist",
|
|
50
|
-
"README.md",
|
|
51
|
-
"LICENSE"
|
|
52
|
-
],
|
|
53
98
|
"scripts": {
|
|
54
|
-
"build": "
|
|
55
|
-
"
|
|
56
|
-
"typecheck": "tsc -p tsconfig.json
|
|
99
|
+
"build": "tsdown --config-loader native",
|
|
100
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test-types.json",
|
|
101
|
+
"typecheck:types": "tsc -p tsconfig.test-types.json"
|
|
57
102
|
},
|
|
58
|
-
"
|
|
59
|
-
|
|
60
|
-
"
|
|
61
|
-
"
|
|
103
|
+
"homepage": "https://shadowjs.net/reference/core/",
|
|
104
|
+
"keywords": [
|
|
105
|
+
"shadowjs",
|
|
106
|
+
"core"
|
|
107
|
+
],
|
|
108
|
+
"repository": {
|
|
109
|
+
"type": "git",
|
|
110
|
+
"url": "git+https://github.com/shadowjs-dev/shadow.git",
|
|
111
|
+
"directory": "packages/core"
|
|
62
112
|
},
|
|
63
|
-
"
|
|
64
|
-
"
|
|
113
|
+
"bugs": {
|
|
114
|
+
"url": "https://github.com/shadowjs-dev/shadow/issues"
|
|
115
|
+
},
|
|
116
|
+
"devDependencies": {
|
|
117
|
+
"@biomejs/biome": "2.5.15",
|
|
118
|
+
"@shadow-js/compiler": "*",
|
|
119
|
+
"@shadow-js/web": "*",
|
|
120
|
+
"@types/node": "^24.0.0",
|
|
121
|
+
"fast-check": "^4.10.2",
|
|
122
|
+
"happy-dom": "^21.0.3",
|
|
123
|
+
"tsdown": "0.23.0",
|
|
124
|
+
"typescript": "7.0.2",
|
|
125
|
+
"vitest": "5.0.3"
|
|
65
126
|
}
|
|
66
127
|
}
|