@shadow-js/web 1.0.4 → 1.0.6

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +1 -1
  3. package/dist/dev/class-style.js +6 -1
  4. package/dist/dev/class-style.js.map +1 -1
  5. package/dist/dev/control-flow/dynamic.js +4 -4
  6. package/dist/dev/control-flow/no-hydration.js +1 -1
  7. package/dist/dev/control-flow/portal.js +1 -1
  8. package/dist/dev/element.js +2 -2
  9. package/dist/dev/extend.js +6 -6
  10. package/dist/dev/head/use-head.js +1 -1
  11. package/dist/dev/head/validate.js +1 -1
  12. package/dist/dev/hydration.js +21 -13
  13. package/dist/dev/hydration.js.map +1 -1
  14. package/dist/dev/index.d.ts +5 -5
  15. package/dist/dev/index.js +6 -6
  16. package/dist/dev/insert.js +12 -1
  17. package/dist/dev/insert.js.map +1 -1
  18. package/dist/dev/jsx/global.d.ts +2 -2
  19. package/dist/dev/jsx/html.d.ts +1 -1
  20. package/dist/dev/jsx/intrinsic.d.ts +1 -1
  21. package/dist/dev/jsx/mathml.d.ts +1 -1
  22. package/dist/dev/jsx/svg.d.ts +1 -1
  23. package/dist/dev/jsx-runtime.d.ts +3 -3
  24. package/dist/dev/render.js +22 -11
  25. package/dist/dev/render.js.map +1 -1
  26. package/dist/dev/select-value.d.ts +3 -1
  27. package/dist/dev/select-value.js +11 -1
  28. package/dist/dev/select-value.js.map +1 -1
  29. package/dist/dev/server/class-style.js +1 -1
  30. package/dist/dev/server/element.js +3 -3
  31. package/dist/dev/server/form-controls.js +1 -1
  32. package/dist/dev/server/hydration-script.js +1 -1
  33. package/dist/dev/server/portals.js +1 -1
  34. package/dist/dev/server/raw-text.js +1 -1
  35. package/dist/dev/server/render.js +2 -2
  36. package/dist/dev/server/stream.js +3 -3
  37. package/dist/dev/spread.js +12 -4
  38. package/dist/dev/spread.js.map +1 -1
  39. package/dist/dev/template.js +3 -3
  40. package/dist/prod/class-style.js +1 -1
  41. package/dist/prod/class-style.js.map +1 -1
  42. package/dist/prod/control-flow/dynamic.js +1 -1
  43. package/dist/prod/control-flow/no-hydration.js +1 -1
  44. package/dist/prod/control-flow/portal.js +1 -1
  45. package/dist/prod/element.js +1 -1
  46. package/dist/prod/events.js +1 -1
  47. package/dist/prod/events.js.map +1 -1
  48. package/dist/prod/extend.js +1 -1
  49. package/dist/prod/head/use-head.js +1 -1
  50. package/dist/prod/head/validate.js +1 -1
  51. package/dist/prod/hydration.js +1 -1
  52. package/dist/prod/hydration.js.map +1 -1
  53. package/dist/prod/index.js +1 -1
  54. package/dist/prod/insert.js +1 -1
  55. package/dist/prod/insert.js.map +1 -1
  56. package/dist/prod/render.js +1 -1
  57. package/dist/prod/render.js.map +1 -1
  58. package/dist/prod/select-value.js +1 -1
  59. package/dist/prod/select-value.js.map +1 -1
  60. package/dist/prod/server/class-style.js +1 -1
  61. package/dist/prod/server/element.js +1 -1
  62. package/dist/prod/server/form-controls.js +2 -2
  63. package/dist/prod/server/hydration-script.js +1 -1
  64. package/dist/prod/server/portals.js +1 -1
  65. package/dist/prod/server/raw-text.js +1 -1
  66. package/dist/prod/server/render.js +1 -1
  67. package/dist/prod/server/stream.js +1 -1
  68. package/dist/prod/spread.js +1 -1
  69. package/dist/prod/spread.js.map +1 -1
  70. package/dist/prod/template.js +1 -1
  71. package/dist/server/class-style.js +1 -1
  72. package/dist/server/class-style.js.map +1 -1
  73. package/dist/server/control-flow/dynamic.js +1 -1
  74. package/dist/server/control-flow/portal.js +1 -1
  75. package/dist/server/control-flow/suspense.js +1 -1
  76. package/dist/server/element.js +1 -1
  77. package/dist/server/events.js +1 -1
  78. package/dist/server/events.js.map +1 -1
  79. package/dist/server/extend.js +1 -1
  80. package/dist/server/head/use-head.js +1 -1
  81. package/dist/server/head/validate.js +1 -1
  82. package/dist/server/hydration.js +1 -1
  83. package/dist/server/hydration.js.map +1 -1
  84. package/dist/server/index.js +1 -1
  85. package/dist/server/insert.js +1 -1
  86. package/dist/server/insert.js.map +1 -1
  87. package/dist/server/render.js +1 -1
  88. package/dist/server/render.js.map +1 -1
  89. package/dist/server/select-value.js +1 -1
  90. package/dist/server/select-value.js.map +1 -1
  91. package/dist/server/server/class-style.js +1 -1
  92. package/dist/server/server/element.js +1 -1
  93. package/dist/server/server/form-controls.js +2 -2
  94. package/dist/server/server/hydration-script.js +1 -1
  95. package/dist/server/server/portals.js +1 -1
  96. package/dist/server/server/raw-text.js +1 -1
  97. package/dist/server/server/render.js +1 -1
  98. package/dist/server/server/stream.js +1 -1
  99. package/dist/server/spread.js +1 -1
  100. package/dist/server/spread.js.map +1 -1
  101. package/dist/server/template.js +1 -1
  102. package/dist/server-dev/class-style.js +6 -1
  103. package/dist/server-dev/class-style.js.map +1 -1
  104. package/dist/server-dev/control-flow/dynamic.js +1 -1
  105. package/dist/server-dev/control-flow/portal.js +1 -1
  106. package/dist/server-dev/control-flow/suspense.js +2 -2
  107. package/dist/server-dev/element.js +1 -1
  108. package/dist/server-dev/extend.js +6 -6
  109. package/dist/server-dev/head/use-head.js +1 -1
  110. package/dist/server-dev/head/validate.js +1 -1
  111. package/dist/server-dev/hydration.js +21 -13
  112. package/dist/server-dev/hydration.js.map +1 -1
  113. package/dist/server-dev/index.js +6 -6
  114. package/dist/server-dev/insert.js +12 -1
  115. package/dist/server-dev/insert.js.map +1 -1
  116. package/dist/server-dev/render.js +22 -11
  117. package/dist/server-dev/render.js.map +1 -1
  118. package/dist/server-dev/select-value.js +11 -1
  119. package/dist/server-dev/select-value.js.map +1 -1
  120. package/dist/server-dev/server/class-style.js +1 -1
  121. package/dist/server-dev/server/element.js +3 -3
  122. package/dist/server-dev/server/form-controls.js +1 -1
  123. package/dist/server-dev/server/hydration-script.js +1 -1
  124. package/dist/server-dev/server/portals.js +1 -1
  125. package/dist/server-dev/server/raw-text.js +1 -1
  126. package/dist/server-dev/server/render.js +2 -2
  127. package/dist/server-dev/server/stream.js +3 -3
  128. package/dist/server-dev/spread.js +12 -4
  129. package/dist/server-dev/spread.js.map +1 -1
  130. package/dist/server-dev/template.js +3 -3
  131. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","commit","next","attached","first","end","reconcileNodes","commitValue","raw","created","createRegion","initial","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","bindRegion","value","latest","ordered","useRenderEffect","owner","memos","touched","fn","createComputation","readComputation","disposeOwner","moveRegion","keepFocus","move","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":"A,oX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AI,EAC/B,IAAK,GAAM,CAACmD,EAAIlE,KAASgE,EACnBC,EAAQ,IAAIC,CAAE,IAClBF,EAAM,OAAOE,CAAE,EACfG,EAAarE,CAAI,GAEnB,OAAOW,CACT,EACC,GAAU,CACT0B,EAAOlC,EAAQQ,CAAK,CACtB,CACF,CACF,MACEgC,EAAYxC,EAAQyC,CAAG,CAE3B,CAAC,EACMgB,CACT,CAYA,SAAgBU,EAAW,EAAgB,EAAc,EAAkC,CACzF,IAAM/B,EAAWpC,EAAO,MAAM,OAAQ,GAASH,EAAK,aAAeG,EAAO,MAAM,EAEhFoE,EAAUpE,EAAO,WAAc,CAC7B,IAAK,IAAMH,KAAQuC,EAAUiC,EAAKxE,CAAI,CACxC,CAAC,EAED,EAA6B,OAASkC,EACtC,EAAO,OAASK,EAAS,EAAE,EAAE,iBAAmBL,EAAO,SACzD,CAOA,SAAgBuC,EAAa,EAAsB,CACjD,IAAK,IAAMzE,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgBqD,EAAO,EAAc,EAA2B,CAC9D,IAAMhD,EAAON,EAAWmC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAa7B,EAAMqE,CAAM,EACzBrE,CACT,CAwCA,SAAgBsE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOU,EADQZ,EAAaZ,EAAQ0C,EADlC7B,IAAY,IAAA,GAAY8B,EAAO,QAAQ,WAAW3C,EAAQ0C,CAAc,EAAI7B,CAEvD,EAAGY,EAAOiB,IAAmB,IAAI,CAC1D,C"}
