@shadow-js/web 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +10 -5
- package/dist/dev/class-style.js +47 -47
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +2 -2
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.js +2 -2
- package/dist/dev/control-flow/error-boundary.js.map +1 -1
- package/dist/dev/control-flow/portal.d.ts +2 -2
- package/dist/dev/control-flow/portal.js +15 -13
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/suspense-list.js +2 -2
- package/dist/dev/control-flow/suspense-list.js.map +1 -1
- package/dist/dev/control-flow/suspense.js +2 -2
- package/dist/dev/control-flow/suspense.js.map +1 -1
- package/dist/dev/element.js +5 -2
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/extend.d.ts +2 -2
- package/dist/dev/extend.js +2 -2
- package/dist/dev/insert.d.ts +11 -0
- package/dist/dev/insert.js +50 -33
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/accessor.js +56 -0
- package/dist/dev/internal/accessor.js.map +1 -0
- package/dist/dev/internal/claim.js +0 -1
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +2 -2
- package/dist/dev/internal/css-units.js.map +1 -1
- package/dist/dev/internal/portal-context.d.ts +9 -0
- package/dist/dev/internal/portal-context.js.map +1 -1
- package/dist/dev/internal/react-names.js +22 -12
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +4 -6
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/server/attributes.js +1 -31
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +5 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/index.js +1 -1
- package/dist/dev/server/portals.js +3 -0
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/render.js +1 -1
- package/dist/dev/server/stream.js +1 -1
- package/dist/dev/server.js +1 -1
- package/dist/dev/spread.js +49 -27
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +1 -3
- package/dist/dev/template.js.map +1 -1
- package/dist/dev/view-transition.js +12 -4
- package/dist/dev/view-transition.js.map +1 -1
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js +1 -1
- package/dist/prod/control-flow/suspense.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/extend.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js +2 -0
- package/dist/prod/internal/accessor.js.map +1 -0
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js +1 -1
- package/dist/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js +1 -1
- package/dist/prod/view-transition.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/control-flow/suspense.js.map +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/extend.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js +2 -0
- package/dist/server/internal/accessor.js.map +1 -0
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js +1 -1
- package/dist/server/template.js.map +1 -1
- package/dist/server/view-transition.js.map +1 -1
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +47 -47
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +2 -2
- package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +15 -13
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/suspense-list.js +2 -2
- package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/control-flow/suspense.js.map +1 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/extend.js +2 -2
- package/dist/server-dev/insert.js +50 -33
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/accessor.js +56 -0
- package/dist/server-dev/internal/accessor.js.map +1 -0
- package/dist/server-dev/internal/claim.js +0 -1
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +2 -2
- package/dist/server-dev/internal/css-units.js.map +1 -1
- package/dist/server-dev/internal/portal-context.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +22 -12
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +4 -6
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/attributes.js +1 -31
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +5 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/index.js +1 -1
- package/dist/server-dev/server/portals.js +3 -0
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/render.js +1 -1
- package/dist/server-dev/server/stream.js +1 -1
- package/dist/server-dev/server.js +1 -1
- package/dist/server-dev/spread.js +35 -26
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -3
- package/dist/server-dev/template.js.map +1 -1
- package/dist/server-dev/view-transition.js.map +1 -1
- package/package.json +3 -3
package/dist/prod/insert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","flatten","fn","parts","frames","root","cursors","active","top","frame","cursor","done","item","depth","call","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","reconcileRegion","parent","attached","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","createCallCache","memos","touched","createComputation","readComputation","disposeOwner","bindRegion","value","latest","ordered","useRenderEffect","cache","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { 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 { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { 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/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\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 * 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 = (fn) => fn()): Part[] {\n const parts: Part[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n let item: unknown = frame[cursor];\n for (let depth = 0; typeof item === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__ ? \"insert(): accessor chain is too deep.\" : \"SHADOW_INSERT_DEPTH\",\n );\n item = call(item as () => unknown);\n }\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n for (const child of item.childNodes) parts.push(child);\n } else if (item instanceof Node) parts.push(item);\n else if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(__DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\");\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else parts.push(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/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\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}\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 reconcileRegion(region, materialize(region, parts));\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 = typeof raw === \"string\" ? raw : 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/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\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 adopted.push(part);\n }\n return adopted;\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 const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : 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.\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() ?? [];\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 * One memo per accessor function, owned by `owner` (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\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n 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 prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\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 const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\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 * 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,sSAkBA,MA+BMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQ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AAY,IAAA,GAAY2B,EAAO,QAAQ,WAAWvC,EAAQsC,CAAc,EAAI1B,CAEvD,EAAGkB,EAAOQ,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","reconcileRegion","attached","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","createCallCache","memos","touched","fn","createComputation","readComputation","disposeOwner","bindRegion","value","latest","ordered","useRenderEffect","cache","moveRegion","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 { 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/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\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/** 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 reconcileRegion(region, materialize(region, parts));\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 = typeof raw === \"string\" ? raw : 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/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\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 adopted.push(part);\n }\n return adopted;\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 const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : 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.\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 * One memo per accessor function, owned by `owner` (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\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n 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 prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\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 const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\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 for (const node of attached) move(node);\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,qWA+CA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IAAKA,EAAM,IAAIG,CAAI,EACpCH,IAAUG,IAAM,EAAO,sBAAQ,IAAI,IAAI,CAACH,EAAOG,CAAI,CAAC,EAC/D,CAGA,SAASC,EAAW,EAAgB,EAA6B,CAC/D,IAAMJ,EAAQC,EAAO,MACrB,GAAID,IAAU,KACd,IAAIA,aAAiB,IAAK,CACxB,IAAMK,EAAO,IAAI,IAAUC,CAAI,EAC/B,IAAK,IAAMH,KAAQH,EACZK,EAAK,IAAIF,CAAI,GAAGH,EAAM,OAAOG,CAAI,CAE1C,MAAYG,EAAK,SAASN,CAAK,IAAG,EAAO,MAAQ,KAAA,CACnD,CAMA,MAAMO,kBAAmB,IAAI,QAM7B,SAASC,EAAQ,EAAe,EAA+C,CAC7E,IAAMC,EAAgB,CAAC,EAEvB,IAAK,IAAMC,KAAQC,EAAOC,EAAM,sBAAOC,CAAI,EACzC,GAAIH,GAAS,MAA8B,OAAOA,GAAS,UAC3D,IAAIA,aAAgB,iBAAkB,CACpC,IAAMI,EAAOP,EAAiB,IAAIG,CAAI,GAAK,CAAC,GAAGA,EAAK,UAAU,EAC9DH,EAAiB,IAAIG,EA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,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAa7B,EAAMwE,CAAM,EACzBxE,CACT,CAwCA,SAAgByE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOiB,EADQlB,EAAahB,EAAQ6C,EADlC9B,IAAY,IAAA,GAAY+B,EAAO,QAAQ,WAAW9C,EAAQ6C,CAAc,EAAI9B,CAEvD,EAAGoB,EAAOU,IAAmB,IAAI,CAC1D,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t=e=>e()){for(let n=0;typeof e==`function`;n+=1){if(n>=1e4)throw TypeError(`SHADOW_INSERT_DEPTH`);e=t(e)}return e}function t(t,n,r){let i=[],a=[[t]],o=[0],s=/* @__PURE__ */ new Set;for(;a.length>0;){let t=a.length-1,c=a[t],l=o[t];if(l>=c.length){s.delete(a.pop()),o.pop();continue}o[t]=l+1;let u=e(c[l],r);if(!Array.isArray(u))i.push(u);else if(s.has(u))throw TypeError(n);else s.add(u),a.push(u),o.push(0)}return i}export{t as leaves,e as unwrap};
|
|
2
|
+
//# sourceMappingURL=accessor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accessor.js","names":["unwrap","fn","depth","value","call","leaves","found","frames","root","cursors","active","top","frame","cursor","item","cycle"],"sources":["../../../src/internal/accessor.ts"],"sourcesContent":["/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * Calls `value` while it is a function, so an accessor that returns an accessor is followed to the\n * value at its end. `call` runs each function (default: a plain call); `insert` passes one that\n * memoizes. Class and style values use the default, inside the effect that applies them, so the\n * signals an accessor reads are tracked by it.\n * @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.\n * @internal\n */\nexport function unwrap(\n value: unknown,\n call: (fn: () => unknown) => unknown = (fn) => fn(),\n): unknown {\n for (let depth = 0; typeof value === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__\n ? \"An accessor returns accessors more than 10,000 levels deep.\"\n : \"SHADOW_INSERT_DEPTH\",\n );\n value = call(value as () => unknown);\n }\n return value;\n}\n\n/**\n * The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is\n * the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.\n * `insert` and the class writer share it.\n * @param root The value; an array is entered, any other value is a leaf.\n * @param cycle The message of the `TypeError` thrown when an array contains itself.\n * @param call Passed to {@link unwrap}.\n * @internal\n */\nexport function leaves(\n root: unknown,\n cycle: string,\n call?: (fn: () => unknown) => unknown,\n): unknown[] {\n const found: unknown[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top] as unknown[];\n const cursor = cursors[top] as number;\n if (cursor >= frame.length) {\n active.delete(frames.pop() as unknown[]);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = unwrap(frame[cursor], call);\n if (!Array.isArray(item)) found.push(item);\n else if (active.has(item)) throw new TypeError(cycle);\n else {\n active.add(item);\n frames.push(item);\n cursors.push(0);\n }\n }\n return found;\n}\n"],"mappings":"AAWA,SAAgBA,EACd,EACA,EAAwC,GAAOC,EAAG,EACzC,CACT,IAAK,IAAIC,EAAQ,EAAG,OAAOC,GAAU,WAAY,GAAS,EAAG,CAC3D,GAAID,GAAS,IACX,MAAU,UAGJ,qBACN,EACF,EAAQE,EAAKD,CAAsB,CACrC,CACA,OAAOA,CACT,CAWA,SAAgBE,EACd,EACA,EACA,EACW,CACX,IAAMC,EAAmB,CAAC,EACpBC,EAAsB,CAAC,CAACC,CAAI,CAAC,EAC7BC,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOH,EAAO,OAAS,GAAG,CACxB,IAAMI,EAAMJ,EAAO,OAAS,EACtBK,EAAQL,EAAOI,GACfE,EAASJ,EAAQE,GACvB,GAAIE,GAAUD,EAAM,OAAQ,CAC1BF,EAAO,OAAOH,EAAO,IAAI,CAAc,EACvCE,EAAQ,IAAI,EACZ,QACF,CACA,EAAQE,GAAOE,EAAS,EACxB,IAAMC,EAAOd,EAAOY,EAAMC,GAAST,CAAI,EACvC,GAAI,CAAC,MAAM,QAAQU,CAAI,EAAGR,EAAM,KAAKQ,CAAI,OACpC,GAAIJ,EAAO,IAAII,CAAI,EAAG,MAAU,UAAUC,CAAK,OAElDL,EAAO,IAAII,CAAI,EACfP,EAAO,KAAKO,CAAI,EAChBL,EAAQ,KAAK,CAAC,CAElB,CACA,OAAOH,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"@shadow-js/core/extend";let e=null;function t(t,n){e={registry:t,recoverable:n,pending:/* @__PURE__ */ new WeakMap,lifted:[]}}function n(){e=null}function r(){return e!==null}function i(e,t){if(e.nodeType!==8)return!1;let n=e.data;return n===t||t===`[`&&n.startsWith(`[b:`)}function a(e,t,n){let r=[e];for(;r.length>0;){let e=r.pop()
|
|
1
|
+
import"@shadow-js/core/extend";let e=null;function t(t,n){e={registry:t,recoverable:n,pending:/* @__PURE__ */ new WeakMap,lifted:[]}}function n(){e=null}function r(){return e!==null}function i(e,t){if(e.nodeType!==8)return!1;let n=e.data;return n===t||t===`[`&&n.startsWith(`[b:`)}function a(e,t,n){let r=[e];for(;r.length>0;){let e=r.pop(),a=e.firstChild;for(;a!==null;){let o=a.nextSibling;if(i(a,`[`)){let r=[],o=1,s=a.nextSibling;for(;s!==null;){if(i(s,`[`))o+=1;else if(i(s,`]`)&&(--o,o===0))break;r.push(s),s=s.nextSibling}let c=s===null?null:s.nextSibling;n.push(r);for(let t of r)e.removeChild(t);e.removeChild(a),s!==null&&e.removeChild(s);let l=t.get(e);l===void 0?t.set(e,[r]):l.push(r),a=c}else a.nodeType===1&&r.push(a),a=o}}e.normalize()}function o(t){let n=e;if(n===null||t===void 0)return null;let r=n.registry.get(t);return r===void 0?(n.recoverable?.(/* @__PURE__ */ Error(`SHADOW_HYDRATION_KEY_MISS`)),null):(n.registry.delete(t),r.removeAttribute(`data-hk`),a(r,n.pending,n.lifted),r)}const s=/* @__PURE__ */ new Set([`script`,`style`,`title`,`textarea`]);function c(e){return e.nodeType===1&&s.has(e.localName)}function l(t,n){let r=e;if(r===null)return;let i=r.pending.get(t)?.shift();if(i===void 0)return c(t)?Array.from(t.childNodes):void 0;for(let e of i)t.insertBefore(e,n);return i}function u(){return e?.lifted}function d(t){let n=e;e=null;try{return t()}finally{e=n}}const f=`portal:`,p=`/portal:`;function m(t){let n=e;if(n===null||t===void 0||typeof document>`u`)return;let r=document.body;if(r===null)return;let i=Array.from(r.childNodes),a=i.findIndex(e=>g(e,f+t));if(a===-1)return;let o=i.findIndex((e,n)=>n>a&&g(e,p+t));if(o===-1)return;let s=[];for(let e of i.slice(a+1,o))e.nodeType===8&&_(e)?r.removeChild(e):s.push(e);for(let e of[i[a],i[o]])e!==void 0&&r.removeChild(e);for(let e of s){if(e.nodeType!==1)continue;let t=e,r=t.getAttribute(`data-hk`);r!==null&&n.registry.set(r,t);for(let e of Array.from(t.querySelectorAll(`[data-hk]`))){let t=e.getAttribute(`data-hk`);t!==null&&n.registry.set(t,e)}}return s}function h(e){let t=Array.from(e.childNodes);for(let n=0;n<t.length;n+=1){let r=t[n];if(r===void 0||r.nodeType!==8)continue;let i=r.data;if(!i.startsWith(f))continue;let a=t.findIndex((e,t)=>t>n&&g(e,p+i.slice(7))),o=a===-1?n:a;for(let r of t.slice(n,o+1))r.parentNode===e&&e.removeChild(r);n=o}}function g(e,t){return e.nodeType===8&&e.data===t}function _(e){return e.data===`[`||e.data===`]`}export{t as beginClaiming,o as claimElement,m as claimPortal,n as endClaiming,r as isClaiming,u as liftedRegions,h as releaseUnclaimedPortals,l as takeRegion,d as withoutClaiming};
|
|
2
2
|
//# sourceMappingURL=claim.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop();\n if (parent === undefined) break;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `<` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClC,EAAQ,IACV,CAkBA,SAAgBC,GAAsB,CACpC,OAAOH,IAAU,IACnB,CAEA,SAASI,EAAS,EAAY,EAAuB,CACnD,GAAIC,EAAK,WAAa,EAAG,MAAO,GAChC,IAAMC,EAAQD,EAAiB,KAE/B,OAAOC,IAASC,GAASA,IAAS,KAAOD,EAAK,WAAW,KAAK,CAChE,CAQA,SAASE,EAAQ,EAAe,EAAkC,EAAwB,CACxF,IAAMC,EAAmB,CAACC,CAAI,EAC9B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAASF,EAAM,IAAI,EACzB,GAAIE,IAAW,IAAA,GAAW,MAC1B,IAAIC,EAA0BD,EAAO,WACrC,KAAOC,IAAU,MAAM,CACrB,IAAMC,EAA8BD,EAAM,YAC1C,GAAIR,EAASQ,EAAO,GAAG,EAAG,CACxB,IAAME,EAAkB,CAAC,EACrBC,EAAQ,EACRC,EAA2BJ,EAAM,YACrC,KAAOI,IAAW,MAAM,CACtB,GAAIZ,EAASY,EAAQ,GAAG,EAAG,GAAS,OAC/B,GAAIZ,EAASY,EAAQ,GAAG,IAC3B,IACID,IAAU,GAAG,MAEnBD,EAAQ,KAAKE,CAAM,EACnB,EAASA,EAAO,WAClB,CACA,IAAMC,EAA0BD,IAAW,KAAO,KAAOA,EAAO,YAChEE,EAAO,KAAKJ,CAAO,EACnB,IAAK,IAAMT,KAAQS,EAASH,EAAO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D,CACF,CACA,OAAO9B,CACT,CAQA,SAAgBgC,EAAwB,EAAkB,CACxD,IAAMT,EAAQ,MAAM,KAAKD,EAAK,UAAU,EACxC,IAAK,IAAIE,EAAO,EAAGA,EAAOD,EAAM,OAAQ,GAAQ,EAAG,CACjD,IAAMU,EAAUV,EAAMC,GACtB,GAAIS,IAAY,IAAA,IAAaA,EAAQ,WAAa,EAAG,SACrD,IAAMxC,EAAQwC,EAAoB,KAClC,GAAI,CAACxC,EAAK,WAAW0B,CAAW,EAAG,SACnC,IAAMO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUlC,EAAM6B,EAAe3B,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMyC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMnC,KAAQgC,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvC3C,EAAK,aAAe+B,GAAMA,EAAK,YAAY/B,CAAI,EAErD,EAAO2C,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOlC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASmC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
|
|
1
|
+
{"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop() as Element;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `<` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClC,EAAQ,IACV,CAkBA,SAAgBC,GAAsB,CACpC,OAAOH,IAAU,IACnB,CAEA,SAASI,EAAS,EAAY,EAA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AQgC,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvC3C,EAAK,aAAe+B,GAAMA,EAAK,YAAY/B,CAAI,EAErD,EAAO2C,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOlC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASmC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e
|
|
1
|
+
const e=/^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;function t(t,n){if(typeof n!=`number`||n===0||t.startsWith(`--`))return String(n);let r=t.replace(/^-(?:webkit|moz|ms|o)-/,``);return e.test(r)?String(n):`${n}px`}export{t as cssValueText};
|
|
2
2
|
//# sourceMappingURL=css-units.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","value","property","bare"],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS
|
|
1
|
+
{"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","value","property","bare"],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS =\n /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.test(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":"AAQA,MAAMA,EACJ,oaASF,SAAgBC,EAAa,EAAkB,EAAwB,CACrE,GAAI,OAAOC,GAAU,UAAYA,IAAU,GAAKC,EAAS,WAAW,IAAI,EAAG,OAAO,OAAOD,CAAK,EAC9F,IAAME,EAAOD,EAAS,QAAQ,yBAA0B,EAAE,EAC1D,OAAOH,EAAS,KAAKI,CAAI,EAAI,OAAOF,CAAK,EAAI,GAAGA,EAAM,GACxD,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"portal-context.js","names":["PortalContext"],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":"A,
|
|
1
|
+
{"version":3,"file":"portal-context.js","names":["PortalContext"],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n /**\n * Renders a `Portal`'s content into this sink under hydration key `key`. The collectors the\n * renderers provide have it; `Portal` calls it instead of importing the markup writer, so the\n * browser bundle of an app that uses `Portal` does not carry server rendering code. A sink without\n * it receives nothing from `Portal`.\n * @param key The portal's key, `undefined` when the render has no scope (nothing is written).\n * @param children Reads the content: a thunk, because it must be built inside the portal's scope.\n */\n render?(key: string | undefined, children: () => unknown): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":"A,gDA8CA,MAAaA,EACK,kBAAiC,KAAM,CACrD,KAAM,QACR,CAAC,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=/^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/,t=/* @__PURE__ */ new Map([[`className`,`class`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`],[`acceptCharset`,`accept-charset`]]);function n(n,r){let i=t.get(n);if(i!==void 0)return i;if(!r)return n.toLowerCase();if(n.includes(`:`))return n;let a=/^(xlink|xml)([A-Z])(.*)$/.exec(n);return a===null?e.test(n)?n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`):n:`${a[1]}:${a[2]?.toLowerCase()}${a[3]}`}const r
|
|
1
|
+
const e=/^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/,t=/* @__PURE__ */ new Map([[`className`,`class`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`],[`acceptCharset`,`accept-charset`]]);function n(n,r){let i=t.get(n);if(i!==void 0)return i;if(!r)return n.toLowerCase();if(n.includes(`:`))return n;let a=/^(xlink|xml)([A-Z])(.*)$/.exec(n);return a===null?e.test(n)?n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`):n:`${a[1]}:${a[2]?.toLowerCase()}${a[3]}`}const r=/^(?:key|suppress(?:Hydration|ContentEditable)Warning)$/,i=/* @__PURE__ */ new Map([[`focus`,`focusin`],[`blur`,`focusout`],[`doubleclick`,`dblclick`]]),a=/^(?:checkbox|radio|file)$/;function o(e,t,n){let r=/^on[A-Z]/.test(e),o=r&&e.endsWith(`Capture`),s=e.slice(2,o?-7:void 0).toLowerCase(),c=s;return r&&(c=s===`change`?t===`textarea`||t===`input`&&(n===null||!a.test(n))?`input`:`change`:i.get(s)??s),{type:c,capture:o,passive:r&&s===`wheel`&&!o}}function s(e,t){return` async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert ismap loop multiple muted nomodule novalidate open playsinline readonly required reversed selected `.includes(` ${e} `)&&(e!==`hidden`||t!==`until-found`)}export{r as IGNORED_KEYS,n as attributeName,o as eventPlan,s as isFlagAttribute};
|
|
2
2
|
//# sourceMappingURL=react-names.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","RENAMED","attributeName","renamed","name","svg","prefixed","letter","IGNORED_KEYS","REACT_EVENTS","CHANGE_ON_TYPES","eventPlan","reactSpelling","attribute","capture","lower","planned","tag","type"],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS:
|
|
1
|
+
{"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","RENAMED","attributeName","renamed","name","svg","prefixed","letter","IGNORED_KEYS","REACT_EVENTS","CHANGE_ON_TYPES","eventPlan","reactSpelling","attribute","capture","lower","planned","tag","type","isFlagAttribute","value"],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: RegExp = /^(?:key|suppress(?:Hydration|ContentEditable)Warning)$/;\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES = /^(?:checkbox|radio|file)$/;\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.test(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only. The server and the client share this test, so a value that\n * renders a flag on one side renders it on the other. One space-separated string, not a set of\n * strings, because every bundle that spreads props carries it. A name with a space in it can match\n * two neighbors, but such a name is not a valid attribute name and both renderers refuse it before\n * they write anything.\n */\nconst BOOLEAN_ATTRIBUTES =\n \" async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert \" +\n \"ismap loop multiple muted nomodule novalidate open playsinline readonly required reversed selected \";\n\n/**\n * True when a prop written under attribute name `name` is a presence flag for `value`: one of the\n * boolean attributes, except `hidden=\"until-found\"`, a keyword that only collapses the element\n * (a bare `hidden` would hide it). The client writes the flag with truthiness, as the server does.\n * @internal\n */\nexport function isFlagAttribute(name: string, value: unknown): boolean {\n return (\n BOOLEAN_ATTRIBUTES.includes(` ${name} `) && !(name === \"hidden\" && value === \"until-found\")\n );\n}\n"],"mappings":"AAgBA,MAAMA,EACJ,mSAGIC,kBAAuC,IAAI,IAAI,CACnD,CAAC,YAAa,OAAO,EACrB,CAAC,UAAW,KAAK,EACjB,CAAC,YAAa,YAAY,EAC1B,CAAC,gBAAiB,gBAAgB,CACpC,CAAC,EAQD,SAAgBC,EAAc,EAAc,EAAsB,CAChE,IAAMC,EAAUF,EAAQ,IAAIG,CAAI,EAChC,GAAID,IAAY,IAAA,GAAW,OAAOA,EAClC,GAAI,CAACE,EAAK,OAAOD,EAAK,YAAY,EAClC,GAAIA,EAAK,SAAS,GAAG,EAAG,OAAOA,EAC/B,IAAME,EAAW,2BAA2B,KAAKF,CAAI,EAGrD,OAFIE,IAAa,KACZN,EAAoB,KAAKI,CAAI,EAC3BA,EAAK,QAAQ,SAAW,GAAW,IAAIG,EAAO,YAAY,GAAG,EADxBH,EADd,GAAGE,EAAS,GAAG,GAAGA,EAAS,EAAE,EAAE,YAAY,IAAIA,EAAS,IAGxF,CAGA,MAAaE,EAAuB,yDAU9BC,kBAA4C,IAAI,IAAI,CACxD,CAAC,QAAS,SAAS,EACnB,CAAC,OAAQ,UAAU,EACnB,CAAC,cAAe,UAAU,CAC5B,CAAC,EAEKC,EAAkB,4BASxB,SAAgBC,EAAU,EAAmB,EAAa,EAAgC,CACxF,IAAMC,EAAgB,WAAW,KAAKC,CAAS,EACzCC,EAAUF,GAAiBC,EAAU,SAAS,SAAS,EACvDE,EAAQF,EAAU,MAAM,EAAGC,EAAU,GAAoB,IAAA,EAAS,CAAC,CAAC,YAAY,EAClFE,EAAUD,EASd,OARIH,IACF,EACEG,IAAU,SACNE,IAAQ,YAAeA,IAAQ,UAAYC,IAAS,MAAQ,CAACR,EAAgB,KAAKQ,CAAI,GACpF,QACA,SACDT,EAAa,IAAIM,CAAK,GAAKA,GAE7B,CAAE,KAAMC,EAAS,UAAS,QAASJ,GAAiBG,IAAU,SAAW,CAACD,CAAQ,CAC3F,CAoBA,SAAgBK,EAAgB,EAAc,EAAyB,CACrE,MACE,oMAAmB,SAAS,IAAIf,EAAK,EAAE,IAAOA,IAAS,UAAYgB,IAAU,cAEjF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function t(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t]
|
|
1
|
+
function e(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function t(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t],a=0,o=r.length;for(;a<o;){let t=a+o>>1;e[r[t]]<n?a=t+1:o=t}i[t]=r[a-1]??-1,r[a]=t}let a=r.at(-1)??-1;for(;a!==-1;)n[e[a]-t]=1,a=i[a]}function n(n,r,i,a){let o=r.length,s=i.length,c=0;for(;c<o&&c<s&&r[c]===i[c];)c+=1;let l=o,u=s;for(;l>c&&u>c&&r[l-1]===i[u-1];)--l,--u;if(l===c&&u===c)return;let d=u<s?i[u]??null:a;if(u===c){for(let t=c;t<l;t+=1)e(n,r[t]);return}let f=/* @__PURE__ */ new Map;for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&f.set(t,e)}let p=[];for(let t=c;t<l;t+=1){let i=r[t],a=f.get(i);a===void 0?e(n,i):p.push(a)}if(p.length===0){for(let e of i.slice(c,u))n.insertBefore(e,d);return}let m=new Uint8Array(u-c);t(p,c,m);let h=typeof n.moveBefore==`function`,g=d;for(let e=u-1;e>=c;--e){let t=i[e];m[e-c]!==1&&(h&&t.parentNode===n?n.moveBefore(t,g):n.insertBefore(t,g)),g=t}}export{n as reconcileNodes};
|
|
2
2
|
//# sourceMappingURL=reconcile.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.js","names":["removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index]
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":["removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n}\n"],"mappings":"AAMA,SAASA,EAAW,EAAc,EAA8B,CAC1DC,IAAS,IAAA,IAAaA,EAAK,aAAeC,GAAQA,EAAO,YAAYD,CAAI,CAC/E,CAOA,SAASE,EAAsB,EAA2B,EAAgB,EAAyB,CAEjG,IAAMC,EAAkB,CAAC,EACnBC,EAAqBC,EAAO,QAAU,EAAE,EAC9C,IAAK,IAAIC,EAAQ,EAAGA,EAAQD,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAME,EAAQF,EAAOC,GACjBE,EAAM,EACNC,EAAON,EAAM,OACjB,KAAOK,EAAMC,GAAM,CACjB,IAAMC,EAAUF,EAAMC,GAAS,EACjBJ,EAAOF,EAAMO,IACfH,EAAO,EAAMG,EAAS,EAC7B,EAAOA,CACd,CAEA,EAASJ,GAASH,EAAMK,EAAM,IAAM,GACpC,EAAMA,GAAOF,CACf,CACA,IAAIK,EAASR,EAAM,GAAG,EAAE,GAAK,GAC7B,KAAOQ,IAAW,IAChB,EAAON,EAAOM,GAAqBC,GAAU,EAC7C,EAASR,EAASO,EAEtB,CAsCA,SAAgBE,EACd,EACA,EACA,EACA,EACM,CACN,IAAMC,EAAaC,EAAK,OAClBC,EAAaC,EAAK,OAEpBC,EAAO,EACX,KAAOA,EAAOJ,GAAcI,EAAOF,GAAcD,EAAKG,KAAUD,EAAKC,IAAO,GAAQ,EACpF,IAAIC,EAAWL,EACXM,EAAWJ,EACf,KAAOG,EAAWD,GAAQE,EAAWF,GAAQH,EAAKI,EAAW,KAAOF,EAAKG,EAAW,IAClF,IACA,IAEF,GA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ml as t,resolveValue as n}from"./escape.js";const r=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,i=/* @__PURE__ */ new Set([`href`,`src`,`action`,`formaction`,`xlink:href`,`poster`,`data`]),a=/* @__PURE__ */ new Set([`values`,`from`,`to`,`by`]),o=/* @__PURE__ */ new Set([`draggable`,`spellcheck`,`contenteditable`]),s
|
|
1
|
+
import{invalid as e}from"./errors.js";import{escapeHtml as t,resolveValue as n}from"./escape.js";const r=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,i=/* @__PURE__ */ new Set([`href`,`src`,`action`,`formaction`,`xlink:href`,`poster`,`data`]),a=/* @__PURE__ */ new Set([`values`,`from`,`to`,`by`]),o=/* @__PURE__ */ new Set([`draggable`,`spellcheck`,`contenteditable`]),s=[`javascript:`,`data:text/html`,`vbscript:`];function c(t){if(!r.test(t))throw e(`INVALID_ATTRIBUTE_NAME`,`"${t}" is not a valid attribute name.`)}function l(e){return e.length>2&&e.startsWith(`on`)}function u(e){return e.startsWith(`aria-`)||e.startsWith(`data-`)||o.has(e)}function d(e){let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&(e<127||e>159)&&(t+=n)}return t}function f(e){let t=d(e).trim().toLowerCase();return s.some(e=>t.startsWith(e))}function p(e,t){return i.has(e)?f(t):a.has(e)&&t.split(`;`).some(f)}function m(e,t){return t==null?null:t===!1?u(e)?`false`:null:t===!0?u(e)?`true`:``:String(t)}function h(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be an attribute value.`)}function g(e,r,i=!1){c(e);let a=e.toLowerCase();if(l(a))return``;let o=n(r);if(h(o),i)return o?` ${e}`:``;let s=m(a,o);return s===null||p(a,s)?``:` ${e}="${t(s)}"`}export{c as assertAttributeName,m as attributeText,l as isEventName,f as isUnsafeUrl,g as ssrAttribute};
|
|
2
2
|
//# sourceMappingURL=attributes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ANIMATION_VALUE_ATTRIBUTES","ENUMERATED_ATTRIBUTES","
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ANIMATION_VALUE_ATTRIBUTES","ENUMERATED_ATTRIBUTES","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalid","isEventName","lowerName","isStringValued","stripControls","kept","char","text","code","isUnsafeUrl","normalized","value","prefix","isUnsafeAttributeValue","attributeText","assertNotSymbol","ssrAttribute","resolved","resolveValue","isBoolean","escapeHtml"],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"../internal/diagnostics\";\nimport { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"poster\",\n \"data\",\n]);\n\n/**\n * SVG animation attributes (`animate`, `set`): with `attributeName=\"href\"` they write an `href` by animation, so their value\n * is checked like one. `values` is a `;` list and every entry is checked. Same as the client.\n */\nconst ANIMATION_VALUE_ATTRIBUTES: ReadonlySet<string> = new Set([\"values\", \"from\", \"to\", \"by\"]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"draggable\",\n \"spellcheck\",\n \"contenteditable\",\n]);\n\n/** URL prefixes (after normalization) that are never written. Same as the client. */\nconst UNSAFE_URL_PREFIXES: readonly string[] = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/** Throws a TypeError unless `name` can be written as an attribute name. @internal */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) {\n throw invalid(\"INVALID_ATTRIBUTE_NAME\", `\"${name}\" is not a valid attribute name.`);\n }\n}\n\n/** True for `on*` names, which never reach markup. Length matches the client's event test. @internal */\nexport function isEventName(lowerName: string): boolean {\n return lowerName.length > 2 && lowerName.startsWith(\"on\");\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their booleans are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters, which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script, after the normalization browsers apply. @internal */\nexport function isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** True when `lowerName` carries a URL (or an animated one) and `value` would run script. */\nfunction isUnsafeAttributeValue(lowerName: string, value: string): boolean {\n if (URL_ATTRIBUTES.has(lowerName)) return isUnsafeUrl(value);\n return ANIMATION_VALUE_ATTRIBUTES.has(lowerName) && value.split(\";\").some(isUnsafeUrl);\n}\n\n/** Text to write for `value`, or null when the attribute is removed. Same rules as the client. @internal */\nexport function attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** Refuses symbols, which have no markup form and would otherwise be coerced silently. */\nfunction assertNotSymbol(value: unknown): void {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be an attribute value.\");\n }\n}\n\n/**\n * Renders one attribute as markup with a leading space, or `\"\"` when the attribute is absent: the\n * helper the compiler's server output calls for a dynamic attribute. It applies the client's value\n * rules and URL check, so server and client agree on what is written.\n *\n * - `null`, `undefined` and `false` give `\"\"` (except `false` on `aria-*`, `data-*`, `draggable`,\n * `spellcheck` and `contenteditable`, which is written as `\"false\"`); `true` writes `=\"\"` (or\n * `\"true\"` for those same names). Other values are written as `String(value)`, HTML-escaped.\n * - URL attributes whose value would run script are dropped, with the check of\n * `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).\n * - `srcdoc` is an HTML sink, not a URL: its value is a document the frame runs, escaped for the attribute\n * and otherwise written as it is, with the trust of `innerHTML`. Sanitize it and give the frame a `sandbox`\n * attribute. Development builds warn once with `SRCDOC_DYNAMIC`.\n * - `on*` names are dropped: event handlers never reach markup.\n * - Accessors are called (untracked) until a plain value remains.\n *\n * @param name Attribute name, matching `[A-Za-z_:][A-Za-z0-9_:.-]*`. It is validated before\n * anything else, so an invalid name always throws.\n * @param value The value, or an accessor of it.\n * @param isBoolean `true` for a presence attribute such as `disabled`: a truthy value writes the bare\n * name, a falsy one writes nothing. Default: `false`.\n * @returns Markup such as `' title=\"a&b\"'`, or `\"\"`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an invalid name, and `UNRECOGNIZED_INSERT_VALUE`\n * when the value is a symbol.\n * @example\n * import { ssrAttribute } from \"@shadow-js/web/server\";\n *\n * ssrAttribute(\"title\", \"Tom & Jerry\"); // ' title=\"Tom & Jerry\"'\n * ssrAttribute(\"disabled\", true, true); // \" disabled\"\n * ssrAttribute(\"href\", \"javascript:alert(1)\"); // \"\"\n * @since 1.0.0\n */\nexport function ssrAttribute(name: string, value: unknown, isBoolean = false): string {\n assertAttributeName(name);\n const lowerName = name.toLowerCase();\n if (isEventName(lowerName)) return \"\";\n const resolved = resolveValue(value);\n assertNotSymbol(resolved);\n if (isBoolean) return resolved ? ` ${name}` : \"\";\n const text = attributeText(lowerName, resolved);\n if (text === null) return \"\";\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeAttributeValue(lowerName, text)) return \"\";\n return ` ${name}=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":"A,iGAKA,MAAMA,EAAiB,+BAGjBC,kBAAsC,IAAI,IAAI,CAClD,OACA,MACA,SACA,aACA,aACA,SACA,MACF,CAAC,EAMKC,kBAAkD,IAAI,IAAI,CAAC,SAAU,OAAQ,KAAM,IAAI,CAAC,EAGxFC,kBAA6C,IAAI,IAAI,CACzD,YACA,aACA,iBACF,CAAC,EAGKC,EAAyC,CAAC,cAAe,iBAAkB,WAAW,EAG5F,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACL,EAAe,KAAKM,CAAI,EAC3B,MAAMC,EAAQ,yBAA0B,IAAID,EAAK,iCAAiC,CAEtF,CAGA,SAAgBE,EAAY,EAA4B,CACtD,OAAOC,EAAU,OAAS,GAAKA,EAAU,WAAW,IAAI,CAC1D,CAGA,SAASC,EAAe,EAA4B,CAClD,OACED,EAAU,WAAW,OAAO,GAC5BA,EAAU,WAAW,OAAO,GAC5BN,EAAsB,IAAIM,CAAS,CAEvC,CAGA,SAASE,EAAc,EAAsB,CAC3C,IAAIC,EAAO,GACX,IAAK,IAAMC,KAAQC,EAAM,CACvB,IAAMC,EAAOF,EAAK,WAAW,CAAC,EAC1BE,EAAO,KAASA,EAAO,KAAQA,EAAO,OAAO,GAAQF,EAC3D,CACA,OAAOD,CACT,CAGA,SAAgBI,EAAY,EAAwB,CAClD,IAAMC,EAAaN,EAAcO,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,EAC3D,OAAOd,EAAoB,KAAM,GAAWa,EAAW,WAAWE,CAAM,CAAC,CAC3E,CAGA,SAASC,EAAuB,EAAmB,EAAwB,CAEzE,OADInB,EAAe,IAAIQ,CAAS,EAAUO,EAAYE,CAAK,EACpDhB,EAA2B,IAAIO,CAAS,GAAKS,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKF,CAAW,CACvF,CAGA,SAAgBK,EAAc,EAAmB,EAA+B,CAI9E,OAHIH,GAAU,KAAoC,KAC9CA,IAAU,GAAcR,EAAeD,CAAS,EAAI,QAAU,KAC9DS,IAAU,GAAaR,EAAeD,CAAS,EAAI,OAAS,GACzD,OAAOS,CAAK,CACrB,CAGA,SAASI,EAAgB,EAAsB,CAC7C,GAAI,OAAOJ,GAAU,SACnB,MAAMX,EAAQ,4BAA6B,wCAAwC,CAEvF,CAkCA,SAAgBgB,EAAa,EAAc,EAAgB,EAAY,GAAe,CACpFlB,EAAoBC,CAAI,EACxB,IAAMG,EAAYH,EAAK,YAAY,EACnC,GAAIE,EAAYC,CAAS,EAAG,MAAO,GACnC,IAAMe,EAAWC,EAAaP,CAAK,EAEnC,GADAI,EAAgBE,CAAQ,EACpBE,EAAW,OAAOF,EAAW,IAAIlB,IAAS,GAC9C,IAAMQ,EAAOO,EAAcZ,EAAWe,CAAQ,EAI9C,OAHIV,IAAS,MAETM,EAAuBX,EAAWK,CAAI,EAAU,GAC7C,IAAIR,EAAK,IAAIqB,EAAWb,CAAI,EAAE,EACvC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n}from"../internal/react-names.js";import{invalid as
|
|
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};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|