@shadow-js/core 1.0.1 → 1.0.2
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 +13 -0
- package/dist/dev/cache.d.ts +2 -1
- package/dist/dev/cache.js +5 -3
- package/dist/dev/cache.js.map +1 -1
- package/dist/dev/effect.js +17 -33
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/extend/index.d.ts +7 -6
- package/dist/dev/extend/index.js +7 -7
- package/dist/dev/extend/index.js.map +1 -1
- package/dist/dev/external-store.js +8 -3
- package/dist/dev/external-store.js.map +1 -1
- package/dist/dev/internal/concurrency.js +42 -20
- package/dist/dev/internal/concurrency.js.map +1 -1
- package/dist/dev/internal/diagnostics.js +0 -2
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/flags.js +1 -3
- package/dist/dev/internal/flags.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +0 -1
- package/dist/dev/internal/graph.js +20 -37
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/owner.d.ts +7 -5
- package/dist/dev/internal/owner.js +12 -22
- package/dist/dev/internal/owner.js.map +1 -1
- package/dist/dev/internal/scheduler.js +33 -71
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/list.js +0 -8
- package/dist/dev/list.js.map +1 -1
- package/dist/dev/memo.d.ts +2 -1
- package/dist/dev/memo.js +4 -4
- package/dist/dev/memo.js.map +1 -1
- package/dist/dev/ownership.d.ts +4 -2
- package/dist/dev/ownership.js +59 -3
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.js +18 -11
- package/dist/dev/props.js.map +1 -1
- package/dist/dev/reaction.d.ts +1 -1
- package/dist/dev/reaction.js +5 -1
- package/dist/dev/reaction.js.map +1 -1
- package/dist/dev/reducer.js +1 -1
- package/dist/dev/reducer.js.map +1 -1
- package/dist/dev/resource.js +21 -12
- package/dist/dev/resource.js.map +1 -1
- package/dist/dev/selector.js +1 -5
- package/dist/dev/selector.js.map +1 -1
- package/dist/dev/signal.d.ts +3 -2
- package/dist/dev/signal.js.map +1 -1
- package/dist/dev/store/nodes.js +6 -0
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/use-store.d.ts +5 -0
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/transitions.js +1 -1
- package/dist/dev/transitions.js.map +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/cache.js.map +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/extend/index.js.map +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/external-store.js.map +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/flags.js +1 -1
- package/dist/prod/internal/flags.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/owner.js +1 -1
- package/dist/prod/internal/owner.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/list.js +1 -1
- package/dist/prod/list.js.map +1 -1
- package/dist/prod/memo.js +1 -1
- package/dist/prod/memo.js.map +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js.map +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/reaction.js.map +1 -1
- package/dist/prod/reducer.js +1 -1
- package/dist/prod/reducer.js.map +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/resource.js.map +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/selector.js.map +1 -1
- package/dist/prod/signal.js.map +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/prod/transitions.js.map +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/cache.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/extend/index.js.map +1 -1
- package/dist/server/external-store.js.map +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/flags.js +1 -1
- package/dist/server/internal/flags.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/owner.js +1 -1
- package/dist/server/internal/owner.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/list.js +1 -1
- package/dist/server/list.js.map +1 -1
- package/dist/server/memo.js +1 -1
- package/dist/server/memo.js.map +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js.map +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/reaction.js.map +1 -1
- package/dist/server/reducer.js +1 -1
- package/dist/server/reducer.js.map +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/resource.js.map +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/selector.js.map +1 -1
- package/dist/server/signal.js.map +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js.map +1 -1
- package/dist/server-dev/cache.js +5 -3
- package/dist/server-dev/cache.js.map +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/extend/index.js +7 -7
- package/dist/server-dev/extend/index.js.map +1 -1
- package/dist/server-dev/external-store.js.map +1 -1
- package/dist/server-dev/internal/concurrency.js +42 -20
- package/dist/server-dev/internal/concurrency.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +0 -2
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/flags.js +1 -3
- package/dist/server-dev/internal/flags.js.map +1 -1
- package/dist/server-dev/internal/graph.js +20 -37
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/owner.js +12 -22
- package/dist/server-dev/internal/owner.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +33 -71
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/list.js +0 -8
- package/dist/server-dev/list.js.map +1 -1
- package/dist/server-dev/memo.js +4 -4
- package/dist/server-dev/memo.js.map +1 -1
- package/dist/server-dev/ownership.js +59 -3
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +18 -11
- package/dist/server-dev/props.js.map +1 -1
- package/dist/server-dev/reaction.js +5 -1
- package/dist/server-dev/reaction.js.map +1 -1
- package/dist/server-dev/reducer.js +1 -1
- package/dist/server-dev/reducer.js.map +1 -1
- package/dist/server-dev/resource.js +21 -12
- package/dist/server-dev/resource.js.map +1 -1
- package/dist/server-dev/selector.js +1 -5
- package/dist/server-dev/selector.js.map +1 -1
- package/dist/server-dev/signal.js.map +1 -1
- package/dist/server-dev/store/nodes.js +6 -0
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/transitions.js.map +1 -1
- package/package.json +2 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,updateIfNecessary as u}from"./graph.js";const d=1e3;let f=!1;function p(e,t){return e.depth-t.depth||e.seq-t.seq}function m(e){
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,updateIfNecessary as u}from"./graph.js";const d=1e3;let f=!1;function p(e,t){return e.depth-t.depth||e.seq-t.seq}function m(e){let r=e.splice(0,e.length);r.sort(p);for(let e of r)if(e.flags&=-3,!(e.flags&4)){if(e.pauses>0)e.flags=e.flags&~n|t;else try{e.state===2?l(e):u(e)}catch(t){i(t,e)}}return r.length}function h(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function g(){if(r.flushing)return;r.flushing=!0;let t=0,n=0;try{for(;o();){if(t+=1,t>1e3){a(),r.uncaught.push(new e(`INFINITE_LOOP`));break}n+=m(s.length>0?s:c)}}finally{r.flushing=!1}let i=r.uncaught;i.length>0&&(r.uncaught=[],h(i))}function _(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function v(){if(f=!1,o())try{g()}catch(e){_(e)}}function y(){r.inTransition||r.batchDepth>0||r.flushing||f||(f=!0,queueMicrotask(v))}function b(e){r.batchDepth+=1;try{return e()}finally{--r.batchDepth,r.batchDepth===0&&o()&&y()}}function x(e,t){r.batchDepth+=1;let n,i,a=!1;try{n=e===void 0?void 0:e()}catch(e){a=!0,i=e}finally{--r.batchDepth}if(t||r.batchDepth===0&&!r.flushing&&o())try{g()}catch(e){throw a?AggregateError([i,e],`SHADOW_BATCH_ERRORS`):e}if(a)throw i;return n}function S(e){return x(e,!1)}function C(e){return r.flushing?e===void 0?void 0:e():x(e,!0)}export{d as MAX_FLUSH_PASSES,S as batch,p as byCreation,g as flush,C as flushSync,b as group,_ as reportUncaught,y as schedule};
|
|
2
2
|
//# sourceMappingURL=scheduler.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","isOrdered","i","list","previous","current","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","aborted","renderQueue","userQueue","clearQueues","ShadowError","reportUncaught","runScheduled","schedule","group","fn","combine","primary","secondary","result","failure","failed","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Effects mostly arrive in creation order already; checking is O(n), sorting is not.\n * @internal\n */\nexport function isOrdered(list: readonly Computation[]): boolean {\n for (let i = 1; i < list.length; i += 1) {\n const previous = list[i - 1];\n const current = list[i];\n if (previous !== undefined && current !== undefined && byCreation(previous, current) > 0) {\n return false;\n }\n }\n return true;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n let aborted = false;\n // Render passes count too: a render effect that keeps writing its own source must abort.\n while (renderQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n aborted = true;\n break;\n }\n runs += drain(renderQueue);\n }\n if (!aborted && userQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) aborted = true;\n else runs += drain(userQueue);\n }\n if (aborted) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\nfunction combine(primary: unknown, secondary: unknown): unknown {\n return new AggregateError(\n [primary, secondary],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n if (failed) throw failure;\n return result as T;\n}\n"],"mappings":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAMA,SAAgBC,EAAU,EAAuC,CAC/D,IAAK,IAAIC,EAAI,EAAGA,EAAIC,EAAK,OAAQ,GAAK,EAAG,CACvC,IAAMC,EAAWD,EAAKD,EAAI,GACpBG,EAAUF,EAAKD,GACrB,GAAIE,IAAa,IAAA,IAAaC,IAAY,IAAA,IAAaP,EAAWM,EAAUC,CAAO,EAAI,EACrF,MAAO,EAEX,CACA,MAAO,EACT,CAGA,SAASC,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EACrCP,EAAUM,CAAK,GAAGA,EAAM,KAAKT,CAAU,EAC5C,IAAK,IAAMW,KAAUF,EAEnB,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,CAE3BX,EAAG,cAAgBA,EAAG,WAAa,GAAKA,EAAG,UAAYvB,IAC3D,EAAqB,GACrB,eAAeiC,CAAY,EAC7B,CAuBA,SAAgBE,EAAS,EAAgB,CACvC,EAAG,YAAc,EACjB,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,IAAG,WACCb,EAAG,aAAe,GAAKG,EAAW,GAAGQ,EAAS,CACpD,CACF,CAEA,SAASG,EAAQ,EAAkB,EAA6B,CAC9D,OAAW,eACT,CAACC,EAASC,CAAS,EACkC,qBACvD,CACF,CAwBA,SAAgB7B,EAAS,EAAgB,CACvC,EAAG,YAAc,EACjB,IAAI8B,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASN,EAAG,CACd,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAIM,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYG,EAAW,EACpD,GAAI,CACFJ,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CAEF,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,CAyBA,SAAgBG,EAAoB,EAAiB,CACnD,GAAIpB,EAAG,SAEL,OAAQa,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAE5C,EAAG,YAAc,EACjB,IAAII,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASN,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,CAC7C,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAI,CACFK,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CACA,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,C"}
|
|
1
|
+
{"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","clearQueues","ShadowError","renderQueue","userQueue","reportUncaught","runScheduled","schedule","group","fn","runBatched","result","failure","failed","sync","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (sync || (rt.batchDepth === 0 && !rt.flushing && hasPending())) {\n try {\n flush();\n } catch (error) {\n if (failed) {\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n }\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAGA,SAASC,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EAE1CD,EAAM,KAAKJ,CAAU,EACrB,IAAK,IAAMM,KAAUF,EAEnB,GADA,EAAO,OAAS,GACX,IAAO,MAAA,GACZ,IAAIE,EAAO,OAAS,EAElB,EAAO,MAASA,EAAO,MAAQ,CAACC,EAAmBC,OAGrD,GAAI,CAEEF,EAAO,QAAA,EAAiBG,EAAUH,CAAM,EACvCI,EAAkBJ,CAAM,CAC/B,OAASK,EAAO,CACdC,EAAYD,EAAOL,CAAM,CAC3B,CAPA,CASF,OAAOF,EAAM,MACf,CAEA,SAASS,EAAM,EAAyB,CACtC,GAAM,CAACC,GAASC,EAEhB,MADIA,EAAO,SAAW,EAASD,EACrB,eACRC,EACiE,qBACnE,CACF,CAwBA,SAAgBC,GAAc,CAC5B,GAAIC,EAAG,SAAU,OACjB,EAAG,SAAW,GACd,IAAIC,EAAS,EACTC,EAAO,EAEX,GAAI,CACF,KAAOC,EAAW,GAAG,CAInB,GADA,GAAU,EACNF,EAAA,IAA2B,CAC7BG,EAAY,EACZJ,EAAG,SAAS,KAAK,IAAIK,EAAY,eAAe,CAAC,EACjD,KACF,CACA,GAAQnB,EAAMoB,EAAY,OAAS,EAAIA,EAAcC,CA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AY,IAAA,GAAYA,EAAG,EAErCC,EAAWD,EAAI,EAAI,CAC5B,C"}
|
package/dist/prod/list.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{readSignal as t}from"./internal/graph.js";import{createRoot as n,getOwner as r,onCleanup as i,runWithOwner as a,untrack as o}from"./ownership.js";import{disposeTree as s}from"./internal/dispose.js";import{createSignalNode as c,writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.js";var d=class{
|
|
1
|
+
import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{readSignal as t}from"./internal/graph.js";import{createRoot as n,getOwner as r,onCleanup as i,runWithOwner as a,untrack as o}from"./ownership.js";import{disposeTree as s}from"./internal/dispose.js";import{createSignalNode as c,writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.js";var d=class{value=void 0;dispose=f;itemNode=null;indexNode=null;constructor(e,t,n,r){this.key=e,this.first=t,this.item=n,this.index=r}readItem(){return this.itemNode??=c(this.item,Object.is),t(this.itemNode)}readIndex(){return this.indexNode??=c(this.index,Object.is),t(this.indexNode)}setItem(e){this.item=e,this.itemNode!==null&&l(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&l(this.indexNode,e,{allowInMemo:!0})}};function f(){}function p(e,t,n){let r=n?.key;return h(e,r===void 0?{keyOf:e=>e,distinct:!1}:{keyOf:e=>r(e),distinct:!0},(e,n,i)=>t(r===void 0?e:n,i),n?.fallback)}function m(e,t,n){return h(e,{keyOf:(e,t)=>t,distinct:!1},(e,n,r)=>t(n,o(r)),n?.fallback)}function h(t,n,a,c){let l=new e(r());i(()=>{s(l)});let d=[],f;return u(()=>{let e=g(t()),r=Array.isArray(e)?Array.prototype.slice.call(e):e,i=o(()=>_(r,n)),s=b(d,i),u=[],p=[],m;try{i.forEach((e,t)=>{let n=s[t]??-1,r=n===-1?void 0:d[n];if(r!==void 0){p.push({row:r,item:e.item,position:t,fresh:!1});return}let i=x(l,e.key,e.first,e.item,t,a);u.push(i),p.push({row:i,item:e.item,position:t,fresh:!0})}),i.length===0&&c!==void 0&&(m=f??S(l,c))}catch(e){let t=[];for(let e of u)C(e.dispose,t);throw m!==void 0&&m!==f&&C(m.dispose,t),w(e,t)}let h=[],v=d,y=f;d=p.map(e=>e.row),f=m;let E=new Uint8Array(v.length);for(let e of s)e!==-1&&(E[e]=1);v.forEach((e,t)=>{E[t]!==1&&C(e.dispose,h)}),y!==void 0&&y!==m&&C(y.dispose,h);for(let e of p){if(e.fresh)continue;let t=e.row;t.index!==e.position&&t.setIndex(e.position),Object.is(t.item,e.item)||t.setItem(e.item)}return T(h),m===void 0?d.map(e=>e.value):[m.value]},{lazy:!0,allowWrites:!0})}function g(e){return e==null||e===!1?[]:e}function _(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let[i,a]of e.entries()){let e=t.keyOf(a,i),o=!0;t.distinct&&(r.has(e)?o=!1:r.add(e)),n.push({item:a,key:e,first:o})}return n}function v(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function y(e,t){return e!==void 0&&t!==void 0&&e.first&&t.first&&v(e.key,t.key)}function b(e,t){let n=e.length,r=t.length,i=new Int32Array(r).fill(-1),a=0;for(;a<n&&a<r&&y(e[a],t[a]);)i[a]=a,a+=1;let o=n-1,s=r-1;for(;o>=a&&s>=a&&y(e[o],t[s]);)i[s]=o,--o,--s;if(a>o||a>s)return i;let c=/* @__PURE__ */ new Map,l=new Int32Array(n).fill(-1);for(let t=o;t>=a;--t){let n=e[t];n!==void 0&&n.first&&(l[t]=c.get(n.key)??-1,c.set(n.key,t))}for(let e=a;e<=s;e+=1){let n=t[e];if(n===void 0||!n.first)continue;let r=c.get(n.key);r!==void 0&&r!==-1&&(i[e]=r,c.set(n.key,l[r]??-1))}return i}function x(e,t,r,i,s,c){let l=new d(t,r,i,s),u=()=>l.readItem(),f=()=>l.readIndex();return a(e,()=>n(e=>{l.dispose=e,l.value=o(()=>c(i,u,f))})),l}function S(e,t){return a(e,()=>n(e=>({value:o(t),dispose:e})))}function C(e,t){try{e()}catch(e){t.push(e)}}function w(e,t){return t.length===0?e:AggregateError([e,...t],`SHADOW_MAP_ERRORS`)}function T(e){if(e.length!==0)throw e.length===1?e[0]:AggregateError(e,`SHADOW_LIST_DISPOSE_ERRORS`)}export{m as indexArray,p as mapArray};
|
|
2
2
|
//# sourceMappingURL=list.js.map
|
package/dist/prod/list.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.js","names":["Row","noop","key","first","item","index","createSignalNode","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n item: T;\n /** Index last written to the row. */\n index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":"A,qYAuBA,IAAMA,EAAN,KAAgB,CAEd,IAEA,MAEA,KAEA,MACA,MAAW,IAAA,GACX,QAAsBC,EAEtB,SAAyC,KAEzC,UAA+C,KAE/C,YAAY,EAAc,EAAgB,EAAS,EAAe,CAChE,KAAK,IAAMC,EACX,KAAK,MAAQC,EACb,KAAK,KAAOC,EACZ,KAAK,MAAQC,CACf,CAEA,UAAc,CAEZ,MADA,MAAK,WAAaC,EAAiB,KAAK,KAAM,OAAO,EAAE,EAChDC,EAAW,KAAK,QAAQ,CACjC,CAEA,WAAoB,CAElB,MADA,MAAK,YAAcD,EAAiB,KAAK,MAAO,OAAO,EAAE,EAClDC,EAAW,KAAK,SAAS,CAClC,CAGA,QAAQ,EAAe,CACrB,KAAK,KAAOC,EACR,KAAK,WAAa,MAAMC,EAAY,KAAK,SAAUD,EAAM,CAAE,YAAa,EAAK,CAAC,CACpF,CAEA,SAAS,EAAoB,CAC3B,KAAK,MAAQA,EACT,KAAK,YAAc,MAAMC,EAAY,KAAK,UAAWD,EAAM,CAAE,YAAa,EAAK,CAAC,CACtF,CACF,EAGA,SAASP,GAAa,CAEtB,CA6FA,SAAgBS,EACd,EACA,EACA,EACe,CACf,IAAMC,EAAQC,GAAS,IACvB,OAAOC,EACLC,EACAH,IAAU,IAAA,GACN,CAAE,MAAQ,GAAYP,EAAM,SAAU,EAAM,EAC5C,CAAE,MAAQ,GAAYO,EAAMP,CAAI,EAAG,SAAU,EAAK,GACrD,EAAM,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":"list.js","names":["Row","noop","key","first","item","index","createSignalNode","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n declare readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n declare readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n declare item: T;\n /** Index last written to the row. */\n declare index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":"A,qYAuBA,IAAMA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S,EAAE,EACxC,CACA,OAAOrC,CACT,CAMA,SAASS,EACP,EACA,EACA,EACA,EACA,EACA,EACW,CACX,IAAMD,EAAM,IAAI3C,EAAUE,EAAKC,EAAOC,EAAMC,CAAK,EAC3CW,MAAoB2B,EAAI,SAAS,EACjC1B,MAA0B0B,EAAI,UAAU,EAO9C,OANA8B,EAAapD,MACXqD,EAAY,GAAY,CACtB,EAAI,QAAUC,EACd,EAAI,MAAQvD,MAAcyB,EAAMzC,EAAMY,EAAUC,CAAS,CAAC,CAC5D,CAAC,CACH,EACO0B,CACT,CAGA,SAASI,EAAgB,EAAe,EAAgC,CACtE,OAAO0B,EAAapD,MAClBqD,EAAY,IAAa,CAAE,MAAOtD,EAAQ0B,CAAQ,EAAG,SAAQ,EAAE,CACjE,CACF,CAGA,SAASI,EAAkB,EAAqB,EAA2B,CACzE,GAAI,CACFyB,EAAQ,CACV,OAAS3B,EAAO,CACdC,EAAS,KAAKD,CAAK,CACrB,CACF,CAEA,SAASG,EAAgB,EAAkB,EAAuC,CAEhF,OADIF,EAAS,SAAW,EAAU2B,EACvB,eACT,CAACA,EAAS,GAAG3B,CAAQ,EAC0C,mBACjE,CACF,CAGA,SAASM,EAAc,EAAoC,CACzD,GAAIN,EAAS,SAAW,EAExB,MADIA,EAAS,SAAW,EAASA,EAAS,GAChC,eACRA,EAGI,4BACN,CACF,C"}
|
package/dist/prod/memo.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createComputation as e,readComputation as t}from"./extend/index.js";function n(n,r){let i=e({kind:`memo`,fn:n,equals:r?.equals
|
|
1
|
+
import{createComputation as e,readComputation as t}from"./extend/index.js";function n(n,r){let i=e({kind:`memo`,fn:n,equals:r?.equals,lazy:r?.lazy,allowWrites:r?.allowWrites,name:r?.name});return()=>t(i)}export{n as useMemo};
|
|
2
2
|
//# sourceMappingURL=memo.js.map
|
package/dist/prod/memo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memo.js","names":["useMemo","node","createComputation","options","readComputation"],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals:
|
|
1
|
+
{"version":3,"file":"memo.js","names":["useMemo","node","createComputation","options","readComputation"],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates. It runs untracked: a signal it reads is not a dependency of\n * the memo or of the reader that pulled it.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: options?.equals as Equals<unknown> | undefined,\n lazy: options?.lazy,\n allowWrites: options?.allowWrites,\n name: options?.name,\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":"A,2EA2DA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAOC,EAAkB,CAC7B,KAAM,OACF,KACJ,OAAQC,GAAS,OACjB,KAAMA,GAAS,KACf,YAAaA,GAAS,YACtB,KAAMA,GAAS,IACjB,CAAC,EACD,UAAaC,EAAmBH,CAAI,CACtC,C"}
|
package/dist/prod/ownership.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{return o({owner:c,listener:null},()=>e(()=>i(c)))}catch(e){
|
|
1
|
+
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{return o({owner:c,listener:null},()=>e(()=>i(c)))}catch(e){try{i(c)}catch(t){throw AggregateError([e,t],`SHADOW_ROOT_ERRORS`)}throw e}}function l(){return a()}function u(e,t){let n=e;return n?.disposed&&(n=null),o({owner:n,listener:null},t)}function d(e){let t=a();t!==null&&n(t,e)}function f(e){let t=a();t!==null&&(t.errorHandlers===null?t.errorHandlers=[e]:t.errorHandlers.push(e))}function p(e,n){let i=new t(a());i.errorHandlers=[n];try{return u(i,e)}catch(e){r(e,i);return}}function m(){let t=a();if(t===null)throw new e(`NO_OWNER_ID`);for(let e=t;e!==null;e=e.parent){if(e.idPrefix===void 0)continue;let t=e.idCount;return e.idCount+=1,`s${e.idPrefix}${t}`}let n=[];for(let e=t;e!==null;e=e.parent)n.push(e.index);n.reverse();let r=t.idCount;return t.idCount+=1,`s${n.join(`-`)}_${r}`}export{p as catchError,c as createRoot,l as getOwner,d as onCleanup,f as onError,u as runWithOwner,s as untrack,m as useId};
|
|
2
2
|
//# sourceMappingURL=ownership.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownership.js","names":["disposeOwner","untrack","runInScope","fn","createRoot","detached","options","current","currentOwner","root","Owner","disposeTree","error","getOwner","runWithOwner","target","owner","onCleanup","addCleanup","onError","handler","catchError","scope","handleError","useId","ShadowError","host","hosted","path","node","sequence"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n disposeOwner(root);\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":"A,0PAmCA,SAAgBC,EAAW,EAAgB,CACzC,OAAOC,EAAW,CAAE,SAAU,IAAK,EAAGC,CAAE,CAC1C,CAyCA,SAAgBC,EAAc,EAAgC,EAA0B,CACtF,IAAMC,EAAWC,GAAS,WAAa,GACjCC,EAAUC,EAAa,EACvBC,EAAO,IAAIC,EAAML,EAAW,KAAOE,CAAO,EAC5CF,IAAU,EAAK,QAAUE,IAAY,KAAO,KAAOA,EAAQ,SAC/D,GAAI,CACF,OAAOL,EAAW,CAAE,MAAOO,EAAM,SAAU,IAAK,MAASN,MAASH,EAAaS,CAAI,CAAC,CAAC,CACvF,OAASG,EAAO,CAEd,MADAD,EAAaF,CAAI,EACXG,CACR,CACF,CAqBA,SAAgBC,GAAyB,CACvC,OAAOL,EAAa,CACtB,CA4BA,SAAgBM,EAAgB,EAAqB,EAAgB,CACnE,IAAIC,EAASC,EAKb,OAJID,GAAQ,WAEV,EAAS,MAEJb,EAAW,CAAE,MAAOa,EAAQ,SAAU,IAAK,EAAGZ,CAAE,CACzD,CAoBA,SAAgBc,EAAU,EAAmB,CAC3C,IAAMD,EAAQR,EAAa,EACvBQ,IAAU,MAIdE,EAAWF,EAAOb,CAAE,CACtB,CAsBA,SAAgBgB,EAAQ,EAA6B,CACnD,IAAMH,EAAQR,EAAa,EACvBQ,IAAU,OAIVA,EAAM,gBAAkB,KAAM,EAAM,cAAgB,CAACI,CAAO,EAC3DJ,EAAM,cAAc,KAAKI,CAAO,EACvC,CA4BA,SAAgBC,EAAc,EAAa,EAAsC,CAC/E,IAAMC,EAAQ,IAAIZ,EAAMF,EAAa,CAAC,EACtC,EAAM,cAAgB,CAACY,CAAO,EAC9B,GAAI,CACF,OAAON,EAAaQ,EAAOnB,CAAE,CAC/B,OAASS,EAAO,CACPW,EAAiBX,EAAOU,CAAK,EAApC,MACF,CACF,CAyBA,SAAgBE,GAAgB,CAC9B,IAAMR,EAAQR,EAAa,EAC3B,GAAIQ,IAAU,KAAM,MAAM,IAAIS,EAAY,aAAa,EAIvD,IAAK,IAAIC,EAAqBV,EAAOU,IAAS,KAAM,EAAOA,EAAK,OAAQ,CACtE,GAAIA,EAAK,WAAa,IAAA,GAAW,SACjC,IAAMC,EAASD,EAAK,QAEpB,MADA,GAAK,SAAW,EACT,IAAIA,EAAK,WAAWC,GAC7B,CACA,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAqBb,EAAOa,IAAS,KAAM,EAAOA,EAAK,OAAQD,EAAK,KAAKC,EAAK,KAAK,EAC5FD,EAAK,QAAQ,EACb,IAAME,EAAWd,EAAM,QAEvB,MADA,GAAM,SAAW,EACV,IAAIY,EAAK,KAAK,GAAG,EAAE,GAAGE,GAC/B,C"}
|
|
1
|
+
{"version":3,"file":"ownership.js","names":["disposeOwner","untrack","runInScope","fn","createRoot","detached","options","current","currentOwner","root","Owner","disposeTree","error","cleanupError","getOwner","runWithOwner","target","owner","onCleanup","addCleanup","onError","handler","catchError","scope","handleError","useId","ShadowError","host","hosted","path","node","sequence"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */\nconst REGISTRY_KEY = \"shadow-js.core.instances\";\n\n/**\n * The most copies the registry lists. Real programs have one, a misconfigured one two or three; the\n * limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.\n */\nconst MAX_LISTED_COPIES = 8;\n\n/**\n * The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:\n * the server build and the client build are different files by design, and tests that render on the server\n * and hydrate in one process load one of each, so only copies of the same build count as duplicates.\n */\nconst COPY: { readonly server: boolean } = { server: __SERVER__ };\n\n/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */\nfunction copyRegistry(): Map<{ readonly server: boolean }, number> | undefined {\n const found = (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)];\n return found instanceof Map ? found : undefined;\n}\n\n/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */\nfunction releaseRoot(): void {\n const registry = copyRegistry();\n const live = registry?.get(COPY);\n if (registry === undefined || live === undefined) return;\n if (live > 1) registry.set(COPY, live - 1);\n else registry.delete(COPY);\n}\n\n/**\n * Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the\n * live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has\n * live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies\n * that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only\n * behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one\n * shared function, so a root costs no closure: rows of a list make a root each.\n */\nfunction listRoot(root: Owner): void {\n let registry = copyRegistry();\n if (registry === undefined) {\n registry = new Map();\n (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)] = registry;\n }\n const listed = registry.has(COPY);\n for (const copy of registry.keys()) {\n if (copy !== COPY && copy.server === COPY.server) {\n warn(\"DUPLICATE_CORE\");\n break;\n }\n }\n // A copy past the limit is not listed; the warning above has been given by then.\n if (!listed && registry.size >= MAX_LISTED_COPIES) return;\n registry.set(COPY, (registry.get(COPY) ?? 0) + 1);\n addCleanup(root, releaseRoot);\n}\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects. Development builds also use the root to find a second copy of core: a root\n * created while a root of another copy is alive warns `DUPLICATE_CORE` once.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed. When a cleanup of the root throws as well, both errors are thrown together as an\n * `AggregateError` (the body's first), so the body's error is never replaced.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n if (__DEV__) listRoot(root);\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n try {\n disposeOwner(root);\n } catch (cleanupError) {\n // The body's error says what went wrong; a cleanup error must not replace it.\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"The root body threw and so did its disposal.\" : \"SHADOW_ROOT_ERRORS\",\n );\n }\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":"A,0PA6FA,SAAgBC,EAAW,EAAgB,CACzC,OAAOC,EAAW,CAAE,SAAU,IAAK,EAAGC,CAAE,CAC1C,CA2CA,SAAgBC,EAAc,EAAgC,EAA0B,CACtF,IAAMC,EAAWC,GAAS,WAAa,GACjCC,EAAUC,EAAa,EACvBC,EAAO,IAAIC,EAAML,EAAW,KAAOE,CAAO,EAC5CF,IAAU,EAAK,QAAUE,IAAY,KAAO,KAAOA,EAAQ,SAE/D,GAAI,CACF,OAAOL,EAAW,CAAE,MAAOO,EAAM,SAAU,IAAK,MAASN,MAASH,EAAaS,CAAI,CAAC,CAAC,CACvF,OAASG,EAAO,CACd,GAAI,CACFD,EAAaF,CAAI,CACnB,OAASI,EAAc,CAErB,MAAU,eACR,CAACD,EAAOC,CAAY,EACuC,oBAC7D,CACF,CACA,MAAMD,CACR,CACF,CAqBA,SAAgBE,GAAyB,CACvC,OAAON,EAAa,CACtB,CA4BA,SAAgBO,EAAgB,EAAqB,EAAgB,CACnE,IAAIC,EAASC,EAKb,OAJID,GAAQ,WAEV,EAAS,MAEJd,EAAW,CAAE,MAAOc,EAAQ,SAAU,IAAK,EAAGb,CAAE,CACzD,CAoBA,SAAgBe,EAAU,EAAmB,CAC3C,IAAMD,EAAQT,EAAa,EACvBS,IAAU,MAIdE,EAAWF,EAAOd,CAAE,CACtB,CAsBA,SAAgBiB,EAAQ,EAA6B,CACnD,IAAMH,EAAQT,EAAa,EACvBS,IAAU,OAIVA,EAAM,gBAAkB,KAAM,EAAM,cAAgB,CAACI,CAAO,EAC3DJ,EAAM,cAAc,KAAKI,CAAO,EACvC,CA4BA,SAAgBC,EAAc,EAAa,EAAsC,CAC/E,IAAMC,EAAQ,IAAIb,EAAMF,EAAa,CAAC,EACtC,EAAM,cAAgB,CAACa,CAAO,EAC9B,GAAI,CACF,OAAON,EAAaQ,EAAOpB,CAAE,CAC/B,OAASS,EAAO,CACPY,EAAiBZ,EAAOW,CAAK,EAApC,MACF,CACF,CAyBA,SAAgBE,GAAgB,CAC9B,IAAMR,EAAQT,EAAa,EAC3B,GAAIS,IAAU,KAAM,MAAM,IAAIS,EAAY,aAAa,EAIvD,IAAK,IAAIC,EAAqBV,EAAOU,IAAS,KAAM,EAAOA,EAAK,OAAQ,CACtE,GAAIA,EAAK,WAAa,IAAA,GAAW,SACjC,IAAMC,EAASD,EAAK,QAEpB,MADA,GAAK,SAAW,EACT,IAAIA,EAAK,WAAWC,GAC7B,CACA,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAqBb,EAAOa,IAAS,KAAM,EAAOA,EAAK,OAAQD,EAAK,KAAKC,EAAK,KAAK,EAC5FD,EAAK,QAAQ,EACb,IAAME,EAAWd,EAAM,QAEvB,MADA,GAAM,SAAW,EACV,IAAIY,EAAK,KAAK,GAAG,EAAE,GAAGE,GAC/B,C"}
|
package/dist/prod/props.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"props.js","names":["UNSAFE_KEYS","DYNAMIC_PROPS","isEmptySource","value","ownEnumerableKeys","source","key","defineGetter","target","read","resolveSource","resolveAll","resolved","sources","object","readMerged","index","objects","mergedKeys","seen","keys","readDepth","readStates","stateOf","known","view","state","load","duringRead","run","liveView","mergeProps","inputs","dynamic","merged","splitProps","listed","groups","group","picked","props","restKeys","readRest","rest","flattenChildren","leaves","frames","open","fn","layer","advanced","top","children","memo","useMemo","untrack","leaf"],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\n/**\n * How deep the live reads are running, and the state each live view computed during the outermost\n * read. A view's traps read the views beneath it, and those read the views beneath them: without a\n * cache every trap recomputes each level below, and a few nested components (a chain of `{...props}`\n * forwards) take exponential time. Within one outermost read a view's state is computed once, so a\n * read costs time linear in the number of views. The cache is dropped when that read returns, so each\n * read still sees the current values.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n : \"SHADOW_CHILDREN_ONLY\",\n );\n }\n return leaves[0];\n },\n });\n}\n"],"mappings":"A,6EAOA,MAAMA,kBAAwC,IAAI,IAAiB,CACjE,YACA,cACA,WACF,CAAC,EAOKC,kBAAgB,IAAI,QAmF1B,SAASC,EAAc,EAAmD,CACxE,OAAOC,GAAU,MAA+BA,IAAU,EAC5D,CAGA,SAASC,EAAkB,EAAuB,CAChD,OAAO,QAAQ,QAAQC,CAAM,CAAC,CAAC,OAC5B,GAAQ,CAACL,EAAY,IAAIM,CAAG,GAAK,OAAO,UAA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CAAC,KAAK,EAAM,IAAUE,MAAcP,EAAGQ,EAAMxC,CAAK,CAAC,CAAC,EAC5D,QAAU,GAAqD,CAC7DqC,EAAK,CAAC,CAAC,SAAS,EAAM,IAAU,CAC9BE,MAAcP,EAAGQ,EAAMxC,CAAK,CAAC,CAC/B,CAAC,CACH,EACA,SAAqB,CACnB,IAAM6B,EAASQ,EAAK,EACpB,GAAIR,EAAO,SAAW,EACpB,MAAU,UAGJ,sBACN,EAEF,OAAOA,EAAO,EAChB,CACF,CAAC,CACH,C"}
|
|
1
|
+
{"version":3,"file":"props.js","names":["UNSAFE_KEYS","DYNAMIC_PROPS","isEmptySource","value","ownEnumerableKeys","source","key","defineGetter","target","read","resolveSource","resolveAll","resolved","sources","object","readMerged","index","objects","mergedKeys","seen","keys","readDepth","readStates","stateOf","known","view","state","load","duringRead","run","liveView","mergeProps","inputs","dynamic","merged","splitProps","listed","groups","group","picked","props","restKeys","readRest","rest","flattenChildren","leaves","frames","open","fn","layer","advanced","top","children","memo","useMemo","untrack","leaf"],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * The cache of the live views: `readDepth` counts how deep the live reads are running and\n * `readStates` holds the state each live view computed during the outermost read. A view's traps\n * read the views beneath them, and those read the views beneath them: without a cache every trap\n * recomputes each level below, and a few nested components (a chain of `{...props}` forwards) take\n * exponential time. Within one outermost read a view's state is computed once, so a read costs time\n * linear in the number of views. The cache is dropped when that read returns, so each read still\n * sees the current values.\n *\n * These two are module-level scratch state (R-CODE-4, the scratch-array class), and not registers\n * of `internal/state.ts`: this file may import only the public extension API (EXT-01), which has no\n * place for them, and a new public export for two private counters is not worth it. They are safe\n * because every write is undone in `finally` (`duringRead`), so a getter that throws leaves depth 0\n * and an empty map, and because the map holds a view only while one outermost read is running.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n : \"SHADOW_CHILDREN_ONLY\",\n );\n }\n return leaves[0];\n },\n });\n}\n"],"mappings":"A,6EAOA,MAAMA,kBAAwC,IAAI,IAAiB,CACjE,YACA,cACA,WACF,CAAC,EAOKC,kBAAgB,IAAI,QAmF1B,SAASC,EAAc,EAAmD,CACxE,OAAOC,GAAU,MAA+BA,IAAU,EAC5D,CAGA,SAASC,EAAkB,EAAuB,CAChD,OAAO,QAAQ,QAAQC,CAAM,CAAC,CAAC,OAC5B,GAAQ,CAACL,EAAY,IAAIM,CAAG,GAAK,OAAO,UAAU,qBAAqB,KAAKD,EAAQC,CAAG,CAC1F,CACF,CAGA,SAASC,EAAa,EAAgB,EAAkB,EAA2B,CACjF,OAAO,eAAeC,EAAQF,EAAK,CAAE,WAAY,GAAM,aAAc,GAAM,IAAKG,CAAK,CAAC,CACxF,CAGA,SAASC,EAAc,EAAoC,CACzD,IAAMP,EAAiB,OAAOE,GAAW,WAAcA,EAAyB,EAAIA,EACpF,GAA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EACpB,MAAU,UAGJ,sBACN,EAEF,OAAOA,EAAO,EAChB,CACF,CAAC,CACH,C"}
|
package/dist/prod/reaction.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{untrack as e}from"./ownership.js";import{disposeTree as t}from"./internal/dispose.js";import{createComputation as n,createOwner as r,currentOwner as i,runInScope as a}from"./extend/index.js";function o(o){let s=i(),c=null;return i=>{c!==null&&t(c);let l=r(s);c=l;let u=!0;a({owner:l,listener:null},()=>{n({kind:`effect`,render:!0,owner:l,fn:()=>{u?(u=!1,i()):e(o)}})})}}export{o as useReaction};
|
|
1
|
+
import{untrack as e}from"./ownership.js";import{disposeTree as t}from"./internal/dispose.js";import{createComputation as n,createOwner as r,currentOwner as i,runInScope as a}from"./extend/index.js";function o(o){let s=i(),c=null;return i=>{if(c!==null&&t(c),s?.disposed===!0){c=null;return}let l=r(s);c=l;let u=!0;a({owner:l,listener:null},()=>{n({kind:`effect`,render:!0,owner:l,fn:()=>{u?(u=!1,i()):e(o)}})})}}export{o as useReaction};
|
|
2
2
|
//# sourceMappingURL=reaction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reaction.js","names":["useReaction","owner","currentOwner","scope","disposeTree","next","createOwner","tracking","runInScope","createComputation","track","untrack","onInvalidate"],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":"A,sMAmCA,SAAgBA,EAAY,EAAuD,CACjF,IAAMC,EAAQC,EAAa,EACvBC,EAAsB,KAC1B,MAAQ,IAA4B,
|
|
1
|
+
{"version":3,"file":"reaction.js","names":["useReaction","owner","currentOwner","scope","disposeTree","next","createOwner","tracking","runInScope","createComputation","track","untrack","onInvalidate"],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed; calling `track` after that does nothing.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n // The owner is gone: a scope made now would hang on it and never be disposed.\n if (owner?.disposed === true) {\n scope = null;\n return;\n }\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":"A,sMAmCA,SAAgBA,EAAY,EAAuD,CACjF,IAAMC,EAAQC,EAAa,EACvBC,EAAsB,KAC1B,MAAQ,IAA4B,CAGlC,GAFIA,IAAU,MAAMC,EAAaD,CAAK,EAElCF,GAAO,WAAa,GAAM,CAC5B,EAAQ,KACR,MACF,CACA,IAAMI,EAAOC,EAAYL,CAAK,EAC9B,EAAQI,EACR,IAAIE,EAAW,GACfC,EAAW,CAAE,MAAOH,EAAM,SAAU,IAAK,MAAS,CAChDI,EAAkB,CAChB,KAAM,SACN,OAAQ,GACR,MAAOJ,EACP,OAAU,CACJE,GACF,EAAW,GACXG,EAAM,GAGRC,EAAQC,CAAY,CAEtB,CACF,CAAC,CACH,CAAC,CACH,CACF,C"}
|
package/dist/prod/reducer.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useSignal as e}from"./signal.js";function t(t,n,r){let[i,a]=e(n,{equals:r?.equals??Object.is
|
|
1
|
+
import{useSignal as e}from"./signal.js";function t(t,n,r){let[i,a]=e(n,{equals:r?.equals??Object.is,name:r?.name});return[i,e=>{a(n=>t(n,e))}]}export{t as useReducer};
|
|
2
2
|
//# sourceMappingURL=reducer.js.map
|
package/dist/prod/reducer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reducer.js","names":["useReducer","state","setState","useSignal","initialState","options","reducer","previous","action"],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n
|
|
1
|
+
{"version":3,"file":"reducer.js","names":["useReducer","state","setState","useSignal","initialState","options","reducer","previous","action"],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n name: options?.name,\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":"A,wCAwCA,SAAgBA,EACd,EACA,EACA,EACoC,CACpC,GAAM,CAACC,EAAOC,GAAYC,EAAaC,EAAc,CACnD,OAASC,GAAS,QAAU,OAAO,GACnC,KAAMA,GAAS,IACjB,CAAC,EAID,MAAO,CAACJ,EAHU,GAAoB,CACpCC,EAAU,GAAaI,EAAQC,EAAUC,CAAM,CAAC,CAClD,CACuB,CACzB,C"}
|
package/dist/prod/resource.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readSignal as e}from"./internal/graph.js";import{batch as t}from"./internal/scheduler.js";import{onCleanup as n,untrack as r}from"./ownership.js";import{useRenderEffect as i}from"./effect.js";import{useContext as a}from"./context.js";import{ResourceCacheContext as o,SuspenseContext as s}from"./suspense.js";import{holdReader as c,inTransition as l}from"./internal/concurrency.js";import{createSignalNode as u,currentListener as d,writeSignal as f}from"./extend/index.js";function p(t,n){let r=u(t,n?Object.is:!1);return[()=>e(r),e=>{f(r,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,u,f){let h=typeof u==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?u:(e,t)=>_(t),y=(h?f:u)??{},b=`initialValue`in y,[x,S]=p(y.initialValue,!1),[C,w]=p(b?`ready`:`unresolved`,!0),T=e=>{w(e)},[E,D]=p(void 0,!1),O=a(o),k=O===null?void 0:O.key(y.key),A=O!==null&&k!==void 0?O.read(k):void 0,j=!1,M=0,N,P=!1,F=b,I=/* @__PURE__ */ new Set,L=()=>{if(I.size===0)return;let e=[...I];I.clear();for(let t of e)t.decrement()},R=(e,n)=>P||e!==M
|
|
1
|
+
import{readSignal as e}from"./internal/graph.js";import{batch as t}from"./internal/scheduler.js";import{onCleanup as n,untrack as r}from"./ownership.js";import{useRenderEffect as i}from"./effect.js";import{useContext as a}from"./context.js";import{ResourceCacheContext as o,SuspenseContext as s}from"./suspense.js";import{holdReader as c,inTransition as l}from"./internal/concurrency.js";import{createSignalNode as u,currentListener as d,writeSignal as f}from"./extend/index.js";function p(t,n){let r=u(t,n?Object.is:!1);return[()=>e(r),e=>{f(r,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,u,f){let h=typeof u==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?u:(e,t)=>_(t),y=(h?f:u)??{},b=`initialValue`in y,[x,S]=p(y.initialValue,!1),[C,w]=p(b?`ready`:`unresolved`,!0),T=e=>{w(e)},[E,D]=p(void 0,!1),O=a(o),k=O===null?void 0:O.key(y.key),A=O!==null&&k!==void 0?O.read(k):void 0,j=!1,M=0,N,P=!1,F=b,I=/* @__PURE__ */ new Set,L=()=>{if(I.size===0)return;let e=[...I];I.clear();for(let t of e)t.decrement()},R=(e,n)=>{if(P||e!==M)return!1;try{t(n)}finally{L()}return!0},z=(e,n)=>{if(A!==void 0&&!j&&!n)return j=!0,F=!0,t(()=>{S(A.value),T(`ready`)}),Promise.resolve(A.value);N?.abort();let i=new AbortController;N=i,M+=1;let a=M;t(()=>{T(F?`refreshing`:`pending`),D(void 0)});let o;try{let t=n||O===null||k===void 0?void 0:O.pending?.(k);o=t===void 0?r(()=>v(e,{signal:i.signal,refetching:n,value:r(x)})):t}catch(e){return R(a,()=>{D(e),T(`errored`)}),Promise.resolve(void 0)}if(m(o))return O!==null&&k!==void 0&&O.track(k,Promise.resolve(o),{deferStream:y.deferStream}),Promise.resolve(o).then(e=>R(a,()=>{F=!0,S(e),T(`ready`)})?e:void 0,e=>{R(a,()=>{D(e),T(`errored`)})});let s=o,c=R(a,()=>{F=!0,S(s),T(`ready`)});return Promise.resolve(c?s:void 0)},B=e=>{e===!1||e==null?(N?.abort(),M+=1,L(),T(F?`ready`:`unresolved`)):z(e,F)},V=(()=>{let e=C();if(e===`errored`)throw E();if(e===`pending`){let e=a(s);e!==null&&!I.has(e)&&(I.add(e),e.increment()),e!==null&&d()!==null&&l()&&c(e)}return x()});return Object.defineProperties(V,{state:{get:C},loading:{get:()=>C()===`pending`||C()===`refreshing`},error:{get:E},latest:{get:x},refetch:{value:()=>{if(P)return Promise.resolve(void 0);let e=r(g);return e===!1||e==null?Promise.resolve(void 0):z(e,F)}},mutate:{value:e=>{let n,i=!1;try{t(()=>{n=typeof e==`function`?r(()=>e(x())):e,i=!0,N?.abort(),M+=1,F=!0,S(n),D(void 0),T(`ready`)})}finally{i&&L()}return n}}}),i(g,B),n(()=>{P=!0,N?.abort(),L()}),V}export{h as useResource};
|
|
2
2
|
//# sourceMappingURL=resource.js.map
|