1
+ {"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","keepWatchingCommits","commit","next","attached","first","end","reconcileNodes","commitValue","raw","created","createRegion","initial","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","bindRegion","value","latest","ordered","useRenderEffect","owner","memos","touched","fn","createComputation","readComputation","disposeOwner","moveRegion","keepFocus","move","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region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,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOU,EADQZ,EAAab,EAAQ2C,EADlC7B,IAAY,IAAA,GAAY8B,EAAO,QAAQ,WAAW5C,EAAQ2C,CAAc,EAAI7B,CAEvD,EAAGY,EAAOiB,IAAmB,IAAI,CAC1D,C"}
@@ -1,2 +1,2 @@
1
- import{withScope as e}from"./internal/hydration-scope.js";import{claims as t}from"./internal/hydration-hooks.js";import{bindRegion as n,createRegion as r,removeRegion as i}from"./insert.js";import{attachRootErrors as a}from"./control-flow/root-errors.js";import{batch as o,createRoot as s,flushSync as c,untrack as l}from"@shadow-js/core";function u(u,d,f){let p=r(d,null,void 0),m=t.current.withoutClaiming(()=>e(null,()=>o(()=>s(e=>(f!==void 0&&a(f),n(p,l(u)),e)))));c();let h=!1;return()=>{h||(h=!0,m(),i(p))}}export{u as render};
1
+ import{attachRootErrors as e}from"./control-flow/root-errors.js";import{bindRegion as t,createRegion as n,removeRegion as r}from"./insert.js";import{claims as i}from"./internal/hydration-hooks.js";import{withScope as a}from"./internal/hydration-scope.js";import{batch as o,createRoot as s,flushSync as c,untrack as l}from"@shadow-js/core";function u(u,d,f){let p=n(d,null,void 0),m,h=!1,g=()=>{h||(h=!0,m?.(),r(p))};try{i.current.withoutClaiming(()=>a(null,()=>o(()=>s(n=>{m=n,f!==void 0&&e(f),t(p,l(u))})))),c()}catch(e){try{g()}catch(t){throw AggregateError([e,t],`SHADOW_RENDER_ERRORS`)}throw e}return g}export{u as render};
2
2
  //# sourceMappingURL=render.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","claims","withScope","batch","createRoot","options","attachRootErrors","bindRegion","untrack","code","dispose","flushSync","disposed","removeRegion"],"sources":["../../src/render.ts"],"sourcesContent":["import { batch, createRoot, flushSync, untrack } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link render}: the error reporters of the root.\n * @since 1.0.0\n */\nexport type RenderOptions = RootErrorOptions;\n\n/**\n * Mounts `code` into `container`. Creates an owner, inserts the output, flushes the effects, and\n * returns a dispose function that stops the owner and removes the nodes this call inserted. A\n * second render into the same container appends after the first.\n *\n * @param code Runs once, untracked, to build the tree (a component call, a node, text or an array).\n * Return an accessor (for example `() => count`) from it to make the root content reactive.\n * @param container Element, Document or DocumentFragment that receives the output.\n * @param options The root's error reporters (`onUncaughtError`, `onCaughtError`). Undefined sets\n * no reporter.\n * @returns A dispose function, safe to call more than once.\n * @example\n * import { createComponent, render } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const dispose = render(\n * () => createComponent(App, {}),\n * document.getElementById(\"root\") as Element,\n * );\n * dispose(); // stops the root and removes the text it inserted\n * @see hydrate\n * @since 1.0.0\n */\nexport function render(\n code: () => unknown,\n container: Element | Document | DocumentFragment,\n options?: RenderOptions,\n): () => void {\n const region = createRegion(container, null, undefined);\n // One batch around the build: effects (and anything a resource's batch would flush mid-build)\n // wait until the whole tree exists, so a Suspense boundary knows what is pending before its\n // content's effects are considered.\n // A fresh root never consumes the enclosing hydration pass's nodes or key sequence.\n const stop = claims.current.withoutClaiming(() =>\n withScope(null, () =>\n batch(() =>\n createRoot((dispose) => {\n // An error nothing else took ends here; with onUncaughtError it is reported instead of thrown.\n if (options !== undefined) attachRootErrors(options);\n // The component tree is built once; only accessors inside the result stay reactive.\n bindRegion(region, untrack(code));\n return dispose;\n }),\n ),\n ),\n );\n flushSync();\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n stop();\n removeRegion(region);\n };\n}\n"],"mappings":"A,mVAsCA,SAAgBA,EACd,EACA,EACA,EACY,CACZ,IAAMC,EAASC,EAAaC,EAAW,KAAM,IAAA,EAAS,EAKhDC,EAAOC,EAAO,QAAQ,oBAC1BC,EAAU,SACRC,MACEC,EAAY,IAENC,IAAY,IAAA,IAAWC,EAAiBD,CAAO,EAEnDE,EAAWV,EAAQW,EAAQC,CAAI,CAAC,EACzBC,EACR,CACH,CACF,CACF,EACAC,EAAU,EACV,IAAIC,EAAW,GACf,UAAa,CACPA,IACJ,EAAW,GACXZ,EAAK,EACLa,EAAahB,CAAM,EACrB,CACF,C"}
