@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":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"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":"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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"suspense.js","names":["SuspenseContext","ResourceCacheContext"],"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":"A,6CA8CA,MAAaA,EACK,kBAAsC,KAAM,CAAE,KAAM,UAAW,CAAC,EAsDrEC,EACK,kBAAoC,KAAM,CAAE,KAAM,eAAgB,CAAC,E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{untrack as e}from"./ownership.js";import{useSignal as t}from"./signal.js";import{startTransition as n}from"./internal/concurrency.js";function r(){let[r,i]=t(!1),a=0;return[r,t=>{a+=1,e(()=>i(!0));let r;try{r=n(t)}catch(t){throw--a,a===0&&e(()=>i(!1)),t}return r.then(()=>{--a,a===0&&e(()=>i(!1))})}]}function i(e,t){return e}export{i as useDeferredValue,r as useTransition};
|
|
2
|
+
//# sourceMappingURL=transitions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transitions.js","names":["useTransition","pending","setPending","useSignal","running","untrack","applied","startTransition","fn","error","useDeferredValue","source"],"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":"A,6IAwDA,SAAgBA,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EACzCC,EAAU,EAkBd,MAAO,CAACH,EAjBO,GAAkC,CAC/C,GAAW,EAEXI,MAAcH,EAAW,EAAI,CAAC,EAC9B,IAAII,EACJ,GAAI,CACF,EAAUC,EAAgBC,CAAE,CAC9B,OAASC,EAAO,CAGd,KAFA,IACIL,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,EAC5CO,CACR,CACA,OAAOH,EAAQ,SAAW,CACxB,IACIF,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBQ,EACd,EACA,EACa,CACG,OAAOC,CAkBzB,C"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { handleError } from "./internal/owner.js";
|
|
2
|
+
import { batch } from "./internal/scheduler.js";
|
|
3
|
+
import { untrack } from "./ownership.js";
|
|
4
|
+
import { useSignal } from "./signal.js";
|
|
5
|
+
import { currentOwner } from "./extend/index.js";
|
|
6
|
+
// src/action.ts
|
|
7
|
+
function isPromiseLike(value) {
|
|
8
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,
|
|
12
|
+
* tracks whether it is pending, and commits its result. The ShadowJS form of React's
|
|
13
|
+
* `useActionState` (state, dispatch, pending). `previous` is the last committed state.
|
|
14
|
+
*
|
|
15
|
+
* Only the latest dispatch commits: when two actions overlap, a slower result that settles after a
|
|
16
|
+
* newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not
|
|
17
|
+
* change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an
|
|
18
|
+
* error boundary can show it. Without an owner the returned promise rejects instead.
|
|
19
|
+
*
|
|
20
|
+
* @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.
|
|
21
|
+
* @param initialState The state before the first dispatch.
|
|
22
|
+
* @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true
|
|
23
|
+
* only while a returned promise is unsettled. `dispatch` returns a promise that settles when this
|
|
24
|
+
* call has finished, whether it committed or not.
|
|
25
|
+
* @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with
|
|
26
|
+
* the action's error. With an owner, the error goes to its error handler, or is reported as an
|
|
27
|
+
* uncaught error (`reportError`) when no handler is registered above it.
|
|
28
|
+
* @example
|
|
29
|
+
* import { useAction } from "@shadow-js/core";
|
|
30
|
+
*
|
|
31
|
+
* const [message, send, sending] = useAction(async (_prev: string, text: string) => {
|
|
32
|
+
* await fetch("/api/messages", { method: "POST", body: text });
|
|
33
|
+
* return `sent: ${text}`;
|
|
34
|
+
* }, "");
|
|
35
|
+
* void send("hello");
|
|
36
|
+
* console.log(sending(), message());
|
|
37
|
+
* @see useOptimistic
|
|
38
|
+
* @see useTransition
|
|
39
|
+
* @since 1.0.0
|
|
40
|
+
*/
|
|
41
|
+
function useAction(action, initialState) {
|
|
42
|
+
const owner = currentOwner();
|
|
43
|
+
const [state, setState] = useSignal(initialState);
|
|
44
|
+
const [pending, setPending] = useSignal(false);
|
|
45
|
+
let latest = 0;
|
|
46
|
+
const dispatch = (...args) => {
|
|
47
|
+
latest += 1;
|
|
48
|
+
const id = latest;
|
|
49
|
+
const previous = untrack(state);
|
|
50
|
+
const commit = (value) => {
|
|
51
|
+
if (id !== latest) return;
|
|
52
|
+
batch(() => {
|
|
53
|
+
setState(() => value);
|
|
54
|
+
setPending(false);
|
|
55
|
+
});
|
|
56
|
+
};
|
|
57
|
+
const fail = (error) => {
|
|
58
|
+
if (id !== latest) return;
|
|
59
|
+
setPending(false);
|
|
60
|
+
if (owner === null) throw error;
|
|
61
|
+
handleError(error, owner);
|
|
62
|
+
};
|
|
63
|
+
let result;
|
|
64
|
+
try {
|
|
65
|
+
result = untrack(() => action(previous, ...args));
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (owner === null) {
|
|
68
|
+
if (id === latest) setPending(false);
|
|
69
|
+
return Promise.reject(error);
|
|
70
|
+
}
|
|
71
|
+
fail(error);
|
|
72
|
+
return Promise.resolve();
|
|
73
|
+
}
|
|
74
|
+
if (!isPromiseLike(result)) {
|
|
75
|
+
commit(result);
|
|
76
|
+
return Promise.resolve();
|
|
77
|
+
}
|
|
78
|
+
setPending(true);
|
|
79
|
+
return Promise.resolve(result).then(commit, fail);
|
|
80
|
+
};
|
|
81
|
+
return [
|
|
82
|
+
state,
|
|
83
|
+
dispatch,
|
|
84
|
+
pending
|
|
85
|
+
];
|
|
86
|
+
}
|
|
87
|
+
export { useAction };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=action.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"action.js","names":[],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id !== latest) return;\n setPending(false);\n if (owner === null) throw error;\n handleError(error, owner);\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n if (owner === null) {\n // `fail` would rethrow synchronously; without an owner the promise carries the error.\n if (id === latest) setPending(false);\n return Promise.reject(error);\n }\n fail(error);\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":";;;;;;AAIA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,UACd,QACA,cAC2F;CAC3F,MAAM,QAAQ,aAAa;CAC3B,MAAM,CAAC,OAAO,YAAY,UAAa,YAAY;CACnD,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,SAAS;CAEb,MAAM,YAAY,GAAG,SAA2B;EAC9C,UAAU;EACV,MAAM,KAAK;EACX,MAAM,WAAW,QAAQ,KAAK;EAC9B,MAAM,UAAU,UAAmB;GACjC,IAAI,OAAO,QAAQ;GACnB,YAAY;IACV,eAAe,KAAK;IACpB,WAAW,KAAK;GAClB,CAAC;EACH;EACA,MAAM,QAAQ,UAAyB;GACrC,IAAI,OAAO,QAAQ;GACnB,WAAW,KAAK;GAChB,IAAI,UAAU,MAAM,MAAM;GAC1B,YAAY,OAAO,KAAK;EAC1B;EACA,IAAI;EACJ,IAAI;GACF,SAAS,cAAc,OAAO,UAAU,GAAG,IAAI,CAAC;EAClD,SAAS,OAAO;GACd,IAAI,UAAU,MAAM;IAElB,IAAI,OAAO,QAAQ,WAAW,KAAK;IACnC,OAAO,QAAQ,OAAO,KAAK;GAC7B;GACA,KAAK,KAAK;GACV,OAAO,QAAQ,QAAQ;EACzB;EACA,IAAI,CAAC,cAAiB,MAAM,GAAG;GAC7B,OAAO,MAAM;GACb,OAAO,QAAQ,QAAQ;EACzB;EACA,WAAW,IAAI;EACf,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,KAAK,QAAQ,IAAI;CAClD;CACA,OAAO;EAAC;EAAO;EAAU;CAAO;AAClC"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { currentOwner } from "./extend/index.js";
|
|
2
|
+
// src/cache.ts
|
|
3
|
+
function sameArgs(a, b) {
|
|
4
|
+
if (a.length !== b.length) return false;
|
|
5
|
+
for (let i = 0; i < a.length; i += 1) if (!Object.is(a[i], b[i])) return false;
|
|
6
|
+
return true;
|
|
7
|
+
}
|
|
8
|
+
/** The outermost owner: the root of the render (a request on the server, the app on the client). */
|
|
9
|
+
function rootOf(owner) {
|
|
10
|
+
let root = owner;
|
|
11
|
+
while (root !== null && root.parent !== null) root = root.parent;
|
|
12
|
+
return root;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
|
|
16
|
+
* arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
|
|
17
|
+
* position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
|
|
18
|
+
* A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.
|
|
19
|
+
*
|
|
20
|
+
* Use it to share one data fetch between components rendered in the same request.
|
|
21
|
+
*
|
|
22
|
+
* @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.
|
|
23
|
+
* @param options Per-scope limit. Undefined uses the default.
|
|
24
|
+
* @returns A function with the same signature.
|
|
25
|
+
* @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in
|
|
26
|
+
* production builds). The returned function rethrows what `fn` throws.
|
|
27
|
+
* @example
|
|
28
|
+
* import { cache } from "@shadow-js/core";
|
|
29
|
+
*
|
|
30
|
+
* const loadUser = cache((id: string) =>
|
|
31
|
+
* fetch(`/api/users/${id}`).then((response) => response.json()),
|
|
32
|
+
* );
|
|
33
|
+
* // Two components calling loadUser("u1") in the same render fetch once.
|
|
34
|
+
* @see useResource
|
|
35
|
+
* @since 1.0.0
|
|
36
|
+
*/
|
|
37
|
+
function cache(fn, options) {
|
|
38
|
+
const limit = options?.limit ?? 100;
|
|
39
|
+
if (!Number.isInteger(limit) || limit < 1) throw new RangeError("cache: limit must be a positive integer");
|
|
40
|
+
const scopes = /* @__PURE__ */ new WeakMap();
|
|
41
|
+
return (...args) => {
|
|
42
|
+
const root = rootOf(currentOwner());
|
|
43
|
+
if (root === null) return fn(...args);
|
|
44
|
+
let entries = scopes.get(root);
|
|
45
|
+
if (entries === void 0) {
|
|
46
|
+
entries = [];
|
|
47
|
+
scopes.set(root, entries);
|
|
48
|
+
}
|
|
49
|
+
for (const entry of entries) if (sameArgs(entry.args, args)) return entry.value;
|
|
50
|
+
const value = fn(...args);
|
|
51
|
+
entries.push({
|
|
52
|
+
args,
|
|
53
|
+
value
|
|
54
|
+
});
|
|
55
|
+
if (entries.length > limit) entries.shift();
|
|
56
|
+
return value;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export { cache };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","names":[],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return fn(...args);\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = fn(...args);\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":";;AAgBA,SAAS,SAAS,GAAuB,GAAgC;CACvE,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GACjC,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO;CAErC,OAAO;AACT;;AAGA,SAAS,OAAO,OAAmC;CACjD,IAAI,OAAO;CACX,OAAO,SAAS,QAAQ,KAAK,WAAW,MAAM,OAAO,KAAK;CAC1D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,MACd,IACA,SACmB;CACnB,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WACE,yCACZ;CAEF,MAAM,yBAAS,IAAI,QAAwB;CAC3C,QAAQ,GAAG,SAAe;EACxB,MAAM,OAAO,OAAO,aAAa,CAAC;EAClC,IAAI,SAAS,MAAM,OAAO,GAAG,GAAG,IAAI;EACpC,IAAI,UAAU,OAAO,IAAI,IAAI;EAC7B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,CAAC;GACX,OAAO,IAAI,MAAM,OAAO;EAC1B;EACA,KAAK,MAAM,SAAS,SAClB,IAAI,SAAS,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM;EAE/C,MAAM,QAAQ,GAAG,GAAG,IAAI;EACxB,QAAQ,KAAK;GAAE;GAAM;EAAM,CAAC;EAC5B,IAAI,QAAQ,SAAS,OAAO,QAAQ,MAAM;EAC1C,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { ShadowError } from "./internal/diagnostics.js";
|
|
2
|
+
import { Owner } from "./internal/owner.js";
|
|
3
|
+
import { runWithOwner } from "./ownership.js";
|
|
4
|
+
import { currentOwner } from "./extend/index.js";
|
|
5
|
+
// src/context.ts
|
|
6
|
+
/**
|
|
7
|
+
* Creates a context: a value that components read with {@link useContext} without passing it
|
|
8
|
+
* through props. Render the returned component around a subtree to provide a value. The value is
|
|
9
|
+
* read once; pass a signal accessor or a store to provide something reactive. On the server the
|
|
10
|
+
* provider builds its subtree once.
|
|
11
|
+
*
|
|
12
|
+
* @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined
|
|
13
|
+
* (or omitted) means the context has no default, so reading it without a provider throws.
|
|
14
|
+
* @param options A diagnostics name. Undefined uses the default.
|
|
15
|
+
* @returns The context, which is also its provider component.
|
|
16
|
+
* @example
|
|
17
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
18
|
+
*
|
|
19
|
+
* const Theme = createContext<"light" | "dark">("light", { name: "Theme" });
|
|
20
|
+
*
|
|
21
|
+
* function Label() {
|
|
22
|
+
* return <p>Theme: {useContext(Theme)}</p>;
|
|
23
|
+
* }
|
|
24
|
+
*
|
|
25
|
+
* const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;
|
|
26
|
+
* @see useContext
|
|
27
|
+
* @since 1.0.0
|
|
28
|
+
*/
|
|
29
|
+
function createContext(defaultValue, options) {
|
|
30
|
+
const id = Symbol(options?.name ?? "context");
|
|
31
|
+
const provider = (props) => {
|
|
32
|
+
const scope = new Owner(currentOwner());
|
|
33
|
+
const inherited = scope.context;
|
|
34
|
+
const next = Object.create(inherited);
|
|
35
|
+
next[id] = props.value;
|
|
36
|
+
scope.context = next;
|
|
37
|
+
return runWithOwner(scope, () => {
|
|
38
|
+
{
|
|
39
|
+
const built = props.children;
|
|
40
|
+
return () => built;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
return Object.assign(provider, {
|
|
45
|
+
id,
|
|
46
|
+
defaultValue,
|
|
47
|
+
Provider: provider
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the
|
|
52
|
+
* value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer
|
|
53
|
+
* builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new
|
|
54
|
+
* child owner of the current owner that is disposed with it.
|
|
55
|
+
*
|
|
56
|
+
* @param context The context to provide.
|
|
57
|
+
* @param value The value `useContext(context)` returns inside `fn`.
|
|
58
|
+
* @param fn Runs once, synchronously.
|
|
59
|
+
* @returns What `fn` returns.
|
|
60
|
+
* @example
|
|
61
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
62
|
+
* import { runWithContext } from "@shadow-js/core/extend";
|
|
63
|
+
*
|
|
64
|
+
* const Theme = createContext("light");
|
|
65
|
+
* const theme = runWithContext(Theme, "dark", () => useContext(Theme));
|
|
66
|
+
* console.log(theme); // "dark"
|
|
67
|
+
* @see createContext
|
|
68
|
+
* @since 1.0.0
|
|
69
|
+
*/
|
|
70
|
+
function runWithContext(context, value, fn) {
|
|
71
|
+
const scope = new Owner(currentOwner());
|
|
72
|
+
const next = Object.create(scope.context);
|
|
73
|
+
next[context.id] = value;
|
|
74
|
+
scope.context = next;
|
|
75
|
+
return runWithOwner(scope, fn);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Reads the nearest provided value of `context`. Falls back to its default; throws when there is
|
|
79
|
+
* neither a provider nor a default, because no correct value exists. The lookup follows the current
|
|
80
|
+
* owner, so call it while a component runs (or in an effect or memo it creates), not after an
|
|
81
|
+
* `await` or in an event handler. The read is not tracked.
|
|
82
|
+
*
|
|
83
|
+
* @param context A context made by {@link createContext}.
|
|
84
|
+
* @returns The value of the nearest provider above the current owner, else the default value.
|
|
85
|
+
* @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the
|
|
86
|
+
* context's default is `undefined`.
|
|
87
|
+
* @example
|
|
88
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
89
|
+
*
|
|
90
|
+
* const User = createContext<{ name: string }>();
|
|
91
|
+
*
|
|
92
|
+
* function Greeting() {
|
|
93
|
+
* const user = useContext(User); // throws CONTEXT_MISSING without a provider
|
|
94
|
+
* return <p>Hello, {user.name}</p>;
|
|
95
|
+
* }
|
|
96
|
+
* @see createContext
|
|
97
|
+
* @since 1.0.0
|
|
98
|
+
*/
|
|
99
|
+
function useContext(context) {
|
|
100
|
+
const map = currentOwner()?.context;
|
|
101
|
+
if (map !== null && map !== void 0 && context.id in map) return map[context.id];
|
|
102
|
+
if (context.defaultValue === void 0) throw new ShadowError("CONTEXT_MISSING");
|
|
103
|
+
return context.defaultValue;
|
|
104
|
+
}
|
|
105
|
+
export { createContext, runWithContext, useContext };
|
|
106
|
+
|
|
107
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../../src/context.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { currentOwner, Owner, ShadowError } from \"./extend\";\nimport { runWithOwner } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * A context made by {@link createContext}: a value that a subtree receives from the nearest provider\n * above it. The context is itself the provider component; `Provider` is the same function.\n * @since 1.0.0\n */\nexport interface Context<T> {\n /**\n * Renders `children` with `value` provided. The value is read once, when the provider is created;\n * provide an accessor or a store for a value that changes. Returns an accessor of the children.\n */\n (props: { value: T; children?: unknown }): unknown;\n /** The unique key the provided value is stored under, described by the context's `name`. */\n readonly id: symbol;\n /** The value {@link useContext} returns without a provider. `undefined` means none: it throws. */\n readonly defaultValue: T | undefined;\n /** The same component, for code written as `<Ctx.Provider value={...}>`. */\n readonly Provider: (props: { value: T; children?: unknown }) => unknown;\n}\n\n/**\n * Options of {@link createContext}.\n * @since 1.0.0\n */\nexport interface ContextOptions {\n /**\n * Label shown in diagnostics and used as the description of the context's `id` symbol.\n * @default \"context\"\n */\n name?: string;\n}\n\n/**\n * Creates a context: a value that components read with {@link useContext} without passing it\n * through props. Render the returned component around a subtree to provide a value. The value is\n * read once; pass a signal accessor or a store to provide something reactive. On the server the\n * provider builds its subtree once.\n *\n * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined\n * (or omitted) means the context has no default, so reading it without a provider throws.\n * @param options A diagnostics name. Undefined uses the default.\n * @returns The context, which is also its provider component.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const Theme = createContext<\"light\" | \"dark\">(\"light\", { name: \"Theme\" });\n *\n * function Label() {\n * return <p>Theme: {useContext(Theme)}</p>;\n * }\n *\n * const app = <Theme.Provider value=\"dark\"><Label /></Theme.Provider>;\n * @see useContext\n * @since 1.0.0\n */\nexport function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T> {\n const id = Symbol(options?.name ?? \"context\");\n const provider = (props: { value: T; children?: unknown }): unknown => {\n const scope = new Owner(currentOwner());\n const inherited = scope.context;\n const next = Object.create(inherited) as Record<symbol, unknown>;\n next[id] = props.value;\n scope.context = next;\n // A render effect, so a children expression that reads signals stays reactive and still sees\n // the provided value. An effect (not a memo) because component setup may legitimately write\n // signals, and errors thrown while building the subtree must reach the error boundaries.\n return runWithOwner(scope, () => {\n if (__SERVER__) {\n // Nothing is reactive on the server: build the subtree once.\n const built = props.children;\n return () => built;\n }\n const [children, setChildren] = useSignal<unknown>(undefined, { equals: false });\n useRenderEffect(\n () => props.children,\n (value) => {\n setChildren(() => value);\n },\n );\n return children;\n });\n };\n return Object.assign(provider, { id, defaultValue, Provider: provider }) as Context<T>;\n}\n\n/**\n * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the\n * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer\n * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new\n * child owner of the current owner that is disposed with it.\n *\n * @param context The context to provide.\n * @param value The value `useContext(context)` returns inside `fn`.\n * @param fn Runs once, synchronously.\n * @returns What `fn` returns.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n * import { runWithContext } from \"@shadow-js/core/extend\";\n *\n * const Theme = createContext(\"light\");\n * const theme = runWithContext(Theme, \"dark\", () => useContext(Theme));\n * console.log(theme); // \"dark\"\n * @see createContext\n * @since 1.0.0\n */\nexport function runWithContext<T, R>(context: Context<T>, value: T, fn: () => R): R {\n const scope = new Owner(currentOwner());\n const next = Object.create(scope.context) as Record<symbol, unknown>;\n next[context.id] = value;\n scope.context = next;\n return runWithOwner(scope, fn);\n}\n\n/**\n * Reads the nearest provided value of `context`. Falls back to its default; throws when there is\n * neither a provider nor a default, because no correct value exists. The lookup follows the current\n * owner, so call it while a component runs (or in an effect or memo it creates), not after an\n * `await` or in an event handler. The read is not tracked.\n *\n * @param context A context made by {@link createContext}.\n * @returns The value of the nearest provider above the current owner, else the default value.\n * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the\n * context's default is `undefined`.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const User = createContext<{ name: string }>();\n *\n * function Greeting() {\n * const user = useContext(User); // throws CONTEXT_MISSING without a provider\n * return <p>Hello, {user.name}</p>;\n * }\n * @see createContext\n * @since 1.0.0\n */\nexport function useContext<T>(context: Context<T>): T {\n const map = currentOwner()?.context;\n if (map !== null && map !== undefined && context.id in map) return map[context.id] as T;\n if (context.defaultValue === undefined) throw new ShadowError(\"CONTEXT_MISSING\");\n return context.defaultValue;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,cAAiB,cAAkB,SAAsC;CACvF,MAAM,KAAK,OAAO,SAAS,QAAQ,SAAS;CAC5C,MAAM,YAAY,UAAqD;EACrE,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;EACtC,MAAM,YAAY,MAAM;EACxB,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,KAAK,MAAM,MAAM;EACjB,MAAM,UAAU;EAIhB,OAAO,aAAa,aAAa;GACf;IAEd,MAAM,QAAQ,MAAM;IACpB,aAAa;GACf;EASF,CAAC;CACH;CACA,OAAO,OAAO,OAAO,UAAU;EAAE;EAAI;EAAc,UAAU;CAAS,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,eAAqB,SAAqB,OAAU,IAAgB;CAClF,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;CACtC,MAAM,OAAO,OAAO,OAAO,MAAM,OAAO;CACxC,KAAK,QAAQ,MAAM;CACnB,MAAM,UAAU;CAChB,OAAO,aAAa,OAAO,EAAE;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,WAAc,SAAwB;CACpD,MAAM,MAAM,aAAa,CAAC,EAAE;CAC5B,IAAI,QAAQ,QAAQ,QAAQ,KAAA,KAAa,QAAQ,MAAM,KAAK,OAAO,IAAI,QAAQ;CAC/E,IAAI,QAAQ,iBAAiB,KAAA,GAAW,MAAM,IAAI,YAAY,iBAAiB;CAC/E,OAAO,QAAQ;AACjB"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { warn } from "./internal/diagnostics.js";
|
|
2
|
+
// src/effect.ts
|
|
3
|
+
function useEffect(first, second, third) {
|
|
4
|
+
if (typeof second === "function") third?.defer, third?.name;
|
|
5
|
+
else {
|
|
6
|
+
if (Array.isArray(second)) warn("EFFECT_DEPS_IGNORED");
|
|
7
|
+
second?.name;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and
|
|
12
|
+
* before user effects on every flush. Used for DOM bindings; application code rarely needs it.
|
|
13
|
+
* It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In
|
|
14
|
+
* development, one created outside any owner warns `NO_OWNER_EFFECT`.
|
|
15
|
+
*
|
|
16
|
+
* @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself
|
|
17
|
+
* and may return a cleanup function.
|
|
18
|
+
* @param apply Untracked; receives the value and the previous value (`undefined` on the first
|
|
19
|
+
* run), and may return a cleanup function. Undefined: only `compute` runs.
|
|
20
|
+
* @example
|
|
21
|
+
* import { createRoot, useRenderEffect, useSignal } from "@shadow-js/core";
|
|
22
|
+
*
|
|
23
|
+
* const button = document.createElement("button");
|
|
24
|
+
* createRoot(() => {
|
|
25
|
+
* const [label] = useSignal("Save");
|
|
26
|
+
* useRenderEffect(label, (text) => {
|
|
27
|
+
* button.textContent = text; // runs now, and again when label changes
|
|
28
|
+
* });
|
|
29
|
+
* });
|
|
30
|
+
* @see useEffect
|
|
31
|
+
* @since 1.0.0
|
|
32
|
+
*/
|
|
33
|
+
function useRenderEffect(compute, apply) {}
|
|
34
|
+
/**
|
|
35
|
+
* Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never
|
|
36
|
+
* run it again. Its return value, if a function, is the cleanup, which runs when the owner is
|
|
37
|
+
* disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`
|
|
38
|
+
* boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.
|
|
39
|
+
*
|
|
40
|
+
* @param fn Runs once, untracked. It may return a cleanup function.
|
|
41
|
+
* @example
|
|
42
|
+
* import { onMount } from "@shadow-js/core";
|
|
43
|
+
*
|
|
44
|
+
* function SearchBox() {
|
|
45
|
+
* let input: HTMLInputElement | undefined;
|
|
46
|
+
* onMount(() => input?.focus());
|
|
47
|
+
* return <input ref={(el: HTMLInputElement) => (input = el)} />;
|
|
48
|
+
* }
|
|
49
|
+
* @see useEffect
|
|
50
|
+
* @since 1.0.0
|
|
51
|
+
*/
|
|
52
|
+
function onMount(fn) {}
|
|
53
|
+
export { onMount, useEffect, useRenderEffect };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=effect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\n/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */\nconst HELD: unique symbol = Symbol(\"held\");\n\n/** The nearest gate above the current owner (see `Owner.gate`), or null. */\nfunction nearestGate(): (() => boolean) | null {\n for (let owner = currentOwner(); owner !== null; owner = owner.parent) {\n if (owner.gate !== null) return owner.gate;\n }\n return null;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : nearestGate();\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect.\n let opened = false;\n const held = (): boolean => {\n if (opened) return false;\n if (gate()) return true;\n opened = true;\n return false;\n };\n if (apply === null) {\n const inner = fn;\n fn = (previous) => (held() ? undefined : inner(previous));\n } else {\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => (held() ? HELD : innerFn(previous));\n apply = (value, previous) => {\n if ((value as unknown) === HELD) return undefined;\n if (skipFirst) {\n skipFirst = false;\n return undefined;\n }\n return innerApply(value, ((previous as unknown) === HELD ? undefined : previous) as never);\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n ...(apply === null ? {} : { apply }),\n ...(name === undefined ? {} : { name }),\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":";;AAqJA,SAAgB,UACd,OACA,QACA,OACM;CACN,IAAI,OAAO,WAAW,YACpB,OAIS,OACP,OAAO;MAEJ;EACL,IAAI,MAAM,QAAQ,MAAM,GAAG,KAAK,qBAAqB;EACrD,QAA+E;CACjF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBACd,SACA,OACM,CAQR;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,IAAgC,CAExD"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// src/env.ts
|
|
2
|
+
/**
|
|
3
|
+
* True in the server condition build, where effects never run and rendering produces strings. Use
|
|
4
|
+
* it to skip browser-only work. The value is fixed per build: the package export conditions
|
|
5
|
+
* (`node`, `worker`, `browser`, ...) choose the build, not a runtime check.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* import { isServer } from "@shadow-js/core";
|
|
9
|
+
*
|
|
10
|
+
* const width = isServer ? 1024 : window.innerWidth;
|
|
11
|
+
* @see isDev
|
|
12
|
+
* @since 1.0.0
|
|
13
|
+
*/
|
|
14
|
+
const isServer = true;
|
|
15
|
+
/**
|
|
16
|
+
* True in development builds; false in production builds where `__DEV__` is compiled away. The
|
|
17
|
+
* `development` export condition selects the development build. Use it to guard checks and logging
|
|
18
|
+
* meant for development only.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* import { isDev } from "@shadow-js/core";
|
|
22
|
+
*
|
|
23
|
+
* if (isDev) console.info("debug panel enabled");
|
|
24
|
+
* @see isServer
|
|
25
|
+
* @since 1.0.0
|
|
26
|
+
*/
|
|
27
|
+
const isDev = true;
|
|
28
|
+
export { isDev, isServer };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=env.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.js","names":[],"sources":["../../src/env.ts"],"sourcesContent":["/**\n * True in the server condition build, where effects never run and rendering produces strings. Use\n * it to skip browser-only work. The value is fixed per build: the package export conditions\n * (`node`, `worker`, `browser`, ...) choose the build, not a runtime check.\n *\n * @example\n * import { isServer } from \"@shadow-js/core\";\n *\n * const width = isServer ? 1024 : window.innerWidth;\n * @see isDev\n * @since 1.0.0\n */\nexport const isServer: boolean = __SERVER__;\n\n/**\n * True in development builds; false in production builds where `__DEV__` is compiled away. The\n * `development` export condition selects the development build. Use it to guard checks and logging\n * meant for development only.\n *\n * @example\n * import { isDev } from \"@shadow-js/core\";\n *\n * if (isDev) console.info(\"debug panel enabled\");\n * @see isServer\n * @since 1.0.0\n */\nexport const isDev: boolean = __DEV__;\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,WAAA;;;;;;;;;;;;;AAcb,MAAa,QAAA"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { untrack } from "./ownership.js";
|
|
2
|
+
// src/events.ts
|
|
3
|
+
/**
|
|
4
|
+
* A stable callback that always runs its handler untracked. The ShadowJS form of React's
|
|
5
|
+
* `useEffectEvent`: components run once and props are getters, so the handler already sees the
|
|
6
|
+
* latest values. What it adds is the untracked call: an effect that calls the event does not
|
|
7
|
+
* subscribe to the signals the handler reads.
|
|
8
|
+
*
|
|
9
|
+
* @param handler The handler. Its arguments and result are passed through.
|
|
10
|
+
* @returns A new function with the same signature that calls `handler` untracked. Create it once,
|
|
11
|
+
* in the component body, and keep the reference.
|
|
12
|
+
* @example
|
|
13
|
+
* import { useEffect, useEvent, useSignal } from "@shadow-js/core";
|
|
14
|
+
*
|
|
15
|
+
* function Ticker() {
|
|
16
|
+
* const [count] = useSignal(0);
|
|
17
|
+
* const onTick = useEvent(() => console.log(count())); // count() is not tracked by the effect
|
|
18
|
+
* useEffect(() => {
|
|
19
|
+
* const id = setInterval(() => onTick(), 1000);
|
|
20
|
+
* return () => clearInterval(id);
|
|
21
|
+
* });
|
|
22
|
+
* return null;
|
|
23
|
+
* }
|
|
24
|
+
* @see untrack
|
|
25
|
+
* @since 1.0.0
|
|
26
|
+
*/
|
|
27
|
+
function useEvent(handler) {
|
|
28
|
+
return (...args) => untrack(() => handler(...args));
|
|
29
|
+
}
|
|
30
|
+
export { useEvent };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=events.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.js","names":[],"sources":["../../src/events.ts"],"sourcesContent":["import { untrack } from \"./ownership\";\n\n/**\n * A stable callback that always runs its handler untracked. The ShadowJS form of React's\n * `useEffectEvent`: components run once and props are getters, so the handler already sees the\n * latest values. What it adds is the untracked call: an effect that calls the event does not\n * subscribe to the signals the handler reads.\n *\n * @param handler The handler. Its arguments and result are passed through.\n * @returns A new function with the same signature that calls `handler` untracked. Create it once,\n * in the component body, and keep the reference.\n * @example\n * import { useEffect, useEvent, useSignal } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const [count] = useSignal(0);\n * const onTick = useEvent(() => console.log(count())); // count() is not tracked by the effect\n * useEffect(() => {\n * const id = setInterval(() => onTick(), 1000);\n * return () => clearInterval(id);\n * });\n * return null;\n * }\n * @see untrack\n * @since 1.0.0\n */\nexport function useEvent<A extends unknown[], R>(handler: (...args: A) => R): (...args: A) => R {\n return (...args: A): R => untrack(() => handler(...args));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,SAAiC,SAA+C;CAC9F,QAAQ,GAAG,SAAe,cAAc,QAAQ,GAAG,IAAI,CAAC;AAC1D"}
|