@wcstack/signals 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +437 -0
- package/README.md +439 -0
- package/dist/core-DCHZTbGv.esm.min.js +2 -0
- package/dist/core-DCHZTbGv.esm.min.js.map +1 -0
- package/dist/core-DRLhLwcb.esm.js +0 -0
- package/dist/core-DRLhLwcb.esm.js.map +1 -0
- package/dist/dom.d.ts +311 -0
- package/dist/dom.esm.js +743 -0
- package/dist/dom.esm.js.map +1 -0
- package/dist/dom.esm.min.js +2 -0
- package/dist/dom.esm.min.js.map +1 -0
- package/dist/index.d.ts +248 -0
- package/dist/index.esm.js +2 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/index.esm.min.js +2 -0
- package/dist/index.esm.min.js.map +1 -0
- package/package.json +74 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dom.esm.js","sources":["../src/dom.ts"],"sourcesContent":["// Fine-grained hyperscript (v1 design notes). The \"step before JSX\" (docs §4-1).\n//\n// `h(tag, props, ...children)` is the classic JSX factory shape, but it does NOT\n// build a virtual DOM and re-render. It creates a REAL DOM node once; any prop or\n// child given as a function (thunk) or signal is wired to a targeted `effect`, so\n// only that one binding updates when its signals change (Solid-style). This is\n// what keeps the package lightweight: no reconciler is shipped.\n//\n// JSX is intentionally NOT shipped. A consumer who wants it sets, in their own\n// tsconfig, `jsxFactory: \"h\"` + `jsxFragmentFactory: \"Fragment\"` (classic runtime)\n// — opting into a build step is their choice; the buildless path is calling `h`\n// directly. See docs/signals-state-design.md §4-1.\n//\n// OWNERSHIP: effects created here are owned by the enclosing reactive scope.\n// A reactive child's effect owns the prop/child effects of the subtree it builds,\n// so rebuilding that subtree disposes the previous one's effects (no leak). Mount\n// an app under `createRoot` so the whole tree can be torn down on unmount; a\n// dynamic child establishes its own scope automatically (it IS an effect).\n\nimport { signal, effect, onCleanup, createRoot, hasOwner, ReadSignal, WriteSignal } from \"./reactive.js\";\nimport { isDev, warnDev } from \"./dev.js\";\n\n// `@wcstack/signals/dom` re-exports the headless core (signals, resource,\n// streamResource, bindNode, nodeSource) so UI code can import everything from one\n// module. Both built entries import a single shared `core-*.esm.js` chunk\n// (rollup.config.js `manualChunks`), so importing from BOTH `@wcstack/signals` and\n// `@wcstack/signals/dom` on a buildless page yields ONE reactive instance — the\n// tracking context is shared, not duplicated. `__tests__/packaging.test.ts` pins\n// this (both entries reference the same core chunk; a signal made via one entry is\n// observed by an effect from the other).\nexport {\n signal,\n computed,\n effect,\n createRoot,\n onCleanup,\n flushSync,\n} from \"./reactive.js\";\nexport type { ReadSignal, WriteSignal, EffectHandle, Cleanup, Equals } from \"./reactive.js\";\nexport { resource } from \"./resource.js\";\nexport type { ResourceState, ResourceOptions, ResourceSource } from \"./resource.js\";\nexport { streamResource } from \"./streamResource.js\";\nexport type {\n StreamResourceState,\n StreamResourceOptions,\n StreamSource,\n StreamProducer,\n StreamStatus,\n} from \"./streamResource.js\";\nexport { bindNode, nodeSource, DisposedError, isDisposedError } from \"./bindNode.js\";\nexport type {\n BoundNode,\n NodeShape,\n DefaultNodeShape,\n WcBindableDescriptor,\n WcBindableProperty,\n EventStreamOptions,\n} from \"./bindNode.js\";\n\nexport const Fragment = Symbol(\"signals.Fragment\");\n\nexport type Child = unknown;\nexport type Props = Record<string, unknown> | null;\n// h() always injects `children` into the props object it passes to a component, so\n// the parameter type makes that explicit (a component can declare `{ children }`).\nexport type Component = (\n props: Record<string, unknown> & { children?: Child[] },\n) => Node | Child[];\n\nfunction isReadSignal(value: unknown): value is ReadSignal<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { get?: unknown }).get === \"function\" &&\n typeof (value as { peek?: unknown }).peek === \"function\"\n );\n}\n\nexport function h(\n tag: string | typeof Fragment | Component,\n props?: Props,\n ...children: Child[]\n): Node {\n if (tag === Fragment) {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n }\n\n if (typeof tag === \"function\") {\n const result = tag({ ...(props ?? {}), children });\n return Array.isArray(result) ? wrapFragment(result) : result;\n }\n\n const el = createElement(tag);\n if (props) {\n for (const key in props) {\n bindProp(el, key, props[key]);\n }\n }\n appendChildren(el, children);\n return el;\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n// Tags created in the SVG namespace. Ambiguous names shared with HTML (`a`,\n// `title`, `script`, `style`) are intentionally EXCLUDED so ordinary HTML usage is\n// not broken; an SVG `<a>` / `<title>` must be created in an explicitly-namespaced\n// way by the caller. SVG DOM props are largely read-only, so `setProp`'s\n// settable-property check routes SVG attributes through `setAttribute` for free.\nconst SVG_TAGS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\",\n \"text\", \"tspan\", \"defs\", \"use\", \"symbol\", \"marker\", \"linearGradient\",\n \"radialGradient\", \"stop\", \"clipPath\", \"mask\", \"pattern\", \"image\", \"foreignObject\",\n]);\n\nfunction createElement(tag: string): Element {\n return SVG_TAGS.has(tag)\n ? document.createElementNS(SVG_NS, tag)\n : document.createElement(tag);\n}\n\n/** Append `child` into `container`, resolving fragments/arrays. */\nexport function render(child: Child, container: Node): Node {\n appendChild(container, child);\n return container;\n}\n\nfunction wrapFragment(children: Child[]): DocumentFragment {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n}\n\n// --- props ------------------------------------------------------------------\n\n// Attribute names whose corresponding JS DOM property differs. `class` is handled\n// separately (it has reactive-falsy semantics in setProp), so it is not listed here.\nconst ATTR_TO_PROP: Record<string, string> = {\n for: \"htmlFor\",\n tabindex: \"tabIndex\",\n colspan: \"colSpan\",\n rowspan: \"rowSpan\",\n readonly: \"readOnly\",\n maxlength: \"maxLength\",\n minlength: \"minLength\",\n contenteditable: \"contentEditable\",\n};\n\n// True only if `key` resolves to a WRITABLE property on the element or its\n// prototype chain (a data property with `writable !== false`, or an accessor with a\n// setter). `key in el` is not enough: it also matches read-only members like\n// `firstChild` / `childNodes`, whose assignment throws in strict mode. The walk\n// starts at `el` itself so own instance fields (e.g. a custom element's properties)\n// are still matched, exactly as the previous `key in el` did — just without the\n// read-only false positives.\n//\n// MEMOIZATION: the prototype-chain walk runs on every bindProp/setProp. The result\n// depends only on the element's PROTOTYPE (its class) and the key, since DOM props\n// live on the prototype — not on per-instance own fields, which this library never\n// adds dynamically per element. So cache by `(prototype, key)`: a WeakMap keyed by\n// prototype (no leak — entries die with the class) holding a Map of key→result.\nconst settableCache = new WeakMap<object, Map<string, boolean>>();\n\nfunction computeSettable(el: Element, key: string): boolean {\n let obj: object | null = el;\n while (obj !== null) {\n const desc = Object.getOwnPropertyDescriptor(obj, key);\n if (desc) {\n return \"set\" in desc ? typeof desc.set === \"function\" : desc.writable !== false;\n }\n obj = Object.getPrototypeOf(obj);\n }\n return false;\n}\n\nfunction isSettableProperty(el: Element, key: string): boolean {\n // A real Element always has a prototype (HTMLElement.prototype → … → Object), so\n // `getPrototypeOf` is non-null here; use it as the cache key.\n const proto = Object.getPrototypeOf(el) as object;\n let byKey = settableCache.get(proto);\n if (byKey === undefined) {\n byKey = new Map<string, boolean>();\n settableCache.set(proto, byKey);\n }\n let result = byKey.get(key);\n if (result === undefined) {\n result = computeSettable(el, key);\n byKey.set(key, result);\n }\n return result;\n}\n\nfunction bindProp(el: Element, key: string, value: unknown): void {\n // Event handlers (`onClick` → \"click\") are special-cased BEFORE the reactive\n // check: a function here is the listener, not a thunk to track.\n if (/^on[A-Z]/.test(key) && typeof value === \"function\") {\n const type = key.slice(2).toLowerCase();\n const listener = value as EventListener;\n el.addEventListener(type, listener);\n // Remove the listener when the owning scope is torn down (e.g. a dynamic\n // child that rebuilds this subtree), so handlers don't accumulate.\n onCleanup(() => el.removeEventListener(type, listener));\n return;\n }\n\n if (typeof value === \"function\") {\n effect(() => setProp(el, key, (value as () => unknown)()));\n return;\n }\n\n if (isReadSignal(value)) {\n effect(() => setProp(el, key, value.get()));\n return;\n }\n\n setProp(el, key, value);\n}\n\nfunction setProp(el: Element, key: string, value: unknown): void {\n if (key === \"style\") {\n setStyle(el as HTMLElement, value);\n return;\n }\n if (key === \"class\" || key === \"className\") {\n // Set the `class` ATTRIBUTE, not the `className` property. On an SVGElement\n // `className` is a read-only `SVGAnimatedString`, so assigning it throws in\n // strict mode (ESM is always strict) — `setAttribute(\"class\", …)` works for both\n // HTML and SVG. Treat false like null → empty class (consistent with the\n // attribute path's false-removes-it rule), so `() => cond && \"active\"` yields \"\"\n // (not \"false\") when the condition is falsy.\n // STRING-ONLY: a non-null/non-false value is coerced via String(value). Array\n // (`[\"a\", \"b\"]`) and object (`{ active: true }`) class forms are NOT supported —\n // they would stringify to \"a,b\" / \"[object Object]\". Compose the class string in\n // the binding itself (e.g. `() => [a, b].join(\" \")`) and pass a string. This keeps\n // the core free of a class-merging convention.\n el.setAttribute(\"class\", value == null || value === false ? \"\" : String(value));\n return;\n }\n // Remap the handful of attribute names whose JS property differs, so `for` /\n // `tabindex` / `colspan` etc. reach the right property instead of falling through\n // to setAttribute (which works for some but not e.g. `htmlFor`).\n const propKey = ATTR_TO_PROP[key] ?? key;\n if (isSettableProperty(el, propKey)) {\n // Known, WRITABLE DOM property (value, checked, disabled, id, htmlFor, ...).\n // The settability check excludes read-only members (firstChild, childNodes, …)\n // that `key in el` would wrongly accept — assigning to those throws in strict\n // mode; we fall through to the attribute path for them instead.\n //\n // NORMALIZATION: null/undefined are coerced to \"\" before assignment. Without\n // this, a STRING prop (id/title/value/src) given a reactive null/undefined\n // lands as the literal \"null\"/\"undefined\" (e.g. img.src=\"null\" fires a real\n // request) — a correctness footgun. \"\" clears the prop instead. Safe for\n // non-string props too: boolean props coerce \"\"→false (same as null), numeric\n // props coerce \"\"→0 (same as null). We do NOT normalize `false`:\n // `el.disabled = false` is the intended boolean clear.\n (el as unknown as Record<string, unknown>)[propKey] = value == null ? \"\" : value;\n return;\n }\n if (value == null || value === false) {\n el.removeAttribute(key);\n return;\n }\n if (value === true) {\n el.setAttribute(key, \"\");\n return;\n }\n el.setAttribute(key, String(value));\n}\n\nfunction setStyle(el: HTMLElement, value: unknown): void {\n if (value == null) {\n el.removeAttribute(\"style\");\n return;\n }\n if (typeof value === \"string\") {\n el.style.cssText = value;\n return;\n }\n // Object form: the object fully describes the style. Reset first so keys present\n // in a previous run but absent now are removed — otherwise a reactive style that\n // drops a key (e.g. {color,fontWeight} → {color}) would leave the stale property\n // applied. The object is the source of truth, so wiping cssText is correct here.\n el.style.cssText = \"\";\n const style = el.style as CSSStyleDeclaration & Record<string, string>;\n const obj = value as Record<string, string>;\n for (const k in obj) {\n // A key with a hyphen is either kebab-case (`font-weight`) or a CSS custom\n // property (`--accent`). Neither works via property assignment (`style[k]` would\n // just set an inert expando), so route them through setProperty. camelCase keys\n // (`fontWeight`) keep the faster property path.\n if (k.includes(\"-\")) {\n style.setProperty(k, obj[k]);\n } else {\n style[k] = obj[k];\n }\n }\n}\n\n// --- children ---------------------------------------------------------------\n\nfunction appendChildren(parent: Node, children: Child[]): void {\n for (const child of children) {\n appendChild(parent, child);\n }\n}\n\nfunction appendChild(parent: Node, child: Child): void {\n if (child == null || typeof child === \"boolean\") {\n return; // null / undefined / boolean render nothing\n }\n if (Array.isArray(child)) {\n for (const c of child) {\n appendChild(parent, c);\n }\n return;\n }\n if (isListView(child)) {\n // A keyed list (For / Index): it manages its own anchored region with in-place\n // reconciliation, so it does NOT go through the wholesale insertReactive path.\n child.mount(parent);\n return;\n }\n if (child instanceof Node) {\n parent.appendChild(child);\n return;\n }\n if (typeof child === \"function\") {\n insertReactive(parent, child as () => unknown);\n return;\n }\n if (isReadSignal(child)) {\n insertReactive(parent, () => child.get());\n return;\n }\n parent.appendChild(document.createTextNode(String(child)));\n}\n\n/**\n * A reactive insertion point. An anchor comment marks the position; on each run\n * the previous nodes are removed and the freshly-resolved nodes inserted before\n * the anchor. Using `anchor.parentNode` (not the original `parent`) keeps it\n * correct after the subtree is moved/mounted elsewhere.\n *\n * PRECONDITION: the Nodes returned by `accessor` are owned by this insertion point\n * — do not move them to another parent externally. On the next run they are\n * removed from wherever they currently are (`node.parentNode?.removeChild`), so an\n * externally-moved node would be yanked out of its new home without warning.\n *\n * OWNERSHIP: the `effect` below is owned by the enclosing reactive scope at call\n * time (the `currentOwner`). Used under `createRoot` / `SignalsElement` (the module\n * header's mount contract) it is disposed on teardown. Calling `h`/`render` with a\n * reactive child OUTSIDE any owner (no `createRoot`/`SignalsElement`) leaves this\n * effect un-owned and therefore never cleaned up — by design, per that contract.\n */\nfunction insertReactive(parent: Node, accessor: () => unknown): void {\n if (isDev() && !hasOwner()) {\n // A reactive child inserted with no enclosing owner: the effect below is never\n // disposed (the module header documents this as by-design, but it is a frequent\n // accidental leak). Warn once in dev so the un-owned mount is visible.\n warnDev(\n \"UNOWNED_INSERT\",\n \"\",\n \"reactive child inserted with no owner — its update effect will never be \" +\n \"disposed and may leak. Mount under createRoot / SignalsElement.\",\n );\n }\n const anchor = document.createComment(\"\");\n parent.appendChild(anchor);\n let current: Node[] = [];\n\n effect(() => {\n const value = accessor();\n // FAST PATH: a plain text result that replaces a plain text result. The common\n // reactive child is a string/number thunk (`() => \\`count: ${n.get()}\\``); the\n // wholesale path would remove the old Text node, allocate a new one, and re-insert\n // it on every change. When BOTH the previous and next renders are a single Text\n // node, mutate the existing node's `data` in place instead — no allocation, no\n // remove/insert, and the same DOM node identity is preserved across updates.\n if ((typeof value === \"string\" || typeof value === \"number\") && current.length === 1) {\n const node = current[0];\n if (node.nodeType === 3 /* TEXT_NODE */) {\n (node as Text).data = String(value);\n return;\n }\n }\n const next = toNodes(value);\n for (const node of current) {\n node.parentNode?.removeChild(node);\n }\n const host = anchor.parentNode;\n if (host) {\n for (const node of next) {\n host.insertBefore(node, anchor);\n }\n }\n current = next;\n });\n\n // On teardown, drop the references to the inserted Nodes. The disposed effect's\n // closure still captures `current`; if anything retains the effect after disposal\n // (e.g. a parent owner kept alive longer than the subtree), those Nodes would be\n // pinned via that closure even though they have left the DOM. Clearing the array\n // lets them be GC'd as soon as the enclosing owner tears this insertion point down.\n onCleanup(() => {\n current = [];\n });\n}\n\n// --- keyed lists: For / Index (migration-plan §9-3) --------------------------\n//\n// `insertReactive` rebuilds its whole subtree on every change. For lists that is\n// wasteful (and drops per-row state). `For` / `Index` instead keep a stable DOM row\n// per item and reconcile in place. Each row is built under its OWN `createRoot`, so\n// removing a row disposes exactly that row's effects/resources/listeners — the owner\n// tree (§8 (d)) is what makes this leak-free. The reconcile runs in a single\n// `effect` owned by the enclosing scope; an `onCleanup` disposes surviving rows when\n// that scope (e.g. the component) tears down.\n//\n// CONTRACT: `each` must return a SINGLE Node (one row = one node). Keys (For) must\n// be unique. `For` keys by value identity (=== / explicit `key`) and passes the\n// index as an accessor (it changes on move); `Index` keys by position and passes the\n// item as an accessor (the value at a slot changes, the slot does not).\n\nexport type ListAccessor<T> = ReadSignal<readonly T[]> | (() => readonly T[]);\nexport type ForEach<T> = (item: T, index: () => number) => Node;\nexport type IndexEach<T> = (item: () => T, index: number) => Node;\n\n/**\n * The return type of {@link For} / {@link Index}: a keyed list that owns an anchored\n * region and reconciles rows in place. Exported (D4) so consumers can annotate\n * helpers that build or pass around lists. `mount` is called by `h`/`render` when the\n * list is used as a child; `__wcsList` is the brand `appendChild` checks.\n */\nexport interface ListView {\n readonly __wcsList: true;\n mount(parent: Node): void;\n}\n\nfunction isListView(value: unknown): value is ListView {\n return typeof value === \"object\" && value !== null && (value as ListView).__wcsList === true;\n}\n\nfunction readList<T>(list: ListAccessor<T>): () => readonly T[] {\n return isReadSignal(list) ? () => (list as ReadSignal<readonly T[]>).get() : (list as () => readonly T[]);\n}\n\nexport interface ForOptions<T> {\n /** Derive a unique key per item. Default: the item value itself (identity). */\n key?: (item: T, index: number) => unknown;\n}\n\n// --- LIS-based DOM reorder ---------------------------------------------------\n//\n// `reconcileOrder` brings the live DOM under `host` (the contiguous region ending\n// at `anchor`) into `order` — the desired final node sequence — using the FEWEST\n// `insertBefore` moves, while producing EXACTLY the order a naive full re-place\n// would. The naive approach (walk and insert every out-of-place node) does up to\n// O(n) DOM moves on a full reverse or a head insert; here we instead keep the\n// largest set of reused rows that are ALREADY in the right relative order, and\n// move only the others (Solid's reconcileArrays / udomdiff idea).\n//\n// HOW: `prevOrder` is the node sequence the previous run left in the DOM. For each\n// node in the new `order`, a reused row maps to its index in `prevOrder`; a freshly\n// created row has no previous position. The longest increasing subsequence (LIS)\n// of those previous indices marks the reused rows that need NOT move (their pairwise\n// relative order is already correct). Every other node — fresh ones, and reused\n// ones outside the LIS — is inserted before its already-correct successor, walking\n// back-to-front so the \"successor\" reference is always a settled node or the anchor.\n\n/**\n * Indices into `arr` (with value -1 meaning \"no previous position\") whose values\n * form a longest strictly-increasing subsequence. Entries equal to -1 are treated\n * as never part of the subsequence (a fresh node always moves). Classic\n * patience-sorting LIS in O(n log n); returns the chosen indices in ascending order.\n */\nfunction longestIncreasingSubsequence(arr: number[]): number[] {\n const n = arr.length;\n // `tails[k]` = index (into arr) of the smallest tail of an increasing\n // subsequence of length k+1. `prev[i]` = predecessor index, to rebuild the chain.\n const tails: number[] = [];\n const prev: number[] = new Array(n).fill(-1);\n for (let i = 0; i < n; i++) {\n const value = arr[i];\n if (value < 0) {\n continue; // fresh node: not eligible for the stable subsequence\n }\n // Binary search for the first tail whose value is >= this value, and replace it\n // (or extend the tails when this value beats every tail).\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (arr[tails[mid]] < value) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n if (lo > 0) {\n prev[i] = tails[lo - 1];\n }\n tails[lo] = i;\n }\n // Rebuild the index chain from the longest tail backwards.\n const result: number[] = [];\n let k = tails.length > 0 ? tails[tails.length - 1] : -1;\n while (k >= 0) {\n result.push(k);\n k = prev[k];\n }\n result.reverse();\n return result;\n}\n\nfunction reconcileOrder(\n host: Node,\n anchor: Node,\n order: Node[],\n prevOrder: Node[],\n): void {\n const n = order.length;\n if (n === 0) {\n return; // nothing to place (removals already happened)\n }\n\n // Map each previous node to its previous position, so a node in `order` can look\n // up where it used to be. A node absent from this map is FRESH (created this run,\n // or the first run where prevOrder is empty) and is encoded as -1 — it always moves.\n const prevIndex = new Map<Node, number>();\n for (let i = 0; i < prevOrder.length; i++) {\n prevIndex.set(prevOrder[i], i);\n }\n\n // previous-position sequence aligned to the new order. -1 marks a fresh node.\n const seq: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const p = prevIndex.get(order[i]);\n seq[i] = p === undefined ? -1 : p;\n }\n\n // Rows whose relative order is already correct: leave them in place, move the rest.\n const lis = longestIncreasingSubsequence(seq);\n let lisPtr = lis.length - 1;\n\n // Walk back-to-front. `ref` is the node that must follow the one being placed; it\n // starts at the anchor (the region's tail) and becomes each placed node. A node in\n // the LIS is the maximal already-correctly-ordered set, so it is left untouched\n // (only adopted as the new `ref`). Every OTHER node is, by construction, out of\n // position relative to its settled successor and is inserted before `ref` — no\n // \"is it already in place?\" guard is needed (it never is, unlike the old\n // full-walk reconciler which visited correctly-placed nodes too).\n let ref: Node = anchor;\n for (let i = n - 1; i >= 0; i--) {\n const node = order[i];\n if (lisPtr >= 0 && lis[lisPtr] === i) {\n lisPtr--; // stable: do not move\n } else {\n host.insertBefore(node, ref);\n }\n ref = node;\n }\n}\n\n// Dev-only key sanity check (no effect in production — guarded by `isDev()` at the\n// call site so this is never reached when dev is off). Flags the silent-failure key\n// shapes: a nullish key (NaN / null / undefined collide under SameValueZero, so two\n// such items map to one row and a row is silently dropped), and — when no explicit\n// `key` was given — a non-primitive item used as its own identity key (every render\n// gets a fresh object reference, so the row is rebuilt instead of reused, silently\n// dropping per-row state). Warns once per distinct shape (deduped in warnDev).\nfunction checkKeyDev(key: unknown, item: unknown, hasExplicitKey: boolean): void {\n if (key == null || (typeof key === \"number\" && Number.isNaN(key))) {\n warnDev(\n \"NULLISH_KEY\",\n String(key),\n \"For: a key is null/undefined/NaN. Such keys collide under SameValueZero, \" +\n \"so rows silently merge/drop. Provide a stable unique `key`.\",\n { key },\n );\n return;\n }\n if (!hasExplicitKey && (typeof key === \"object\" || typeof key === \"function\")) {\n warnDev(\n \"NON_PRIMITIVE_KEY\",\n typeof key,\n \"For: a non-primitive item is used as its own key (no `key` option given). \" +\n \"Object identity changes across renders, so every row is rebuilt and per-row \" +\n \"state is lost. Pass `{ key: item => item.id }`.\",\n { item },\n );\n }\n}\n\nexport function For<T>(list: ListAccessor<T>, each: ForEach<T>, options?: ForOptions<T>): ListView {\n const read = readList(list);\n const keyOf = options?.key;\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"for\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n idx: WriteSignal<number>;\n }\n let rows = new Map<unknown, Row>();\n // The node order placed by the previous reconcile run. Empty on first run.\n // Used to find which reused rows already sit in increasing relative order so\n // only the rest are moved (LIS reorder, see reconcileOrder).\n let prevOrder: Node[] = [];\n\n const make = (item: T, i: number): Row => {\n const idx = signal(i);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(item, () => idx.get());\n return d;\n });\n return { node, dispose, idx };\n };\n\n effect(() => {\n const items = read() ?? [];\n\n // Key-uniqueness PRE-PASS (no side effects): throwing here, before any row is\n // created or moved, keeps a duplicate-key error from leaving half-built rows\n // orphaned (make() runs createRoot) and the DOM mid-reorder. Keys are reused\n // below so keyOf runs once per item.\n const keys: unknown[] = [];\n const seen = new Set<unknown>();\n const dev = isDev();\n for (let i = 0; i < items.length; i++) {\n const k = keyOf ? keyOf(items[i], i) : items[i];\n if (dev) {\n checkKeyDev(k, items[i], keyOf !== undefined);\n }\n if (seen.has(k)) {\n if (dev) {\n // The throw below still halts (production behaviour unchanged); the warn\n // adds the offending key + a pointer to the cause so the silent\n // \"updates stopped\" symptom is diagnosable.\n warnDev(\n \"DUPLICATE_KEY\",\n String(k),\n `For: duplicate key \"${String(k)}\" at index ${i} — keys must be unique. ` +\n \"Rendering throws and the list stops updating until keys are fixed.\",\n { key: k, index: i },\n );\n }\n throw new Error(`For: duplicate key \"${String(k)}\" — keys must be unique.`);\n }\n seen.add(k);\n keys.push(k);\n }\n\n const next = new Map<unknown, Row>();\n const order: Node[] = [];\n\n // Rows freshly created in THIS run (not reused from `rows`). If a later\n // `make()` — i.e. a user `each` — throws mid-loop, the rows already built\n // here are owned by their own detached `createRoot` and are not yet tracked\n // in any surviving map, so they would leak. Dispose them before re-throwing,\n // leaving the old `rows` map untouched (it is recoverable on the next run).\n const fresh: Row[] = [];\n try {\n for (let i = 0; i < items.length; i++) {\n const k = keys[i];\n let row = rows.get(k);\n if (row) {\n if (row.idx.peek() !== i) {\n row.idx.set(i); // position changed — refresh the index accessor\n }\n } else {\n row = make(items[i], i);\n fresh.push(row);\n }\n next.set(k, row);\n order.push(row.node);\n }\n } catch (err) {\n for (const row of fresh) {\n row.dispose();\n }\n throw err;\n }\n\n // Dispose rows whose key vanished. `remove()` no-ops if already detached.\n for (const [k, row] of rows) {\n if (!next.has(k)) {\n (row.node as ChildNode).remove();\n row.dispose();\n }\n }\n\n // Reorder relative to the LIVE parent (`anchor.parentNode`, not the mount\n // arg) so the region stays correct after being moved (e.g. built inside a\n // Fragment, then appended elsewhere). `host` is null only if the anchor was\n // detached without disposing this scope (a misuse) — then there is nothing\n // to place into.\n const host = anchor.parentNode;\n if (host) {\n reconcileOrder(host, anchor, order, prevOrder);\n }\n\n // Snapshot this run's final order so the NEXT run's reconcile can detect\n // which rows kept their relative position (the LIS basis below). Capturing\n // the array we just placed avoids re-deriving it from the map.\n prevOrder = order;\n rows = next;\n });\n\n onCleanup(() => {\n for (const row of rows.values()) {\n row.dispose();\n }\n rows.clear();\n });\n },\n };\n}\n\nexport function Index<T>(list: ListAccessor<T>, each: IndexEach<T>): ListView {\n const read = readList(list);\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"index\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n item: WriteSignal<T>;\n }\n const rows: Row[] = [];\n\n effect(() => {\n const items = read() ?? [];\n // Live parent (see `For`), null only if the anchor was detached undisposed.\n const host = anchor.parentNode;\n\n for (let i = 0; i < items.length; i++) {\n if (i < rows.length) {\n // Slot reused: just push the new value into the row's item signal. The\n // signal's equality guard skips the update when the value is unchanged.\n rows[i].item.set(items[i]);\n } else {\n const item = signal(items[i]);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(() => item.get(), i);\n return d;\n });\n rows.push({ node, dispose, item });\n // Positions never move for index keying, so append at the tail (before\n // the anchor) in order. ORDERING CONTRACT (shared with For and the other\n // anchored insertions): the list owns the contiguous region ENDING at its\n // anchor comment. New rows go immediately before the anchor, so the list's\n // own rows always stay correctly ordered and grouped, and static siblings\n // before the anchor (or another list with its own anchor) are never\n // disturbed. Do NOT splice unrelated nodes into the middle of this region.\n host?.insertBefore(node, anchor);\n }\n }\n\n // Trailing slots that no longer exist: dispose and drop.\n if (items.length < rows.length) {\n for (let i = items.length; i < rows.length; i++) {\n (rows[i].node as ChildNode).remove();\n rows[i].dispose();\n }\n rows.length = items.length;\n }\n });\n\n onCleanup(() => {\n for (const row of rows) {\n row.dispose();\n }\n rows.length = 0;\n });\n },\n };\n}\n\n// --- custom element lifecycle (docs §8 (e)) ---------------------------------\n//\n// The exit point for ownership: a custom element that mounts a signals view under\n// `createRoot` on connect and disposes that root on disconnect. This wires the\n// reactive ownership tree to the real DOM lifecycle — every effect, resource and\n// listener created in `render()` is torn down when the element leaves the DOM, and\n// rebuilt fresh on reconnect. Subclasses only implement `render()`.\n//\n// SCOPE (v1 intentional constraints — drive these reactively, not via this base):\n// - No attribute reactivity. There is no `attributeChangedCallback`/\n// `observedAttributes` wiring: this base does NOT turn HTML attributes into\n// signals. Feed reactive inputs as signals/props from the code that constructs\n// the view (or have a subclass map attributes to signals itself).\n// - Shadow DOM is opt-in and subclass-owned. The default mount point is light DOM\n// (`this`); a subclass that wants encapsulation overrides `getMountPoint()` to\n// return a shadow root it created (e.g. `this.attachShadow(...)` in its\n// constructor). This base never calls attachShadow implicitly.\n// - Mount/unmount only: render() runs once per connect and the whole subtree is\n// disposed on disconnect — there is no partial/incremental re-render hook here\n// (fine-grained updates come from the signals wired inside render()).\n\n// TYPE-ONLY shape of the lifecycle base. `declare abstract class` emits NO runtime\n// code (so it does not reference `HTMLElement` at module-evaluation time — the whole\n// point of the lazy factory below), but it gives the exported `SignalsElement` value\n// and `createSignalsElement()`'s return a precise type that preserves the original\n// contract: `render` is `protected abstract` (a subclass MUST implement it and may\n// only reach it from within), and `getMountPoint` is `protected` (overridable). This\n// is the same surface the previous concrete `abstract class SignalsElement` exposed.\n// (Used only via `typeof` below; the lint rule does not see that as a value use.)\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ndeclare abstract class SignalsElementType extends HTMLElement {\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node;\n connectedCallback(): void;\n disconnectedCallback(): void;\n}\n\n/**\n * The lifecycle base contract: the abstract constructor type of the `SignalsElement`\n * base. Abstract, so `new SignalsElement()` is rejected (the base has an unimplemented\n * `render`) while `class X extends SignalsElement` is allowed. Returned by\n * {@link createSignalsElement} and the type of the {@link SignalsElement} value.\n */\nexport type SignalsElementClass = typeof SignalsElementType;\n\n// Memoized base class. Built lazily on first access so the `./dom` module can be\n// EVALUATED in a non-DOM environment (SSR pre-pass, a worker without a DOM shim)\n// without a top-level `class … extends HTMLElement` blowing up with\n// `ReferenceError: HTMLElement is not defined`. The class body is only constructed\n// when the consumer actually reaches for the base — at which point a DOM is required\n// and its absence yields a clear, actionable error instead of a raw ReferenceError.\nlet cachedBase: SignalsElementClass | null = null;\n\n/**\n * Build (once, memoized) the `SignalsElement` lifecycle base class. Resolves\n * `HTMLElement` at CALL TIME, so importing `@wcstack/signals/dom` no longer requires\n * a DOM at module-evaluation time — only *calling* this (or subclassing\n * {@link SignalsElement}) does.\n *\n * Contract:\n * - The `.` entry (`@wcstack/signals`) is non-DOM: it evaluates and runs in SSR,\n * Node, and Web Workers with no DOM globals.\n * - The `./dom` entry (`@wcstack/signals/dom`) may now also be *evaluated* without a\n * DOM (so an SSR pre-pass that imports it for the headless re-exports does not\n * crash). The DOM-touching surface — `h`/`render`/`For`/`Index` and this base —\n * still requires DOM globals when actually used.\n *\n * @throws a clear `Error` (not a raw `ReferenceError`) when no `HTMLElement` global is\n * present, naming the offending entry so the failure is self-explanatory.\n */\nexport function createSignalsElement(): SignalsElementClass {\n if (cachedBase !== null) {\n return cachedBase;\n }\n if (typeof HTMLElement === \"undefined\") {\n throw new Error(\n \"@wcstack/signals/dom: SignalsElement requires a DOM (HTMLElement is not defined). \" +\n \"The `./dom` entry's element/render surface is browser-only; in SSR/Node/worker \" +\n \"code import the headless core from `@wcstack/signals` instead, or inject a DOM \" +\n \"(e.g. happy-dom) before constructing custom elements.\",\n );\n }\n\n abstract class SignalsElementBase extends HTMLElement {\n private _dispose: (() => void) | null = null;\n\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node {\n return this;\n }\n\n connectedCallback(): void {\n if (this._dispose !== null) {\n return; // already mounted (defensive against a redundant connect)\n }\n const mount = this.getMountPoint();\n // If render() throws, createRoot disposes any effects it built before the throw,\n // so nothing leaks; _dispose stays null (the element is simply not mounted) and\n // a later disconnectedCallback safely no-ops. The error propagates to the caller.\n this._dispose = createRoot((dispose) => {\n mount.appendChild(this.render());\n return dispose;\n });\n }\n\n disconnectedCallback(): void {\n if (this._dispose === null) {\n return; // not mounted\n }\n this._dispose();\n this._dispose = null;\n const mount = this.getMountPoint();\n while (mount.firstChild) {\n mount.removeChild(mount.firstChild);\n }\n }\n }\n\n cachedBase = SignalsElementBase as unknown as SignalsElementClass;\n return cachedBase;\n}\n\n// `SignalsElement` is the ergonomic name to `extends`. It is a lazily-resolved alias\n// for the class built by `createSignalsElement()`: a Proxy that forwards construct /\n// get / has / getPrototypeOf to the real (memoized) base, building it on first touch.\n// This keeps `class X extends SignalsElement { … }` working exactly as before WHILE\n// deferring the `HTMLElement` reference to subclass-definition time (in a real DOM),\n// instead of `./dom` module-evaluation time (which may be a non-DOM SSR pre-pass).\n//\n// BREAKING note: the value is now a Proxy, not the class object literal. Subclassing,\n// `instanceof`, and static/prototype access all still work; a consumer that relied on\n// `SignalsElement` being a *frozen* concrete class reference (uncommon) should call\n// `createSignalsElement()` to obtain the real class.\n// The Proxy target is a never-called placeholder (every operation is intercepted by a\n// trap below); it only needs to be constructable/callable so `new` / `extends` and the\n// `apply` trap engage. It is intentionally a no-op and never executed.\n/* v8 ignore next */\nconst signalsElementTarget = function (): void {};\nexport const SignalsElement: SignalsElementClass = new Proxy(signalsElementTarget as unknown as SignalsElementClass, {\n construct(_target, args, newTarget): object {\n return Reflect.construct(createSignalsElement(), args, newTarget);\n },\n get(_target, prop, receiver): unknown {\n return Reflect.get(createSignalsElement(), prop, receiver);\n },\n has(_target, prop): boolean {\n return Reflect.has(createSignalsElement(), prop);\n },\n apply(): never {\n throw new TypeError(\"SignalsElement is a class and cannot be invoked without `new`/`extends`.\");\n },\n getPrototypeOf(): object | null {\n return Reflect.getPrototypeOf(createSignalsElement());\n },\n});\n\nfunction toNodes(value: unknown): Node[] {\n const out: Node[] = [];\n const visit = (v: unknown): void => {\n if (v == null || typeof v === \"boolean\") {\n return;\n }\n if (Array.isArray(v)) {\n v.forEach(visit);\n return;\n }\n if (v instanceof Node) {\n out.push(v);\n return;\n }\n out.push(document.createTextNode(String(v)));\n };\n visit(value);\n return out;\n}\n"],"names":[],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;MA0Ca,QAAQ,GAAG,MAAM,CAAC,kBAAkB;AAUjD,SAAS,YAAY,CAAC,KAAc,E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IAC5D,CAAC;IACD,GAAG,CAAC,OAAO,EAAE,IAAI,EAAA;QACf,OAAO,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,EAAE,IAAI,CAAC;IAClD,CAAC;IACD,KAAK,GAAA;AACH,QAAA,MAAM,IAAI,SAAS,CAAC,0EAA0E,CAAC;IACjG,CAAC;IACD,cAAc,GAAA;AACZ,QAAA,OAAO,OAAO,CAAC,cAAc,CAAC,oBAAoB,EAAE,CAAC;IACvD,CAAC;AACF,CAAA;AAED,SAAS,OAAO,CAAC,KAAc,EAAA;IAC7B,MAAM,GAAG,GAAW,EAAE;AACtB,IAAA,MAAM,KAAK,GAAG,CAAC,CAAU,KAAU;QACjC,IAAI,CAAC,IAAI,IAAI,IAAI,OAAO,CAAC,KAAK,SAAS,EAAE;YACvC;QACF;AACA,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;AACpB,YAAA,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;YAChB;QACF;AACA,QAAA,IAAI,CAAC,YAAY,IAAI,EAAE;AACrB,YAAA,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;YACX;QACF;AACA,QAAA,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9C,IAAA,CAAC;IACD,KAAK,CAAC,KAAK,CAAC;AACZ,IAAA,OAAO,GAAG;AACZ;;;;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{e,o as t,g as o,h as s,w as l,s as a,a as u}from"./core-DCHZTbGv.esm.min.js";export{D as DisposedError,b as bindNode,c as computed,f as flushSync,i as isDisposedError,n as nodeSource,r as resource,d as streamResource}from"./core-DCHZTbGv.esm.min.js";const p=Symbol("signals.Fragment");function m(e){return"object"==typeof e&&null!==e&&"function"==typeof e.get&&"function"==typeof e.peek}function g(e,t,...n){if(e===p){const e=document.createDocumentFragment();return x(e,n),e}if("function"==typeof e){const o=e({...t??{},children:n});return Array.isArray(o)?function(e){const t=document.createDocumentFragment();return x(t,e),t}(o):o}const o=function(e){return y.has(e)?document.createElementNS(h,e):document.createElement(e)}(e);if(t)for(const e in t)E(o,e,t[e]);return x(o,n),o}const h="http://www.w3.org/2000/svg",y=new Set(["svg","g","path","rect","circle","ellipse","line","polyline","polygon","text","tspan","defs","use","symbol","marker","linearGradient","radialGradient","stop","clipPath","mask","pattern","image","foreignObject"]);function w(e,t){return C(t,e),t}const v={for:"htmlFor",tabindex:"tabIndex",colspan:"colSpan",rowspan:"rowSpan",readonly:"readOnly",maxlength:"maxLength",minlength:"minLength",contenteditable:"contentEditable"},k=new WeakMap;function S(e,t){const n=Object.getPrototypeOf(e);let o=k.get(n);void 0===o&&(o=new Map,k.set(n,o));let s=o.get(t);return void 0===s&&(s=function(e,t){let n=e;for(;null!==n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return"set"in e?"function"==typeof e.set:!1!==e.writable;n=Object.getPrototypeOf(n)}return!1}(e,t),o.set(t,s)),s}function E(n,o,s){if(/^on[A-Z]/.test(o)&&"function"==typeof s){const e=o.slice(2).toLowerCase(),r=s;return n.addEventListener(e,r),void t(()=>n.removeEventListener(e,r))}"function"!=typeof s?m(s)?e(()=>N(n,o,s.get())):N(n,o,s):e(()=>N(n,o,s()))}function N(e,t,n){if("style"===t)return void function(e,t){if(null==t)return void e.removeAttribute("style");if("string"==typeof t)return void(e.style.cssText=t);e.style.cssText="";const n=e.style,o=t;for(const e in o)e.includes("-")?n.setProperty(e,o[e]):n[e]=o[e]}(e,n);if("class"===t||"className"===t)return void e.setAttribute("class",null==n||!1===n?"":String(n));const o=v[t]??t;S(e,o)?e[o]=null==n?"":n:null!=n&&!1!==n?!0!==n?e.setAttribute(t,String(n)):e.setAttribute(t,""):e.removeAttribute(t)}function x(e,t){for(const n of t)C(e,n)}function C(e,t){var n;if(null!=t&&"boolean"!=typeof t)if(Array.isArray(t))for(const n of t)C(e,n);else"object"!=typeof(n=t)||null===n||!0!==n.__wcsList?t instanceof Node?e.appendChild(t):"function"!=typeof t?m(t)?_(e,()=>t.get()):e.appendChild(document.createTextNode(String(t))):_(e,t):t.mount(e)}function _(n,r){o()&&!s()&&l("UNOWNED_INSERT","","reactive child inserted with no owner — its update effect will never be disposed and may leak. Mount under createRoot / SignalsElement.");const i=document.createComment("");n.appendChild(i);let c=[];e(()=>{const e=r();if(("string"==typeof e||"number"==typeof e)&&1===c.length){const t=c[0];if(3===t.nodeType)return void(t.data=String(e))}const t=function(e){const t=[],n=e=>{null!=e&&"boolean"!=typeof e&&(Array.isArray(e)?e.forEach(n):e instanceof Node?t.push(e):t.push(document.createTextNode(String(e))))};return n(e),t}(e);for(const e of c)e.parentNode?.removeChild(e);const n=i.parentNode;if(n)for(const e of t)n.insertBefore(e,i);c=t}),t(()=>{c=[]})}function A(e){return m(e)?()=>e.get():e}function M(e,t,n,o){const s=n.length;if(0===s)return;const r=new Map;for(let e=0;e<o.length;e++)r.set(o[e],e);const i=new Array(s);for(let e=0;e<s;e++){const t=r.get(n[e]);i[e]=void 0===t?-1:t}const c=function(e){const t=e.length,n=[],o=new Array(t).fill(-1);for(let s=0;s<t;s++){const t=e[s];if(t<0)continue;let r=0,i=n.length;for(;r<i;){const o=r+i>>1;e[n[o]]<t?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(i);let l=c.length-1,a=t;for(let t=s-1;t>=0;t--){const o=n[t];l>=0&&c[l]===t?l--:e.insertBefore(o,a),a=o}}function O(e,t,n){null==e||"number"==typeof e&&Number.isNaN(e)?l("NULLISH_KEY",String(e),"For: a key is null/undefined/NaN. Such keys collide under SameValueZero, so rows silently merge/drop. Provide a stable unique `key`.",{key:e}):n||"object"!=typeof e&&"function"!=typeof e||l("NON_PRIMITIVE_KEY",typeof e,"For: a non-primitive item is used as its own key (no `key` option given). Object identity changes across renders, so every row is rebuilt and per-row state is lost. Pass `{ key: item => item.id }`.",{item:t})}function P(n,s,r){const i=A(n),c=r?.key;return{__wcsList:!0,mount(n){const r=document.createComment("for");n.appendChild(r);let d=new Map,f=[];const p=(e,t)=>{const n=a(t);let o;const r=u(t=>(o=s(e,()=>n.get()),t));return{node:o,dispose:r,idx:n}};e(()=>{const e=i()??[],t=[],n=new Set,s=o();for(let o=0;o<e.length;o++){const r=c?c(e[o],o):e[o];if(s&&O(r,e[o],void 0!==c),n.has(r))throw s&&l("DUPLICATE_KEY",String(r),`For: duplicate key "${String(r)}" at index ${o} — keys must be unique. Rendering throws and the list stops updating until keys are fixed.`,{key:r,index:o}),new Error(`For: duplicate key "${String(r)}" — keys must be unique.`);n.add(r),t.push(r)}const a=new Map,u=[],m=[];try{for(let n=0;n<e.length;n++){const o=t[n];let s=d.get(o);s?s.idx.peek()!==n&&s.idx.set(n):(s=p(e[n],n),m.push(s)),a.set(o,s),u.push(s.node)}}catch(e){for(const e of m)e.dispose();throw e}for(const[e,t]of d)a.has(e)||(t.node.remove(),t.dispose());const g=r.parentNode;g&&M(g,r,u,f),f=u,d=a}),t(()=>{for(const e of d.values())e.dispose();d.clear()})}}}function L(n,o){const s=A(n);return{__wcsList:!0,mount(n){const r=document.createComment("index");n.appendChild(r);const i=[];e(()=>{const e=s()??[],t=r.parentNode;for(let n=0;n<e.length;n++)if(n<i.length)i[n].item.set(e[n]);else{const s=a(e[n]);let c;const l=u(e=>(c=o(()=>s.get(),n),e));i.push({node:c,dispose:l,item:s}),t?.insertBefore(c,r)}if(e.length<i.length){for(let t=e.length;t<i.length;t++)i[t].node.remove(),i[t].dispose();i.length=e.length}}),t(()=>{for(const e of i)e.dispose();i.length=0})}}}let T=null;function j(){if(null!==T)return T;if("undefined"==typeof HTMLElement)throw new Error("@wcstack/signals/dom: SignalsElement requires a DOM (HTMLElement is not defined). The `./dom` entry's element/render surface is browser-only; in SSR/Node/worker code import the headless core from `@wcstack/signals` instead, or inject a DOM (e.g. happy-dom) before constructing custom elements.");class e extends HTMLElement{_dispose=null;getMountPoint(){return this}connectedCallback(){if(null!==this._dispose)return;const e=this.getMountPoint();this._dispose=u(t=>(e.appendChild(this.render()),t))}disconnectedCallback(){if(null===this._dispose)return;this._dispose(),this._dispose=null;const e=this.getMountPoint();for(;e.firstChild;)e.removeChild(e.firstChild)}}return T=e,T}const R=new Proxy(function(){},{construct:(e,t,n)=>Reflect.construct(j(),t,n),get:(e,t,n)=>Reflect.get(j(),t,n),has:(e,t)=>Reflect.has(j(),t),apply(){throw new TypeError("SignalsElement is a class and cannot be invoked without `new`/`extends`.")},getPrototypeOf:()=>Reflect.getPrototypeOf(j())});export{P as For,p as Fragment,L as Index,R as SignalsElement,u as createRoot,j as createSignalsElement,e as effect,g as h,t as onCleanup,w as render,a as signal};
|
|
2
|
+
//# sourceMappingURL=dom.esm.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dom.esm.min.js","sources":["../src/dom.ts"],"sourcesContent":["// Fine-grained hyperscript (v1 design notes). The \"step before JSX\" (docs §4-1).\n//\n// `h(tag, props, ...children)` is the classic JSX factory shape, but it does NOT\n// build a virtual DOM and re-render. It creates a REAL DOM node once; any prop or\n// child given as a function (thunk) or signal is wired to a targeted `effect`, so\n// only that one binding updates when its signals change (Solid-style). This is\n// what keeps the package lightweight: no reconciler is shipped.\n//\n// JSX is intentionally NOT shipped. A consumer who wants it sets, in their own\n// tsconfig, `jsxFactory: \"h\"` + `jsxFragmentFactory: \"Fragment\"` (classic runtime)\n// — opting into a build step is their choice; the buildless path is calling `h`\n// directly. See docs/signals-state-design.md §4-1.\n//\n// OWNERSHIP: effects created here are owned by the enclosing reactive scope.\n// A reactive child's effect owns the prop/child effects of the subtree it builds,\n// so rebuilding that subtree disposes the previous one's effects (no leak). Mount\n// an app under `createRoot` so the whole tree can be torn down on unmount; a\n// dynamic child establishes its own scope automatically (it IS an effect).\n\nimport { signal, effect, onCleanup, createRoot, hasOwner, ReadSignal, WriteSignal } from \"./reactive.js\";\nimport { isDev, warnDev } from \"./dev.js\";\n\n// `@wcstack/signals/dom` re-exports the headless core (signals, resource,\n// streamResource, bindNode, nodeSource) so UI code can import everything from one\n// module. Both built entries import a single shared `core-*.esm.js` chunk\n// (rollup.config.js `manualChunks`), so importing from BOTH `@wcstack/signals` and\n// `@wcstack/signals/dom` on a buildless page yields ONE reactive instance — the\n// tracking context is shared, not duplicated. `__tests__/packaging.test.ts` pins\n// this (both entries reference the same core chunk; a signal made via one entry is\n// observed by an effect from the other).\nexport {\n signal,\n computed,\n effect,\n createRoot,\n onCleanup,\n flushSync,\n} from \"./reactive.js\";\nexport type { ReadSignal, WriteSignal, EffectHandle, Cleanup, Equals } from \"./reactive.js\";\nexport { resource } from \"./resource.js\";\nexport type { ResourceState, ResourceOptions, ResourceSource } from \"./resource.js\";\nexport { streamResource } from \"./streamResource.js\";\nexport type {\n StreamResourceState,\n StreamResourceOptions,\n StreamSource,\n StreamProducer,\n StreamStatus,\n} from \"./streamResource.js\";\nexport { bindNode, nodeSource, DisposedError, isDisposedError } from \"./bindNode.js\";\nexport type {\n BoundNode,\n NodeShape,\n DefaultNodeShape,\n WcBindableDescriptor,\n WcBindableProperty,\n EventStreamOptions,\n} from \"./bindNode.js\";\n\nexport const Fragment = Symbol(\"signals.Fragment\");\n\nexport type Child = unknown;\nexport type Props = Record<string, unknown> | null;\n// h() always injects `children` into the props object it passes to a component, so\n// the parameter type makes that explicit (a component can declare `{ children }`).\nexport type Component = (\n props: Record<string, unknown> & { children?: Child[] },\n) => Node | Child[];\n\nfunction isReadSignal(value: unknown): value is ReadSignal<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { get?: unknown }).get === \"function\" &&\n typeof (value as { peek?: unknown }).peek === \"function\"\n );\n}\n\nexport function h(\n tag: string | typeof Fragment | Component,\n props?: Props,\n ...children: Child[]\n): Node {\n if (tag === Fragment) {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n }\n\n if (typeof tag === \"function\") {\n const result = tag({ ...(props ?? {}), children });\n return Array.isArray(result) ? wrapFragment(result) : result;\n }\n\n const el = createElement(tag);\n if (props) {\n for (const key in props) {\n bindProp(el, key, props[key]);\n }\n }\n appendChildren(el, children);\n return el;\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n// Tags created in the SVG namespace. Ambiguous names shared with HTML (`a`,\n// `title`, `script`, `style`) are intentionally EXCLUDED so ordinary HTML usage is\n// not broken; an SVG `<a>` / `<title>` must be created in an explicitly-namespaced\n// way by the caller. SVG DOM props are largely read-only, so `setProp`'s\n// settable-property check routes SVG attributes through `setAttribute` for free.\nconst SVG_TAGS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\",\n \"text\", \"tspan\", \"defs\", \"use\", \"symbol\", \"marker\", \"linearGradient\",\n \"radialGradient\", \"stop\", \"clipPath\", \"mask\", \"pattern\", \"image\", \"foreignObject\",\n]);\n\nfunction createElement(tag: string): Element {\n return SVG_TAGS.has(tag)\n ? document.createElementNS(SVG_NS, tag)\n : document.createElement(tag);\n}\n\n/** Append `child` into `container`, resolving fragments/arrays. */\nexport function render(child: Child, container: Node): Node {\n appendChild(container, child);\n return container;\n}\n\nfunction wrapFragment(children: Child[]): DocumentFragment {\n const frag = document.createDocumentFragment();\n appendChildren(frag, children);\n return frag;\n}\n\n// --- props ------------------------------------------------------------------\n\n// Attribute names whose corresponding JS DOM property differs. `class` is handled\n// separately (it has reactive-falsy semantics in setProp), so it is not listed here.\nconst ATTR_TO_PROP: Record<string, string> = {\n for: \"htmlFor\",\n tabindex: \"tabIndex\",\n colspan: \"colSpan\",\n rowspan: \"rowSpan\",\n readonly: \"readOnly\",\n maxlength: \"maxLength\",\n minlength: \"minLength\",\n contenteditable: \"contentEditable\",\n};\n\n// True only if `key` resolves to a WRITABLE property on the element or its\n// prototype chain (a data property with `writable !== false`, or an accessor with a\n// setter). `key in el` is not enough: it also matches read-only members like\n// `firstChild` / `childNodes`, whose assignment throws in strict mode. The walk\n// starts at `el` itself so own instance fields (e.g. a custom element's properties)\n// are still matched, exactly as the previous `key in el` did — just without the\n// read-only false positives.\n//\n// MEMOIZATION: the prototype-chain walk runs on every bindProp/setProp. The result\n// depends only on the element's PROTOTYPE (its class) and the key, since DOM props\n// live on the prototype — not on per-instance own fields, which this library never\n// adds dynamically per element. So cache by `(prototype, key)`: a WeakMap keyed by\n// prototype (no leak — entries die with the class) holding a Map of key→result.\nconst settableCache = new WeakMap<object, Map<string, boolean>>();\n\nfunction computeSettable(el: Element, key: string): boolean {\n let obj: object | null = el;\n while (obj !== null) {\n const desc = Object.getOwnPropertyDescriptor(obj, key);\n if (desc) {\n return \"set\" in desc ? typeof desc.set === \"function\" : desc.writable !== false;\n }\n obj = Object.getPrototypeOf(obj);\n }\n return false;\n}\n\nfunction isSettableProperty(el: Element, key: string): boolean {\n // A real Element always has a prototype (HTMLElement.prototype → … → Object), so\n // `getPrototypeOf` is non-null here; use it as the cache key.\n const proto = Object.getPrototypeOf(el) as object;\n let byKey = settableCache.get(proto);\n if (byKey === undefined) {\n byKey = new Map<string, boolean>();\n settableCache.set(proto, byKey);\n }\n let result = byKey.get(key);\n if (result === undefined) {\n result = computeSettable(el, key);\n byKey.set(key, result);\n }\n return result;\n}\n\nfunction bindProp(el: Element, key: string, value: unknown): void {\n // Event handlers (`onClick` → \"click\") are special-cased BEFORE the reactive\n // check: a function here is the listener, not a thunk to track.\n if (/^on[A-Z]/.test(key) && typeof value === \"function\") {\n const type = key.slice(2).toLowerCase();\n const listener = value as EventListener;\n el.addEventListener(type, listener);\n // Remove the listener when the owning scope is torn down (e.g. a dynamic\n // child that rebuilds this subtree), so handlers don't accumulate.\n onCleanup(() => el.removeEventListener(type, listener));\n return;\n }\n\n if (typeof value === \"function\") {\n effect(() => setProp(el, key, (value as () => unknown)()));\n return;\n }\n\n if (isReadSignal(value)) {\n effect(() => setProp(el, key, value.get()));\n return;\n }\n\n setProp(el, key, value);\n}\n\nfunction setProp(el: Element, key: string, value: unknown): void {\n if (key === \"style\") {\n setStyle(el as HTMLElement, value);\n return;\n }\n if (key === \"class\" || key === \"className\") {\n // Set the `class` ATTRIBUTE, not the `className` property. On an SVGElement\n // `className` is a read-only `SVGAnimatedString`, so assigning it throws in\n // strict mode (ESM is always strict) — `setAttribute(\"class\", …)` works for both\n // HTML and SVG. Treat false like null → empty class (consistent with the\n // attribute path's false-removes-it rule), so `() => cond && \"active\"` yields \"\"\n // (not \"false\") when the condition is falsy.\n // STRING-ONLY: a non-null/non-false value is coerced via String(value). Array\n // (`[\"a\", \"b\"]`) and object (`{ active: true }`) class forms are NOT supported —\n // they would stringify to \"a,b\" / \"[object Object]\". Compose the class string in\n // the binding itself (e.g. `() => [a, b].join(\" \")`) and pass a string. This keeps\n // the core free of a class-merging convention.\n el.setAttribute(\"class\", value == null || value === false ? \"\" : String(value));\n return;\n }\n // Remap the handful of attribute names whose JS property differs, so `for` /\n // `tabindex` / `colspan` etc. reach the right property instead of falling through\n // to setAttribute (which works for some but not e.g. `htmlFor`).\n const propKey = ATTR_TO_PROP[key] ?? key;\n if (isSettableProperty(el, propKey)) {\n // Known, WRITABLE DOM property (value, checked, disabled, id, htmlFor, ...).\n // The settability check excludes read-only members (firstChild, childNodes, …)\n // that `key in el` would wrongly accept — assigning to those throws in strict\n // mode; we fall through to the attribute path for them instead.\n //\n // NORMALIZATION: null/undefined are coerced to \"\" before assignment. Without\n // this, a STRING prop (id/title/value/src) given a reactive null/undefined\n // lands as the literal \"null\"/\"undefined\" (e.g. img.src=\"null\" fires a real\n // request) — a correctness footgun. \"\" clears the prop instead. Safe for\n // non-string props too: boolean props coerce \"\"→false (same as null), numeric\n // props coerce \"\"→0 (same as null). We do NOT normalize `false`:\n // `el.disabled = false` is the intended boolean clear.\n (el as unknown as Record<string, unknown>)[propKey] = value == null ? \"\" : value;\n return;\n }\n if (value == null || value === false) {\n el.removeAttribute(key);\n return;\n }\n if (value === true) {\n el.setAttribute(key, \"\");\n return;\n }\n el.setAttribute(key, String(value));\n}\n\nfunction setStyle(el: HTMLElement, value: unknown): void {\n if (value == null) {\n el.removeAttribute(\"style\");\n return;\n }\n if (typeof value === \"string\") {\n el.style.cssText = value;\n return;\n }\n // Object form: the object fully describes the style. Reset first so keys present\n // in a previous run but absent now are removed — otherwise a reactive style that\n // drops a key (e.g. {color,fontWeight} → {color}) would leave the stale property\n // applied. The object is the source of truth, so wiping cssText is correct here.\n el.style.cssText = \"\";\n const style = el.style as CSSStyleDeclaration & Record<string, string>;\n const obj = value as Record<string, string>;\n for (const k in obj) {\n // A key with a hyphen is either kebab-case (`font-weight`) or a CSS custom\n // property (`--accent`). Neither works via property assignment (`style[k]` would\n // just set an inert expando), so route them through setProperty. camelCase keys\n // (`fontWeight`) keep the faster property path.\n if (k.includes(\"-\")) {\n style.setProperty(k, obj[k]);\n } else {\n style[k] = obj[k];\n }\n }\n}\n\n// --- children ---------------------------------------------------------------\n\nfunction appendChildren(parent: Node, children: Child[]): void {\n for (const child of children) {\n appendChild(parent, child);\n }\n}\n\nfunction appendChild(parent: Node, child: Child): void {\n if (child == null || typeof child === \"boolean\") {\n return; // null / undefined / boolean render nothing\n }\n if (Array.isArray(child)) {\n for (const c of child) {\n appendChild(parent, c);\n }\n return;\n }\n if (isListView(child)) {\n // A keyed list (For / Index): it manages its own anchored region with in-place\n // reconciliation, so it does NOT go through the wholesale insertReactive path.\n child.mount(parent);\n return;\n }\n if (child instanceof Node) {\n parent.appendChild(child);\n return;\n }\n if (typeof child === \"function\") {\n insertReactive(parent, child as () => unknown);\n return;\n }\n if (isReadSignal(child)) {\n insertReactive(parent, () => child.get());\n return;\n }\n parent.appendChild(document.createTextNode(String(child)));\n}\n\n/**\n * A reactive insertion point. An anchor comment marks the position; on each run\n * the previous nodes are removed and the freshly-resolved nodes inserted before\n * the anchor. Using `anchor.parentNode` (not the original `parent`) keeps it\n * correct after the subtree is moved/mounted elsewhere.\n *\n * PRECONDITION: the Nodes returned by `accessor` are owned by this insertion point\n * — do not move them to another parent externally. On the next run they are\n * removed from wherever they currently are (`node.parentNode?.removeChild`), so an\n * externally-moved node would be yanked out of its new home without warning.\n *\n * OWNERSHIP: the `effect` below is owned by the enclosing reactive scope at call\n * time (the `currentOwner`). Used under `createRoot` / `SignalsElement` (the module\n * header's mount contract) it is disposed on teardown. Calling `h`/`render` with a\n * reactive child OUTSIDE any owner (no `createRoot`/`SignalsElement`) leaves this\n * effect un-owned and therefore never cleaned up — by design, per that contract.\n */\nfunction insertReactive(parent: Node, accessor: () => unknown): void {\n if (isDev() && !hasOwner()) {\n // A reactive child inserted with no enclosing owner: the effect below is never\n // disposed (the module header documents this as by-design, but it is a frequent\n // accidental leak). Warn once in dev so the un-owned mount is visible.\n warnDev(\n \"UNOWNED_INSERT\",\n \"\",\n \"reactive child inserted with no owner — its update effect will never be \" +\n \"disposed and may leak. Mount under createRoot / SignalsElement.\",\n );\n }\n const anchor = document.createComment(\"\");\n parent.appendChild(anchor);\n let current: Node[] = [];\n\n effect(() => {\n const value = accessor();\n // FAST PATH: a plain text result that replaces a plain text result. The common\n // reactive child is a string/number thunk (`() => \\`count: ${n.get()}\\``); the\n // wholesale path would remove the old Text node, allocate a new one, and re-insert\n // it on every change. When BOTH the previous and next renders are a single Text\n // node, mutate the existing node's `data` in place instead — no allocation, no\n // remove/insert, and the same DOM node identity is preserved across updates.\n if ((typeof value === \"string\" || typeof value === \"number\") && current.length === 1) {\n const node = current[0];\n if (node.nodeType === 3 /* TEXT_NODE */) {\n (node as Text).data = String(value);\n return;\n }\n }\n const next = toNodes(value);\n for (const node of current) {\n node.parentNode?.removeChild(node);\n }\n const host = anchor.parentNode;\n if (host) {\n for (const node of next) {\n host.insertBefore(node, anchor);\n }\n }\n current = next;\n });\n\n // On teardown, drop the references to the inserted Nodes. The disposed effect's\n // closure still captures `current`; if anything retains the effect after disposal\n // (e.g. a parent owner kept alive longer than the subtree), those Nodes would be\n // pinned via that closure even though they have left the DOM. Clearing the array\n // lets them be GC'd as soon as the enclosing owner tears this insertion point down.\n onCleanup(() => {\n current = [];\n });\n}\n\n// --- keyed lists: For / Index (migration-plan §9-3) --------------------------\n//\n// `insertReactive` rebuilds its whole subtree on every change. For lists that is\n// wasteful (and drops per-row state). `For` / `Index` instead keep a stable DOM row\n// per item and reconcile in place. Each row is built under its OWN `createRoot`, so\n// removing a row disposes exactly that row's effects/resources/listeners — the owner\n// tree (§8 (d)) is what makes this leak-free. The reconcile runs in a single\n// `effect` owned by the enclosing scope; an `onCleanup` disposes surviving rows when\n// that scope (e.g. the component) tears down.\n//\n// CONTRACT: `each` must return a SINGLE Node (one row = one node). Keys (For) must\n// be unique. `For` keys by value identity (=== / explicit `key`) and passes the\n// index as an accessor (it changes on move); `Index` keys by position and passes the\n// item as an accessor (the value at a slot changes, the slot does not).\n\nexport type ListAccessor<T> = ReadSignal<readonly T[]> | (() => readonly T[]);\nexport type ForEach<T> = (item: T, index: () => number) => Node;\nexport type IndexEach<T> = (item: () => T, index: number) => Node;\n\n/**\n * The return type of {@link For} / {@link Index}: a keyed list that owns an anchored\n * region and reconciles rows in place. Exported (D4) so consumers can annotate\n * helpers that build or pass around lists. `mount` is called by `h`/`render` when the\n * list is used as a child; `__wcsList` is the brand `appendChild` checks.\n */\nexport interface ListView {\n readonly __wcsList: true;\n mount(parent: Node): void;\n}\n\nfunction isListView(value: unknown): value is ListView {\n return typeof value === \"object\" && value !== null && (value as ListView).__wcsList === true;\n}\n\nfunction readList<T>(list: ListAccessor<T>): () => readonly T[] {\n return isReadSignal(list) ? () => (list as ReadSignal<readonly T[]>).get() : (list as () => readonly T[]);\n}\n\nexport interface ForOptions<T> {\n /** Derive a unique key per item. Default: the item value itself (identity). */\n key?: (item: T, index: number) => unknown;\n}\n\n// --- LIS-based DOM reorder ---------------------------------------------------\n//\n// `reconcileOrder` brings the live DOM under `host` (the contiguous region ending\n// at `anchor`) into `order` — the desired final node sequence — using the FEWEST\n// `insertBefore` moves, while producing EXACTLY the order a naive full re-place\n// would. The naive approach (walk and insert every out-of-place node) does up to\n// O(n) DOM moves on a full reverse or a head insert; here we instead keep the\n// largest set of reused rows that are ALREADY in the right relative order, and\n// move only the others (Solid's reconcileArrays / udomdiff idea).\n//\n// HOW: `prevOrder` is the node sequence the previous run left in the DOM. For each\n// node in the new `order`, a reused row maps to its index in `prevOrder`; a freshly\n// created row has no previous position. The longest increasing subsequence (LIS)\n// of those previous indices marks the reused rows that need NOT move (their pairwise\n// relative order is already correct). Every other node — fresh ones, and reused\n// ones outside the LIS — is inserted before its already-correct successor, walking\n// back-to-front so the \"successor\" reference is always a settled node or the anchor.\n\n/**\n * Indices into `arr` (with value -1 meaning \"no previous position\") whose values\n * form a longest strictly-increasing subsequence. Entries equal to -1 are treated\n * as never part of the subsequence (a fresh node always moves). Classic\n * patience-sorting LIS in O(n log n); returns the chosen indices in ascending order.\n */\nfunction longestIncreasingSubsequence(arr: number[]): number[] {\n const n = arr.length;\n // `tails[k]` = index (into arr) of the smallest tail of an increasing\n // subsequence of length k+1. `prev[i]` = predecessor index, to rebuild the chain.\n const tails: number[] = [];\n const prev: number[] = new Array(n).fill(-1);\n for (let i = 0; i < n; i++) {\n const value = arr[i];\n if (value < 0) {\n continue; // fresh node: not eligible for the stable subsequence\n }\n // Binary search for the first tail whose value is >= this value, and replace it\n // (or extend the tails when this value beats every tail).\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (arr[tails[mid]] < value) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n if (lo > 0) {\n prev[i] = tails[lo - 1];\n }\n tails[lo] = i;\n }\n // Rebuild the index chain from the longest tail backwards.\n const result: number[] = [];\n let k = tails.length > 0 ? tails[tails.length - 1] : -1;\n while (k >= 0) {\n result.push(k);\n k = prev[k];\n }\n result.reverse();\n return result;\n}\n\nfunction reconcileOrder(\n host: Node,\n anchor: Node,\n order: Node[],\n prevOrder: Node[],\n): void {\n const n = order.length;\n if (n === 0) {\n return; // nothing to place (removals already happened)\n }\n\n // Map each previous node to its previous position, so a node in `order` can look\n // up where it used to be. A node absent from this map is FRESH (created this run,\n // or the first run where prevOrder is empty) and is encoded as -1 — it always moves.\n const prevIndex = new Map<Node, number>();\n for (let i = 0; i < prevOrder.length; i++) {\n prevIndex.set(prevOrder[i], i);\n }\n\n // previous-position sequence aligned to the new order. -1 marks a fresh node.\n const seq: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const p = prevIndex.get(order[i]);\n seq[i] = p === undefined ? -1 : p;\n }\n\n // Rows whose relative order is already correct: leave them in place, move the rest.\n const lis = longestIncreasingSubsequence(seq);\n let lisPtr = lis.length - 1;\n\n // Walk back-to-front. `ref` is the node that must follow the one being placed; it\n // starts at the anchor (the region's tail) and becomes each placed node. A node in\n // the LIS is the maximal already-correctly-ordered set, so it is left untouched\n // (only adopted as the new `ref`). Every OTHER node is, by construction, out of\n // position relative to its settled successor and is inserted before `ref` — no\n // \"is it already in place?\" guard is needed (it never is, unlike the old\n // full-walk reconciler which visited correctly-placed nodes too).\n let ref: Node = anchor;\n for (let i = n - 1; i >= 0; i--) {\n const node = order[i];\n if (lisPtr >= 0 && lis[lisPtr] === i) {\n lisPtr--; // stable: do not move\n } else {\n host.insertBefore(node, ref);\n }\n ref = node;\n }\n}\n\n// Dev-only key sanity check (no effect in production — guarded by `isDev()` at the\n// call site so this is never reached when dev is off). Flags the silent-failure key\n// shapes: a nullish key (NaN / null / undefined collide under SameValueZero, so two\n// such items map to one row and a row is silently dropped), and — when no explicit\n// `key` was given — a non-primitive item used as its own identity key (every render\n// gets a fresh object reference, so the row is rebuilt instead of reused, silently\n// dropping per-row state). Warns once per distinct shape (deduped in warnDev).\nfunction checkKeyDev(key: unknown, item: unknown, hasExplicitKey: boolean): void {\n if (key == null || (typeof key === \"number\" && Number.isNaN(key))) {\n warnDev(\n \"NULLISH_KEY\",\n String(key),\n \"For: a key is null/undefined/NaN. Such keys collide under SameValueZero, \" +\n \"so rows silently merge/drop. Provide a stable unique `key`.\",\n { key },\n );\n return;\n }\n if (!hasExplicitKey && (typeof key === \"object\" || typeof key === \"function\")) {\n warnDev(\n \"NON_PRIMITIVE_KEY\",\n typeof key,\n \"For: a non-primitive item is used as its own key (no `key` option given). \" +\n \"Object identity changes across renders, so every row is rebuilt and per-row \" +\n \"state is lost. Pass `{ key: item => item.id }`.\",\n { item },\n );\n }\n}\n\nexport function For<T>(list: ListAccessor<T>, each: ForEach<T>, options?: ForOptions<T>): ListView {\n const read = readList(list);\n const keyOf = options?.key;\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"for\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n idx: WriteSignal<number>;\n }\n let rows = new Map<unknown, Row>();\n // The node order placed by the previous reconcile run. Empty on first run.\n // Used to find which reused rows already sit in increasing relative order so\n // only the rest are moved (LIS reorder, see reconcileOrder).\n let prevOrder: Node[] = [];\n\n const make = (item: T, i: number): Row => {\n const idx = signal(i);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(item, () => idx.get());\n return d;\n });\n return { node, dispose, idx };\n };\n\n effect(() => {\n const items = read() ?? [];\n\n // Key-uniqueness PRE-PASS (no side effects): throwing here, before any row is\n // created or moved, keeps a duplicate-key error from leaving half-built rows\n // orphaned (make() runs createRoot) and the DOM mid-reorder. Keys are reused\n // below so keyOf runs once per item.\n const keys: unknown[] = [];\n const seen = new Set<unknown>();\n const dev = isDev();\n for (let i = 0; i < items.length; i++) {\n const k = keyOf ? keyOf(items[i], i) : items[i];\n if (dev) {\n checkKeyDev(k, items[i], keyOf !== undefined);\n }\n if (seen.has(k)) {\n if (dev) {\n // The throw below still halts (production behaviour unchanged); the warn\n // adds the offending key + a pointer to the cause so the silent\n // \"updates stopped\" symptom is diagnosable.\n warnDev(\n \"DUPLICATE_KEY\",\n String(k),\n `For: duplicate key \"${String(k)}\" at index ${i} — keys must be unique. ` +\n \"Rendering throws and the list stops updating until keys are fixed.\",\n { key: k, index: i },\n );\n }\n throw new Error(`For: duplicate key \"${String(k)}\" — keys must be unique.`);\n }\n seen.add(k);\n keys.push(k);\n }\n\n const next = new Map<unknown, Row>();\n const order: Node[] = [];\n\n // Rows freshly created in THIS run (not reused from `rows`). If a later\n // `make()` — i.e. a user `each` — throws mid-loop, the rows already built\n // here are owned by their own detached `createRoot` and are not yet tracked\n // in any surviving map, so they would leak. Dispose them before re-throwing,\n // leaving the old `rows` map untouched (it is recoverable on the next run).\n const fresh: Row[] = [];\n try {\n for (let i = 0; i < items.length; i++) {\n const k = keys[i];\n let row = rows.get(k);\n if (row) {\n if (row.idx.peek() !== i) {\n row.idx.set(i); // position changed — refresh the index accessor\n }\n } else {\n row = make(items[i], i);\n fresh.push(row);\n }\n next.set(k, row);\n order.push(row.node);\n }\n } catch (err) {\n for (const row of fresh) {\n row.dispose();\n }\n throw err;\n }\n\n // Dispose rows whose key vanished. `remove()` no-ops if already detached.\n for (const [k, row] of rows) {\n if (!next.has(k)) {\n (row.node as ChildNode).remove();\n row.dispose();\n }\n }\n\n // Reorder relative to the LIVE parent (`anchor.parentNode`, not the mount\n // arg) so the region stays correct after being moved (e.g. built inside a\n // Fragment, then appended elsewhere). `host` is null only if the anchor was\n // detached without disposing this scope (a misuse) — then there is nothing\n // to place into.\n const host = anchor.parentNode;\n if (host) {\n reconcileOrder(host, anchor, order, prevOrder);\n }\n\n // Snapshot this run's final order so the NEXT run's reconcile can detect\n // which rows kept their relative position (the LIS basis below). Capturing\n // the array we just placed avoids re-deriving it from the map.\n prevOrder = order;\n rows = next;\n });\n\n onCleanup(() => {\n for (const row of rows.values()) {\n row.dispose();\n }\n rows.clear();\n });\n },\n };\n}\n\nexport function Index<T>(list: ListAccessor<T>, each: IndexEach<T>): ListView {\n const read = readList(list);\n return {\n __wcsList: true,\n mount(parent: Node): void {\n const anchor = document.createComment(\"index\");\n parent.appendChild(anchor);\n\n interface Row {\n node: Node;\n dispose: () => void;\n item: WriteSignal<T>;\n }\n const rows: Row[] = [];\n\n effect(() => {\n const items = read() ?? [];\n // Live parent (see `For`), null only if the anchor was detached undisposed.\n const host = anchor.parentNode;\n\n for (let i = 0; i < items.length; i++) {\n if (i < rows.length) {\n // Slot reused: just push the new value into the row's item signal. The\n // signal's equality guard skips the update when the value is unchanged.\n rows[i].item.set(items[i]);\n } else {\n const item = signal(items[i]);\n let node!: Node;\n const dispose = createRoot((d) => {\n node = each(() => item.get(), i);\n return d;\n });\n rows.push({ node, dispose, item });\n // Positions never move for index keying, so append at the tail (before\n // the anchor) in order. ORDERING CONTRACT (shared with For and the other\n // anchored insertions): the list owns the contiguous region ENDING at its\n // anchor comment. New rows go immediately before the anchor, so the list's\n // own rows always stay correctly ordered and grouped, and static siblings\n // before the anchor (or another list with its own anchor) are never\n // disturbed. Do NOT splice unrelated nodes into the middle of this region.\n host?.insertBefore(node, anchor);\n }\n }\n\n // Trailing slots that no longer exist: dispose and drop.\n if (items.length < rows.length) {\n for (let i = items.length; i < rows.length; i++) {\n (rows[i].node as ChildNode).remove();\n rows[i].dispose();\n }\n rows.length = items.length;\n }\n });\n\n onCleanup(() => {\n for (const row of rows) {\n row.dispose();\n }\n rows.length = 0;\n });\n },\n };\n}\n\n// --- custom element lifecycle (docs §8 (e)) ---------------------------------\n//\n// The exit point for ownership: a custom element that mounts a signals view under\n// `createRoot` on connect and disposes that root on disconnect. This wires the\n// reactive ownership tree to the real DOM lifecycle — every effect, resource and\n// listener created in `render()` is torn down when the element leaves the DOM, and\n// rebuilt fresh on reconnect. Subclasses only implement `render()`.\n//\n// SCOPE (v1 intentional constraints — drive these reactively, not via this base):\n// - No attribute reactivity. There is no `attributeChangedCallback`/\n// `observedAttributes` wiring: this base does NOT turn HTML attributes into\n// signals. Feed reactive inputs as signals/props from the code that constructs\n// the view (or have a subclass map attributes to signals itself).\n// - Shadow DOM is opt-in and subclass-owned. The default mount point is light DOM\n// (`this`); a subclass that wants encapsulation overrides `getMountPoint()` to\n// return a shadow root it created (e.g. `this.attachShadow(...)` in its\n// constructor). This base never calls attachShadow implicitly.\n// - Mount/unmount only: render() runs once per connect and the whole subtree is\n// disposed on disconnect — there is no partial/incremental re-render hook here\n// (fine-grained updates come from the signals wired inside render()).\n\n// TYPE-ONLY shape of the lifecycle base. `declare abstract class` emits NO runtime\n// code (so it does not reference `HTMLElement` at module-evaluation time — the whole\n// point of the lazy factory below), but it gives the exported `SignalsElement` value\n// and `createSignalsElement()`'s return a precise type that preserves the original\n// contract: `render` is `protected abstract` (a subclass MUST implement it and may\n// only reach it from within), and `getMountPoint` is `protected` (overridable). This\n// is the same surface the previous concrete `abstract class SignalsElement` exposed.\n// (Used only via `typeof` below; the lint rule does not see that as a value use.)\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ndeclare abstract class SignalsElementType extends HTMLElement {\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node;\n connectedCallback(): void;\n disconnectedCallback(): void;\n}\n\n/**\n * The lifecycle base contract: the abstract constructor type of the `SignalsElement`\n * base. Abstract, so `new SignalsElement()` is rejected (the base has an unimplemented\n * `render`) while `class X extends SignalsElement` is allowed. Returned by\n * {@link createSignalsElement} and the type of the {@link SignalsElement} value.\n */\nexport type SignalsElementClass = typeof SignalsElementType;\n\n// Memoized base class. Built lazily on first access so the `./dom` module can be\n// EVALUATED in a non-DOM environment (SSR pre-pass, a worker without a DOM shim)\n// without a top-level `class … extends HTMLElement` blowing up with\n// `ReferenceError: HTMLElement is not defined`. The class body is only constructed\n// when the consumer actually reaches for the base — at which point a DOM is required\n// and its absence yields a clear, actionable error instead of a raw ReferenceError.\nlet cachedBase: SignalsElementClass | null = null;\n\n/**\n * Build (once, memoized) the `SignalsElement` lifecycle base class. Resolves\n * `HTMLElement` at CALL TIME, so importing `@wcstack/signals/dom` no longer requires\n * a DOM at module-evaluation time — only *calling* this (or subclassing\n * {@link SignalsElement}) does.\n *\n * Contract:\n * - The `.` entry (`@wcstack/signals`) is non-DOM: it evaluates and runs in SSR,\n * Node, and Web Workers with no DOM globals.\n * - The `./dom` entry (`@wcstack/signals/dom`) may now also be *evaluated* without a\n * DOM (so an SSR pre-pass that imports it for the headless re-exports does not\n * crash). The DOM-touching surface — `h`/`render`/`For`/`Index` and this base —\n * still requires DOM globals when actually used.\n *\n * @throws a clear `Error` (not a raw `ReferenceError`) when no `HTMLElement` global is\n * present, naming the offending entry so the failure is self-explanatory.\n */\nexport function createSignalsElement(): SignalsElementClass {\n if (cachedBase !== null) {\n return cachedBase;\n }\n if (typeof HTMLElement === \"undefined\") {\n throw new Error(\n \"@wcstack/signals/dom: SignalsElement requires a DOM (HTMLElement is not defined). \" +\n \"The `./dom` entry's element/render surface is browser-only; in SSR/Node/worker \" +\n \"code import the headless core from `@wcstack/signals` instead, or inject a DOM \" +\n \"(e.g. happy-dom) before constructing custom elements.\",\n );\n }\n\n abstract class SignalsElementBase extends HTMLElement {\n private _dispose: (() => void) | null = null;\n\n /** Build the view with `h` + signals. Runs inside an ownership root. */\n protected abstract render(): Node;\n\n /** Mount target. Override to return a shadow root; default is light DOM. */\n protected getMountPoint(): Node {\n return this;\n }\n\n connectedCallback(): void {\n if (this._dispose !== null) {\n return; // already mounted (defensive against a redundant connect)\n }\n const mount = this.getMountPoint();\n // If render() throws, createRoot disposes any effects it built before the throw,\n // so nothing leaks; _dispose stays null (the element is simply not mounted) and\n // a later disconnectedCallback safely no-ops. The error propagates to the caller.\n this._dispose = createRoot((dispose) => {\n mount.appendChild(this.render());\n return dispose;\n });\n }\n\n disconnectedCallback(): void {\n if (this._dispose === null) {\n return; // not mounted\n }\n this._dispose();\n this._dispose = null;\n const mount = this.getMountPoint();\n while (mount.firstChild) {\n mount.removeChild(mount.firstChild);\n }\n }\n }\n\n cachedBase = SignalsElementBase as unknown as SignalsElementClass;\n return cachedBase;\n}\n\n// `SignalsElement` is the ergonomic name to `extends`. It is a lazily-resolved alias\n// for the class built by `createSignalsElement()`: a Proxy that forwards construct /\n// get / has / getPrototypeOf to the real (memoized) base, building it on first touch.\n// This keeps `class X extends SignalsElement { … }` working exactly as before WHILE\n// deferring the `HTMLElement` reference to subclass-definition time (in a real DOM),\n// instead of `./dom` module-evaluation time (which may be a non-DOM SSR pre-pass).\n//\n// BREAKING note: the value is now a Proxy, not the class object literal. Subclassing,\n// `instanceof`, and static/prototype access all still work; a consumer that relied on\n// `SignalsElement` being a *frozen* concrete class reference (uncommon) should call\n// `createSignalsElement()` to obtain the real class.\n// The Proxy target is a never-called placeholder (every operation is intercepted by a\n// trap below); it only needs to be constructable/callable so `new` / `extends` and the\n// `apply` trap engage. It is intentionally a no-op and never executed.\n/* v8 ignore next */\nconst signalsElementTarget = function (): void {};\nexport const SignalsElement: SignalsElementClass = new Proxy(signalsElementTarget as unknown as SignalsElementClass, {\n construct(_target, args, newTarget): object {\n return Reflect.construct(createSignalsElement(), args, newTarget);\n },\n get(_target, prop, receiver): unknown {\n return Reflect.get(createSignalsElement(), prop, receiver);\n },\n has(_target, prop): boolean {\n return Reflect.has(createSignalsElement(), prop);\n },\n apply(): never {\n throw new TypeError(\"SignalsElement is a class and cannot be invoked without `new`/`extends`.\");\n },\n getPrototypeOf(): object | null {\n return Reflect.getPrototypeOf(createSignalsElement());\n },\n});\n\nfunction toNodes(value: unknown): Node[] {\n const out: Node[] = [];\n const visit = (v: unknown): void => {\n if (v == null || typeof v === \"boolean\") {\n return;\n }\n if (Array.isArray(v)) {\n v.forEach(visit);\n return;\n }\n if (v instanceof Node) {\n out.push(v);\n return;\n }\n out.push(document.createTextNode(String(v)));\n };\n visit(value);\n return out;\n}\n"],"names":["Fragment","Symbol","isReadSignal","value","get","peek","h","tag","props","children","frag","document","createDocumentFragment","appendChildren","result","Array","isArray","wrapFragment","el","SVG_TAGS","has","createElementNS","SVG_NS","createElement","key","bindProp","Set","render","child","container","appendChild","ATTR_TO_PROP","for","tabindex","colspan","rowspan","readonly","maxlength","minlength","contenteditable","settableCache","WeakMap","isSettableProperty","proto","Object","getPrototypeOf","byKey","undefined","Map","set","obj","desc","getOwnPropertyDescriptor","writable","computeSettable","test","type","slice","toLowerCase","listener","addEventListener","onCleanup","removeEventListener","effect","setProp","removeAttribute","style","cssText","k","includes","setProperty","setStyle","setAttribute","String","propKey","parent","c","__wcsList","Node","insertReactive","createTextNode","mount","accessor","isDev","hasOwner","warnDev","anchor","createComment","current","length","node","nodeType","data","next","out","visit","v","forEach","push","toNodes","parentNode","removeChild","host","insertBefore","readList","list","reconcileOrder","order","prevOrder","n","prevIndex","i","seq","p","lis","arr","tails","prev","fill","lo","hi","mid","reverse","longestIncreasingSubsequence","lisPtr","ref","checkKeyDev","item","hasExplicitKey","Number","isNaN","For","each","options","read","keyOf","rows","make","idx","signal","dispose","createRoot","d","items","keys","seen","dev","index","Error","add","fresh","row","err","remove","values","clear","Index","cachedBase","createSignalsElement","HTMLElement","SignalsElementBase","_dispose","getMountPoint","this","connectedCallback","disconnectedCallback","firstChild","SignalsElement","Proxy","construct","_target","args","newTarget","Reflect","prop","receiver","apply","TypeError"],"mappings":"uQA2DaA,EAAWC,OAAO,oBAU/B,SAASC,EAAaC,GACpB,MACmB,iBAAVA,GACG,OAAVA,GAC4C,mBAApCA,EAA4BC,KACU,mBAAtCD,EAA6BE,IAEzC,CAEM,SAAUC,EACdC,EACAC,KACGC,GAEH,GAAIF,IAAQP,EAAU,CACpB,MAAMU,EAAOC,SAASC,yBAEtB,OADAC,EAAeH,EAAMD,GACdC,CACT,CAEA,GAAmB,mBAARH,EAAoB,CAC7B,MAAMO,EAASP,EAAI,IAAMC,GAAS,CAAA,EAAKC,aACvC,OAAOM,MAAMC,QAAQF,GAsCzB,SAAsBL,GACpB,MAAMC,EAAOC,SAASC,yBAEtB,OADAC,EAAeH,EAAMD,GACdC,CACT,CA1CmCO,CAAaH,GAAUA,CACxD,CAEA,MAAMI,EAuBR,SAAu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,EAAsC,IAAIC,MAD1B,WAAmB,EACqE,CACnHC,UAAS,CAACC,EAASC,EAAMC,IAChBC,QAAQJ,UAAUX,IAAwBa,EAAMC,GAEzDxK,IAAG,CAACsK,EAASI,EAAMC,IACVF,QAAQzK,IAAI0J,IAAwBgB,EAAMC,GAEnD3J,IAAG,CAACsJ,EAASI,IACJD,QAAQzJ,IAAI0I,IAAwBgB,GAE7C,KAAAE,GACE,MAAM,IAAIC,UAAU,2EACtB,EACApI,eAAc,IACLgI,QAAQhI,eAAeiH"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
type Cleanup = () => void;
|
|
2
|
+
type Equals<T> = (a: T, b: T) => boolean;
|
|
3
|
+
interface ReadSignal<T> {
|
|
4
|
+
/** Read the value AND register the current observer as a dependent. */
|
|
5
|
+
get(): T;
|
|
6
|
+
/** Read the value WITHOUT tracking (no dependency edge created). */
|
|
7
|
+
peek(): T;
|
|
8
|
+
}
|
|
9
|
+
interface WriteSignal<T> extends ReadSignal<T> {
|
|
10
|
+
set(value: T): void;
|
|
11
|
+
}
|
|
12
|
+
interface EffectHandle {
|
|
13
|
+
dispose(): void;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Synchronously flush queued effects. Provided for tests and for callers that
|
|
17
|
+
* need DOM updates applied before reading the DOM back. In normal use effects
|
|
18
|
+
* settle on their own microtask.
|
|
19
|
+
*/
|
|
20
|
+
declare function flushSync(): void;
|
|
21
|
+
declare function signal<T>(initial: T, equals?: Equals<T>): WriteSignal<T>;
|
|
22
|
+
declare function computed<T>(fn: () => T, equals?: Equals<T>): ReadSignal<T>;
|
|
23
|
+
declare function effect(fn: () => Cleanup | void): EffectHandle;
|
|
24
|
+
/**
|
|
25
|
+
* Run `fn` inside a fresh ownership scope and return its result. Every effect (or
|
|
26
|
+
* nested cleanup) created during `fn` — directly or transitively — is owned by
|
|
27
|
+
* this root; calling the `dispose` passed to `fn` tears them all down.
|
|
28
|
+
*
|
|
29
|
+
* The root is detached: it is NOT auto-disposed by an enclosing owner. The caller
|
|
30
|
+
* holds `dispose` (e.g. a custom element disposes it in disconnectedCallback).
|
|
31
|
+
*
|
|
32
|
+
* If `fn` throws, any effects/cleanups it created BEFORE the throw are disposed
|
|
33
|
+
* before the error propagates — a caller that never received `dispose` (because the
|
|
34
|
+
* call threw) cannot leak the half-built scope.
|
|
35
|
+
*/
|
|
36
|
+
declare function createRoot<T>(fn: (dispose: () => void) => T): T;
|
|
37
|
+
/**
|
|
38
|
+
* Register a teardown callback with the current owner. Runs when the owning effect
|
|
39
|
+
* re-runs or is disposed, or when the enclosing root is disposed. A no-op when
|
|
40
|
+
* there is no current owner.
|
|
41
|
+
*/
|
|
42
|
+
declare function onCleanup(fn: () => void): void;
|
|
43
|
+
|
|
44
|
+
interface ResourceState<T> {
|
|
45
|
+
value: ReadSignal<T | undefined>;
|
|
46
|
+
loading: ReadSignal<boolean>;
|
|
47
|
+
/** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */
|
|
48
|
+
error: ReadSignal<unknown>;
|
|
49
|
+
/** Abort any in-flight request and stop reacting to `args` changes. */
|
|
50
|
+
dispose(): void;
|
|
51
|
+
}
|
|
52
|
+
interface ResourceOptions<T, A> {
|
|
53
|
+
/** Reactive inputs. Reading signals here wires restart-on-change. */
|
|
54
|
+
args?: () => A;
|
|
55
|
+
/** Seed value before the first resolution. */
|
|
56
|
+
initial?: T;
|
|
57
|
+
}
|
|
58
|
+
type ResourceSource<T, A> = (args: A, signal: AbortSignal) => Promise<T> | T;
|
|
59
|
+
declare function resource<T, A = void>(source: ResourceSource<T, A>, options?: ResourceOptions<T, A>): ResourceState<T>;
|
|
60
|
+
|
|
61
|
+
type StreamStatus = "idle" | "active" | "done" | "error";
|
|
62
|
+
interface StreamResourceState<T> {
|
|
63
|
+
value: ReadSignal<T | undefined>;
|
|
64
|
+
status: ReadSignal<StreamStatus>;
|
|
65
|
+
/** Last error, or `null` when there is none. Initial value is `null`; a (re)start resets it to `null`. */
|
|
66
|
+
error: ReadSignal<unknown>;
|
|
67
|
+
/** Abort the in-flight stream and stop reacting to `args`. */
|
|
68
|
+
dispose(): void;
|
|
69
|
+
}
|
|
70
|
+
interface StreamResourceOptions<T, C, A> {
|
|
71
|
+
/** Reactive inputs. Reading signals here wires restart-on-change. */
|
|
72
|
+
args?: () => A;
|
|
73
|
+
/** Combine the running value with each chunk. Default: latest (replace). */
|
|
74
|
+
fold?: (acc: T | undefined, chunk: C) => T;
|
|
75
|
+
/** Seed value, and the value `value` is reset to on each (re)start. */
|
|
76
|
+
initial?: T;
|
|
77
|
+
}
|
|
78
|
+
type StreamProducer<C> = AsyncIterable<C> | ReadableStream<C>;
|
|
79
|
+
/**
|
|
80
|
+
* Produce a stream for the current `args`. The `signal` aborts on restart/dispose —
|
|
81
|
+
* the source **MUST honor it** (this is a hard contract, not a suggestion): a
|
|
82
|
+
* `ReadableStream` is fully cancelled via `reader.cancel()`, and an async generator
|
|
83
|
+
* should observe `signal` (e.g. reject/break on `signal.aborted`) so a parked `await`
|
|
84
|
+
* can unwind. On abort the adapter also calls the iterator's `return()` to run a
|
|
85
|
+
* generator's `finally`, but a generator that parks forever while ignoring `signal`
|
|
86
|
+
* cannot be force-unwound and will leak. See the module header's CONTRACT.
|
|
87
|
+
*/
|
|
88
|
+
type StreamSource<C, A> = (args: A, signal: AbortSignal) => StreamProducer<C> | Promise<StreamProducer<C>>;
|
|
89
|
+
declare function streamResource<T, C = T, A = void>(source: StreamSource<C, A>, options?: StreamResourceOptions<T, C, A>): StreamResourceState<T>;
|
|
90
|
+
|
|
91
|
+
interface WcBindableProperty<V = unknown> {
|
|
92
|
+
readonly name: string;
|
|
93
|
+
readonly event: string;
|
|
94
|
+
readonly getter?: (event: Event) => V;
|
|
95
|
+
}
|
|
96
|
+
interface WcBindableDescriptor {
|
|
97
|
+
readonly properties: readonly WcBindableProperty[];
|
|
98
|
+
readonly inputs?: readonly {
|
|
99
|
+
readonly name: string;
|
|
100
|
+
}[];
|
|
101
|
+
readonly commands?: readonly {
|
|
102
|
+
readonly name: string;
|
|
103
|
+
}[];
|
|
104
|
+
}
|
|
105
|
+
type OpenCommandMap = Record<string, (...args: any[]) => unknown>;
|
|
106
|
+
interface NodeShape {
|
|
107
|
+
/** propertyName → latest-snapshot value type (what `signals[name]` / `on(name)` carry). */
|
|
108
|
+
signals?: Record<string, unknown>;
|
|
109
|
+
/** inputName → settable value type (what `set` / `bindInput` accept). */
|
|
110
|
+
inputs?: Record<string, unknown>;
|
|
111
|
+
/** commandName → its call signature (what `command` / `bindCommand` invoke). */
|
|
112
|
+
commands?: OpenCommandMap;
|
|
113
|
+
}
|
|
114
|
+
interface DefaultNodeShape extends NodeShape {
|
|
115
|
+
signals: Record<string, unknown>;
|
|
116
|
+
inputs: Record<string, unknown>;
|
|
117
|
+
commands: OpenCommandMap;
|
|
118
|
+
}
|
|
119
|
+
type SignalsOf<S extends NodeShape> = S["signals"] extends Record<string, unknown> ? S["signals"] : Record<string, unknown>;
|
|
120
|
+
type InputsOf<S extends NodeShape> = S["inputs"] extends Record<string, unknown> ? S["inputs"] : Record<string, unknown>;
|
|
121
|
+
type CommandsOf<S extends NodeShape> = S["commands"] extends OpenCommandMap ? S["commands"] : OpenCommandMap;
|
|
122
|
+
/** Options for `on` — how each event emission folds into the stream signal. */
|
|
123
|
+
interface EventStreamOptions<T, C> {
|
|
124
|
+
/** Combine the running value with each emission. Default: latest (replace). */
|
|
125
|
+
fold?: (acc: T | undefined, chunk: C) => T;
|
|
126
|
+
/** Seed value before the first emission. */
|
|
127
|
+
initial?: T;
|
|
128
|
+
}
|
|
129
|
+
interface BoundNode<S extends NodeShape = DefaultNodeShape> {
|
|
130
|
+
/**
|
|
131
|
+
* Output properties as read-only signals (latest value), keyed by property name and
|
|
132
|
+
* typed from the node shape: `bound.signals.value.get()` carries the declared value
|
|
133
|
+
* type (no longer `unknown`). Keys are the declared property names.
|
|
134
|
+
*/
|
|
135
|
+
readonly signals: {
|
|
136
|
+
readonly [K in keyof SignalsOf<S>]: ReadSignal<SignalsOf<S>[K]>;
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* An event-token STREAM for a declared property's event: a read signal that folds
|
|
140
|
+
* every emission (latest by default). Unlike `signals[prop]`, it updates on EVERY
|
|
141
|
+
* emit — even when the derived value is equal — because it models occurrences, not
|
|
142
|
+
* state. The chunk per emit is `getter(event)` if the property declares one, else
|
|
143
|
+
* the property's current value.
|
|
144
|
+
*
|
|
145
|
+
* With no fold the value type defaults to the property's declared snapshot type; a
|
|
146
|
+
* `fold` may reshape it (explicit `T`/`C` type args override).
|
|
147
|
+
*/
|
|
148
|
+
on<K extends keyof SignalsOf<S>>(prop: K): ReadSignal<SignalsOf<S>[K] | undefined>;
|
|
149
|
+
on<T, C = SignalsOf<S>[keyof SignalsOf<S>]>(prop: keyof SignalsOf<S>, options: EventStreamOptions<T, C>): ReadSignal<T | undefined>;
|
|
150
|
+
/** Write a declared input on the node (imperative); value type checked against the shape. */
|
|
151
|
+
set<K extends keyof InputsOf<S>>(name: K, value: InputsOf<S>[K]): void;
|
|
152
|
+
/**
|
|
153
|
+
* Reactively write a declared input from a signal: an effect mirrors `source` into
|
|
154
|
+
* `node[name]`. A same-value guard (`node[name] !== v`) skips redundant writes, so
|
|
155
|
+
* a property whose write re-dispatches an event cannot feed back into an infinite
|
|
156
|
+
* loop. Returns a disposer; the effect is also torn down by `dispose()`.
|
|
157
|
+
*/
|
|
158
|
+
bindInput<K extends keyof InputsOf<S>>(name: K, source: ReadSignal<InputsOf<S>[K]>): () => void;
|
|
159
|
+
/** Invoke a declared command on the node (imperative); args/return typed from the shape. */
|
|
160
|
+
command<K extends keyof CommandsOf<S>>(name: K, ...args: Parameters<CommandsOf<S>[K]>): ReturnType<CommandsOf<S>[K]>;
|
|
161
|
+
/**
|
|
162
|
+
* Command-token: invoke a declared command whenever `trigger` CHANGES. The initial
|
|
163
|
+
* value does not fire (subscribe-without-firing), so a command like `abort` is not
|
|
164
|
+
* triggered on mount. `mapArgs` shapes the call arguments from the trigger value
|
|
165
|
+
* (default: the value itself as a single argument). Returns a disposer; also torn
|
|
166
|
+
* down by `dispose()`.
|
|
167
|
+
*/
|
|
168
|
+
bindCommand<K extends keyof CommandsOf<S>, V = unknown>(name: K, trigger: ReadSignal<V>, mapArgs?: (value: V) => Parameters<CommandsOf<S>[K]>): () => void;
|
|
169
|
+
/**
|
|
170
|
+
* Detach all listeners/effects and make the adapter inert. After dispose the output
|
|
171
|
+
* signals/streams stop updating and `set`/`command`/`bindInput`/`bindCommand`/`on`
|
|
172
|
+
* throw (use-after-dispose). Idempotent.
|
|
173
|
+
*/
|
|
174
|
+
dispose(): void;
|
|
175
|
+
}
|
|
176
|
+
declare const DISPOSED_ERROR: unique symbol;
|
|
177
|
+
/**
|
|
178
|
+
* Error thrown when a {@link BoundNode} method is invoked after the adapter has been
|
|
179
|
+
* disposed. Every surface that mutates or subscribes — `on` / `set` / `bindInput` /
|
|
180
|
+
* `command` / `bindCommand` — throws this once `dispose()` has run, so a
|
|
181
|
+
* use-after-dispose is loud instead of silently writing/invoking on an inert adapter.
|
|
182
|
+
*
|
|
183
|
+
* Prefer {@link isDisposedError} over `instanceof` for the check: the brand survives a
|
|
184
|
+
* bundler that duplicates the class across realms, where `instanceof` would not. Use it
|
|
185
|
+
* to make teardown-order races robust — e.g. swallow a post-dispose throw while letting
|
|
186
|
+
* any other error surface:
|
|
187
|
+
*
|
|
188
|
+
* ```ts
|
|
189
|
+
* try {
|
|
190
|
+
* bound.command("abort");
|
|
191
|
+
* } catch (err) {
|
|
192
|
+
* if (!isDisposedError(err)) throw err; // expected during teardown; ignore
|
|
193
|
+
* }
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
declare class DisposedError extends Error {
|
|
197
|
+
readonly [DISPOSED_ERROR] = true;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* True if `err` is a {@link DisposedError} — i.e. a use-after-dispose error thrown by a
|
|
201
|
+
* {@link BoundNode} method after `dispose()`. Brand-based (checks a Symbol on the
|
|
202
|
+
* instance), so it stays correct even if a consumer's bundler duplicates the
|
|
203
|
+
* `DisposedError` class across module realms, where `err instanceof DisposedError`
|
|
204
|
+
* could be false.
|
|
205
|
+
*/
|
|
206
|
+
declare function isDisposedError(err: unknown): boolean;
|
|
207
|
+
/**
|
|
208
|
+
* Adapt a wc-bindable node into signals. The public `target` parameter is a plain
|
|
209
|
+
* `EventTarget` (the internal `Record<string, any>` indexing is cast away here, not
|
|
210
|
+
* leaked to callers — see {@link NodeTarget}). Pass an optional {@link NodeShape} type
|
|
211
|
+
* argument to type the result; omit it for the back-compat all-`unknown` shape.
|
|
212
|
+
*
|
|
213
|
+
* @example typed
|
|
214
|
+
* interface FetchShape extends NodeShape {
|
|
215
|
+
* signals: { value: Person[]; loading: boolean };
|
|
216
|
+
* inputs: { url: string };
|
|
217
|
+
* commands: { fetch: (url: string) => Promise<Person[]>; abort: () => void };
|
|
218
|
+
* }
|
|
219
|
+
* const bound = bindNode<FetchShape>(fetchEl, FetchCore.wcBindable);
|
|
220
|
+
* bound.signals.value.get(); // ReadSignal<Person[]>
|
|
221
|
+
* bound.set("url", "/api/people"); // string enforced
|
|
222
|
+
*/
|
|
223
|
+
declare function bindNode<S extends NodeShape = DefaultNodeShape>(target: EventTarget, descriptor?: WcBindableDescriptor): BoundNode<S>;
|
|
224
|
+
/**
|
|
225
|
+
* Build a `resource` source from a wc-bindable node, bridging the resource's
|
|
226
|
+
* AbortSignal to the node's cancel command (default `"abort"`) before delegating to
|
|
227
|
+
* `run`. This generalizes the earlier hand-wired `sig → core.abort()` bridge (docs §8
|
|
228
|
+
* (e), §5-2): wrap the result in `resource({ args })` and any node that declares an
|
|
229
|
+
* abort command gets switchMap-style cancel/restart for free — an `args` change
|
|
230
|
+
* aborts the in-flight call (firing the node's abort command, which cancels its real
|
|
231
|
+
* AbortController) and starts the next.
|
|
232
|
+
*
|
|
233
|
+
* The node's own value/loading/error stay available via `bound.signals`; `resource`
|
|
234
|
+
* here is used for the cancel/restart lifecycle, not to re-derive that triad.
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* const bound = bindNode(fetchEl);
|
|
238
|
+
* const r = resource(
|
|
239
|
+
* nodeSource(bound, (b, id) => b.command("fetch", `/api/${id}`)),
|
|
240
|
+
* { args: () => id.get() },
|
|
241
|
+
* );
|
|
242
|
+
*/
|
|
243
|
+
declare function nodeSource<T, A = void, S extends NodeShape = DefaultNodeShape>(bound: BoundNode<S>, run: (node: BoundNode<S>, args: A) => Promise<T> | T, options?: {
|
|
244
|
+
abort?: string;
|
|
245
|
+
}): ResourceSource<T, A>;
|
|
246
|
+
|
|
247
|
+
export { DisposedError, bindNode, computed, createRoot, effect, flushSync, isDisposedError, nodeSource, onCleanup, resource, signal, streamResource };
|
|
248
|
+
export type { BoundNode, Cleanup, DefaultNodeShape, EffectHandle, Equals, EventStreamOptions, NodeShape, ReadSignal, ResourceOptions, ResourceSource, ResourceState, StreamProducer, StreamResourceOptions, StreamResourceState, StreamSource, StreamStatus, WcBindableDescriptor, WcBindableProperty, WriteSignal };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { D as DisposedError, b as bindNode, c as computed, a as createRoot, e as effect, f as flushSync, i as isDisposedError, n as nodeSource, o as onCleanup, r as resource, s as signal, d as streamResource } from './core-DRLhLwcb.esm.js';
|
|
2
|
+
//# sourceMappingURL=index.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.esm.min.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|