1
+ {"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","disposed","teardown","removeRegion","claims","withScope","batch","createRoot","dispose","options","attachRootErrors","bindRegion","untrack","code","flushSync","error","cleanupError"],"sources":["../../src/render.ts"],"sourcesContent":["import { batch, createRoot, flushSync, untrack } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link render}: the error reporters of the root.\n * @since 1.0.0\n */\nexport type RenderOptions = RootErrorOptions;\n\n/**\n * Mounts `code` into `container`. Creates an owner, inserts the output, flushes the effects, and\n * returns a dispose function that stops the owner and removes the nodes this call inserted. A\n * second render into the same container appends after the first.\n *\n * @param code Runs once, untracked, to build the tree (a component call, a node, text or an array).\n * Return an accessor (for example `() => count`) from it to make the root content reactive.\n * @param container Element, Document or DocumentFragment that receives the output.\n * @param options The root's error reporters (`onUncaughtError`, `onCaughtError`). Undefined sets\n * no reporter.\n * @returns A dispose function, safe to call more than once.\n * @example\n * import { createComponent, render } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const dispose = render(\n * () => createComponent(App, {}),\n * document.getElementById(\"root\") as Element,\n * );\n * dispose(); // stops the root and removes the text it inserted\n * @see hydrate\n * @since 1.0.0\n */\nexport function render(\n code: () => unknown,\n container: Element | Document | DocumentFragment,\n options?: RenderOptions,\n): () => void {\n const region = createRegion(container, null, undefined);\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n // One batch around the build: effects (and anything a resource's batch would flush mid-build)\n // wait until the whole tree exists, so a Suspense boundary knows what is pending before its\n // content's effects are considered.\n // A fresh root never consumes the enclosing hydration pass's nodes or key sequence.\n try {\n claims.current.withoutClaiming(() =>\n withScope(null, () =>\n batch(() =>\n createRoot((dispose) => {\n stop = dispose;\n // An error nothing else took ends here; with onUncaughtError it is reported instead of thrown.\n if (options !== undefined) attachRootErrors(options);\n // The component tree is built once; only accessors inside the result stay reactive.\n bindRegion(region, untrack(code));\n }),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a render that throws (an effect of the first flush failed),\n // so the root must not stay alive with its DOM and effects.\n try {\n teardown();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"render() failed and so did its teardown.\" : \"SHADOW_RENDER_ERRORS\",\n );\n }\n throw error;\n }\n return teardown;\n}\n"],"mappings":"A,mVAsCA,SAAgBA,EACd,EACA,EACA,EACY,CACZ,IAAMC,EAASC,EAAaC,EAAW,KAAM,IAAA,EAAS,EAClDC,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaN,CAAM,EACrB,EAKA,GAAI,CACFO,EAAO,QAAQ,oBACbC,EAAU,SACRC,MACEC,EAAY,GAAY,CACtB,EAAOC,EAEHC,IAAY,IAAA,IAAWC,EAAiBD,CAAO,EAEnDE,EAAWd,EAAQe,EAAQC,CAAI,CAAC,CAClC,CAAC,CACH,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFb,EAAS,CACX,OAASc,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACmC,sBACzD,CACF,CACA,MAAMD,CACR,CACA,OAAOb,CACT,C"}
@@ -1,2 +1,2 @@
1
- function e(e){return new Set(e.filter(e=>e!=null).map(String))}function t(e){return e==null?``:String(e)}function n(n,r){if(n.multiple&&Array.isArray(r)){let t=e(r);for(let e of Array.from(n.options))e.selected=t.has(e.value)}else n.value=t(r)}export{t as plainText,n as setSelectValue};
1
+ import{keepWatchingCommits as e}from"./insert.js";const t=/* @__PURE__ */ new WeakMap;function n(e){return new Set(e.filter(e=>e!=null).map(String))}function r(e){return e==null?``:String(e)}function i(n,r){t.has(n)||e(n,()=>a(n,t.get(n))),t.set(n,r),a(n,r)}function a(e,t){if(e.multiple&&Array.isArray(t)){let r=n(t);for(let t of Array.from(e.options))t.selected=r.has(t.value)}else e.value=r(t)}export{r as plainText,i as setSelectValue};
2
2
  //# sourceMappingURL=select-value.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"select-value.js","names":["listed","value","item","plainText","setSelectValue","select","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`).\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"AACA,SAASA,EAAO,EAAwC,CACtD,OAAO,IAAI,IAAIC,EAAM,OAAQ,GAASC,GAAS,IAA0B,CAAC,CAAC,IAAI,MAAM,CAAC,CACxF,CAGA,SAAgBC,EAAU,EAAwB,CAChD,OAAOF,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAsBA,SAAgBG,EAAe,EAA2B,EAAsB,CAC9E,GAAIC,EAAO,UAAY,MAAM,QAAQJ,CAAK,EAAG,CAC3C,IAAMK,EAASN,EAAOC,CAAK,EAC3B,IAAK,IAAMM,KAAU,MAAM,KAAKF,EAAO,OAAO,EAAG,EAAO,SAAWC,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACA,GAAO,MAAQJ,EAAUF,CAAK,CAChC,C"}
