@shadow-js/web 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/dev/attributes.d.ts +10 -3
- package/dist/dev/attributes.js +27 -49
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +6 -2
- package/dist/dev/class-style.js +24 -7
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.d.ts +11 -2
- package/dist/dev/control-flow/dynamic.js +56 -39
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/portal.js +2 -0
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/element.js +1 -1
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +15 -44
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/insert.d.ts +15 -5
- package/dist/dev/insert.js +35 -13
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +2 -1
- package/dist/dev/internal/claim.js +18 -2
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/diagnostics.d.ts +7 -3
- package/dist/dev/internal/diagnostics.js +14 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +20 -2
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/react-names.js +25 -61
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +3 -6
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/jsx/global.d.ts +5 -2
- package/dist/dev/jsx/html.d.ts +1 -0
- package/dist/dev/resource-hints.js +4 -2
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.js +5 -15
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -0
- package/dist/dev/server/attributes.js +5 -1
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +8 -4
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +7 -1
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.js +14 -6
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.js +5 -2
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +2 -1
- package/dist/dev/server/raw-text.d.ts +28 -0
- package/dist/dev/server/raw-text.js +66 -0
- package/dist/dev/server/raw-text.js.map +1 -0
- package/dist/dev/server/render.d.ts +2 -1
- package/dist/dev/server/render.js +2 -2
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/stream.d.ts +1 -1
- package/dist/dev/server/stream.js +2 -2
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +2 -1
- package/dist/dev/server.js +2 -1
- package/dist/dev/spread.js +7 -54
- package/dist/dev/spread.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/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js +1 -1
- package/dist/prod/internal/early-events.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/resource-hints.js +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js +1 -1
- package/dist/prod/select-value.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/errors.js +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/raw-text.js +2 -0
- package/dist/prod/server/raw-text.js.map +1 -0
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server/stream.js.map +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/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 +1 -1
- package/dist/server/control-flow/dynamic.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/element.js +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js +1 -1
- package/dist/server/internal/early-events.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/resource-hints.js +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js +1 -1
- package/dist/server/select-value.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/errors.js +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/raw-text.js +2 -0
- package/dist/server/server/raw-text.js.map +1 -0
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server/stream.js.map +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-dev/attributes.js +27 -49
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +24 -7
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +22 -10
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +2 -0
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/element.js +3 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +15 -44
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/insert.js +35 -13
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/claim.js +18 -2
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +14 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +20 -2
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +25 -61
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +3 -6
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/resource-hints.js +4 -2
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +5 -15
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +5 -1
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +8 -4
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +7 -1
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +14 -6
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +5 -2
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/index.js +2 -1
- package/dist/server-dev/server/raw-text.js +86 -0
- package/dist/server-dev/server/raw-text.js.map +1 -0
- package/dist/server-dev/server/render.js +2 -2
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/stream.js +2 -2
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +2 -1
- package/dist/server-dev/spread.js +7 -54
- package/dist/server-dev/spread.js.map +1 -1
- package/package.json +3 -2
package/dist/prod/insert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insert.js","names":["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","attached","marker","reconcileRegion","parent","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","containsFunction","stack","createCallCache","memos","touched","createComputation","readComputation","disposeOwner","bindRegion","value","latest","useRenderEffect","cache","currentOwner","removeRegion","anchor","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\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.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n readonly anchor: Node | null;\n marker: Node | 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 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 (typeof item === \"string\") parts.push(item);\n else if (typeof item === \"number\") parts.push(String(item));\n else 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));\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, or its marker. */\nfunction endOf(region: Region, attached: readonly Node[]): Node | null {\n if (region.anchor !== null) return region.anchor;\n const last = attached.at(-1);\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);\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, nodes));\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 = { parent, anchor: anchorNode, marker, nodes, texts: null };\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 * 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.\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\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.\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);\n}\n"],"mappings":"A,sRA0CA,SAASA,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,IAA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OA,SAAgBI,EAAa,EAAsB,CACjD,IAAK,IAAMnE,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgBoE,EAAO,EAAc,EAA2B,CAC9D,IAAM/D,EAAON,EAAWwC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAalC,EAAMgE,CAAM,EACzBhE,CACT,CAqCA,SAAgBiE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiBnB,GAAc,KAIrC,OAAOS,EADQV,EAAaZ,EAAQgC,EADlCrB,IAAY,IAAA,GAAYsB,EAAO,QAAQ,WAAWjC,EAAQgC,CAAc,EAAIrB,CAEvD,EAAGY,CAAK,CACjC,C"}
|
|
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,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,SAASO,EAAQ,EAAe,EAAwC,GAAOC,EAAG,EAAW,CAC3F,IAAMC,EAAgB,CAAC,EACjBC,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,IAAQ,EAC/B,GAAIC,IAAU,IAAA,IAAaC,GAAUD,EAAM,OAAQ,CACjD,IAAME,EAA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A2B,CAC9D,IAAMpD,EAAON,EAAWuC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAajC,EAAMqE,CAAM,EACzBrE,CACT,CAwCA,SAAgBsE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiBxB,GAAc,KAIrC,OAAOe,EADQhB,EAAab,EAAQsC,EADlC1B,IAAY,IAAA,GAAY2B,EAAO,QAAQ,WAAWvC,EAAQsC,CAAc,EAAI1B,CAEvD,EAAGkB,EAAOQ,IAAmB,IAAI,CAC1D,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();if(e===void 0)break;let 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)}function s(t,n){let r=e;if(r===null)return;let i=r.pending.get(t)?.shift();if(i
|
|
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();if(e===void 0)break;let 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","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/**\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).\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 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,E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jD,IAAMU,EAAUV,EAAMC,GACtB,GAAIS,IAAY,IAAA,IAAaA,EAAQ,WAAa,EAAG,SACrD,IAAMtC,EAAQsC,EAAoB,KAClC,GAAI,CAACtC,EAAK,WAAWwB,CAAW,EAAG,SACnC,IAAMO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUhC,EAAM2B,EAAezB,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMuC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMjC,KAAQ8B,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvCzC,EAAK,aAAe6B,GAAMA,EAAK,YAAY7B,CAAI,EAErD,EAAOyC,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOhC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASiC,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();\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,E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AAST,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
|
-
function e(e,t){}function t(e){return/* @__PURE__ */ TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: "${e}"`)}export{t as invalidAttributeName,e as warnOnce};
|
|
1
|
+
function e(e,t,n){}function t(e){return/* @__PURE__ */ TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: "${e}"`)}export{t as invalidAttributeName,e as warnOnce};
|
|
2
2
|
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\";\n\nconst seen = new Set<
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one)\n * `SRCDOC_DYNAMIC` (a value computed at run time was written to `srcdoc`, an HTML sink) and\n * `DYNAMIC_SVG_CASE` (`Dynamic` was given an SVG element name in a case SVG does not spell it in).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\"\n | \"SRCDOC_DYNAMIC\"\n | \"DYNAMIC_SVG_CASE\";\n\n/** The codes reported, and the `code:key` pairs of the warnings that pass a key. */\nconst seen = new Set<string>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @param key Optional. With a key the warning is once per `code` and `key` instead of once per code, for a\n * warning about a name where each name deserves a report. Pass a bounded set of keys: each is remembered.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string, key?: string): void {\n if (!__DEV__) return;\n const id = key === undefined ? code : `${code}:${key}`;\n if (seen.has(id)) return;\n seen.add(id);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/**\n * The text of the `SRCDOC_DYNAMIC` warning, shared by the client and the server writer. `srcdoc` is a whole HTML\n * document the frame runs, so it has the trust of `innerHTML`, not of a URL: no scheme check applies to it.\n * @internal\n */\nexport const SRCDOC_DYNAMIC_DETAIL =\n 'A computed value was written to \"srcdoc\". It is an HTML document the frame runs, with the trust of innerHTML: sanitize it, and add the sandbox attribute to the frame.';\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":"AAuCA,SAAgBA,EAAS,EAAsB,EAAgB,EAAoB,CAMnF,CAoBA,SAAgBC,EAAqB,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCC,EAAK,EAAE,CAE/E,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=[`click`,`input`],t=`__SHADOWJS_EARLY__`,n=/^[a-z]+$/;function r(e){return`(function(){var d=document,n=`+JSON.stringify(e.filter(e=>n.test(e)))+`,q=[];function c(e){q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${t}={queue:q,names:n,listener:c};})();`}function i(){let e=Reflect.get(globalThis,t);if(typeof e!=`object`||!e)return;let n=Reflect.get(e,`queue`),r=Reflect.get(e,`names`),i=Reflect.get(e,`listener`);if(Array.isArray(n)&&Array.isArray(r)&&typeof i==`function`)return{queue:n.filter(e=>e instanceof Event),names:r.filter(e=>typeof e==`string`),listener:i}}function a(e){let t={bubbles:!0,cancelable:e.cancelable,composed:!0};return e instanceof MouseEvent?new MouseEvent(e.type,{...t,clientX:e.clientX,clientY:e.clientY,button:e.button,buttons:e.buttons,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey}):new Event(e.type,t)}function o(){let e=i();if(e!==void 0){Reflect.deleteProperty(globalThis,t);for(let t of e.names)document.removeEventListener(t,e.listener,!0);for(let t of e.queue){let e=t.target;e instanceof Node&&e.dispatchEvent(a(t))}}}export{e as DEFAULT_EARLY_EVENTS,t as EARLY_CAPTURE_KEY,r as captureScriptBody,o as replayEarlyEvents};
|
|
1
|
+
const e=[`click`,`input`],t=`__SHADOWJS_EARLY__`,n=/^[a-z]+$/;function r(e){return`(function(){var d=document,n=`+JSON.stringify(e.filter(e=>n.test(e)))+`,q=[];function c(e){if(q.length<100)q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${t}={queue:q,names:n,listener:c};})();`}function i(){let e=Reflect.get(globalThis,t);if(typeof e!=`object`||!e)return;let n=Reflect.get(e,`queue`),r=Reflect.get(e,`names`),i=Reflect.get(e,`listener`);if(Array.isArray(n)&&Array.isArray(r)&&typeof i==`function`)return{queue:n.filter(e=>e instanceof Event),names:r.filter(e=>typeof e==`string`),listener:i}}function a(e){let t={bubbles:!0,cancelable:e.cancelable,composed:!0};return e instanceof MouseEvent?new MouseEvent(e.type,{...t,clientX:e.clientX,clientY:e.clientY,button:e.button,buttons:e.buttons,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey}):new Event(e.type,t)}function o(){let e=i();if(e!==void 0){Reflect.deleteProperty(globalThis,t);for(let t of e.names)document.removeEventListener(t,e.listener,!0);for(let t of e.queue){let e=t.target;e instanceof Node&&e.dispatchEvent(s(a(t)))}}}function s(e){e.preventDefault();let t=!1;return Object.defineProperties(e,{defaultPrevented:{get:()=>t},preventDefault:{value:()=>{t=!0}}}),e}export{e as DEFAULT_EARLY_EVENTS,t as EARLY_CAPTURE_KEY,r as captureScriptBody,o as replayEarlyEvents};
|
|
2
2
|
//# sourceMappingURL=early-events.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","init","event","replayEarlyEvents","capture","target"],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n
|
|
1
|
+
{"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","init","event","replayEarlyEvents","capture","target","withoutDefaultAction","prevented"],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/**\n * The most events the capture script keeps. A page whose bundle never loads would otherwise hold every\n * click and keystroke of the visit; the first ones are the ones worth replaying. @internal\n */\nexport const MAX_EARLY_EVENTS = 100;\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n `,q=[];function c(e){if(q.length<${MAX_EARLY_EVENTS})q.push(e)}` +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(withoutDefaultAction(reissue(event)));\n }\n}\n\n/**\n * The replayed event runs the page's handlers, not the browser's default action: the real event\n * already ran it when the user made it. A dispatched `click` on a link follows the link, so without\n * this a link was followed twice. The native flag is set right away, which cancels the default action,\n * and the handlers still see `defaultPrevented` as false (a router skips a click that is already\n * prevented) until one of them prevents it itself.\n */\nfunction withoutDefaultAction(event: Event): Event {\n event.preventDefault();\n let prevented = false;\n Object.defineProperties(event, {\n defaultPrevented: { get: () => prevented },\n preventDefault: {\n value: () => {\n prevented = true;\n },\n },\n });\n return event;\n}\n"],"mappings":"AASA,MAAaA,EAA0C,CAAC,QAAS,OAAO,EAG3DC,EAAoB,qBAS3BC,EAAa,WAQnB,SAAgBC,EAAkB,EAAkC,CAElE,MACE,gCAFW,KAAK,UAAUC,EAAM,OAAQ,GAASF,EAAW,KAAKG,CAAI,CAAC,CAGnE,EACH,mHAEUJ,EAAkB,oCAEhC,CASA,SAASK,GAAmC,CAC1C,IAAMC,EAAiB,QAAQ,IAAI,WAAYN,CAAiB,EAChE,GAAI,OAAOM,GAAU,WAAYA,EAAgB,OACjD,IAAMC,EAAiB,QAAQ,IAAID,EAAO,OAAO,EAC3CH,EAAiB,QAAQ,IAAIG,EAAO,OAAO,EAC3CE,EAAoB,QAAQ,IAAIF,EAAO,UAAU,EACvD,GAAK,MAAM,QAAQC,CAAK,GAAM,MAAM,QAAQJ,CAAK,GAAK,OAAOK,GAAa,WAK1E,MAAO,CAAE,MAFMD,EAAM,OAAQ,GAAwBE,aAAgB,KAEhD,EAAG,MADVN,EAAM,OAAQ,GAAyB,OAAOC,GAAS,QAClC,EAAa,UAAmC,CACrF,CAGA,SAASM,EAAQ,EAAqB,CACpC,IAAMC,EAAkB,CAAE,QAAS,GAAM,WAAYC,EAAM,WAAY,SAAU,EAAK,EActF,OAbIA,aAAiB,WACZ,IAAI,WAAWA,EAAM,KAAM,CAChC,GAAGD,EACH,QAASC,EAAM,QACf,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,QAASA,EAAM,QACf,SAAUA,EAAM,QAClB,CAAC,EAEI,IAAI,MAAMA,EAAM,KAAMD,CAAI,CACnC,CAOA,SAAgBE,GAA0B,CACxC,IAAMC,EAAUT,EAAY,EAC5B,GAAIS,IAAY,IAAA,GAChB,SAAQ,eAAe,WAAYd,CAAiB,EACpD,IAAK,IAAMI,KAAQU,EAAQ,MAAO,SAAS,oBAAoBV,EAAMU,EAAQ,SAAU,EAAI,EAC3F,IAAK,IAAMF,KAASE,EAAQ,MAAO,CACjC,IAAMC,EAASH,EAAM,OACjBG,aAAkB,MAAMA,EAAO,cAAcC,EAAqBN,EAAQE,CAAK,CAAC,CAAC,CACvF,CALoD,CAMtD,CASA,SAASI,EAAqB,EAAqB,CACjDJ,EAAM,eAAe,EACrB,IAAIK,EAAY,GAShB,OARA,OAAO,iBAAiBL,EAAO,CAC7B,iBAAkB,CAAE,QAAWK,CAAU,EACzC,eAAgB,CACd,UAAa,CACX,EAAY,EACd,CACF,CACF,CAAC,EACML,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=/^(?: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
|
|
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=/* @__PURE__ */ new Set([`key`,`suppressHydrationWarning`,`suppressContentEditableWarning`]),i=/* @__PURE__ */ new Map([[`focus`,`focusin`],[`blur`,`focusout`],[`doubleclick`,`dblclick`]]),a=/* @__PURE__ */ new Set([`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.has(n))?`input`:`change`:i.get(s)??s),{type:c,capture:o,passive:r&&s===`wheel`&&!o}}export{r as IGNORED_KEYS,n as attributeName,o as eventPlan};
|
|
2
2
|
//# sourceMappingURL=react-names.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","
|
|
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: ReadonlySet<string> = new Set([\n \"key\",\n \"suppressHydrationWarning\",\n \"suppressContentEditableWarning\",\n]);\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: ReadonlySet<string> = new Set([\"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.has(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\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,kBAAoC,IAAI,IAAI,CACvD,MACA,2BACA,gCACF,CAAC,EAUKC,kBAA4C,IAAI,IAAI,CACxD,CAAC,QAAS,SAAS,EACnB,CAAC,OAAQ,UAAU,EACnB,CAAC,cAAe,UAAU,CAC5B,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CAAC,WAAY,QAAS,MAAM,CAAC,EASlF,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,IAAIQ,CAAI,GACnF,QACA,SACDT,EAAa,IAAIM,CAAK,GAAKA,GAE7B,CAAE,KAAMC,EAAS,UAAS,QAASJ,GAAiBG,IAAU,SAAW,CAACD,CAAQ,CAC3F,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]??0,a=0,o=r.length;for(;a<o;){let t=a+o>>1;(e[r[t]??0]??0)<n?a=t+1:o=t}i[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]??0,a=0,o=r.length;for(;a<o;){let t=a+o>>1;(e[r[t]??0]??0)<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]??0)-t]=1,a=i[a]??-1}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];if(i===void 0)continue;let 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];t!==void 0&&(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] ?? 0;\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] ?? 0] ?? 0;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n
|
|
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] ?? 0;\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] ?? 0] ?? 0;\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] ?? 0) - offset] = 1;\n cursor = previous[cursor] ?? -1;\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];\n if (node === undefined) continue;\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];\n if (node === undefined) continue;\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,IAAU,EAC3BE,EAAM,EACNC,EAAON,EAAM,OACjB,KAAOK,EAAMC,GAAM,CACjB,IAA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,EAAQD,CAAI,EAC9CwB,EAAU,KAAKC,CAAQ,CAC9B,CAKA,GAAID,EAAU,SAAW,EAAG,CAC1B,IAAK,IAAMxB,KAAQiB,EAAK,MAAMC,EAAME,CAAQ,EAAGnB,EAAO,aAAaD,EAAMqB,CAAM,EAC/E,MACF,CAEA,IAAMK,EAAS,IAAI,WAAWN,EAAWF,CAAI,EAC7ChB,EAAsBsB,EAAWN,EAAMQ,CAAM,EAC7C,IAAMC,EAAU,OAAQ1B,EAAkC,YAAe,WAErE2B,EAAaP,EACjB,IAAK,IAAIf,EAAQc,EAAW,EAAGd,GAASY,EAAM,IAAY,CACxD,IAAMlB,EAAOiB,EAAKX,GACdN,IAAS,IAAA,KACT0B,EAAOpB,EAAQY,KAAU,IACvBS,GAAW3B,EAAK,aAAeC,EACjCA,EAA0B,WAAWD,EAAM4B,CAAU,EAClD3B,EAAO,aAAaD,EAAM4B,CAAU,GAE3C,EAAa5B,EACf,CACF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useHead as e}from"./head/use-head.js";import{isServer as t}from"@shadow-js/core";function n(e){let t=new URL(e,`https://base.invalid`);if(t.protocol!==`https:`&&t.protocol!==`http:`)throw TypeError(`SHADOW_RESOURCE_HINT_URL`)}function r(e,t){for(let[n,r]of Object.entries(t))if(e.getAttribute(n)!==r)return!1;return!0}function i(e,n,i=()=>void 0){if(t){i();return}if(typeof document>`u`)return;for(let t of
|
|
1
|
+
import{useHead as e}from"./head/use-head.js";import{isServer as t}from"@shadow-js/core";function n(e){let t=new URL(e,`https://base.invalid`);if(t.protocol!==`https:`&&t.protocol!==`http:`)throw TypeError(`SHADOW_RESOURCE_HINT_URL`)}function r(e,t){for(let[n,r]of Object.entries(t))if(e.getAttribute(n)!==r)return!1;return!0}function i(e,n,i=()=>void 0){if(t){i();return}if(typeof document>`u`)return;let a=e===`script`?e=>e.getAttribute(`src`)===n.src&&(e.getAttribute(`type`)??``)===(n.type??``):e=>r(e,n);for(let t of(e===`script`?document:document.head).querySelectorAll(e))if(a(t))return;let o=document.createElement(e);for(let[e,t]of Object.entries(n))o.setAttribute(e,t);document.head.append(o)}function a(t){return()=>e({tag:`link`,props:t})}function o(e,t){n(e);let r={rel:`preconnect`,href:e,...t?.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}};i(`link`,r,a(r))}function s(e){n(e);let t={rel:`dns-prefetch`,href:e};i(`link`,t,a(t))}function c(e,t){n(e);let r={rel:`preload`,href:e,as:t.as,...t.type===void 0?{}:{type:t.type},...t.media===void 0?{}:{media:t.media},...t.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}};i(`link`,r,a(r))}function l(e,t){n(e);let r={rel:`modulepreload`,href:e,...t?.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}};i(`link`,r,a(r))}function u(e,t){if(n(e),t.as===`style`){let n={rel:`stylesheet`,href:e,...t.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}};i(`link`,n,a(n))}else i(`script`,{src:e,async:``,...t.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}},a({rel:`preload`,href:e,as:`script`}))}function d(e,t){n(e),i(`script`,{src:e,type:`module`,...t?.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}},a({rel:`modulepreload`,href:e,...t?.crossOrigin===void 0?{}:{crossorigin:t.crossOrigin}}))}export{o as preconnect,s as prefetchDNS,u as preinit,d as preinitModule,c as preload,l as preloadModule};
|
|
2
2
|
//# sourceMappingURL=resource-hints.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-hints.js","names":["checkUrl","url","href","carries","name","value","attributes","element","hint","isServer","serverTag","existing","tag","serverLink","useHead","preconnect","options","prefetchDNS","preload","preloadModule","preinit","preinitModule"],"sources":["../../src/resource-hints.ts"],"sourcesContent":["import { isServer } from \"@shadow-js/core\";\nimport { useHead } from \"./head/use-head\";\nimport type { HeadAttributeValue } from \"./head/validate\";\n\n/**\n * Options of {@link preconnect}, {@link preloadModule} and {@link preinitModule}.\n * @since 1.0.0\n */\nexport interface CrossOriginOptions {\n /**\n * CORS mode of the connection or request: `\"anonymous\"` sends no credentials, `\"use-credentials\"`\n * sends cookies and client certificates. Fonts and `fetch` preloads need one of them.\n * @default undefined (no `crossorigin` attribute; the browser's default for the resource applies)\n */\n readonly crossOrigin?: \"anonymous\" | \"use-credentials\";\n}\n\n/**\n * Options of {@link preload}: the destination is required, as the browser needs it to pick the\n * right request.\n * @since 1.0.0\n */\nexport interface PreloadOptions extends CrossOriginOptions {\n /**\n * The destination of the request, which the browser uses to pick its priority and headers. It\n * must match how the resource is used later, or the preloaded copy is not reused.\n */\n readonly as:\n | \"audio\"\n | \"document\"\n | \"embed\"\n | \"fetch\"\n | \"font\"\n | \"image\"\n | \"object\"\n | \"script\"\n | \"style\"\n | \"track\"\n | \"video\"\n | \"worker\";\n /**\n * MIME type, so the browser can skip unsupported formats (for example `font/woff2`).\n * @default undefined (no `type` attribute)\n */\n readonly type?: string;\n /**\n * Media query the hint applies to (for example `(min-width: 800px)`); the browser skips the\n * preload when it does not match.\n * @default undefined (no `media` attribute; the hint always applies)\n */\n readonly media?: string;\n}\n\n/**\n * Options of {@link preinit}.\n * @since 1.0.0\n */\nexport interface PreinitOptions extends CrossOriginOptions {\n /**\n * What to load: `\"style\"` inserts a stylesheet, `\"script\"` inserts an async script. Required, as\n * the two produce different elements.\n */\n readonly as: \"style\" | \"script\";\n}\n\ntype Attributes = Readonly<Record<string, string>>;\n\n/** Hints are page-level and only ever use http(s) URLs; anything else throws, like head tags do. */\nfunction checkUrl(href: string): void {\n const url = new URL(href, \"https://base.invalid\");\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\n __DEV__\n ? `resource hint: \"${href}\" must be an http(s) or relative URL`\n : \"SHADOW_RESOURCE_HINT_URL\",\n );\n }\n}\n\n/** Whether an element already carries every attribute of a hint (so the hint is already there). */\nfunction carries(element: Element, attributes: Attributes): boolean {\n for (const [name, value] of Object.entries(attributes)) {\n if (element.getAttribute(name) !== value) return false;\n }\n return true;\n}\n\n/**\n * Inserts a hint element once: an identical element already in the head (server-rendered or added\n * earlier) is kept. On the server the hint joins the render's head collector, when there is one.\n */\nfunction hint(\n tag: \"link\" | \"script\",\n attributes: Attributes,\n serverTag: () => void = () => undefined,\n): void {\n if (isServer) {\n serverTag();\n return;\n }\n if (typeof document === \"undefined\") return;\n for (const existing of document.head.querySelectorAll(tag)) {\n if (carries(existing, attributes)) return;\n }\n const element = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);\n document.head.append(element);\n}\n\n/** Server form of a hint: a head link (scripts cannot be head tags, see {@link preinitModule}). */\nfunction serverLink(attributes: Readonly<Record<string, HeadAttributeValue>>): () => void {\n return () => useHead({ tag: \"link\", props: attributes });\n}\n\n/**\n * Tells the browser to open a connection (DNS, TCP, TLS) to an origin the page will use soon.\n * React's `preconnect`. Calling it again for the same origin adds nothing. Works in a component, in\n * an event handler, or at module scope on the client.\n *\n * @param href An http(s) origin or URL.\n * @param options CORS mode (needed for fonts and fetch with credentials). Undefined adds no\n * `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or\n * relative.\n * @example\n * import { preconnect } from \"@shadow-js/web\";\n *\n * preconnect(\"https://fonts.example.com\", { crossOrigin: \"anonymous\" });\n * @see prefetchDNS\n * @see preload\n * @since 1.0.0\n */\nexport function preconnect(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preconnect\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Resolves an origin's DNS ahead of use. Cheaper than {@link preconnect}; React's `prefetchDNS`.\n * @param href An http(s) origin or URL.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { prefetchDNS } from \"@shadow-js/web\";\n *\n * prefetchDNS(\"https://api.example.com\");\n * @see preconnect\n * @since 1.0.0\n */\nexport function prefetchDNS(href: string): void {\n checkUrl(href);\n const attributes: Attributes = { rel: \"dns-prefetch\", href };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts fetching a resource the page will need, at high priority. The browser stores it for the\n * later request with the same URL and destination (React's `preload`).\n *\n * @param href An http(s) or relative URL.\n * @param options The destination (`as`, required) and the optional type, media and CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preload } from \"@shadow-js/web\";\n *\n * preload(\"/fonts/inter.woff2\", { as: \"font\", type: \"font/woff2\", crossOrigin: \"anonymous\" });\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preload(href: string, options: PreloadOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preload\",\n href,\n as: options.as,\n ...(options.type === undefined ? {} : { type: options.type }),\n ...(options.media === undefined ? {} : { media: options.media }),\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts loading an ES module the page will import, so the import does not wait for the module\n * graph to be discovered. React's `preloadModule`.\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preloadModule } from \"@shadow-js/web\";\n *\n * preloadModule(\"/chunks/editor.js\");\n * @see preinitModule\n * @see preload\n * @since 1.0.0\n */\nexport function preloadModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Loads a stylesheet or script now, and keeps it applied or executed (React's `preinit`). A\n * stylesheet becomes a `<link rel=\"stylesheet\">`; a script becomes an async `<script>` in the head.\n * On the server a script can only be hinted as a preload, because head tags cannot be scripts.\n *\n * @param href An http(s) or relative URL.\n * @param options What to load (`style` or `script`, required) and the CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinit } from \"@shadow-js/web\";\n *\n * preinit(\"/theme.css\", { as: \"style\" });\n * @see preload\n * @see preinitModule\n * @since 1.0.0\n */\nexport function preinit(href: string, options: PreinitOptions): void {\n checkUrl(href);\n if (options.as === \"style\") {\n const attributes: Attributes = {\n rel: \"stylesheet\",\n href,\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n return;\n }\n const attributes: Attributes = {\n src: href,\n async: \"\",\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"script\", attributes, serverLink({ rel: \"preload\", href, as: \"script\" }));\n}\n\n/**\n * Loads and runs an ES module now (React's `preinitModule`). On the client it inserts a\n * `<script type=\"module\">`; on the server it hints the module with `modulepreload`, since the\n * script itself is loaded by the page.\n *\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinitModule } from \"@shadow-js/web\";\n *\n * preinitModule(\"/chunks/app.js\");\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preinitModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n src: href,\n type: \"module\",\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\n \"script\",\n attributes,\n serverLink({\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n }),\n );\n}\n"],"mappings":"A,wFAoEA,SAASA,EAAS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AA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CACnF,CAAC,CACH,CACF,C"}
|
|
1
|
+
{"version":3,"file":"resource-hints.js","names":["checkUrl","url","href","carries","name","value","attributes","element","hint","isServer","serverTag","same","tag","existing","\"src\"","\"type\"","serverLink","useHead","preconnect","options","prefetchDNS","preload","preloadModule","preinit","preinitModule"],"sources":["../../src/resource-hints.ts"],"sourcesContent":["import { isServer } from \"@shadow-js/core\";\nimport { useHead } from \"./head/use-head\";\nimport type { HeadAttributeValue } from \"./head/validate\";\n\n/**\n * Options of {@link preconnect}, {@link preloadModule} and {@link preinitModule}.\n * @since 1.0.0\n */\nexport interface CrossOriginOptions {\n /**\n * CORS mode of the connection or request: `\"anonymous\"` sends no credentials, `\"use-credentials\"`\n * sends cookies and client certificates. Fonts and `fetch` preloads need one of them.\n * @default undefined (no `crossorigin` attribute; the browser's default for the resource applies)\n */\n readonly crossOrigin?: \"anonymous\" | \"use-credentials\";\n}\n\n/**\n * Options of {@link preload}: the destination is required, as the browser needs it to pick the\n * right request.\n * @since 1.0.0\n */\nexport interface PreloadOptions extends CrossOriginOptions {\n /**\n * The destination of the request, which the browser uses to pick its priority and headers. It\n * must match how the resource is used later, or the preloaded copy is not reused.\n */\n readonly as:\n | \"audio\"\n | \"document\"\n | \"embed\"\n | \"fetch\"\n | \"font\"\n | \"image\"\n | \"object\"\n | \"script\"\n | \"style\"\n | \"track\"\n | \"video\"\n | \"worker\";\n /**\n * MIME type, so the browser can skip unsupported formats (for example `font/woff2`).\n * @default undefined (no `type` attribute)\n */\n readonly type?: string;\n /**\n * Media query the hint applies to (for example `(min-width: 800px)`); the browser skips the\n * preload when it does not match.\n * @default undefined (no `media` attribute; the hint always applies)\n */\n readonly media?: string;\n}\n\n/**\n * Options of {@link preinit}.\n * @since 1.0.0\n */\nexport interface PreinitOptions extends CrossOriginOptions {\n /**\n * What to load: `\"style\"` inserts a stylesheet, `\"script\"` inserts an async script. Required, as\n * the two produce different elements.\n */\n readonly as: \"style\" | \"script\";\n}\n\ntype Attributes = Readonly<Record<string, string>>;\n\n/** Hints are page-level and only ever use http(s) URLs; anything else throws, like head tags do. */\nfunction checkUrl(href: string): void {\n const url = new URL(href, \"https://base.invalid\");\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\n __DEV__\n ? `resource hint: \"${href}\" must be an http(s) or relative URL`\n : \"SHADOW_RESOURCE_HINT_URL\",\n );\n }\n}\n\n/** Whether an element already carries every attribute of a hint (so the hint is already there). */\nfunction carries(element: Element, attributes: Attributes): boolean {\n for (const [name, value] of Object.entries(attributes)) {\n if (element.getAttribute(name) !== value) return false;\n }\n return true;\n}\n\n/**\n * Inserts a hint element once: an identical element already in the head (server-rendered or added\n * earlier) is kept, and a script already anywhere in the document with the same `src` and `type` is\n * not loaded again. On the server the hint joins the render's head collector, when there is one.\n */\nfunction hint(\n tag: \"link\" | \"script\",\n attributes: Attributes,\n serverTag: () => void = () => undefined,\n): void {\n if (isServer) {\n serverTag();\n return;\n }\n if (typeof document === \"undefined\") return;\n // A script is the same load when its URL and kind match: the page's own bundle usually sits at the end\n // of the body, and carries `defer` or `async` or neither, so the attributes of the hint are no test.\n const same =\n tag === \"script\"\n ? (existing: Element): boolean =>\n existing.getAttribute(\"src\") === attributes[\"src\"] &&\n (existing.getAttribute(\"type\") ?? \"\") === (attributes[\"type\"] ?? \"\")\n : (existing: Element): boolean => carries(existing, attributes);\n for (const existing of (tag === \"script\" ? document : document.head).querySelectorAll(tag)) {\n if (same(existing)) return;\n }\n const element = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);\n document.head.append(element);\n}\n\n/** Server form of a hint: a head link (scripts cannot be head tags, see {@link preinitModule}). */\nfunction serverLink(attributes: Readonly<Record<string, HeadAttributeValue>>): () => void {\n return () => useHead({ tag: \"link\", props: attributes });\n}\n\n/**\n * Tells the browser to open a connection (DNS, TCP, TLS) to an origin the page will use soon.\n * React's `preconnect`. Calling it again for the same origin adds nothing. Works in a component, in\n * an event handler, or at module scope on the client.\n *\n * @param href An http(s) origin or URL.\n * @param options CORS mode (needed for fonts and fetch with credentials). Undefined adds no\n * `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or\n * relative.\n * @example\n * import { preconnect } from \"@shadow-js/web\";\n *\n * preconnect(\"https://fonts.example.com\", { crossOrigin: \"anonymous\" });\n * @see prefetchDNS\n * @see preload\n * @since 1.0.0\n */\nexport function preconnect(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preconnect\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Resolves an origin's DNS ahead of use. Cheaper than {@link preconnect}; React's `prefetchDNS`.\n * @param href An http(s) origin or URL.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { prefetchDNS } from \"@shadow-js/web\";\n *\n * prefetchDNS(\"https://api.example.com\");\n * @see preconnect\n * @since 1.0.0\n */\nexport function prefetchDNS(href: string): void {\n checkUrl(href);\n const attributes: Attributes = { rel: \"dns-prefetch\", href };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts fetching a resource the page will need, at high priority. The browser stores it for the\n * later request with the same URL and destination (React's `preload`).\n *\n * @param href An http(s) or relative URL.\n * @param options The destination (`as`, required) and the optional type, media and CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preload } from \"@shadow-js/web\";\n *\n * preload(\"/fonts/inter.woff2\", { as: \"font\", type: \"font/woff2\", crossOrigin: \"anonymous\" });\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preload(href: string, options: PreloadOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preload\",\n href,\n as: options.as,\n ...(options.type === undefined ? {} : { type: options.type }),\n ...(options.media === undefined ? {} : { media: options.media }),\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts loading an ES module the page will import, so the import does not wait for the module\n * graph to be discovered. React's `preloadModule`.\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preloadModule } from \"@shadow-js/web\";\n *\n * preloadModule(\"/chunks/editor.js\");\n * @see preinitModule\n * @see preload\n * @since 1.0.0\n */\nexport function preloadModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Loads a stylesheet or script now, and keeps it applied or executed (React's `preinit`). A\n * stylesheet becomes a `<link rel=\"stylesheet\">`; a script becomes an async `<script>` in the head.\n * On the server a script can only be hinted as a preload, because head tags cannot be scripts.\n *\n * @param href An http(s) or relative URL.\n * @param options What to load (`style` or `script`, required) and the CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinit } from \"@shadow-js/web\";\n *\n * preinit(\"/theme.css\", { as: \"style\" });\n * @see preload\n * @see preinitModule\n * @since 1.0.0\n */\nexport function preinit(href: string, options: PreinitOptions): void {\n checkUrl(href);\n if (options.as === \"style\") {\n const attributes: Attributes = {\n rel: \"stylesheet\",\n href,\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n return;\n }\n const attributes: Attributes = {\n src: href,\n async: \"\",\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"script\", attributes, serverLink({ rel: \"preload\", href, as: \"script\" }));\n}\n\n/**\n * Loads and runs an ES module now (React's `preinitModule`). On the client it inserts a\n * `<script type=\"module\">`; on the server it hints the module with `modulepreload`, since the\n * script itself is loaded by the page.\n *\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinitModule } from \"@shadow-js/web\";\n *\n * preinitModule(\"/chunks/app.js\");\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preinitModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n src: href,\n type: \"module\",\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\n \"script\",\n attributes,\n serverLink({\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n }),\n );\n}\n"],"mappings":"A,wFAoEA,SAASA,EAAS,EAAoB,CACpC,IAAMC,EAAM,IAAI,IAAIC,EAAM,sBAAsB,EAChD,GAAID,EAAI,WAAa,UAAYA,EAAI,WAAa,QAChD,MAAU,UAGJ,0BACN,CAEJ,CAGA,SAASE,EAAQ,EAAkB,EAAiC,CAClE,IAAK,GAAM,CAACC,EAAMC,KAAU,OAAO,QAAQC,CAAU,EACnD,GAAIC,EAAQ,aAAaH,CAAI,IAAMC,EAAO,MAAO,GAEnD,MAAO,EACT,CAOA,SAASG,EACP,EACA,EACA,MAA8B,IAAA,GACxB,CACN,GAAIC,EAAU,CACZC,EAAU,EACV,MACF,CACA,GAAI,OAAO,SAAa,IAAa,OAGrC,IAAMC,EACJC,IAAQ,SACH,GACCC,EAAS,aAAa,KAAK,IAAMP,EAAWQ,MAC3CD,EAAS,aAAa,MAAM,GAAK,OAASP,EAAWS,MAAW,IAClE,GAA+BZ,EAAQU,EAAUP,CAAU,EACl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,IAAK,gBACL,OACA,GAAIa,GAAS,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CACnF,EACAX,EAAK,OAAQF,EAAYU,EAAWV,CAAU,CAAC,CACjD,CAkBA,SAAgBiB,EAAQ,EAAc,EAA+B,CAEnE,GADAvB,EAASE,CAAI,EACTiB,EAAQ,KAAO,QAAS,CAC1B,IAAMb,EAAyB,CAC7B,IAAK,aACL,OACA,GAAIa,EAAQ,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CAClF,EACAX,EAAK,OAAQF,EAAYU,EAAWV,CAAU,CAAC,CAEjD,MAMAE,EAAK,SAAU,CAJb,IAAKN,EACL,MAAO,GACP,GAAIiB,EAAQ,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CAE1D,EAAGH,EAAW,CAAE,IAAK,UAAW,OAAM,GAAI,QAAS,CAAC,CAAC,CAC/E,CAkBA,SAAgBQ,EAAc,EAAc,EAAoC,CAC9ExB,EAASE,CAAI,EAMbM,EACE,SACA,CANA,IAAKN,EACL,KAAM,SACN,GAAIiB,GAAS,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CAIxE,EACTH,EAAW,CACT,IAAK,gBACL,OACA,GAAIG,GAAS,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CACnF,CAAC,CACH,CACF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){
|
|
1
|
+
function e(e){return new Set(e.filter(e=>e!=null).map(String))}function t(e){return e==null?``:String(e)}function n(n,r){if(n.multiple&&Array.isArray(r)){let t=e(r);for(let e of Array.from(n.options))e.selected=t.has(e.value)}else n.value=t(r)}export{t as plainText,n as setSelectValue};
|
|
2
2
|
//# sourceMappingURL=select-value.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select-value.js","names":["listed","
|
|
1
|
+
{"version":3,"file":"select-value.js","names":["listed","value","item","plainText","setSelectValue","select","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`).\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"AACA,SAASA,EAAO,EAAwC,CACtD,OAAO,IAAI,IAAIC,EAAM,OAAQ,GAASC,GAAS,IAA0B,CAAC,CAAC,IAAI,MAAM,CAAC,CACxF,CAGA,SAAgBC,EAAU,EAAwB,CAChD,OAAOF,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAsBA,SAAgBG,EAAe,EAA2B,EAAsB,CAC9E,GAAIC,EAAO,UAAY,MAAM,QAAQJ,CAAK,EAAG,CAC3C,IAAMK,EAASN,EAAOC,CAAK,EAC3B,IAAK,IAAMM,KAAU,MAAM,KAAKF,EAAO,OAAO,EAAG,EAAO,SAAWC,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACA,GAAO,MAAQJ,EAAUF,CAAK,CAChC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
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`,`
|
|
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=/* @__PURE__ */ new Set([`async`,`autofocus`,`autoplay`,`checked`,`controls`,`default`,`defer`,`disabled`,`formnovalidate`,`hidden`,`inert`,`ismap`,`loop`,`multiple`,`muted`,`nomodule`,`novalidate`,`open`,`playsinline`,`readonly`,`required`,`reversed`,`selected`]),c=[`javascript:`,`data:text/html`,`vbscript:`];function l(t){if(!r.test(t))throw e(`INVALID_ATTRIBUTE_NAME`,`"${t}" is not a valid attribute name.`)}function u(e){return e.length>2&&e.startsWith(`on`)}function d(e){return e.startsWith(`aria-`)||e.startsWith(`data-`)||o.has(e)}function f(e){let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&(e<127||e>159)&&(t+=n)}return t}function p(e){let t=f(e).trim().toLowerCase();return c.some(e=>t.startsWith(e))}function m(e,t){return i.has(e)?p(t):a.has(e)&&t.split(`;`).some(p)}function h(e,t){return t==null?null:t===!1?d(e)?`false`:null:t===!0?d(e)?`true`:``:String(t)}function g(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be an attribute value.`)}function _(e,r,i=!1){l(e);let a=e.toLowerCase();if(u(a))return``;let o=n(r);if(g(o),i)return o?` ${e}`:``;let s=h(a,o);return s===null||m(a,s)?``:` ${e}="${t(s)}"`}export{s as BOOLEAN_ATTRIBUTES,l as assertAttributeName,h as attributeText,u as isEventName,p as isUnsafeUrl,_ as ssrAttribute};
|
|
2
2
|
//# sourceMappingURL=attributes.js.map
|