@shadow-js/web 1.0.0 → 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 +29 -0
- package/dist/dev/attributes.d.ts +10 -5
- package/dist/dev/attributes.js +28 -51
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/autofocus.d.ts +0 -2
- package/dist/dev/autofocus.js +1 -2
- package/dist/dev/class-style.d.ts +6 -4
- package/dist/dev/class-style.js +25 -9
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/component.d.ts +0 -2
- package/dist/dev/component.js +1 -2
- package/dist/dev/control-flow/activity.d.ts +0 -2
- package/dist/dev/control-flow/activity.js +1 -2
- package/dist/dev/control-flow/branch.js +0 -1
- package/dist/dev/control-flow/client-only.d.ts +0 -2
- package/dist/dev/control-flow/client-only.js +1 -2
- package/dist/dev/control-flow/dynamic.d.ts +11 -4
- package/dist/dev/control-flow/dynamic.js +57 -41
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.d.ts +0 -2
- package/dist/dev/control-flow/error-boundary.js +1 -2
- package/dist/dev/control-flow/for.d.ts +0 -2
- package/dist/dev/control-flow/for.js +1 -2
- package/dist/dev/control-flow/fragment.d.ts +0 -2
- package/dist/dev/control-flow/fragment.js +1 -2
- package/dist/dev/control-flow/hot-link.js +1 -2
- package/dist/dev/control-flow/index-list.d.ts +0 -2
- package/dist/dev/control-flow/index-list.js +1 -2
- package/dist/dev/control-flow/lazy.d.ts +0 -2
- package/dist/dev/control-flow/lazy.js +1 -2
- package/dist/dev/control-flow/no-hydration.d.ts +0 -2
- package/dist/dev/control-flow/no-hydration.js +1 -2
- package/dist/dev/control-flow/portal.d.ts +0 -2
- package/dist/dev/control-flow/portal.js +3 -2
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/root-errors.d.ts +0 -2
- package/dist/dev/control-flow/root-errors.js +1 -2
- package/dist/dev/control-flow/show.d.ts +0 -2
- package/dist/dev/control-flow/show.js +1 -2
- package/dist/dev/control-flow/suspense-list.d.ts +0 -2
- package/dist/dev/control-flow/suspense-list.js +1 -2
- package/dist/dev/control-flow/suspense.d.ts +0 -2
- package/dist/dev/control-flow/suspense.js +1 -2
- package/dist/dev/control-flow/switch.d.ts +0 -2
- package/dist/dev/control-flow/switch.js +1 -2
- package/dist/dev/derived.d.ts +0 -2
- package/dist/dev/derived.js +1 -2
- package/dist/dev/element.d.ts +0 -2
- package/dist/dev/element.js +2 -3
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.d.ts +0 -2
- package/dist/dev/events.js +16 -46
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/head/components.d.ts +0 -2
- package/dist/dev/head/components.js +1 -2
- package/dist/dev/head/registry.js +1 -2
- package/dist/dev/head/server-head.d.ts +0 -2
- package/dist/dev/head/server-head.js +1 -2
- package/dist/dev/head/sink.js +1 -2
- package/dist/dev/head/use-head.d.ts +0 -2
- package/dist/dev/head/use-head.js +1 -2
- package/dist/dev/head/validate.d.ts +0 -2
- package/dist/dev/head/validate.js +1 -2
- package/dist/dev/hmr.d.ts +0 -2
- package/dist/dev/hmr.js +1 -2
- package/dist/dev/hydration.d.ts +0 -2
- package/dist/dev/hydration.js +1 -2
- package/dist/dev/insert.d.ts +15 -7
- package/dist/dev/insert.js +36 -15
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +2 -3
- package/dist/dev/internal/claim.js +19 -4
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +1 -2
- package/dist/dev/internal/diagnostics.d.ts +7 -5
- package/dist/dev/internal/diagnostics.js +15 -6
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +21 -4
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/hydration-hooks.d.ts +0 -2
- package/dist/dev/internal/hydration-hooks.js +0 -1
- package/dist/dev/internal/hydration-scope.d.ts +0 -2
- package/dist/dev/internal/hydration-scope.js +1 -2
- package/dist/dev/internal/names.d.ts +0 -2
- package/dist/dev/internal/names.js +1 -2
- package/dist/dev/internal/portal-context.d.ts +0 -2
- package/dist/dev/internal/portal-context.js +1 -2
- package/dist/dev/internal/react-names.js +26 -63
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +0 -2
- package/dist/dev/internal/reconcile.js +4 -8
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/internal/stream-context.d.ts +0 -2
- package/dist/dev/internal/stream-context.js +1 -2
- package/dist/dev/jsx/aria.d.ts +0 -2
- package/dist/dev/jsx/component.d.ts +0 -2
- package/dist/dev/jsx/events.d.ts +0 -2
- package/dist/dev/jsx/global.d.ts +5 -4
- package/dist/dev/jsx/html.d.ts +1 -2
- package/dist/dev/jsx/intrinsic.d.ts +0 -2
- package/dist/dev/jsx/mathml.d.ts +0 -2
- package/dist/dev/jsx/svg.d.ts +0 -2
- package/dist/dev/jsx/types.d.ts +0 -2
- package/dist/dev/jsx-runtime.d.ts +0 -2
- package/dist/dev/reactive.d.ts +0 -2
- package/dist/dev/reactive.js +1 -2
- package/dist/dev/render.d.ts +0 -2
- package/dist/dev/render.js +1 -2
- package/dist/dev/resource-hints.d.ts +0 -2
- package/dist/dev/resource-hints.js +5 -4
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.d.ts +0 -2
- package/dist/dev/select-value.js +6 -17
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -2
- package/dist/dev/server/attributes.js +6 -3
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/class-style.d.ts +0 -2
- package/dist/dev/server/class-style.js +1 -2
- package/dist/dev/server/component.d.ts +0 -2
- package/dist/dev/server/component.js +1 -2
- package/dist/dev/server/derived.d.ts +0 -2
- package/dist/dev/server/derived.js +1 -2
- package/dist/dev/server/element.d.ts +0 -2
- package/dist/dev/server/element.js +9 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +8 -3
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.d.ts +0 -2
- package/dist/dev/server/escape.js +15 -8
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.d.ts +0 -2
- package/dist/dev/server/form-controls.js +6 -4
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/hydration-script.d.ts +0 -2
- package/dist/dev/server/hydration-script.js +1 -2
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +2 -1
- package/dist/dev/server/node.d.ts +0 -2
- package/dist/dev/server/node.js +1 -2
- package/dist/dev/server/portals.d.ts +0 -2
- package/dist/dev/server/portals.js +0 -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 -3
- package/dist/dev/server/render.js +3 -4
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/serialize.d.ts +0 -2
- package/dist/dev/server/serialize.js +1 -2
- package/dist/dev/server/stream.d.ts +1 -3
- package/dist/dev/server/stream.js +3 -4
- 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.d.ts +0 -2
- package/dist/dev/spread.js +8 -56
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.d.ts +0 -2
- package/dist/dev/template.js +1 -2
- package/dist/dev/view-transition.d.ts +0 -2
- package/dist/dev/view-transition.js +1 -2
- 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 +28 -51
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/autofocus.js +1 -2
- package/dist/server-dev/class-style.js +25 -9
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/component.js +1 -2
- package/dist/server-dev/control-flow/activity.js +1 -2
- package/dist/server-dev/control-flow/branch.js +0 -1
- package/dist/server-dev/control-flow/client-only.js +1 -2
- package/dist/server-dev/control-flow/dynamic.js +23 -12
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +1 -2
- package/dist/server-dev/control-flow/for.js +1 -2
- package/dist/server-dev/control-flow/fragment.js +1 -2
- package/dist/server-dev/control-flow/hot-link.js +1 -2
- package/dist/server-dev/control-flow/index-list.js +1 -2
- package/dist/server-dev/control-flow/lazy.js +1 -2
- package/dist/server-dev/control-flow/no-hydration.js +1 -2
- package/dist/server-dev/control-flow/portal.js +3 -2
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/root-errors.js +1 -2
- package/dist/server-dev/control-flow/show.js +1 -2
- package/dist/server-dev/control-flow/suspense-list.js +1 -2
- package/dist/server-dev/control-flow/suspense.js +1 -2
- package/dist/server-dev/control-flow/switch.js +1 -2
- package/dist/server-dev/derived.js +1 -2
- package/dist/server-dev/element.js +4 -3
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +16 -46
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/head/components.js +1 -2
- package/dist/server-dev/head/registry.js +1 -2
- package/dist/server-dev/head/server-head.js +1 -2
- package/dist/server-dev/head/sink.js +1 -2
- package/dist/server-dev/head/use-head.js +1 -2
- package/dist/server-dev/head/validate.js +1 -2
- package/dist/server-dev/hydration.js +1 -2
- package/dist/server-dev/insert.js +36 -15
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/claim.js +19 -4
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +1 -2
- package/dist/server-dev/internal/diagnostics.js +15 -6
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +21 -4
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/hydration-hooks.js +0 -1
- package/dist/server-dev/internal/hydration-scope.js +1 -2
- package/dist/server-dev/internal/names.js +1 -2
- package/dist/server-dev/internal/portal-context.js +1 -2
- package/dist/server-dev/internal/react-names.js +26 -63
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +4 -8
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/internal/stream-context.js +1 -2
- package/dist/server-dev/reactive.js +1 -2
- package/dist/server-dev/render.js +1 -2
- package/dist/server-dev/resource-hints.js +5 -4
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +6 -17
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +6 -3
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/class-style.js +1 -2
- package/dist/server-dev/server/component.js +1 -2
- package/dist/server-dev/server/derived.js +1 -2
- package/dist/server-dev/server/element.js +9 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +8 -3
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +15 -8
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +6 -4
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/hydration-script.js +1 -2
- package/dist/server-dev/server/index.js +2 -1
- package/dist/server-dev/server/node.js +1 -2
- package/dist/server-dev/server/portals.js +0 -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 +3 -4
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/serialize.js +1 -2
- package/dist/server-dev/server/stream.js +3 -4
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +2 -1
- package/dist/server-dev/spread.js +8 -56
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -2
- package/dist/server-dev/view-transition.js +1 -2
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-style.js","names":["collectClasses","frames","root","cursors","active","top","frame","cursor","done","item","parts","record","key","classText","value","applyClass","text","el","svg","className","HTML_NS","asRecord","classList","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n // Explicit frames instead of recursion: array nesting depth is controlled by the user.\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 const item = frame[cursor];\n if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(\n __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\",\n );\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (record[key] && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array).\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness. `undefined` switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next: Record<string, unknown> = value ?? {};\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n const now = Boolean(next[key]);\n const was = Boolean(before[key]);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. `null`, `undefined` and `false` remove the `style` attribute.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n if (value === null || value === undefined || value === false) {\n el.removeAttribute(\"style\");\n return value;\n }\n if (typeof value !== \"object\") {\n el.style.cssText = String(value);\n return value;\n }\n const next = { ...(value as Record<string, unknown>) };\n const before = asRecord(prev) ?? {};\n if (typeof prev === \"string\") el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,qGAIA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAMC,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,EAAOP,EAAO,IAAI,EACpBO,IAAS,IAAA,IAAWJ,EAAO,OAAOI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AG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMX,KAAOc,EACZ,OAAO,GAAGF,EAAOZ,GAAMW,EAAKX,EAAI,GACpCqB,EAAiBhB,EAAIL,EAAKW,EAAKX,EAAI,EAErC,OAAOW,CACT,C"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":["collectClasses","frames","root","cursors","active","top","frame","cursor","done","item","parts","record","key","classText","value","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n // Explicit frames instead of recursion: array nesting depth is controlled by the user.\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 const item = frame[cursor];\n if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(\n __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\",\n );\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (record[key] && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array).\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness. `undefined` switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next: Record<string, unknown> = value ?? {};\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n if (value === null || value === undefined || value === false) {\n el.removeAttribute(\"style\");\n return value;\n }\n if (typeof value !== \"object\") {\n el.style.cssText = String(value);\n return value;\n }\n if (Array.isArray(value)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const item of value) {\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return value;\n }\n const next = { ...(value as Record<string, unknown>) };\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,qGAIA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAMC,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,EAAOP,EAAO,IAAI,EACpBO,IAAS,IAAA,IAAWJ,EAAO,OAAOI,CAAI,EAC1CL,EAAQ,IAAI,EACZ,QACF,CACA,EAAQE,GAAOE,EAAS,EACxB,IAAME,EAAOH,EAAMC,GACnB,GAAI,MAAM,QAAQE,CAAI,EAAG,CACvB,GAAIL,EAAO,IAAIK,CAAI,EACjB,MAAU,UACkD,oBAC5D,EACFL,EAAO,IAAIK,CAAI,EACfR,EAAO,KAAKQ,CAAI,EAChBN,EAAQ,KAAK,CAAC,CAChB,MAAO,GAAI,OAAOM,GAAS,SACrBA,IAAS,IAAIC,EAAM,KAAKD,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,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Y,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMb,KAAOgB,EACZ,OAAO,GAAGF,EAAOd,GAAMa,EAAKb,EAAI,GACpCuB,EAAiBlB,EAAIL,EAAKa,EAAKb,EAAI,EAErC,OAAOa,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"../internal/names.js";import{nextKey as
|
|
1
|
+
import{MATHML_NS as e,SVG_NS as t}from"../internal/names.js";import{nextKey as n}from"../internal/hydration-scope.js";import{createComponent as r}from"../component.js";import{claims as i}from"../internal/hydration-hooks.js";import{bindRegion as a,createRegion as o}from"../insert.js";import{spread as s}from"../spread.js";import{mergeProps as c,splitProps as l,untrack as u,useMemo as d}from"@shadow-js/core";const f=/^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/,p=/^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/,m=/^(?!script$)[a-z][a-z0-9-]*$/i;function h(n){let r=n.toLowerCase();if(p.test(r))return document.createElementNS(e,r);let i=document.createElement(n);return i.constructor!==HTMLUnknownElement&&r!==`image`||!f.test(r)?i:document.createElementNS(t,n)}function g(e,r){if(!m.test(e))throw TypeError(`SHADOW_DYNAMIC_TAG`);let c=i.current.claimElement(n())??h(e);s(c,r,c.namespaceURI===t,!0);let l=o(c,null,i.current.takeRegion(c,null));return a(l,()=>r.children),c}function _(e,t){if(!e)return null;if(typeof e==`string`)return g(e,t);if(typeof e==`function`)return r(e,t);throw TypeError(`SHADOW_DYNAMIC_COMPONENT`)}function v(e){let[,t]=l(e,[`component`]);return d(()=>{let n=e.component;return u(()=>_(n,t))},{allowWrites:!0})}function y(e,t={}){return v(c({get component(){return e()}},t))}export{v as Dynamic,y as createDynamic};
|
|
2
2
|
//# sourceMappingURL=dynamic.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":["SVG_TAGS","TAG_PATTERN","DENIED_TAGS","buildElement","lower","tag","svg","el","claims","nextKey","spread","props","region","createRegion","bindRegion","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, nextKey, SVG_NS } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { spread } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/** Tag names that take the SVG namespace. Anything else is HTML. */\nconst SVG_TAGS: ReadonlySet<string> = new Set([\n \"svg\",\n \"g\",\n \"path\",\n \"circle\",\n \"ellipse\",\n \"line\",\n \"polygon\",\n \"polyline\",\n \"rect\",\n \"text\",\n \"tspan\",\n \"textpath\",\n \"defs\",\n \"use\",\n \"symbol\",\n \"marker\",\n \"clippath\",\n \"mask\",\n \"pattern\",\n \"lineargradient\",\n \"radialgradient\",\n \"stop\",\n \"filter\",\n]);\n\n/** Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** Tags refused in any letter case: a script would bypass CSP nonces and Trusted Types. */\nconst DENIED_TAGS: ReadonlySet<string> = new Set([\"script\"]);\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n const lower = tag.toLowerCase();\n if (!TAG_PATTERN.test(tag) || DENIED_TAGS.has(lower)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n return children === undefined\n ? undefined\n : [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const svg = SVG_TAGS.has(lower);\n const claimed = claims.current.claimElement(nextKey());\n const el = claimed ?? (svg ? document.createElementNS(SVG_NS, tag) : document.createElement(tag));\n // Attributes through spread; children through insert, which adopts the server's children region.\n spread(el, props, svg, true);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. SVG-only names (`circle`, `path`, `svg`, ...) are created\n * in the SVG namespace.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,yXAiCA,MAAMA,kBAAgC,IAAI,IAAI,CAC5C,MACA,IACA,OACA,SACA,UACA,OACA,UACA,WACA,OACA,OACA,QACA,WACA,OACA,MACA,SACA,SACA,WACA,OACA,UACA,iBACA,iBACA,OACA,QACF,CAAC,EAGKC,EAAc,qBAGdC,kBAAmC,IAAI,IAAI,CAAC,QAAQ,CAAC,EAQ3D,SAASC,EAAa,EAAa,EAAwB,CACzD,IAAMC,EAAQC,EAAI,YAAY,EAC9B,GAAI,CAACJ,EAAY,KAAKI,CAAG,GAAKH,EAAY,IAAIE,CAAK,EACjD,MAAU,UAAsD,oBAAoB,EAkBtF,IAAME,EAAMN,EAAS,IAAII,CAAK,EAExBG,EADUC,EAAO,QAAQ,aAAaC,EAAQ,CACnC,IAAMH,EAAM,SAAS,gBAAA,6BAAwBD,CAAG,EAAI,SAAS,cAAcA,CAAG,GAE/FK,EAAOH,EAAII,EAAOL,EAAK,EAAI,EAC3B,IAAMM,EAASC,EAAaN,EAAI,KAAMC,EAAO,QAAQ,WAAWD,EAAI,IAAI,CAAC,EAEzE,OADAO,EAAWF,MAAeD,EAAiC,QAAQ,EAC5DJ,CACT,CAMA,SAASQ,EAAY,EAAiB,EAAwB,CAC5D,GAAI,CAACC,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOb,EAAaa,EAAQL,CAAK,EACjE,GAAI,OAAOK,GAAW,WACpB,OAAOC,EAAgBD,EAAsCL,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CAqCA,SAAgBO,EAAiC,EAAuC,CACtF,GAAM,EAAGC,GAAQC,EAAWT,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOU,MACU,CACb,IAAML,EAAkBL,EAAM,UAC9B,OAAOW,MAAcP,EAAYC,EAAQG,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAd,CACF,CACF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":["SVG_PATTERN","MATHML_TAGS","TAG_PATTERN","createTagged","lower","tag","MATHML_NS","el","SVG_NS","buildElement","claims","nextKey","spread","props","region","createRegion","bindRegion","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spread } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spread(el, props, el.namespaceURI === SVG_NS, true);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,yZAuCA,MAAMA,EACJ,gRAGI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ACF,EACAd,CACF,CACF,CACF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,removeRegion as o}from"../insert.js";import{PortalContext as s}from"../internal/portal-context.js";import{renderServerPortal as c}from"../server/portals.js";import{createRoot as l,isServer as u,onCleanup as d,useContext as f,useRenderEffect as p}from"@shadow-js/core";function m(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function h(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function g(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function _(_){let v=t(),y=f(s);if(u||y!==null)return _.useShadow!==!0&&c(v,()=>_.children,y),null;let b,x=r.current.claimPortal(v),S=()=>{let e=b;e!==void 0&&(b=void 0,e.stopEffects(),o(e.region))},C=(t,o,s)=>{let c=a(t,null,o);return{host:t,region:c,stopEffects:l(t=>{let a=()=>{i(c,()=>_.children)};return s===`plain`?a():s===`claimed`?n(e(v),a):r.current.withoutClaiming(()=>n(e(v),a)),t})}},w=e=>{let t=b;if(t===void 0){let t=x??[],n=`plain`;x===void 0?v!==void 0&&r.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,x=void 0;for(let n of t)n.parentNode!==e&&m(e,n);b=C(e,t,n);return}let n=t.region.nodes.filter(e=>e.parentNode===t.host);t.stopEffects();for(let t of n)m(e,t);b=C(e,n,`plain`)};return p(()=>({host:g(_.mount),shadow:_.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){S();return}let n=t?h(e):e;(b===void 0||b.host!==n)&&w(n)}),d(S),null}export{_ as Portal};
|
|
1
|
+
import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,removeRegion as o}from"../insert.js";import{PortalContext as s}from"../internal/portal-context.js";import{renderServerPortal as c}from"../server/portals.js";import{createRoot as l,isServer as u,onCleanup as d,useContext as f,useRenderEffect as p}from"@shadow-js/core";function m(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function h(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function g(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function _(_){let v=t(),y=f(s);if(u||y!==null)return _.useShadow!==!0&&c(v,()=>_.children,y),null;let b,x=r.current.claimPortal(v),S=()=>{let e=b;e!==void 0&&(b=void 0,e.stopEffects(),o(e.region))},C=(t,o,s)=>{let c=a(t,null,o);return{host:t,region:c,stopEffects:l(t=>{let a=()=>{i(c,()=>_.children)};return s===`plain`?a():s===`claimed`?n(e(v),a):r.current.withoutClaiming(()=>n(e(v),a)),t})}},w=e=>{let t=b;if(t===void 0){let t=x??[],n=`plain`;x===void 0?v!==void 0&&r.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,x=void 0;for(let n of t)n.parentNode!==e&&m(e,n);b=C(e,t,n);return}let n=t.region.nodes.filter(e=>e.parentNode===t.host);t.stopEffects();for(let t of n)m(e,t);b=C(e,n,`plain`)};return p(()=>({host:g(_.mount),shadow:_.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){S();for(let e of x??[])e.parentNode?.removeChild(e);x=void 0;return}let n=t?h(e):e;(b===void 0||b.host!==n)&&w(n)}),d(S),null}export{_ as Portal};
|
|
2
2
|
//# sourceMappingURL=portal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"portal.js","names":["appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","key","nextKey","sink","useContext","PortalContext","isServer","props","renderServerPortal","mounted","adopted","claims","unmount","current","removeRegion","mountInto","region","createRegion","initial","createRoot","bind","bindRegion","mode","withScope","childScope","dispose","moveTo","previous","nodes","useRenderEffect","shadow","onCleanup"],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\nimport { renderServerPortal } from \"../server/portals\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content, and static nodes keep their identity while they\n * move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) renderServerPortal(key, () => props.children, sink);\n return null;\n }\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n });\n return { host, region, stopEffects };\n };\n\n /** Moves the content to `target`. The nodes move first, then the children are bound again. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n const nodes = previous.region.nodes.filter((node) => node.parentNode === previous.host);\n previous.stopEffects();\n for (const node of nodes) appendMoved(target, node);\n mounted = mountInto(target, nodes, \"plain\");\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":"A,qcAiEA,SAASA,EAAY,EAAc,EAAkB,CAC/C,OAAQC,EAAgC,YAAe,WACzDA,EAAwB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAa,EAA2B,CAC/C,OAAOC,EAAK,YAAcA,EAAK,aAAa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,EAAQwB,EAASI,CAAI,EACzC,MACF,CACA,IAAMM,EAAQD,EAAS,OAAO,MAAM,OAAQ,GAAShC,EAAK,aAAegC,EAAS,IAAI,EACtFA,EAAS,YAAY,EACrB,IAAK,IAAMhC,KAAQiC,EAAOnC,EAAYC,EAAQC,CAAI,EAClD,EAAUoB,EAAUrB,EAAQkC,EAAO,OAAO,CAC5C,EAyBA,OAvBAC,OAIW,CAAE,KAFI/B,EAAaS,EAAM,KAEpB,EAAG,OADAA,EAAM,YAAc,EACb,IAEvB,CAAE,OAAM,YAAa,CACpB,GAAIV,IAAS,KAAM,CACjBe,EAAQ,EAOR,MACF,CACA,IAAMlB,EAAeoC,EAASlC,EAAaC,CAAI,EAAIA,GAC/CY,IAAY,IAAA,IAAaA,EAAQ,OAASf,IAC9CgC,EAAOhC,CAAM,CACf,CACF,EACAqC,EAAUnB,CAAO,EACV,IACT,C"}
|
|
1
|
+
{"version":3,"file":"portal.js","names":["appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","key","nextKey","sink","useContext","PortalContext","isServer","props","renderServerPortal","mounted","adopted","claims","unmount","current","removeRegion","mountInto","region","createRegion","initial","createRoot","bind","bindRegion","mode","withScope","childScope","dispose","moveTo","previous","nodes","useRenderEffect","shadow","onCleanup"],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\nimport { renderServerPortal } from \"../server/portals\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content, and static nodes keep their identity while they\n * move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) renderServerPortal(key, () => props.children, sink);\n return null;\n }\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n });\n return { host, region, stopEffects };\n };\n\n /** Moves the content to `target`. The nodes move first, then the children are bound again. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n const nodes = previous.region.nodes.filter((node) => node.parentNode === previous.host);\n previous.stopEffects();\n for (const node of nodes) appendMoved(target, node);\n mounted = mountInto(target, nodes, \"plain\");\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n // The server block was adopted at the call site but has nowhere to live: leaving it would show\n // content the client does not render (stripLeftovers removes the blocks nobody claimed).\n for (const node of adopted ?? []) node.parentNode?.removeChild(node);\n adopted = undefined;\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":"A,qcAiEA,SAASA,EAAY,EAAc,EAAkB,CAC/C,OAAQC,EAAgC,YAAe,WACzDA,EAAwB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAa,EAA2B,CAC/C,OAAOC,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,MAAO,CAAC,CAC9D,CAGA,SAASC,EAAa,EAA6C,CAGjE,OAFIC,IAAU,IAAA,GAAkB,SAAS,MAC3B,OAAOA,GAAU,WAAaA,EAAM,EAAIA,IACtC,IAClB,CAqCA,SAAgBC,EAAO,EAA0B,CAI/C,IAAMC,EAAMC,EAAQ,EAGdC,EA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EAAO,OAAO,CAC5C,EA6BA,OA3BAC,OAIW,CAAE,KAFI/B,EAAaS,EAAM,KAEpB,EAAG,OADAA,EAAM,YAAc,EACb,IAEvB,CAAE,OAAM,YAAa,CACpB,GAAIV,IAAS,KAAM,CACjBe,EAAQ,EAGR,IAAK,IAAMjB,KAAQe,GAAW,CAAC,EAAGf,EAAK,YAAY,YAAYA,CAAI,EACnE,EAAU,IAAA,GAOV,MACF,CACA,IAAMD,EAAeoC,EAASlC,EAAaC,CAAI,EAAIA,GAC/CY,IAAY,IAAA,IAAaA,EAAQ,OAASf,IAC9CgC,EAAOhC,CAAM,CACf,CACF,EACAqC,EAAUnB,CAAO,EACV,IACT,C"}
|
package/dist/prod/element.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{setAttribute as e}from"./attributes.js";import{style as t}from"./class-style.js";import{nextKey as n}from"./internal/hydration-scope.js";import{claims as r}from"./internal/hydration-hooks.js";import{insert as i}from"./insert.js";import{batch as a,untrack as o,useRenderEffect as s}from"@shadow-js/core";const c=/^[a-z][a-z0-9-]*$/i;function l(e){return e.length>2&&e.startsWith(`on`)&&/^[A-Z]/.test(e.charAt(2))?e.slice(2).toLowerCase():void 0}function u(e,t,n){let r;if(typeof n==`function`)r=t=>n.call(e,t);else if(Array.isArray(n)){let[t,i]=n;typeof t==`function`&&(r=n=>t.call(e,i,n))}if(r===void 0)return;let i=r;e.addEventListener(t,e=>{a(()=>o(()=>i(e)))})}function d(a,
|
|
1
|
+
import{setAttribute as e}from"./attributes.js";import{style as t}from"./class-style.js";import{nextKey as n}from"./internal/hydration-scope.js";import{claims as r}from"./internal/hydration-hooks.js";import{insert as i}from"./insert.js";import{batch as a,untrack as o,useRenderEffect as s}from"@shadow-js/core";const c=/^[a-z][a-z0-9-]*$/i;function l(e){return e.length>2&&e.startsWith(`on`)&&/^[A-Z]/.test(e.charAt(2))?e.slice(2).toLowerCase():void 0}function u(e,t,n){let r;if(typeof n==`function`)r=t=>n.call(e,t);else if(Array.isArray(n)){let[t,i]=n;typeof t==`function`&&(r=n=>t.call(e,i,n))}if(r===void 0)return;let i=r;e.addEventListener(t,e=>{a(()=>o(()=>i(e)))})}function d(a,d){if(!c.test(a)||a.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let f=d,p=r.current.claimElement(n())??document.createElement(a);for(let n of Object.keys(d)){if(n===`children`||n===`ref`)continue;let r=l(n);if(r!==void 0)u(p,r,f[n]);else if(n===`style`){let e;s(()=>f[n],n=>{e=t(p,n,e)})}else s(()=>f[n],t=>{e(p,n,t)})}let m=f.ref;return typeof m==`function`&&o(()=>m(p)),i(p,()=>f.children),p}export{d as element};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|
package/dist/prod/element.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":["TAG_PATTERN","eventNameOf","key","bindListener","call","handler","el","event","fn","data","run","name","batch","untrack","element","tag","read","props","claims","nextKey","applied","useRenderEffect","style","value","setAttribute","ref","\"ref\"","insert","\"children\""],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n
|
|
1
|
+
{"version":3,"file":"element.js","names":["TAG_PATTERN","eventNameOf","key","bindListener","call","handler","el","event","fn","data","run","name","batch","untrack","element","tag","read","props","claims","nextKey","applied","useRenderEffect","style","value","setAttribute","ref","\"ref\"","insert","\"children\""],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n const event = eventNameOf(key);\n if (event !== undefined) {\n bindListener(el, event, read[key]);\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":"A,sTAqBA,MAAMA,EAAc,qBAGpB,SAASC,EAAY,EAAiC,CACpD,OAAOC,EAA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B,OAFI,OAAOD,GAAQ,YAAYZ,MAAcY,EAAInB,CAAE,CAAC,EACpDqB,EAAOrB,MAAUU,EAAKY,QAAW,EAC1BtB,CACT,C"}
|
package/dist/prod/events.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i
|
|
1
|
+
import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/,a=/* @__PURE__ */ new WeakMap;function o(e,t,n,i){Object.defineProperty(n,"currentTarget",{configurable:!0,get:()=>t});try{r(()=>e.call(t,...i))}finally{Reflect.deleteProperty(n,`currentTarget`)}}function s(t){e(()=>c(t))}function c(e){let t=`$$${e.type}`,n=`${t}Data`,r=[];for(let i of e.composedPath()){if(e.cancelBubble)break;let a=Reflect.get(i,t);if(typeof a!=`function`)continue;let s=Reflect.get(i,n);try{o(a,i,e,s===void 0?[e]:[s,e])}catch(e){r.push(e)}}let[i]=r;if(r.length===1)throw i;if(r.length>1)throw AggregateError(r,`SHADOW_EVENT_ERRORS`)}function l(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function u(t,n,i,a){let{once:o,passive:s,signal:c}=i,l={capture:i.capture===!0||a,once:o,passive:s,signal:c},u=t=>{e(()=>r(()=>i.handleEvent(t)))};return t.addEventListener(n,u,l),()=>{t.removeEventListener(n,u,l)}}function d(e){if(typeof e==`function`)return{fn:e,data:void 0,tuple:!1};if(Array.isArray(e)&&typeof e[0]==`function`)return{fn:e[0],data:e[1],tuple:!0};throw TypeError(`SHADOW_EVENT_HANDLER`)}function f(...e){return function(t){for(let n of e)n.call(this,t)}}function p(e,t=globalThis.document){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n));for(let r of e)n.has(r)||(n.add(r),t.addEventListener(r,s))}function m(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,s);a.delete(e)}}function h(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function g(t,n,a,o,s=!1){if(a==null||a===!1)return;if(l(a))return u(t,n,a,s);let c=d(a),f=`$$${n}`,m=!c.tuple||c.data!==void 0;if(o&&m&&!s&&i.test(n)&&Reflect.get(t,f)===void 0){p([n],h(t));let e=`${f}Data`;return Reflect.set(t,f,c.fn),c.tuple?Reflect.set(t,e,c.data):Reflect.deleteProperty(t,e),()=>{Reflect.get(t,f)===c.fn&&(Reflect.deleteProperty(t,f),Reflect.deleteProperty(t,e))}}let g=n=>{let i=c.tuple?[c.data,n]:[n];e(()=>r(()=>c.fn.call(t,...i)))};return t.addEventListener(n,g,s),()=>{t.removeEventListener(n,g,s)}}function _(e,r,i,a,o){let s=g(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{_ as addEventListener,g as bindEvent,f as chainEvents,m as clearDelegatedEvents,p as delegateEvents};
|
|
2
2
|
//# sourceMappingURL=events.js.map
|
package/dist/prod/events.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","names":["holder","DELEGATED_EVENTS","installed","invoke","event","node","untrack","binding","args","expando","key","dispatchDelegated","batch","dispatchPath","dataKey","errors","fn","data","error","first","isListenerObject","handler","bindListenerObject","options","object","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS = new Set([\n \"click\",\n \"dblclick\",\n \"input\",\n \"keydown\",\n \"keyup\",\n \"keypress\",\n \"pointerdown\",\n \"pointerup\",\n \"pointermove\",\n \"mousedown\",\n \"mouseup\",\n \"mousemove\",\n \"focusin\",\n \"focusout\",\n \"beforeinput\",\n \"touchstart\",\n \"touchend\",\n \"touchmove\",\n \"contextmenu\",\n \"mouseover\",\n \"mouseout\",\n \"pointerover\",\n \"pointerout\",\n]);\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(binding: Binding, node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => binding.fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/** Reads a compiler-style expando (`node.$$click`), if present. */\nfunction expando(node: EventTarget, key: string): unknown {\n const holder: object = node;\n return Reflect.get(holder, key);\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = expando(node, key);\n if (typeof fn !== \"function\") continue;\n const data = expando(node, dataKey);\n const binding: Binding = {\n fn: fn as (this: EventTarget, ...args: unknown[]) => unknown,\n data,\n tuple: data !== undefined,\n };\n try {\n invoke(binding, node, event, binding.tuple ? [data, event] : [event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const options: AddEventListenerOptions = { capture: object.capture === true || capture };\n if (object.once !== undefined) options.once = object.once;\n if (object.passive !== undefined) options.passive = object.passive;\n if (object.signal !== undefined) options.signal = object.signal;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n if (delegate && !capture && DELEGATED_EVENTS.has(name) && Reflect.get(el, slot) === undefined) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMC,kBAAmB,IAAI,IAAI,CAC/B,QACA,WACA,QACA,UACA,QACA,WACA,cACA,YACA,cACA,YACA,UACA,YACA,UACA,WACA,cACA,aACA,WACA,YACA,cACA,YACA,WACA,cACA,YACF,CAAC,EAGKC,kBAAY,IAAI,QAUtB,SAASC,EAAO,EAAkB,EAAmB,EAAc,EAAuB,CACxF,OAAO,eAAeC,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWC,CAAK,CAAC,EACrF,GAAI,CACFC,MAAcC,EAAQ,GAAG,KAAKF,EAAM,GAAGG,CAAI,CAAC,CAC9C,QAAU,CACR,QAAQ,eAAeJ,EAAO,eAAe,CAC/C,CACF,CAGA,SAASK,EAAQ,EAAm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AAOC,EAAmBK,EAAIC,EAAMP,EAASI,CAAO,EACnF,IAAMlB,EAAUsB,EAAUR,CAAO,EAG3BmB,EAAO,KAAKZ,IAClB,GAAIa,GAAY,CAAChB,GAAWxB,EAAiB,IAAI2B,CAAI,GAAK,QAAQ,IAAID,EAAIa,CAAI,IAAM,IAAA,GAAW,CAC7FR,EAAe,CAACJ,CAAI,EAAGS,EAAmBV,CAAE,CAAC,EAC7C,IAAMb,EAAU,GAAG0B,EAAK,MAIxB,OAHA,QAAQ,IAAIb,EAAIa,EAAMjC,EAAQ,EAAE,EAC5BA,EAAQ,MAAO,QAAQ,IAAIoB,EAAIb,EAASP,EAAQ,IAAI,EACnD,QAAQ,eAAeoB,EAAIb,CAAO,MAC1B,CACP,QAAQ,IAAIa,EAAIa,CAAI,IAAMjC,EAAQ,KACpC,QAAQ,eAAeoB,EAAIa,CAAI,EAC/B,QAAQ,eAAeb,EAAIb,CAAO,EAEtC,CACF,CACA,IAAMY,EAAY,GAAuB,CACvC,IAAMlB,EAAkBD,EAAQ,MAAQ,CAACA,EAAQ,KAAMH,CAAK,EAAI,CAACA,CAAK,EACtEQ,MAAYN,MAAcC,EAAQ,GAAG,KAAKoB,EAAI,GAAGnB,CAAI,CAAC,CAAC,CACzD,EAEA,OADAmB,EAAG,iBAAiBC,EAAMF,EAAUD,CAAO,MAC9B,CACXE,EAAG,oBAAoBC,EAAMF,EAAUD,CAAO,CAChD,CACF,CA6BA,SAAgBiB,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASJ,EAAUZ,EAAIC,EAAMP,EAASoB,IAAa,GAAMhB,IAAY,EAAI,EAE3EkB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
|
|
1
|
+
{"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","invoke","event","node","untrack","fn","args","dispatchDelegated","batch","dispatchPath","key","dataKey","errors","data","error","first","isListenerObject","handler","bindListenerObject","object","options","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","binding","slot","plain","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(fn: Binding[\"fn\"], node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n invoke(fn as Binding[\"fn\"], node, event, data === undefined ? [event] : [data, event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n const options = {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n const plain = !binding.tuple || binding.data !== undefined;\n if (\n delegate &&\n plain &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAO,EAAmB,EAAmB,EAAc,EAAuB,CACzF,OAAO,eAAeC,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWC,CAAK,CAAC,EACrF,GAAI,CACFC,MAAcC,EAAG,KAAKF,EAAM,GAAGG,CAAI,CAAC,CACtC,QAAU,CACR,QAAQ,eAAeJ,EAAO,eAAe,CAC/C,CACF,CAMA,SAASK,EAAk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Ic,CAAI,IAAM,IAAA,GAC1B,CACAT,EAAe,CAACJ,CAAI,EAAGS,EAAmBV,CAAE,CAAC,EAC7C,IAAMZ,EAAU,GAAG0B,EAAK,MAIxB,OAHA,QAAQ,IAAId,EAAIc,EAAMD,EAAQ,EAAE,EAC5BA,EAAQ,MAAO,QAAQ,IAAIb,EAAIZ,EAASyB,EAAQ,IAAI,EACnD,QAAQ,eAAeb,EAAIZ,CAAO,MAC1B,CACP,QAAQ,IAAIY,EAAIc,CAAI,IAAMD,EAAQ,KACpC,QAAQ,eAAeb,EAAIc,CAAI,EAC/B,QAAQ,eAAed,EAAIZ,CAAO,EAEtC,CACF,CACA,IAAMW,EAAY,GAAuB,CACvC,IAAMhB,EAAkB8B,EAAQ,MAAQ,CAACA,EAAQ,KAAMlC,CAAK,EAAI,CAACA,CAAK,EACtEM,MAAYJ,MAAcgC,EAAQ,GAAG,KAAKb,EAAI,GAAGjB,CAAI,CAAC,CAAC,CACzD,EAEA,OADAiB,EAAG,iBAAiBC,EAAMF,EAAUD,CAAO,MAC9B,CACXE,EAAG,oBAAoBC,EAAMF,EAAUD,CAAO,CAChD,CACF,CA6BA,SAAgBmB,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASN,EAAUZ,EAAIC,EAAMP,EAASsB,IAAa,GAAMlB,IAAY,EAAI,EAE3EoB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
|
package/dist/prod/insert.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{claims as e}from"./internal/hydration-hooks.js";import{reconcileNodes as t}from"./internal/reconcile.js";import{useRenderEffect as n}from"@shadow-js/core";import{
|
|
1
|
+
import{claims as e}from"./internal/hydration-hooks.js";import{reconcileNodes as t}from"./internal/reconcile.js";import{useRenderEffect as n}from"@shadow-js/core";import{addCleanup as r,createComputation as i,currentOwner as a,disposeOwner as o,readComputation as s}from"@shadow-js/core/extend";const c=/* @__PURE__ */ new WeakMap;function l(e){return e instanceof Document?e:e.ownerDocument??document}function u(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function d(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function f(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}function p(e,t=e=>e()){let n=[],r=[[e]],i=[0],a=/* @__PURE__ */ new Set;for(;r.length>0;){let e=r.length-1,o=r[e],s=i[e]??0;if(o===void 0||s>=o.length){let e=r.pop();e!==void 0&&a.delete(e),i.pop();continue}i[e]=s+1;let c=o[s];for(let e=0;typeof c==`function`;e+=1){if(e>=1e4)throw TypeError(`SHADOW_INSERT_DEPTH`);c=t(c)}if(c!=null&&typeof c!=`boolean`){if(c instanceof DocumentFragment)for(let e of c.childNodes)n.push(e);else if(c instanceof Node)n.push(c);else if(Array.isArray(c)){if(a.has(c))throw TypeError(`SHADOW_INSERT_CYCLE`);a.add(c),r.push(c),i.push(0)}else n.push(String(c))}}return n}function m(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!u(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function h(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&u(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=m(e);let t=o.get(n)?.pop();t===void 0&&(t=l(e.parent).createTextNode(n),d(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function g(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}function _(e,n){let r=e.parent,i=e.nodes.filter(e=>e.parentNode===r),a=g(e,i.at(-1)),o=i[0];n.length===0&&o!==void 0&&(e.marker=o.previousSibling),t(r,i,n,a),e.nodes=n,f(e,n)}function v(e,t){_(e,h(e,t))}function y(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=typeof t==`string`?t:String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&u(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=l(e.parent).createTextNode(r);d(e,t),e.parent.insertBefore(t,g(e,void 0)),e.nodes=[t];return}}v(e,p(t))}function b(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i of p(t))typeof i==`string`||r.has(i)||i.parentNode!==e||(r.add(i),n.push(i));return n}function x(e,t,n){let r=n===void 0?[]:b(e,n),i={parent:e,anchor:t,marker:r.length>0?r[0]?.previousSibling??null:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&d(i,e);return i}function S(e){let t=e.parent,n=c.get(t);e.owner=a(),c.set(t,e);let i=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||g(n,n.nodes.at(-1))!==i)return;let o=D(t,i);n.anchor=e.marker=o,n.owner&&r(n.owner,()=>o.remove())}function C(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop()??[];for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function w(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;return{begin(){n=/* @__PURE__ */ new Set},call(r){n.add(r);let a=t.get(r);return a===void 0&&(a=i({kind:`memo`,fn:()=>r(),allowWrites:!0,owner:e}),t.set(r,a)),s(a)},prune(){for(let[e,r]of t)n.has(e)||(t.delete(e),o(r))}}}function T(e,t,r){if(!C(t))return y(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let i;return r===!0&&S(e),n(typeof t==`function`?t:()=>t,t=>{if(i=t,C(t)){let r=w(a());n(()=>{r.begin();let e=p(t,r.call);return r.prune(),e},t=>{v(e,t)})}else y(e,t)}),i}function E(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function D(e,t){let n=l(e).createTextNode(``);return e.insertBefore(n,t),n}function O(t,n,r,i){let a=r??null;return T(x(t,a,i===void 0?e.current.takeRegion(t,a):i),n,a===null)}export{D as anchor,T as bindRegion,x as createRegion,O as insert,E as removeRegion};
|
|
2
2
|
//# sourceMappingURL=insert.js.map
|
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,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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C,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,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CAACR,EAAiBS,CAAK,EAEzB,OADAvB,EAAY1C,EAAQiE,CAAK,EAClBA,aAAiB,iBAAmB,CAAC,GAAGjE,EAAO,KAAK,EAAIiE,EAEjE,IAAIC,EA+BJ,OA9BIC,IAAY,IAAMjB,EAAWlD,CAAM,EAWvCoE,EAViB,OAAOH,GAAU,WAAcA,MAAgCA,EAUrD,GAAQ,CAEjC,GADA,EAAStB,EACLa,EAAiBb,CAAG,EAAG,CACzB,IAAM0B,EAAQX,EAAgBN,EAAa,CAAC,EAC5CgB,MACQ,CACJC,EAAM,MAAM,EACZ,IAAM7D,EAAQF,EAAQqC,EAAK0B,EAAM,IAAI,EAErC,OADAA,EAAM,MAAM,EACL7D,CACT,EACC,GAAU,CACTiC,EAAOzC,EAAQQ,CAAK,CACtB,CACF,CACF,MACEkC,EAAY1C,EAAQ2C,CAAG,CAE3B,CAAC,EACMuB,CACT,CAOA,SAAgBI,EAAa,EAAsB,CACjD,IAAK,IAAMzE,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgByD,EAAO,EAAc,EAA2B,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
|