1
+ {"version":3,"file":"select-value.js","names":["bound","listed","value","item","plainText","setSelectValue","select","keepWatchingCommits","apply","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["import { keepWatchingCommits } from \"./insert\";\n\n/** The value each select was last given, which it takes again when its options change (see {@link setSelectValue}). */\nconst bound = new WeakMap<HTMLSelectElement, unknown>();\n\n/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`). The select\n * takes the value again whenever the nodes inside it change (the options of a `<For>`, a `<Show>` or an optgroup), so\n * options that arrive or are replaced after the value keep it selected.\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n // Options that arrive or are replaced after this call (a `<For>` inside the select) leave the browser's own pick, the\n // first option: the select takes its value again after each commit to its children, as React's does.\n if (!bound.has(select)) keepWatchingCommits(select, () => apply(select, bound.get(select)));\n bound.set(select, value);\n apply(select, value);\n}\n\nfunction apply(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"A,kDAGA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAO,EAAwC,CACtD,OAAO,IAAI,IAAIC,EAAM,OAAQ,GAASC,GAAS,IAA0B,CAAC,CAAC,IAAI,MAAM,CAAC,CACxF,CAGA,SAAgBC,EAAU,EAAwB,CAChD,OAAOF,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAwBA,SAAgBG,EAAe,EAA2B,EAAsB,CAGzEL,EAAM,IAAIM,CAAM,GAAGC,EAAoBD,MAAcE,EAAMF,EAAQN,EAAM,IAAIM,CAAM,CAAC,CAAC,EAC1FN,EAAM,IAAIM,EAAQJ,CAAK,EACvBM,EAAMF,EAAQJ,CAAK,CACrB,CAEA,SAASM,EAAM,EAA2B,EAAsB,CAC9D,GAAIF,EAAO,UAAY,MAAM,QAAQJ,CAAK,EAAG,CAC3C,IAAMO,EAASR,EAAOC,CAAK,EAC3B,IAAK,IAAMQ,KAAU,MAAM,KAAKJ,EAAO,OAAO,EAAG,EAAO,SAAWG,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACA,GAAO,MAAQN,EAAUF,CAAK,CAChC,C"}
@@ -1,2 +1,2 @@
1
- import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{isSsrNode as n}from"./node.js";import{escapeHtml as r,resolveValue as i}from"./escape.js";const a=/^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;function o(e,n){let r=[[e]],a=[0],o=/* @__PURE__ */ new Set;for(;r.length>0;){let e=r.length-1,s=r[e],c=a[e]??0;if(s===void 0||c>=s.length){let e=r.pop();e!==void 0&&o.delete(e),a.pop();continue}a[e]=c+1;let l=i(s[c]);if(Array.isArray(l)){if(o.has(l))throw TypeError(`A class array contains itself.`);o.add(l),r.push(l),a.push(0)}else if(typeof l==`string`)l!==``&&n.push(l);else if(typeof l==`number`)l!==0&&!Number.isNaN(l)&&n.push(String(l));else if(typeof l==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a class name.`);else if(typeof l==`object`&&l){let e=l;for(let t of Object.keys(e))t!==``&&i(e[t])&&n.push(t)}}}function s(e){let t=i(e);if(typeof t==`string`)return t;if(t==null||t===!1)return``;let n=[];return o(t,n),n.join(` `)}function c(e){let t=s(e);return t===``?``:` class="${r(t)}"`}function l(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function u(e){let t=``,n=0,r=!1;for(let i of e)if(r)r=!1;else if(i===`\\`)r=!0;else if(t!==``)i===t&&(t=``);else if(i===`"`||i===`'`)t=i;else if(i===`(`)n+=1;else if(i===`)`)n=Math.max(0,n-1);else if((i===`;`||i===`{`||i===`}`)&&n===0)return!1;return t===``&&n===0&&!r}function d(r,o){let s=i(r);if(s!=null&&s!==!1){if(typeof s==`string`)s!==``&&o.push(s);else{if(typeof s!=`object`||n(s))throw t(`UNRECOGNIZED_INSERT_VALUE`,`A style must be a string, an object or an array of them.`);if(Array.isArray(s))for(let e of s){let t=i(e);if(Array.isArray(t))throw TypeError(`ssrStyle(): a style array may not contain another array.`);d(t,o)}else for(let n of Object.keys(s)){let r=l(n);if(!a.test(r))throw t(`INVALID_STYLE_PROPERTY`,`"${n}" is not a valid CSS property name.`);let c=i(Reflect.get(s,n));if(c==null||c===!1)continue;if(typeof c==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a style value.`);let d=e(r,c);u(d)&&o.push(`${r}:${d}`)}}}}function f(e){let t=[];return d(e,t),t.join(`;`)}function p(e){let t=f(e);return t===``?``:` style="${r(t)}"`}export{s as classText,o as collectClasses,u as isSafeCssValue,c as ssrClass,p as ssrStyle,f as styleText,l as toCssProperty};
1
+ import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{escapeHtml as n,resolveValue as r}from"./escape.js";import{isSsrNode as i}from"./node.js";const a=/^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;function o(e,n){let i=[[e]],a=[0],o=/* @__PURE__ */ new Set;for(;i.length>0;){let e=i.length-1,s=i[e],c=a[e]??0;if(s===void 0||c>=s.length){let e=i.pop();e!==void 0&&o.delete(e),a.pop();continue}a[e]=c+1;let l=r(s[c]);if(Array.isArray(l)){if(o.has(l))throw TypeError(`A class array contains itself.`);o.add(l),i.push(l),a.push(0)}else if(typeof l==`string`)l!==``&&n.push(l);else if(typeof l==`number`)l!==0&&!Number.isNaN(l)&&n.push(String(l));else if(typeof l==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a class name.`);else if(typeof l==`object`&&l){let e=l;for(let t of Object.keys(e))t!==``&&r(e[t])&&n.push(t)}}}function s(e){let t=r(e);if(typeof t==`string`)return t;if(t==null||t===!1)return``;let n=[];return o(t,n),n.join(` `)}function c(e){let t=s(e);return t===``?``:` class="${n(t)}"`}function l(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function u(e){let t=``,n=0,r=!1;for(let i of e)if(r)r=!1;else if(i===`\\`)r=!0;else if(t!==``)i===t&&(t=``);else if(i===`"`||i===`'`)t=i;else if(i===`(`)n+=1;else if(i===`)`)n=Math.max(0,n-1);else if((i===`;`||i===`{`||i===`}`)&&n===0)return!1;return t===``&&n===0&&!r}function d(n,o){let s=r(n);if(s!=null&&s!==!1){if(typeof s==`string`)s!==``&&o.push(s);else{if(typeof s!=`object`||i(s))throw t(`UNRECOGNIZED_INSERT_VALUE`,`A style must be a string, an object or an array of them.`);if(Array.isArray(s))for(let e of s){let t=r(e);if(Array.isArray(t))throw TypeError(`ssrStyle(): a style array may not contain another array.`);d(t,o)}else for(let n of Object.keys(s)){let i=l(n);if(!a.test(i))throw t(`INVALID_STYLE_PROPERTY`,`"${n}" is not a valid CSS property name.`);let c=r(Reflect.get(s,n));if(c==null||c===!1)continue;if(typeof c==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a style value.`);let d=e(i,c);u(d)&&o.push(`${i}:${d}`)}}}}function f(e){let t=[];return d(e,t),t.join(`;`)}function p(e){let t=f(e);return t===``?``:` style="${n(t)}"`}export{s as classText,o as collectClasses,u as isSafeCssValue,c as ssrClass,p as ssrStyle,f as styleText,l as toCssProperty};
2
2
  //# sourceMappingURL=class-style.js.map
@@ -1,2 +1,2 @@
1
- import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n,isFlagAttribute as r}from"../internal/react-names.js";import{invalid as i}from"./errors.js";import{SsrNode as a,isSsrNode as o}from"./node.js";import{escape as s,escapeHtml as c,resolveValue as l}from"./escape.js";import{isEventName as u,ssrAttribute as d}from"./attributes.js";import{classText as f,ssrStyle as p,styleText as m}from"./class-style.js";import{keepLeadingNewline as h,markSelectedOptions as g,textareaContent as _}from"./form-controls.js";import{rawElementContent as v}from"./raw-text.js";const y=/^[A-Za-z][A-Za-z0-9-]*$/,b=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`command`,`embed`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`children`,`ref`]);function S(e){if(typeof e==`object`&&e)return Reflect.get(e,`__html`)}function C(e,...t){if(!Array.isArray(e)||e.length!==t.length+1)throw TypeError(`ssr(): parts must have one more entry than there are holes.`);let n=e[0]??``;for(let r=0;r<t.length;r+=1){let i=t[r];if(typeof i==`string`)n+=i;else if(o(i))n+=i.t;else throw TypeError(`ssr(): a hole must be an escaped string or an SsrNode.`);n+=e[r+1]??``}return new a(n)}function w(e){if(typeof e!=`string`)throw TypeError(`ssrRaw(): the markup must be a string.`);return new a(e)}function T(){let t=e();return t===void 0?``:` data-hk="${c(t)}"`}function E(e,o,C=void 0,w=!1,E=!1){if(typeof e!=`string`||!y.test(e))throw i(`INVALID_TAG_NAME`,`"${String(e)}" is not a valid tag name.`);let A=e.toLowerCase(),j=A===`select`,M=A===`textarea`,N={},P=!1,F=!1,I=w?T():``,L=[],R=``,z;if(typeof o==`object`&&o)for(let e of Object.keys(o)){if(x.has(e)||t.test(e)||e===`ref`||e.startsWith(`on:`)||e.startsWith(`use:`)||e.startsWith(`prop:`)||u(e)||w&&e===`data-hk`)continue;let i=l(Reflect.get(o,e));if(e===`class`||e===`className`){let e=f(i);e!==``&&L.push(e)}else if(e===`classList`)O(i,L);else if(e===`style`)R=m(i);else if(e===`innerHTML`)z=k(i);else if(e===`dangerouslySetInnerHTML`)z=k(l(S(i)));else if((j||M)&&e===`value`)N.value=i,P=!0;else if((j||M)&&e===`defaultValue`)N.fallback=i,F=!0;else if(e.startsWith(`attr:`))I+=d(e.slice(5),i);else if(e.startsWith(`bool:`))I+=d(e.slice(5),i,!0);else if(e===`defaultValue`||e===`defaultChecked`){let t=e===`defaultValue`?`value`:`checked`;Object.hasOwn(o,t)||(I+=d(t,i,t===`checked`))}else{let t=n(e,E);I+=d(t,i,r(t,i))}}if(L.length>0&&(I+=` class="${c(L.join(` `))}"`),R!==``&&(I+=p(R)),b.has(A))return new a(`<${e}${I}>`);let B=!E&&(A===`script`||A===`style`),V=C===void 0?D(o):C,H=z===void 0?B?v(A,V):s(V):z;if(z===void 0&&(P||F)){let e=P?N.value:N.fallback;H=M?_(e):g(e,H)}else(M||A===`pre`||A===`listing`)&&z===void 0&&(H=h(H));return new a(`<${e}${I}>${H}</${e}>`)}function D(e){if(typeof e==`object`&&e)return Reflect.get(e,`children`)}function O(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))for(let n of Object.keys(e))n!==``&&l(Reflect.get(e,n))&&t.push(n)}function k(e){if(e==null)return``;if(o(e))return e.t;if(typeof e==`symbol`)throw i(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be innerHTML.`);return String(e)}export{C as ssr,E as ssrElement,T as ssrHydrationKey,w as ssrRaw};
1
+ import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n,isFlagAttribute as r}from"../internal/react-names.js";import{isEventName as i,ssrAttribute as a}from"./attributes.js";import{classText as o,ssrStyle as s,styleText as c}from"./class-style.js";import{invalid as l}from"./errors.js";import{escape as u,escapeHtml as d,resolveValue as f}from"./escape.js";import{keepLeadingNewline as p,markSelectedOptions as m,textareaContent as h}from"./form-controls.js";import{SsrNode as g,isSsrNode as _}from"./node.js";import{rawElementContent as v}from"./raw-text.js";const y=/^[A-Za-z][A-Za-z0-9-]*$/,b=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`command`,`embed`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`children`,`ref`]);function S(e){if(typeof e==`object`&&e)return Reflect.get(e,`__html`)}function C(e,...t){if(!Array.isArray(e)||e.length!==t.length+1)throw TypeError(`ssr(): parts must have one more entry than there are holes.`);let n=e[0]??``;for(let r=0;r<t.length;r+=1){let i=t[r];if(typeof i==`string`)n+=i;else if(_(i))n+=i.t;else throw TypeError(`ssr(): a hole must be an escaped string or an SsrNode.`);n+=e[r+1]??``}return new g(n)}function w(e){if(typeof e!=`string`)throw TypeError(`ssrRaw(): the markup must be a string.`);return new g(e)}function T(){let t=e();return t===void 0?``:` data-hk="${d(t)}"`}function E(e,_,C=void 0,w=!1,E=!1){if(typeof e!=`string`||!y.test(e))throw l(`INVALID_TAG_NAME`,`"${String(e)}" is not a valid tag name.`);let A=e.toLowerCase(),j=A===`select`,M=A===`textarea`,N={},P=!1,F=!1,I=w?T():``,L=[],R=``,z;if(typeof _==`object`&&_)for(let e of Object.keys(_)){if(x.has(e)||t.test(e)||e===`ref`||e.startsWith(`on:`)||e.startsWith(`use:`)||e.startsWith(`prop:`)||i(e)||w&&e===`data-hk`)continue;let s=f(Reflect.get(_,e));if(e===`class`||e===`className`){let e=o(s);e!==``&&L.push(e)}else if(e===`classList`)O(s,L);else if(e===`style`)R=c(s);else if(e===`innerHTML`)z=k(s);else if(e===`dangerouslySetInnerHTML`)z=k(f(S(s)));else if((j||M)&&e===`value`)N.value=s,P=!0;else if((j||M)&&e===`defaultValue`)N.fallback=s,F=!0;else if(e.startsWith(`attr:`))I+=a(e.slice(5),s);else if(e.startsWith(`bool:`))I+=a(e.slice(5),s,!0);else if(e===`defaultValue`||e===`defaultChecked`){let t=e===`defaultValue`?`value`:`checked`;Object.hasOwn(_,t)||(I+=a(t,s,t===`checked`))}else{let t=n(e,E);I+=a(t,s,r(t,s))}}if(L.length>0&&(I+=` class="${d(L.join(` `))}"`),R!==``&&(I+=s(R)),b.has(A))return new g(`<${e}${I}>`);let B=!E&&(A===`script`||A===`style`),V=C===void 0?D(_):C,H=z===void 0?B?v(A,V):u(V):z;if(z===void 0&&(P||F)){let e=P?N.value:N.fallback;H=M?h(e):m(e,H)}else(M||A===`pre`||A===`listing`)&&z===void 0&&(H=p(H));return new g(`<${e}${I}>${H}</${e}>`)}function D(e){if(typeof e==`object`&&e)return Reflect.get(e,`children`)}function O(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))for(let n of Object.keys(e))n!==``&&f(Reflect.get(e,n))&&t.push(n)}function k(e){if(e==null)return``;if(_(e))return e.t;if(typeof e==`symbol`)throw l(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be innerHTML.`);return String(e)}export{C as ssr,E as ssrElement,T as ssrHydrationKey,w as ssrRaw};
2
2
  //# sourceMappingURL=element.js.map
@@ -1,3 +1,3 @@
1
- import{invalid as e}from"./errors.js";import{SsrNode as t}from"./node.js";import{escape as n,escapeHtml as r,resolveValue as i}from"./escape.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){return s(r(a(i(e))))}function s(e){let t=e.charAt(0);return t===`
2
- `||t===`\r`?`\n${e}`:e}function c(e){return new t(o(e))}function l(e){let t=i(e);if(!Array.isArray(t))return{values:/* @__PURE__ */ new Set([a(t)]),many:!1};let n=/* @__PURE__ */ new Set;for(let e of t){let t=i(e);t!=null&&n.add(a(t))}return{values:n,many:!0}}const u=/[ \t\n\f\r]+/g,d=/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi,f={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},p=/<!--[\s\S]*?-->|<[^>]*>/g;function m(e){return e.replace(d,(e,t,n,r)=>{if(r!==void 0)return f[r.toLowerCase()]??e;let i=t===void 0?Number.parseInt(n??``,16):Number(t);return Number.isInteger(i)&&i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e})}function h(e,t){let n=``;for(let r=t;r<e.length;r+=1){let t=e.charAt(r);if(n!==``)t===n&&(n=``);else if(t===`"`||t===`'`)n=t;else if(t===`>`)return r}return-1}function g(e,t,n){n.lastIndex=t;let r=n.exec(e);return m(e.slice(t,r===null?e.length:r.index).replace(p,``)).replace(u,` `).trim()}function _(e,t){let n=``,r=0,i=0,a=!1,o=/* @__PURE__ */ RegExp(`\\s+([^\\s"'<>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+)))?`,`g`),s=/* @__PURE__ */ RegExp(`<\\/?(?:option|optgroup)(?=[\\s/>])`,`gi`);for(;;){let c=e.indexOf(`<option`,i);if(c===-1)break;let l=c+7;if(i=l,!/[\s/>]/.test(e.charAt(l)))continue;let u=h(e,l);if(u===-1)break;let d=e.slice(l,u),f,p=-1,_=-1;o.lastIndex=0;for(let e=o.exec(d);e!==null;e=o.exec(d)){let t=(e[1]??``).toLowerCase();t===`selected`?(p=e.index,_=e.index+e[0].length):t===`value`&&f===void 0&&(f=m(e[2]??e[3]??e[4]??``))}let v=(t.many||!a)&&t.values.has(f??g(e,u+1,s));if(v&&(a=!0),v&&p===-1){let t=d.endsWith(`/`)?d.length-1:d.length;n+=`${e.slice(r,l+t)} selected`,r=l+t}else!v&&p!==-1&&(n+=e.slice(r,l+p),r=l+_);i=u}return r===0?e:n+e.slice(r)}function v(e,r){return new t(y(e,n(r)))}function y(e,t){return _(t,l(e))}export{s as keepLeadingNewline,y as markSelectedOptions,v as ssrSelectValue,c as ssrTextArea,o as textareaContent};
1
+ import{invalid as e}from"./errors.js";import{escape as t,escapeHtml as n,resolveValue as r}from"./escape.js";import{SsrNode as i}from"./node.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){return s(n(a(r(e))))}function s(e){let t=e.charAt(0);return t===`
2
+ `||t===`\r`?`\n${e}`:e}function c(e){return new i(o(e))}function l(e){let t=r(e);if(!Array.isArray(t))return{values:/* @__PURE__ */ new Set([a(t)]),many:!1};let n=/* @__PURE__ */ new Set;for(let e of t){let t=r(e);t!=null&&n.add(a(t))}return{values:n,many:!0}}const u=/[ \t\n\f\r]+/g,d=/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi,f={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},p=/<!--[\s\S]*?-->|<[^>]*>/g;function m(e){return e.replace(d,(e,t,n,r)=>{if(r!==void 0)return f[r.toLowerCase()]??e;let i=t===void 0?Number.parseInt(n??``,16):Number(t);return Number.isInteger(i)&&i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e})}function h(e,t){let n=``;for(let r=t;r<e.length;r+=1){let t=e.charAt(r);if(n!==``)t===n&&(n=``);else if(t===`"`||t===`'`)n=t;else if(t===`>`)return r}return-1}function g(e,t,n){n.lastIndex=t;let r=n.exec(e);return m(e.slice(t,r===null?e.length:r.index).replace(p,``)).replace(u,` `).trim()}function _(e,t){let n=``,r=0,i=0,a=!1,o=/* @__PURE__ */ RegExp(`\\s+([^\\s"'<>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+)))?`,`g`),s=/* @__PURE__ */ RegExp(`<\\/?(?:option|optgroup)(?=[\\s/>])`,`gi`);for(;;){let c=e.indexOf(`<option`,i);if(c===-1)break;let l=c+7;if(i=l,!/[\s/>]/.test(e.charAt(l)))continue;let u=h(e,l);if(u===-1)break;let d=e.slice(l,u),f,p=-1,_=-1;o.lastIndex=0;for(let e=o.exec(d);e!==null;e=o.exec(d)){let t=(e[1]??``).toLowerCase();t===`selected`?(p=e.index,_=e.index+e[0].length):t===`value`&&f===void 0&&(f=m(e[2]??e[3]??e[4]??``))}let v=(t.many||!a)&&t.values.has(f??g(e,u+1,s));if(v&&(a=!0),v&&p===-1){let t=d.endsWith(`/`)?d.length-1:d.length;n+=`${e.slice(r,l+t)} selected`,r=l+t}else!v&&p!==-1&&(n+=e.slice(r,l+p),r=l+_);i=u}return r===0?e:n+e.slice(r)}function v(e,n){return new i(y(e,t(n)))}function y(e,t){return _(t,l(e))}export{s as keepLeadingNewline,y as markSelectedOptions,v as ssrSelectValue,c as ssrTextArea,o as textareaContent};
3
3
  //# sourceMappingURL=form-controls.js.map
@@ -1,2 +1,2 @@
1
- import{ssrRaw as e}from"./element.js";import{DEFAULT_EARLY_EVENTS as t,captureScriptBody as n}from"../internal/early-events.js";const r=/^[A-Za-z0-9+/=_-]+$/;function i(e={}){let i=e.nonce,a=i!==void 0&&r.test(i)?` nonce="${i}"`:``,o=e.eventNames??t;return`<script${a}>${n(o)}<\/script>`}function a(t={}){return e(i(t))}export{a as HydrationScript,i as generateHydrationScript};
1
+ import{DEFAULT_EARLY_EVENTS as e,captureScriptBody as t}from"../internal/early-events.js";import{ssrRaw as n}from"./element.js";const r=/^[A-Za-z0-9+/=_-]+$/;function i(n={}){let i=n.nonce,a=i!==void 0&&r.test(i)?` nonce="${i}"`:``,o=n.eventNames??e;return`<script${a}>${t(o)}<\/script>`}function a(e={}){return n(i(e))}export{a as HydrationScript,i as generateHydrationScript};
2
2
  //# sourceMappingURL=hydration-script.js.map
@@ -1,2 +1,2 @@
1
- import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{SsrError as n}from"./errors.js";import{escape as r}from"./escape.js";import{PortalContext as i}from"../internal/portal-context.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new n(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}render(e,t){l(e,t,this)}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,i,a){if(a===null||n===void 0)return;let o=t(e(n),()=>r(i()));a.add(n,o)}function u(e,t){return i({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
1
+ import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{PortalContext as n}from"../internal/portal-context.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new r(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}render(e,t){l(e,t,this)}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,r,a){if(a===null||n===void 0)return;let o=t(e(n),()=>i(r()));a.add(n,o)}function u(e,t){return n({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
2
2
  //# sourceMappingURL=portals.js.map
@@ -1,2 +1,2 @@
1
- import{invalid as e}from"./errors.js";import{SsrNode as t,isSsrNode as n}from"./node.js";import{render as r,resolveValue as i}from"./escape.js";const a=/* @__PURE__ */ new Set([`script`,`style`,`title`,`textarea`]);function o(e){return a.has(e.toLowerCase())}const s=/* @__PURE__ */ new Set([`script`,`style`]),c={script:/<\/(script)|<!--/gi,style:/<\/(style)/gi};function l(e,t){return t.replace(c[e],e=>e===`<!--`?`<\\u0021--`:`<\\/${e.slice(2)}`)}function u(e,t){return l(e.toLowerCase()===`script`?`script`:`style`,r(t,e=>e))}function d(e,t){let r=i(t);return n(r)?r.t:u(e,r)}function f(n,r){if(typeof n!=`string`||!s.has(n.toLowerCase()))throw e(`INVALID_RAW_TEXT_TAG`,`ssrRawText(): the tag must be script or style.`);return new t(u(n,r))}export{o as isTextOnlyElement,d as rawElementContent,u as rawTextContent,f as ssrRawText};
1
+ import{invalid as e}from"./errors.js";import{render as t,resolveValue as n}from"./escape.js";import{SsrNode as r,isSsrNode as i}from"./node.js";const a=/* @__PURE__ */ new Set([`script`,`style`,`title`,`textarea`]);function o(e){return a.has(e.toLowerCase())}const s=/* @__PURE__ */ new Set([`script`,`style`]),c={script:/<\/(script)|<!--/gi,style:/<\/(style)/gi};function l(e,t){return t.replace(c[e],e=>e===`<!--`?`<\\u0021--`:`<\\/${e.slice(2)}`)}function u(e,n){return l(e.toLowerCase()===`script`?`script`:`style`,t(n,e=>e))}function d(e,t){let r=n(t);return i(r)?r.t:u(e,r)}function f(t,n){if(typeof t!=`string`||!s.has(t.toLowerCase()))throw e(`INVALID_RAW_TEXT_TAG`,`ssrRawText(): the tag must be script or style.`);return new r(u(t,n))}export{o as isTextOnlyElement,d as rawElementContent,u as rawTextContent,f as ssrRawText};
2
2
  //# sourceMappingURL=raw-text.js.map
@@ -1,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{runWithServerHead as s}from"../head/server-head.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(t,r,i,c,d,f){return o(f),l(d,()=>u({value:i,get children(){return s(c,()=>n(e(r),()=>a(t())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=c(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(t=>(i?.clear(),a?.clear(),{html:h(e,n,p,i,a,u),requested:s,tracked:c,errors:l,dispose:t}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new i(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,a,o,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:a,maxPasses:o}=C(t),s={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{s.canceled=!0,t(new i(`SSR_TIMEOUT`,`The render did not finish within ${a} ms.`))},Math.min(a,r))});try{let r=c(t?.portals);return await Promise.race([S(e,n,o,s,t?.head,r,m(t)),u])}finally{clearTimeout(l),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
1
+ import{attachRootErrors as e}from"../control-flow/root-errors.js";import{runWithServerHead as t}from"../head/server-head.js";import{createRootScope as n,resourceKey as r,withScope as i}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as a,SsrError as o}from"./errors.js";import{escape as s}from"./escape.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(r,a,o,c,d,f){return e(f),l(d,()=>u({value:o,get children(){return t(c,()=>i(n(a),()=>s(r())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=c(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,t,n,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let t=r(e);return s.add(t),t},read:e=>n.has(e)?{value:n.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(n=>(i?.clear(),a?.clear(),{html:h(e,t,p,i,a,u),requested:s,tracked:c,errors:l,dispose:n}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new o(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,i,a,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,i,a,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new o(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:r,maxPasses:i}=C(t),s={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{s.canceled=!0,t(new o(`SSR_TIMEOUT`,`The render did not finish within ${r} ms.`))},Math.min(r,a))});try{let r=c(t?.portals);return await Promise.race([S(e,n,i,s,t?.head,r,m(t)),u])}finally{clearTimeout(l),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
2
2
  //# sourceMappingURL=render.js.map
@@ -1,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{StreamContext as o}from"../internal/stream-context.js";import{attachRootErrors as s}from"../control-flow/root-errors.js";import{runWithServerHead as c}from"../head/server-head.js";import{portalCollectorFor as l,withPortalSink as u}from"./portals.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=l(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(l){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||l.enqueue(C.encode(e))},j=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(r);let i={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let i=t.then(t=>{h.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>k.get(e)},l={defer:e=>{r.boundaries.push(e)}},d={onCaughtError:e=>{r.answered?v.onCaughtError?.(e):r.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?v.onUncaughtError?.(e):r.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),r.html=p(t=>(r.dispose=t,s(d),o({value:l,get children(){return u(S,()=>f({value:i,get children(){return c(v.head,()=>n(e(y),()=>a(_())))}}))}})()())),r},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new i(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,r))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||l.close()}catch(e){F(),E||l.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
1
+ import{attachRootErrors as e}from"../control-flow/root-errors.js";import{runWithServerHead as t}from"../head/server-head.js";import{createRootScope as n,resourceKey as r,withScope as i}from"../internal/hydration-scope.js";import{StreamContext as a}from"../internal/stream-context.js";import{MAX_TIMER_MS as o,SsrError as s}from"./errors.js";import{escape as c}from"./escape.js";import{portalCollectorFor as l,withPortalSink as u}from"./portals.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=l(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(l){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||l.enqueue(C.encode(e))},j=()=>{let o={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(o);let s={key:e=>{let t=r(e);return o.requested.add(t),t},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let r=t.then(t=>{h.set(e,t)},()=>void 0);o.inFlight.add(r),r.finally(()=>o.inFlight.delete(r)),n?.deferStream===!0&&o.held.push({key:e,entry:r})},pending:e=>k.get(e)},l={defer:e=>{o.boundaries.push(e)}},d={onCaughtError:e=>{o.answered?v.onCaughtError?.(e):o.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{o.answered?v.onUncaughtError?.(e):o.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),o.html=p(r=>(o.dispose=r,e(d),a({value:l,get children(){return u(S,()=>f({value:s,get children(){return t(v.head,()=>i(n(y),()=>c(_())))}}))}})()())),o},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new s(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,o))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new s(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||l.close()}catch(e){F(),E||l.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
2
2
  //# sourceMappingURL=stream.js.map
@@ -1,2 +1,2 @@
1
- import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{IGNORED_KEYS as f,attributeName as p,eventPlan as m,isFlagAttribute as h}from"./internal/react-names.js";import{bindEvent as g}from"./events.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";const S=/^(?:__proto__|constructor|prototype)$/;function C(e){let t=e.unref;t!==void 0&&(e.unref=void 0,b(t))}function w(c,l,u,d,f){if(l===`ref`){if(C(d),typeof u==`function`){let e=u,t=b(()=>e(c));typeof t==`function`&&(d.unref=t)}}else if(l===`autoFocus`)d.focused||(d.focused=!0,r(c,u));else if(l===`class`||l===`className`)i(c,u,f);else if(l===`style`)d.styled=s(c,u,d.styled);else if(l===`classList`)d.listed=o(c,a(u),d.listed);else if(l.length>2&&l.startsWith(`on`)){d.unbind.get(l)?.(),d.unbind.delete(l);let e=m(l,c.localName,c.getAttribute(`type`)?.toLowerCase()??null),t=e.passive&&typeof u==`function`?{handleEvent:u,passive:!0}:u,n=g(c,e.type,t,!0,e.capture);n!==void 0&&d.unbind.set(l,n)}else if(l===`innerHTML`||l===`dangerouslySetInnerHTML`)c.innerHTML=_(l===`innerHTML`?u:typeof u==`object`&&u?Reflect.get(u,`__html`):void 0);else if(l===`textContent`)c.textContent=_(u);else if(!f&&(l===`value`||l===`defaultValue`)&&c instanceof HTMLSelectElement)v(c,u);else if(!f&&T.test(l)&&l in c)D(c,l,u,f)&&Reflect.set(c,l,E.test(l)?u??``:!!u),l===`value`&&c instanceof HTMLInputElement&&(c.defaultValue=_(u));else if(l.startsWith(`prop:`))Reflect.set(c,l.slice(5),u);else if(l.startsWith(`attr:`))e(c,l.slice(5),u);else if(l.startsWith(`bool:`))n(c,l.slice(5),u);else{let r=p(l,f);h(r,u)?n(c,r,u):r.startsWith(`xlink:`)?t(c,`http://www.w3.org/1999/xlink`,r,u):e(c,r,u)}}const T=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,E=/^(?:value|defaultValue)$/;function D(e,t,n,r){if(r||!T.test(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return E.test(t)?i!==_(n):i!==!!n}function O(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=A();if(!r&&e.localName!==`textarea`){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),k(e,n,a)}j(e,i,n,a)}function k(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function A(){return{values:/* @__PURE__ */ new Map,unbind:/* @__PURE__ */ new Map}}function j(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbind.values())e();r.unbind.clear(),C(r)}),x(()=>{let e=t(),n=[];if(typeof e!=`object`||!e)return n;let r,a=!1;for(let t of Object.keys(e))S.test(t.slice(t.indexOf(`:`)+1))||f.test(t)||(t===`children`?i&&(r=Reflect.get(e,t),a=!0):n.push([t,Reflect.get(e,t)]));return a&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n},t=>{let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(r.values.has(a)&&Object.is(r.values.get(a),o)&&!D(e,a,o,n))&&(r.values.set(a,o),w(e,a,o,r,n));for(let t of[...r.values.keys()])i.has(t)||(r.values.delete(t),w(e,t,void 0,r,n))})}export{O as spread};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{bindEvent as c}from"./events.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{claims as f}from"./internal/hydration-hooks.js";import{IGNORED_KEYS as p,attributeName as m,eventPlan as h,isFlagAttribute as g}from"./internal/react-names.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";const S=/^(?:__proto__|constructor|prototype)$/;function C(e){let t=e.unref;t!==void 0&&(e.unref=void 0,b(t))}function w(l,u,d,f,p){if(u===`ref`){if(C(f),typeof d==`function`){let e=d,t=b(()=>e(l));typeof t==`function`&&(f.unref=t)}}else if(u===`autoFocus`)f.focused||(f.focused=!0,r(l,d));else if(u===`class`||u===`className`)i(l,d,p);else if(u===`style`)f.styled=s(l,d,f.styled);else if(u===`classList`)f.listed=o(l,a(d),f.listed);else if(u.length>2&&u.startsWith(`on`)){f.unbind.get(u)?.(),f.unbind.delete(u);let e=h(u,l.localName,l.getAttribute(`type`)?.toLowerCase()??null),t=e.passive&&typeof d==`function`?{handleEvent:d,passive:!0}:d,n=c(l,e.type,t,!0,e.capture);n!==void 0&&f.unbind.set(u,n)}else if(u===`innerHTML`||u===`dangerouslySetInnerHTML`)l.innerHTML=_(u===`innerHTML`?d:typeof d==`object`&&d?Reflect.get(d,`__html`):void 0);else if(u===`textContent`)l.textContent=_(d);else if(!p&&(u===`value`||u===`defaultValue`)&&l instanceof HTMLSelectElement)v(l,d);else if(!p&&T.test(u)&&u in l&&!D(l,u))O(l,u,d,p)&&Reflect.set(l,u,E.test(u)?d??``:!!d),u===`value`&&l instanceof HTMLInputElement&&(l.defaultValue=_(d));else if(u.startsWith(`prop:`))Reflect.set(l,u.slice(5),d);else if(u.startsWith(`attr:`))e(l,u.slice(5),d);else if(u.startsWith(`bool:`))n(l,u.slice(5),d);else{let r=m(u,p);g(r,d)?n(l,r,d):r.startsWith(`xlink:`)?t(l,`http://www.w3.org/1999/xlink`,r,d):e(l,r,d)}}const T=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,E=/^(?:value|defaultValue)$/;function D(e,t){return t===`value`&&(e.localName===`progress`||e.localName===`meter`||e.localName===`li`)}function O(e,t,n,r){if(r||!T.test(t)||!(t in e)||D(e,t))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return E.test(t)?i!==_(n):i!==!!n}function k(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=j();if(!r&&e.localName!==`textarea`){let t=f.current.isClaiming()?f.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),A(e,n,a)}M(e,i,n,a)}function A(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function j(){return{values:/* @__PURE__ */ new Map,unbind:/* @__PURE__ */ new Map}}function M(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbind.values())e();r.unbind.clear(),C(r)}),x(()=>{let e=t(),n=[];if(typeof e!=`object`||!e)return n;let r,a=!1;for(let t of Object.keys(e))S.test(t.slice(t.indexOf(`:`)+1))||p.test(t)||(t===`children`?i&&(r=Reflect.get(e,t),a=!0):n.push([t,Reflect.get(e,t)]));return a&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n},t=>{let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),r.values.has(a)&&Object.is(r.values.get(a),o)&&!O(e,a,o,n)||(r.values.set(a,o),w(e,a,o,r,n));for(let t of[...r.values.keys()])i.has(t)||(r.values.delete(t),w(e,t,void 0,r,n))})}export{k as spread};
2
2
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":["FORBIDDEN_NAMES","runRefCleanup","cleanup","state","untrack","applyKey","key","value","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","plainText","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","spread","props","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","textarea","onCleanup","useRenderEffect","entries","hasValue","IGNORED_KEYS","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMA,EAAkB,wCAexB,SAASC,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,MAClBD,IAAY,IAAA,KAChB,EAAM,MAAQ,IAAA,GACdE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIC,IAAQ,MAGV,IADAL,EAAcE,CAAK,EACf,OAAOI,GAAU,WAAY,CAC/B,IAAMC,EAAUD,EACVL,EAAUE,MAAcI,EAAQC,CAAE,CAAC,EACrC,OAAOP,GAAY,aAAY,EAAM,MAAQA,EACnD,OAGF,GAAII,IAAQ,YACLH,EAAM,UACT,EAAM,QAAU,GAChBO,EAAUD,EAAIF,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BK,EAAWF,EAAIF,EAAOK,CAAG,OAG3B,GAAIN,IAAQ,QACV,EAAM,OAASO,EAAMJ,EAAgCF,EAAOJ,EAAM,MAAM,OAG1E,GAAIG,IAAQ,YACV,EAAM,OAASQ,EAAUL,EAAIM,EAASR,CAAK,E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AAO,IAAIA,CAAG,GACpB,OAAO,GAAGH,EAAM,OAAO,IAAIG,CAAG,EAAGC,CAAK,GACtC,CAACiB,EAAYf,EAAIH,EAAKC,EAAOqC,CAAK,KAGpCzC,EAAM,OAAO,IAAIG,EAAKC,CAAK,EAC3BF,EAASI,EAAIH,EAAKC,EAAOJ,EAAOyC,CAAK,GAEvC,IAAK,IAAMtC,IAAO,CAAC,GAAGH,EAAM,OAAO,KAAK,CAAC,EACnCkD,EAAQ,IAAI/C,CAAG,IACnBH,EAAM,OAAO,OAAOG,CAAG,EAGvBD,EAASI,EAAIH,EAAK,IAAA,GAAWH,EAAOyC,CAAK,EAE7C,CACF,CACF,C"}
1
+ {"version":3,"file":"spread.js","names":["FORBIDDEN_NAMES","runRefCleanup","cleanup","state","untrack","applyKey","key","value","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","plainText","setSelectValue","LIVE_PROPERTIES","isMeasure","liveDiffers","STRING_PROPERTIES","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","spread","props","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","textarea","onCleanup","useRenderEffect","entries","hasValue","IGNORED_KEYS","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el && !isMeasure(el, key)) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True for the `value` of a `progress`, `meter` or `li`: a number property that turns `undefined` into `0` and\n * writes `value=\"0\"`, where the server leaves the attribute out (an indeterminate bar, an unnumbered item). It is written as\n * an attribute, which `setAttribute` removes for `null` and `undefined`, like the compiler does.\n */\nfunction isMeasure(el: Element, key: string): boolean {\n // The tag, not `instanceof`: a class of this window is not the class of an iframe's element, and a minimal DOM may\n // not define `HTMLMeterElement` at all.\n return (\n key === \"value\" &&\n (el.localName === \"progress\" || el.localName === \"meter\" || el.localName === \"li\")\n );\n}\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el) || isMeasure(el, key)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMA,EAAkB,wCAexB,SAASC,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,MAClBD,IAAY,IAAA,KAChB,EAAM,MAAQ,IAAA,GACdE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIC,IAAQ,MAGV,IADAL,EAAcE,CAAK,EACf,OAAOI,GAAU,WAAY,CAC/B,IAAMC,EAAUD,EACVL,EAAUE,MAAcI,EAAQC,CAAE,CAAC,EACrC,OAAOP,GAAY,aAAY,EAAM,MAAQA,EACnD,OAGF,GAAII,IAAQ,YACLH,EAAM,UACT,EAAM,QAAU,GAChBO,EAAUD,EAAIF,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BK,EAAWF,EAAIF,EAAOK,CAAG,OAG3B,GAAIN,IAAQ,QACV,EAAM,OAASO,EAAMJ,EAAgCF,EAAOJ,EAAM,MAAM,OAG1E,GAAIG,IAAQ,YACV,EAAM,OAASQ,EAAUL,EAAIM,EAASR,CAAK,EAAGJ,EAAM,MAAM,OAG5D,GAAIG,EAAI,OAAS,GAAKA,EAAI,WAAW,IAAI,EAAG,CAC1CH,EAAM,OAAO,IAAIG,CAAG,CAAC,GAAG,EACxBH,EAAM,OAAO,OAAOG,CAAG,EAEvB,IAAMU,EAAOC,EAAUX,EAAKG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AAIG,CAAG,GACpB,OAAO,GAAGH,EAAM,OAAO,IAAIG,CAAG,EAAGC,CAAK,GACtC,CAACkB,EAAYhB,EAAIH,EAAKC,EAAOsC,CAAK,IAGpC1C,EAAM,OAAO,IAAIG,EAAKC,CAAK,EAC3BF,EAASI,EAAIH,EAAKC,EAAOJ,EAAO0C,CAAK,GAEvC,IAAK,IAAMvC,IAAO,CAAC,GAAGH,EAAM,OAAO,KAAK,CAAC,EACnCmD,EAAQ,IAAIhD,CAAG,IACnBH,EAAM,OAAO,OAAOG,CAAG,EAGvBD,EAASI,EAAIH,EAAK,IAAA,GAAWH,EAAO0C,CAAK,EAE7C,CACF,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{MATHML_NS as e}from"./internal/names.js";import{nextKey as t}from"./internal/hydration-scope.js";import{claims as n}from"./internal/hydration-hooks.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let[e,t]=a.pop();for(let i of Array.from(e.childNodes))if(i instanceof Element){let e=r(i);t.appendChild(e),a.push([i,e])}else i instanceof Text&&t.appendChild(n.createTextNode(i.data))}return i}function i(t,n){let i=document.createElement(`template`),a=n&1?`svg`:n&2?`math`:null;if(a===null)return i.innerHTML=t,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${t}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,e).childNodes):Array.from(o.childNodes):[]}function a(e,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=n.current.claimElement(t());if(a!==null)return a;let c=o??=i(e,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
1
+ import{claims as e}from"./internal/hydration-hooks.js";import{nextKey as t}from"./internal/hydration-scope.js";import{MATHML_NS as n}from"./internal/names.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let[e,t]=a.pop();for(let i of Array.from(e.childNodes))if(i instanceof Element){let e=r(i);t.appendChild(e),a.push([i,e])}else i instanceof Text&&t.appendChild(n.createTextNode(i.data))}return i}function i(e,t){let i=document.createElement(`template`),a=t&1?`svg`:t&2?`math`:null;if(a===null)return i.innerHTML=e,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${e}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,n).childNodes):Array.from(o.childNodes):[]}function a(n,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=e.current.claimElement(t());if(a!==null)return a;let c=o??=i(n,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
2
2
  //# sourceMappingURL=template.js.map
@@ -189,7 +189,12 @@ function style(el, value, prev) {
189
189
  if (typeof item === "string") el.style.cssText += `;${item}`;
190
190
  else if (item !== null && item !== void 0 && item !== false) {
191
191
  if (typeof item !== "object" || Array.isArray(item)) throw new TypeError("style(): an array holds only strings and objects.");
192
- style(el, item, {});
192
+ const declared = {};
193
+ for (const key of Object.keys(item)) {
194
+ const part = unwrap(item[key]);
195
+ if (part !== null && part !== void 0 && part !== false) declared[key] = part;
196
+ }
197
+ style(el, declared, {});
193
198
  }
194
199
  }
195
200
  return resolved;
@@ -1 +1 @@
1
- {"version":3,"file":"class-style.js","names":[],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]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["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":";;;;;AAKA,SAAS,eAAe,MAAe,OAAuB;CAE5D,KAAK,MAAM,QAAQ,OAAO,MAAM,6CAAK,GACnC,IAAI,OAAO,SAAS,UACd;MAAA,SAAS,IAAI,MAAM,KAAK,IAAI;CAAA,OAC3B,IAAI,OAAO,SAAS,UACrB;MAAA,SAAS,KAAK,CAAC,OAAO,MAAM,IAAI,GAAG,MAAM,KAAK,OAAO,IAAI,CAAC;CAAA,OACzD,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU;EACpD,MAAM,SAAS;EACf,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,IAAI,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,KAAK,GAAG;CAEzD;AAEJ;;AAGA,SAAS,UAAU,OAA+B;CAChD,MAAM,QAAQ,OAAO,KAAK;CAC1B,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU,OAAO,OAAO;CACrE,MAAM,QAAkB,CAAC;CACzB,eAAe,OAAO,KAAK;CAC3B,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;AAOA,SAAgB,WAAW,IAAa,OAAgB,KAAoB;CAC1E,MAAM,OAAO,UAAU,KAAK;CAC5B,IAAI,SAAS,MAAM;EACjB,GAAG,gBAAgB,OAAO;EAC1B;CACF;CACA,IAAI,KACE;MAA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