@shadow-js/core 0.1.0 → 1.0.0
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 +11 -0
- package/LICENSE +2 -2
- package/README.md +134 -331
- package/dist/dev/action.d.ts +36 -0
- package/dist/dev/action.js +90 -0
- package/dist/dev/action.js.map +1 -0
- package/dist/dev/cache.d.ts +35 -0
- package/dist/dev/cache.js +62 -0
- package/dist/dev/cache.js.map +1 -0
- package/dist/dev/context.d.ts +106 -0
- package/dist/dev/context.js +111 -0
- package/dist/dev/context.js.map +1 -0
- package/dist/dev/effect.d.ts +122 -0
- package/dist/dev/effect.js +111 -0
- package/dist/dev/effect.js.map +1 -0
- package/dist/dev/env.d.ts +29 -0
- package/dist/dev/env.js +31 -0
- package/dist/dev/env.js.map +1 -0
- package/dist/dev/events.d.ts +28 -0
- package/dist/dev/events.js +33 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend/index.d.ts +331 -0
- package/dist/dev/extend/index.js +317 -0
- package/dist/dev/extend/index.js.map +1 -0
- package/dist/dev/external-store.d.ts +60 -0
- package/dist/dev/external-store.js +60 -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 +213 -0
- package/dist/dev/internal/concurrency.js +632 -0
- package/dist/dev/internal/concurrency.js.map +1 -0
- package/dist/dev/internal/devtools.d.ts +71 -0
- package/dist/dev/internal/devtools.js +77 -0
- package/dist/dev/internal/devtools.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +90 -0
- package/dist/dev/internal/diagnostics.js +102 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/dispose.d.ts +28 -0
- package/dist/dev/internal/dispose.js +49 -0
- package/dist/dev/internal/dispose.js.map +1 -0
- package/dist/dev/internal/flags.js +11 -0
- package/dist/dev/internal/flags.js.map +1 -0
- package/dist/dev/internal/graph.d.ts +233 -0
- package/dist/dev/internal/graph.js +578 -0
- package/dist/dev/internal/graph.js.map +1 -0
- package/dist/dev/internal/hydration-flag.d.ts +33 -0
- package/dist/dev/internal/hydration-flag.js +46 -0
- package/dist/dev/internal/hydration-flag.js.map +1 -0
- package/dist/dev/internal/messages.d.ts +56 -0
- package/dist/dev/internal/messages.js +54 -0
- package/dist/dev/internal/messages.js.map +1 -0
- package/dist/dev/internal/owner.d.ts +142 -0
- package/dist/dev/internal/owner.js +290 -0
- package/dist/dev/internal/owner.js.map +1 -0
- package/dist/dev/internal/queue.js +46 -0
- package/dist/dev/internal/queue.js.map +1 -0
- package/dist/dev/internal/scheduler.d.ts +113 -0
- package/dist/dev/internal/scheduler.js +287 -0
- package/dist/dev/internal/scheduler.js.map +1 -0
- package/dist/dev/internal/state.d.ts +141 -0
- package/dist/dev/internal/state.js +28 -0
- package/dist/dev/internal/state.js.map +1 -0
- package/dist/dev/internal/suspension.d.ts +43 -0
- package/dist/dev/internal/suspension.js +45 -0
- package/dist/dev/internal/suspension.js.map +1 -0
- package/dist/dev/internal/types.d.ts +46 -0
- package/dist/dev/list.d.ts +93 -0
- package/dist/dev/list.js +282 -0
- package/dist/dev/list.js.map +1 -0
- package/dist/dev/memo.d.ts +60 -0
- package/dist/dev/memo.js +41 -0
- package/dist/dev/memo.js.map +1 -0
- package/dist/dev/optimistic.d.ts +26 -0
- package/dist/dev/optimistic.js +45 -0
- package/dist/dev/optimistic.js.map +1 -0
- package/dist/dev/ownership.d.ts +204 -0
- package/dist/dev/ownership.js +261 -0
- package/dist/dev/ownership.js.map +1 -0
- package/dist/dev/props.d.ts +134 -0
- package/dist/dev/props.js +282 -0
- package/dist/dev/props.js.map +1 -0
- package/dist/dev/reaction.d.ts +29 -0
- package/dist/dev/reaction.js +61 -0
- package/dist/dev/reaction.js.map +1 -0
- package/dist/dev/reducer.d.ts +41 -0
- package/dist/dev/reducer.js +39 -0
- package/dist/dev/reducer.js.map +1 -0
- package/dist/dev/refs.d.ts +52 -0
- package/dist/dev/refs.js +58 -0
- package/dist/dev/refs.js.map +1 -0
- package/dist/dev/resource.d.ts +135 -0
- package/dist/dev/resource.js +177 -0
- package/dist/dev/resource.js.map +1 -0
- package/dist/dev/selector.d.ts +34 -0
- package/dist/dev/selector.js +118 -0
- package/dist/dev/selector.js.map +1 -0
- package/dist/dev/signal.d.ts +42 -0
- package/dist/dev/signal.js +39 -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 +192 -0
- package/dist/dev/store/nodes.js.map +1 -0
- package/dist/dev/store/proxies.js +160 -0
- package/dist/dev/store/proxies.js.map +1 -0
- package/dist/dev/store/read.d.ts +39 -0
- package/dist/dev/store/read.js +72 -0
- package/dist/dev/store/read.js.map +1 -0
- package/dist/dev/store/reconcile.d.ts +73 -0
- package/dist/dev/store/reconcile.js +186 -0
- package/dist/dev/store/reconcile.js.map +1 -0
- package/dist/dev/store/types.d.ts +106 -0
- package/dist/dev/store/use-store.d.ts +60 -0
- package/dist/dev/store/use-store.js +168 -0
- package/dist/dev/store/use-store.js.map +1 -0
- package/dist/dev/suspense.d.ts +101 -0
- package/dist/dev/suspense.js +45 -0
- package/dist/dev/suspense.js.map +1 -0
- package/dist/dev/transitions.d.ts +77 -0
- package/dist/dev/transitions.js +101 -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 +90 -0
- package/dist/server-dev/action.js.map +1 -0
- package/dist/server-dev/cache.js +62 -0
- package/dist/server-dev/cache.js.map +1 -0
- package/dist/server-dev/context.js +108 -0
- package/dist/server-dev/context.js.map +1 -0
- package/dist/server-dev/effect.js +56 -0
- package/dist/server-dev/effect.js.map +1 -0
- package/dist/server-dev/env.js +31 -0
- package/dist/server-dev/env.js.map +1 -0
- package/dist/server-dev/events.js +33 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend/index.js +317 -0
- package/dist/server-dev/extend/index.js.map +1 -0
- package/dist/server-dev/external-store.js +46 -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 +633 -0
- package/dist/server-dev/internal/concurrency.js.map +1 -0
- package/dist/server-dev/internal/devtools.js +77 -0
- package/dist/server-dev/internal/devtools.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +102 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/dispose.js +49 -0
- package/dist/server-dev/internal/dispose.js.map +1 -0
- package/dist/server-dev/internal/flags.js +11 -0
- package/dist/server-dev/internal/flags.js.map +1 -0
- package/dist/server-dev/internal/graph.js +578 -0
- package/dist/server-dev/internal/graph.js.map +1 -0
- package/dist/server-dev/internal/hydration-flag.js +46 -0
- package/dist/server-dev/internal/hydration-flag.js.map +1 -0
- package/dist/server-dev/internal/messages.js +54 -0
- package/dist/server-dev/internal/messages.js.map +1 -0
- package/dist/server-dev/internal/owner.js +290 -0
- package/dist/server-dev/internal/owner.js.map +1 -0
- package/dist/server-dev/internal/queue.js +46 -0
- package/dist/server-dev/internal/queue.js.map +1 -0
- package/dist/server-dev/internal/scheduler.js +287 -0
- package/dist/server-dev/internal/scheduler.js.map +1 -0
- package/dist/server-dev/internal/state.js +28 -0
- package/dist/server-dev/internal/state.js.map +1 -0
- package/dist/server-dev/internal/suspension.js +45 -0
- package/dist/server-dev/internal/suspension.js.map +1 -0
- package/dist/server-dev/list.js +282 -0
- package/dist/server-dev/list.js.map +1 -0
- package/dist/server-dev/memo.js +41 -0
- package/dist/server-dev/memo.js.map +1 -0
- package/dist/server-dev/optimistic.js +45 -0
- package/dist/server-dev/optimistic.js.map +1 -0
- package/dist/server-dev/ownership.js +261 -0
- package/dist/server-dev/ownership.js.map +1 -0
- package/dist/server-dev/props.js +282 -0
- package/dist/server-dev/props.js.map +1 -0
- package/dist/server-dev/reaction.js +61 -0
- package/dist/server-dev/reaction.js.map +1 -0
- package/dist/server-dev/reducer.js +39 -0
- package/dist/server-dev/reducer.js.map +1 -0
- package/dist/server-dev/refs.js +58 -0
- package/dist/server-dev/refs.js.map +1 -0
- package/dist/server-dev/resource.js +176 -0
- package/dist/server-dev/resource.js.map +1 -0
- package/dist/server-dev/selector.js +82 -0
- package/dist/server-dev/selector.js.map +1 -0
- package/dist/server-dev/signal.js +39 -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 +192 -0
- package/dist/server-dev/store/nodes.js.map +1 -0
- package/dist/server-dev/store/proxies.js +160 -0
- package/dist/server-dev/store/proxies.js.map +1 -0
- package/dist/server-dev/store/read.js +72 -0
- package/dist/server-dev/store/read.js.map +1 -0
- package/dist/server-dev/store/reconcile.js +186 -0
- package/dist/server-dev/store/reconcile.js.map +1 -0
- package/dist/server-dev/store/use-store.js +168 -0
- package/dist/server-dev/store/use-store.js.map +1 -0
- package/dist/server-dev/suspense.js +45 -0
- package/dist/server-dev/suspense.js.map +1 -0
- package/dist/server-dev/transitions.js +86 -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":"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,35 @@
|
|
|
1
|
+
//#region src/cache.d.ts
|
|
2
|
+
/** Options of {@link cache}. @since 1.0.0 */
|
|
3
|
+
export interface CacheOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Most results kept per scope (one root); the oldest is dropped first. A positive integer.
|
|
6
|
+
* @default 100
|
|
7
|
+
*/
|
|
8
|
+
limit?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
|
|
12
|
+
* arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
|
|
13
|
+
* position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
|
|
14
|
+
* A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.
|
|
15
|
+
*
|
|
16
|
+
* Use it to share one data fetch between components rendered in the same request.
|
|
17
|
+
*
|
|
18
|
+
* @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.
|
|
19
|
+
* @param options Per-scope limit. Undefined uses the default.
|
|
20
|
+
* @returns A function with the same signature.
|
|
21
|
+
* @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in
|
|
22
|
+
* production builds). The returned function rethrows what `fn` throws.
|
|
23
|
+
* @example
|
|
24
|
+
* import { cache } from "@shadow-js/core";
|
|
25
|
+
*
|
|
26
|
+
* const loadUser = cache((id: string) =>
|
|
27
|
+
* fetch(`/api/users/${id}`).then((response) => response.json()),
|
|
28
|
+
* );
|
|
29
|
+
* // Two components calling loadUser("u1") in the same render fetch once.
|
|
30
|
+
* @see useResource
|
|
31
|
+
* @since 1.0.0
|
|
32
|
+
*/
|
|
33
|
+
export declare function cache<A extends unknown[], R>(fn: (...args: A) => R, options?: CacheOptions): (...args: A) => R;
|
|
34
|
+
//#endregion
|
|
35
|
+
//# sourceMappingURL=cache.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { currentOwner } from "./extend/index.js";
|
|
2
|
+
//#region 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
|
+
//#endregion
|
|
60
|
+
export { cache };
|
|
61
|
+
|
|
62
|
+
//# 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,106 @@
|
|
|
1
|
+
//#region src/context.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* A context made by {@link createContext}: a value that a subtree receives from the nearest provider
|
|
4
|
+
* above it. The context is itself the provider component; `Provider` is the same function.
|
|
5
|
+
* @since 1.0.0
|
|
6
|
+
*/
|
|
7
|
+
export interface Context<T> {
|
|
8
|
+
/**
|
|
9
|
+
* Renders `children` with `value` provided. The value is read once, when the provider is created;
|
|
10
|
+
* provide an accessor or a store for a value that changes. Returns an accessor of the children.
|
|
11
|
+
*/
|
|
12
|
+
(props: {
|
|
13
|
+
value: T;
|
|
14
|
+
children?: unknown;
|
|
15
|
+
}): unknown;
|
|
16
|
+
/** The unique key the provided value is stored under, described by the context's `name`. */
|
|
17
|
+
readonly id: symbol;
|
|
18
|
+
/** The value {@link useContext} returns without a provider. `undefined` means none: it throws. */
|
|
19
|
+
readonly defaultValue: T | undefined;
|
|
20
|
+
/** The same component, for code written as `<Ctx.Provider value={...}>`. */
|
|
21
|
+
readonly Provider: (props: {
|
|
22
|
+
value: T;
|
|
23
|
+
children?: unknown;
|
|
24
|
+
}) => unknown;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Options of {@link createContext}.
|
|
28
|
+
* @since 1.0.0
|
|
29
|
+
*/
|
|
30
|
+
export interface ContextOptions {
|
|
31
|
+
/**
|
|
32
|
+
* Label shown in diagnostics and used as the description of the context's `id` symbol.
|
|
33
|
+
* @default "context"
|
|
34
|
+
*/
|
|
35
|
+
name?: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Creates a context: a value that components read with {@link useContext} without passing it
|
|
39
|
+
* through props. Render the returned component around a subtree to provide a value. The value is
|
|
40
|
+
* read once; pass a signal accessor or a store to provide something reactive. On the server the
|
|
41
|
+
* provider builds its subtree once.
|
|
42
|
+
*
|
|
43
|
+
* @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined
|
|
44
|
+
* (or omitted) means the context has no default, so reading it without a provider throws.
|
|
45
|
+
* @param options A diagnostics name. Undefined uses the default.
|
|
46
|
+
* @returns The context, which is also its provider component.
|
|
47
|
+
* @example
|
|
48
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
49
|
+
*
|
|
50
|
+
* const Theme = createContext<"light" | "dark">("light", { name: "Theme" });
|
|
51
|
+
*
|
|
52
|
+
* function Label() {
|
|
53
|
+
* return <p>Theme: {useContext(Theme)}</p>;
|
|
54
|
+
* }
|
|
55
|
+
*
|
|
56
|
+
* const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;
|
|
57
|
+
* @see useContext
|
|
58
|
+
* @since 1.0.0
|
|
59
|
+
*/
|
|
60
|
+
export declare function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T>;
|
|
61
|
+
/**
|
|
62
|
+
* Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the
|
|
63
|
+
* value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer
|
|
64
|
+
* builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new
|
|
65
|
+
* child owner of the current owner that is disposed with it.
|
|
66
|
+
*
|
|
67
|
+
* @param context The context to provide.
|
|
68
|
+
* @param value The value `useContext(context)` returns inside `fn`.
|
|
69
|
+
* @param fn Runs once, synchronously.
|
|
70
|
+
* @returns What `fn` returns.
|
|
71
|
+
* @example
|
|
72
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
73
|
+
* import { runWithContext } from "@shadow-js/core/extend";
|
|
74
|
+
*
|
|
75
|
+
* const Theme = createContext("light");
|
|
76
|
+
* const theme = runWithContext(Theme, "dark", () => useContext(Theme));
|
|
77
|
+
* console.log(theme); // "dark"
|
|
78
|
+
* @see createContext
|
|
79
|
+
* @since 1.0.0
|
|
80
|
+
*/
|
|
81
|
+
export declare function runWithContext<T, R>(context: Context<T>, value: T, fn: () => R): R;
|
|
82
|
+
/**
|
|
83
|
+
* Reads the nearest provided value of `context`. Falls back to its default; throws when there is
|
|
84
|
+
* neither a provider nor a default, because no correct value exists. The lookup follows the current
|
|
85
|
+
* owner, so call it while a component runs (or in an effect or memo it creates), not after an
|
|
86
|
+
* `await` or in an event handler. The read is not tracked.
|
|
87
|
+
*
|
|
88
|
+
* @param context A context made by {@link createContext}.
|
|
89
|
+
* @returns The value of the nearest provider above the current owner, else the default value.
|
|
90
|
+
* @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the
|
|
91
|
+
* context's default is `undefined`.
|
|
92
|
+
* @example
|
|
93
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
94
|
+
*
|
|
95
|
+
* const User = createContext<{ name: string }>();
|
|
96
|
+
*
|
|
97
|
+
* function Greeting() {
|
|
98
|
+
* const user = useContext(User); // throws CONTEXT_MISSING without a provider
|
|
99
|
+
* return <p>Hello, {user.name}</p>;
|
|
100
|
+
* }
|
|
101
|
+
* @see createContext
|
|
102
|
+
* @since 1.0.0
|
|
103
|
+
*/
|
|
104
|
+
export declare function useContext<T>(context: Context<T>): T;
|
|
105
|
+
//#endregion
|
|
106
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { ShadowError } from "./internal/diagnostics.js";
|
|
2
|
+
import { Owner } from "./internal/owner.js";
|
|
3
|
+
import { runWithOwner } from "./ownership.js";
|
|
4
|
+
import { useRenderEffect } from "./effect.js";
|
|
5
|
+
import { useSignal } from "./signal.js";
|
|
6
|
+
import { currentOwner } from "./extend/index.js";
|
|
7
|
+
//#region src/context.ts
|
|
8
|
+
/**
|
|
9
|
+
* Creates a context: a value that components read with {@link useContext} without passing it
|
|
10
|
+
* through props. Render the returned component around a subtree to provide a value. The value is
|
|
11
|
+
* read once; pass a signal accessor or a store to provide something reactive. On the server the
|
|
12
|
+
* provider builds its subtree once.
|
|
13
|
+
*
|
|
14
|
+
* @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined
|
|
15
|
+
* (or omitted) means the context has no default, so reading it without a provider throws.
|
|
16
|
+
* @param options A diagnostics name. Undefined uses the default.
|
|
17
|
+
* @returns The context, which is also its provider component.
|
|
18
|
+
* @example
|
|
19
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
20
|
+
*
|
|
21
|
+
* const Theme = createContext<"light" | "dark">("light", { name: "Theme" });
|
|
22
|
+
*
|
|
23
|
+
* function Label() {
|
|
24
|
+
* return <p>Theme: {useContext(Theme)}</p>;
|
|
25
|
+
* }
|
|
26
|
+
*
|
|
27
|
+
* const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;
|
|
28
|
+
* @see useContext
|
|
29
|
+
* @since 1.0.0
|
|
30
|
+
*/
|
|
31
|
+
function createContext(defaultValue, options) {
|
|
32
|
+
const id = Symbol(options?.name ?? "context");
|
|
33
|
+
const provider = (props) => {
|
|
34
|
+
const scope = new Owner(currentOwner());
|
|
35
|
+
const inherited = scope.context;
|
|
36
|
+
const next = Object.create(inherited);
|
|
37
|
+
next[id] = props.value;
|
|
38
|
+
scope.context = next;
|
|
39
|
+
return runWithOwner(scope, () => {
|
|
40
|
+
const [children, setChildren] = useSignal(void 0, { equals: false });
|
|
41
|
+
useRenderEffect(() => props.children, (value) => {
|
|
42
|
+
setChildren(() => value);
|
|
43
|
+
});
|
|
44
|
+
return children;
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
return Object.assign(provider, {
|
|
48
|
+
id,
|
|
49
|
+
defaultValue,
|
|
50
|
+
Provider: provider
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the
|
|
55
|
+
* value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer
|
|
56
|
+
* builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new
|
|
57
|
+
* child owner of the current owner that is disposed with it.
|
|
58
|
+
*
|
|
59
|
+
* @param context The context to provide.
|
|
60
|
+
* @param value The value `useContext(context)` returns inside `fn`.
|
|
61
|
+
* @param fn Runs once, synchronously.
|
|
62
|
+
* @returns What `fn` returns.
|
|
63
|
+
* @example
|
|
64
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
65
|
+
* import { runWithContext } from "@shadow-js/core/extend";
|
|
66
|
+
*
|
|
67
|
+
* const Theme = createContext("light");
|
|
68
|
+
* const theme = runWithContext(Theme, "dark", () => useContext(Theme));
|
|
69
|
+
* console.log(theme); // "dark"
|
|
70
|
+
* @see createContext
|
|
71
|
+
* @since 1.0.0
|
|
72
|
+
*/
|
|
73
|
+
function runWithContext(context, value, fn) {
|
|
74
|
+
const scope = new Owner(currentOwner());
|
|
75
|
+
const next = Object.create(scope.context);
|
|
76
|
+
next[context.id] = value;
|
|
77
|
+
scope.context = next;
|
|
78
|
+
return runWithOwner(scope, fn);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Reads the nearest provided value of `context`. Falls back to its default; throws when there is
|
|
82
|
+
* neither a provider nor a default, because no correct value exists. The lookup follows the current
|
|
83
|
+
* owner, so call it while a component runs (or in an effect or memo it creates), not after an
|
|
84
|
+
* `await` or in an event handler. The read is not tracked.
|
|
85
|
+
*
|
|
86
|
+
* @param context A context made by {@link createContext}.
|
|
87
|
+
* @returns The value of the nearest provider above the current owner, else the default value.
|
|
88
|
+
* @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the
|
|
89
|
+
* context's default is `undefined`.
|
|
90
|
+
* @example
|
|
91
|
+
* import { createContext, useContext } from "@shadow-js/core";
|
|
92
|
+
*
|
|
93
|
+
* const User = createContext<{ name: string }>();
|
|
94
|
+
*
|
|
95
|
+
* function Greeting() {
|
|
96
|
+
* const user = useContext(User); // throws CONTEXT_MISSING without a provider
|
|
97
|
+
* return <p>Hello, {user.name}</p>;
|
|
98
|
+
* }
|
|
99
|
+
* @see createContext
|
|
100
|
+
* @since 1.0.0
|
|
101
|
+
*/
|
|
102
|
+
function useContext(context) {
|
|
103
|
+
const map = currentOwner()?.context;
|
|
104
|
+
if (map !== null && map !== void 0 && context.id in map) return map[context.id];
|
|
105
|
+
if (context.defaultValue === void 0) throw new ShadowError("CONTEXT_MISSING");
|
|
106
|
+
return context.defaultValue;
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
export { createContext, runWithContext, useContext };
|
|
110
|
+
|
|
111
|
+
//# 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;GAM/B,MAAM,CAAC,UAAU,eAAe,UAAmB,KAAA,GAAW,EAAE,QAAQ,MAAM,CAAC;GAC/E,sBACQ,MAAM,WACX,UAAU;IACT,kBAAkB,KAAK;GACzB,CACF;GACA,OAAO;EACT,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,122 @@
|
|
|
1
|
+
import { Cleanup } from "./internal/types.js";
|
|
2
|
+
//#region src/effect.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.
|
|
5
|
+
* @since 1.0.0
|
|
6
|
+
*/
|
|
7
|
+
export interface EffectOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Label shown by devtools and diagnostics.
|
|
10
|
+
* @default undefined (the effect is unnamed)
|
|
11
|
+
*/
|
|
12
|
+
name?: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.
|
|
16
|
+
* @since 1.0.0
|
|
17
|
+
*/
|
|
18
|
+
export interface DeferredEffectOptions extends EffectOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only
|
|
21
|
+
* runs for later changes of it.
|
|
22
|
+
* @default false
|
|
23
|
+
*/
|
|
24
|
+
defer?: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Runs a side effect after rendering and again whenever a tracked signal changes. The first run
|
|
28
|
+
* is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary
|
|
29
|
+
* that is still showing its fallback, the first run waits until the boundary first shows its content.
|
|
30
|
+
*
|
|
31
|
+
* Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only
|
|
32
|
+
* `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.
|
|
33
|
+
* An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).
|
|
34
|
+
* In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but
|
|
35
|
+
* nothing can dispose it.
|
|
36
|
+
*
|
|
37
|
+
* @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.
|
|
38
|
+
* @param options A devtools name. Undefined uses the default.
|
|
39
|
+
* @example
|
|
40
|
+
* import { useEffect, useSignal } from "@shadow-js/core";
|
|
41
|
+
*
|
|
42
|
+
* function PageTitle(props: { unread: number }) {
|
|
43
|
+
* const [title] = useSignal("Inbox");
|
|
44
|
+
* useEffect(() => {
|
|
45
|
+
* document.title = `${title()} (${props.unread})`; // re-runs when either changes
|
|
46
|
+
* });
|
|
47
|
+
* return null;
|
|
48
|
+
* }
|
|
49
|
+
* @see useRenderEffect
|
|
50
|
+
* @see onMount
|
|
51
|
+
* @since 1.0.0
|
|
52
|
+
*/
|
|
53
|
+
export declare function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;
|
|
54
|
+
/**
|
|
55
|
+
* Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`
|
|
56
|
+
* untracked with the new and the previous value of `deps`. Use it when the effect body reads
|
|
57
|
+
* signals that must not re-run it.
|
|
58
|
+
*
|
|
59
|
+
* @param deps Tracked; its result is passed to `fn`.
|
|
60
|
+
* @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there
|
|
61
|
+
* is none yet). It may return a cleanup function, which runs before the next call or on disposal.
|
|
62
|
+
* @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.
|
|
63
|
+
* @example
|
|
64
|
+
* import { useEffect } from "@shadow-js/core";
|
|
65
|
+
*
|
|
66
|
+
* function Profile(props: { userId: string }) {
|
|
67
|
+
* useEffect(
|
|
68
|
+
* () => props.userId,
|
|
69
|
+
* (next, previous) => console.log(`switched from ${previous} to ${next}`),
|
|
70
|
+
* { defer: true }, // not called for the first id
|
|
71
|
+
* );
|
|
72
|
+
* return null;
|
|
73
|
+
* }
|
|
74
|
+
* @see useEffect
|
|
75
|
+
* @since 1.0.0
|
|
76
|
+
*/
|
|
77
|
+
export declare function useEffect<T>(deps: () => T, fn: (value: T, previous: T | undefined) => void | Cleanup, options?: DeferredEffectOptions): void;
|
|
78
|
+
/**
|
|
79
|
+
* Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and
|
|
80
|
+
* before user effects on every flush. Used for DOM bindings; application code rarely needs it.
|
|
81
|
+
* It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In
|
|
82
|
+
* development, one created outside any owner warns `NO_OWNER_EFFECT`.
|
|
83
|
+
*
|
|
84
|
+
* @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself
|
|
85
|
+
* and may return a cleanup function.
|
|
86
|
+
* @param apply Untracked; receives the value and the previous value (`undefined` on the first
|
|
87
|
+
* run), and may return a cleanup function. Undefined: only `compute` runs.
|
|
88
|
+
* @example
|
|
89
|
+
* import { createRoot, useRenderEffect, useSignal } from "@shadow-js/core";
|
|
90
|
+
*
|
|
91
|
+
* const button = document.createElement("button");
|
|
92
|
+
* createRoot(() => {
|
|
93
|
+
* const [label] = useSignal("Save");
|
|
94
|
+
* useRenderEffect(label, (text) => {
|
|
95
|
+
* button.textContent = text; // runs now, and again when label changes
|
|
96
|
+
* });
|
|
97
|
+
* });
|
|
98
|
+
* @see useEffect
|
|
99
|
+
* @since 1.0.0
|
|
100
|
+
*/
|
|
101
|
+
export declare function useRenderEffect<T>(compute: () => T, apply?: (value: T, previous: T | undefined) => void | Cleanup): void;
|
|
102
|
+
/**
|
|
103
|
+
* Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never
|
|
104
|
+
* run it again. Its return value, if a function, is the cleanup, which runs when the owner is
|
|
105
|
+
* disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`
|
|
106
|
+
* boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.
|
|
107
|
+
*
|
|
108
|
+
* @param fn Runs once, untracked. It may return a cleanup function.
|
|
109
|
+
* @example
|
|
110
|
+
* import { onMount } from "@shadow-js/core";
|
|
111
|
+
*
|
|
112
|
+
* function SearchBox() {
|
|
113
|
+
* let input: HTMLInputElement | undefined;
|
|
114
|
+
* onMount(() => input?.focus());
|
|
115
|
+
* return <input ref={(el: HTMLInputElement) => (input = el)} />;
|
|
116
|
+
* }
|
|
117
|
+
* @see useEffect
|
|
118
|
+
* @since 1.0.0
|
|
119
|
+
*/
|
|
120
|
+
export declare function onMount(fn: () => void | Cleanup): void;
|
|
121
|
+
//#endregion
|
|
122
|
+
//# sourceMappingURL=effect.d.ts.map
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { warn } from "./internal/diagnostics.js";
|
|
2
|
+
import { untrack } from "./ownership.js";
|
|
3
|
+
import { createComputation, currentOwner } from "./extend/index.js";
|
|
4
|
+
//#region src/effect.ts
|
|
5
|
+
/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */
|
|
6
|
+
const HELD = Symbol("held");
|
|
7
|
+
/** The nearest gate above the current owner (see `Owner.gate`), or null. */
|
|
8
|
+
function nearestGate() {
|
|
9
|
+
for (let owner = currentOwner(); owner !== null; owner = owner.parent) if (owner.gate !== null) return owner.gate;
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
function createEffect(fnIn, applyIn, render, deferIn, name) {
|
|
13
|
+
if (currentOwner() === null) warn("NO_OWNER_EFFECT");
|
|
14
|
+
let fn = fnIn;
|
|
15
|
+
let apply = applyIn;
|
|
16
|
+
let defer = deferIn;
|
|
17
|
+
const gate = render ? null : nearestGate();
|
|
18
|
+
if (gate !== null) {
|
|
19
|
+
let opened = false;
|
|
20
|
+
const held = () => {
|
|
21
|
+
if (opened) return false;
|
|
22
|
+
if (gate()) return true;
|
|
23
|
+
opened = true;
|
|
24
|
+
return false;
|
|
25
|
+
};
|
|
26
|
+
if (apply === null) {
|
|
27
|
+
const inner = fn;
|
|
28
|
+
fn = (previous) => held() ? void 0 : inner(previous);
|
|
29
|
+
} else {
|
|
30
|
+
const innerFn = fn;
|
|
31
|
+
const innerApply = apply;
|
|
32
|
+
let skipFirst = defer;
|
|
33
|
+
defer = false;
|
|
34
|
+
fn = (previous) => held() ? HELD : innerFn(previous);
|
|
35
|
+
apply = (value, previous) => {
|
|
36
|
+
if (value === HELD) return void 0;
|
|
37
|
+
if (skipFirst) {
|
|
38
|
+
skipFirst = false;
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
return innerApply(value, previous === HELD ? void 0 : previous);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
createComputation({
|
|
46
|
+
kind: "effect",
|
|
47
|
+
fn,
|
|
48
|
+
render,
|
|
49
|
+
defer,
|
|
50
|
+
...apply === null ? {} : { apply },
|
|
51
|
+
...name === void 0 ? {} : { name }
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function useEffect(first, second, third) {
|
|
55
|
+
if (typeof second === "function") createEffect(first, second, false, third?.defer === true, third?.name);
|
|
56
|
+
else {
|
|
57
|
+
if (Array.isArray(second)) warn("EFFECT_DEPS_IGNORED");
|
|
58
|
+
createEffect(first, null, false, false, second?.name);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and
|
|
63
|
+
* before user effects on every flush. Used for DOM bindings; application code rarely needs it.
|
|
64
|
+
* It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In
|
|
65
|
+
* development, one created outside any owner warns `NO_OWNER_EFFECT`.
|
|
66
|
+
*
|
|
67
|
+
* @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself
|
|
68
|
+
* and may return a cleanup function.
|
|
69
|
+
* @param apply Untracked; receives the value and the previous value (`undefined` on the first
|
|
70
|
+
* run), and may return a cleanup function. Undefined: only `compute` runs.
|
|
71
|
+
* @example
|
|
72
|
+
* import { createRoot, useRenderEffect, useSignal } from "@shadow-js/core";
|
|
73
|
+
*
|
|
74
|
+
* const button = document.createElement("button");
|
|
75
|
+
* createRoot(() => {
|
|
76
|
+
* const [label] = useSignal("Save");
|
|
77
|
+
* useRenderEffect(label, (text) => {
|
|
78
|
+
* button.textContent = text; // runs now, and again when label changes
|
|
79
|
+
* });
|
|
80
|
+
* });
|
|
81
|
+
* @see useEffect
|
|
82
|
+
* @since 1.0.0
|
|
83
|
+
*/
|
|
84
|
+
function useRenderEffect(compute, apply) {
|
|
85
|
+
createEffect(compute, apply ?? null, true, false, void 0);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never
|
|
89
|
+
* run it again. Its return value, if a function, is the cleanup, which runs when the owner is
|
|
90
|
+
* disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`
|
|
91
|
+
* boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.
|
|
92
|
+
*
|
|
93
|
+
* @param fn Runs once, untracked. It may return a cleanup function.
|
|
94
|
+
* @example
|
|
95
|
+
* import { onMount } from "@shadow-js/core";
|
|
96
|
+
*
|
|
97
|
+
* function SearchBox() {
|
|
98
|
+
* let input: HTMLInputElement | undefined;
|
|
99
|
+
* onMount(() => input?.focus());
|
|
100
|
+
* return <input ref={(el: HTMLInputElement) => (input = el)} />;
|
|
101
|
+
* }
|
|
102
|
+
* @see useEffect
|
|
103
|
+
* @since 1.0.0
|
|
104
|
+
*/
|
|
105
|
+
function onMount(fn) {
|
|
106
|
+
createEffect(() => untrack(fn), null, false, false, "onMount");
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
export { onMount, useEffect, useRenderEffect };
|
|
110
|
+
|
|
111
|
+
//# 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":";;;;;AA6BA,MAAM,OAAsB,OAAO,MAAM;;AAGzC,SAAS,cAAsC;CAC7C,KAAK,IAAI,QAAQ,aAAa,GAAG,UAAU,MAAM,QAAQ,MAAM,QAC7D,IAAI,MAAM,SAAS,MAAM,OAAO,MAAM;CAExC,OAAO;AACT;AAEA,SAAS,aACP,MACA,SACA,QACA,SACA,MACM;CAGN,IAAI,aAAa,MAAM,MAAM,KAAK,iBAAiB;CACnD,IAAI,KAAK;CACT,IAAI,QAAQ;CACZ,IAAI,QAAQ;CACZ,MAAM,OAAO,SAAS,OAAO,YAAY;CACzC,IAAI,SAAS,MAAM;EAGjB,IAAI,SAAS;EACb,MAAM,aAAsB;GAC1B,IAAI,QAAQ,OAAO;GACnB,IAAI,KAAK,GAAG,OAAO;GACnB,SAAS;GACT,OAAO;EACT;EACA,IAAI,UAAU,MAAM;GAClB,MAAM,QAAQ;GACd,MAAM,aAAc,KAAK,IAAI,KAAA,IAAY,MAAM,QAAQ;EACzD,OAAO;GACL,MAAM,UAAU;GAChB,MAAM,aAAa;GAEnB,IAAI,YAAY;GAChB,QAAQ;GACR,MAAM,aAAc,KAAK,IAAI,OAAO,QAAQ,QAAQ;GACpD,SAAS,OAAO,aAAa;IAC3B,IAAK,UAAsB,MAAM,OAAO,KAAA;IACxC,IAAI,WAAW;KACb,YAAY;KACZ;IACF;IACA,OAAO,WAAW,OAAS,aAAyB,OAAO,KAAA,IAAY,QAAkB;GAC3F;EACF;CACF;CACA,kBAAkB;EAChB,MAAM;EACN;EACA;EACA;EACA,GAAI,UAAU,OAAO,CAAC,IAAI,EAAE,MAAM;EAClC,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;CACvC,CAAC;AACH;AA0DA,SAAgB,UACd,OACA,QACA,OACM;CACN,IAAI,OAAO,WAAW,YACpB,aACE,OACA,QACA,OACA,OAAO,UAAU,MACjB,OAAO,IACT;MACK;EACL,IAAI,MAAM,QAAQ,MAAM,GAAG,KAAK,qBAAqB;EACrD,aAAa,OAAO,MAAM,OAAO,OAAQ,QAAsC,IAAI;CACrF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBACd,SACA,OACM;CACN,aACE,SACC,SAAS,MACV,MACA,OACA,KAAA,CACF;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,IAAgC;CACtD,mBAAmB,QAAQ,EAAE,GAAG,MAAM,OAAO,OAAO,SAAS;AAC/D"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
//#region src/env.d.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
|
+
export declare const isServer: boolean;
|
|
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
|
+
export declare const isDev: boolean;
|
|
28
|
+
//#endregion
|
|
29
|
+
//# sourceMappingURL=env.d.ts.map
|