@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":[],"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":";;;;AAIA,SAAS,eAAe,MAAe,OAAuB;CAE5D,MAAM,SAAsB,CAAC,CAAC,IAAI,CAAC;CACnC,MAAM,UAAoB,CAAC,CAAC;CAC5B,MAAM,yBAAS,IAAI,IAAe;CAClC,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,SAAS,QAAQ,QAAQ;EAC/B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,QAAQ;GACjD,MAAM,OAAO,OAAO,IAAI;GACxB,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,IAAI;GAC1C,QAAQ,IAAI;GACZ;EACF;EACA,QAAQ,OAAO,SAAS;EACxB,MAAM,OAAO,MAAM;EACnB,IAAI,MAAM,QAAQ,IAAI,GAAG;GACv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AS,UAAU,GAAG,MAAM,UAAU;CACjD,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,GAAG;EACvC,iBAAiB,IAAI,KAAK,KAAK,IAAI;CACrC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":[],"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":";;;;AAIA,SAAS,eAAe,MAAe,OAAuB;CAE5D,MAAM,SAAsB,CAAC,CAAC,IAAI,CAAC;CACnC,MAAM,UAAoB,CAAC,CAAC;CAC5B,MAAM,yBAAS,IAAI,IAAe;CAClC,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,SAAS,QAAQ,QAAQ;EAC/B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,QAAQ;GACjD,MAAM,OAAO,OAAO,IAAI;GACxB,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,IAAI;GAC1C,QAAQ,IAAI;GACZ;EACF;EACA,QAAQ,OAAO,SAAS;EACxB,MAAM,OAAO,MAAM;EACnB,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,IAAI,OAAO,IAAI,IAAI,GACjB,MAAM,IAAI,UACE,6CACZ;GACF,OAAO,IAAI,IAAI;GACf,OAAO,KAAK,IAAI;GAChB,QAAQ,KAAK,CAAC;EAChB,OAAO,IAAI,OAAO,SAAS,UACrB;OAAA,SAAS,IAAI,MAAM,KAAK,IAAI;EAAA,OAC3B,IAAI,OAAO,SAAS,UACrB;OAAA,SAAS,KAAK,CAAC,OAAO,MAAM,IAAI,GAAG,MAAM,KAAK,OAAO,IAAI,CAAC;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AC,CAAC;EACpB;EAEF,OAAO;CACT;CACA,MAAM,OAAO,EAAE,GAAI,MAAkC;CACrD,MAAM,SAAS,SAAS,IAAI,KAAK,CAAC;CAElC,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,GAAG,MAAM,UAAU;CACxE,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,GAAG;EACvC,iBAAiB,IAAI,KAAK,KAAK,IAAI;CACrC;CACA,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { currentScope, enterComponent } from "./internal/hydration-scope.js";
|
|
2
2
|
import { DEVTOOLS_EVENT, addCleanup, createOwner, devtoolsReport, runInScope } from "@shadow-js/core/extend";
|
|
3
|
-
|
|
3
|
+
// src/component.ts
|
|
4
4
|
/** Dev-only: the name each component was created with, for devtools. Weak, so components are not kept alive. */
|
|
5
5
|
const componentNames = /* @__PURE__ */ new WeakMap();
|
|
6
6
|
/**
|
|
@@ -36,7 +36,6 @@ function createComponent(component, props, name) {
|
|
|
36
36
|
return result;
|
|
37
37
|
});
|
|
38
38
|
}
|
|
39
|
-
//#endregion
|
|
40
39
|
export { createComponent };
|
|
41
40
|
|
|
42
41
|
//# sourceMappingURL=component.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "@shadow-js/core";
|
|
2
2
|
import "@shadow-js/core/extend";
|
|
3
|
-
|
|
3
|
+
// src/control-flow/activity.ts
|
|
4
4
|
/**
|
|
5
5
|
* Keeps its children alive while hidden: `mode="hidden"` removes them from sight but keeps their state,
|
|
6
6
|
* their DOM nodes and their focus and scroll position. Hidden content is paused: its effects run their
|
|
@@ -35,7 +35,6 @@ import "@shadow-js/core/extend";
|
|
|
35
35
|
function Activity(props) {
|
|
36
36
|
return () => props.children;
|
|
37
37
|
}
|
|
38
|
-
//#endregion
|
|
39
38
|
export { Activity };
|
|
40
39
|
|
|
41
40
|
//# sourceMappingURL=activity.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Show } from "./show.js";
|
|
2
2
|
import { onMount, useSignal } from "@shadow-js/core";
|
|
3
|
-
|
|
3
|
+
// src/control-flow/client-only.ts
|
|
4
4
|
/**
|
|
5
5
|
* Renders `children` in the browser only. The server (and the first client pass, which must match
|
|
6
6
|
* the server's markup) renders `fallback`; once mounted, the children replace it. Use it for
|
|
@@ -44,7 +44,6 @@ function ClientOnly(props) {
|
|
|
44
44
|
}
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
|
-
//#endregion
|
|
48
47
|
export { ClientOnly };
|
|
49
48
|
|
|
50
49
|
//# sourceMappingURL=client-only.js.map
|
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
import { createComponent } from "../component.js";
|
|
2
|
+
import { isTextOnlyElement } from "../server/raw-text.js";
|
|
2
3
|
import { ssrElement, ssrRaw } from "../server/element.js";
|
|
3
4
|
import { mergeProps, splitProps, untrack, useMemo } from "@shadow-js/core";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
// src/control-flow/dynamic.ts
|
|
6
|
+
/**
|
|
7
|
+
* Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in
|
|
8
|
+
* any letter case: it would bypass CSP nonces and Trusted Types.
|
|
9
|
+
*/
|
|
10
|
+
const TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;
|
|
9
11
|
/**
|
|
10
12
|
* Creates an element for a validated tag name and applies the props to it, children included.
|
|
11
|
-
* The namespace comes from the tag: SVG-only names get the SVG namespace,
|
|
13
|
+
* The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the
|
|
14
|
+
* MathML namespace, the rest are HTML.
|
|
12
15
|
* On the server it renders the element as markup (with the hydration key and the children region
|
|
13
16
|
* the client adopts); while hydrating it claims that element instead of creating one.
|
|
14
17
|
*/
|
|
15
18
|
function buildElement(tag, props) {
|
|
16
|
-
|
|
17
|
-
if (!TAG_PATTERN.test(tag) || DENIED_TAGS.has(lower)) throw new TypeError("ShadowJS Dynamic: invalid tag");
|
|
19
|
+
if (!TAG_PATTERN.test(tag)) throw new TypeError("ShadowJS Dynamic: invalid tag");
|
|
18
20
|
return ssrElement(tag, props, () => {
|
|
19
21
|
const { children } = props;
|
|
20
|
-
|
|
22
|
+
if (children === void 0 || isTextOnlyElement(tag)) return children;
|
|
23
|
+
return [
|
|
21
24
|
ssrRaw("<!--[-->"),
|
|
22
25
|
children,
|
|
23
26
|
ssrRaw("<!--]-->")
|
|
@@ -42,8 +45,17 @@ function buildTarget(target, props) {
|
|
|
42
45
|
* `component` renders nothing.
|
|
43
46
|
*
|
|
44
47
|
* Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so
|
|
45
|
-
* data-driven tags cannot inject markup.
|
|
46
|
-
* in
|
|
48
|
+
* data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,
|
|
49
|
+
* `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not
|
|
50
|
+
* know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter
|
|
51
|
+
* primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a
|
|
52
|
+
* name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.
|
|
53
|
+
* The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG
|
|
54
|
+
* needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG
|
|
55
|
+
* spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.
|
|
56
|
+
* MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML
|
|
57
|
+
* namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent
|
|
58
|
+
* the element will be inserted into.
|
|
47
59
|
*
|
|
48
60
|
* @param props `component` and the props of what it renders.
|
|
49
61
|
* @returns An accessor of the rendered output, to be inserted by the caller.
|
|
@@ -100,7 +112,6 @@ function createDynamic(component, props = {}) {
|
|
|
100
112
|
return component();
|
|
101
113
|
} }, props));
|
|
102
114
|
}
|
|
103
|
-
//#endregion
|
|
104
115
|
export { Dynamic, createDynamic };
|
|
105
116
|
|
|
106
117
|
//# sourceMappingURL=dynamic.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":[],"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":";;;;;AA4DA,MAAM,cAAc;;AAGpB,MAAM,8BAAmC,IAAI,IAAI,CAAC,QAAQ,CAAC;;;;;;;AAQ3D,SAAS,aAAa,KAAa,OAAwB;CACzD,MAAM,QAAQ,IAAI,YAAY;CAC9B,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,YAAY,IAAI,KAAK,GACjD,MAAM,IAAI,UAAoB,+BAAsD;CAMpF,OAAO,WACL,KACA,aACM;EACJ,MAAM,EAAE,aAAa;EACrB,OAAO,aAAa,KAAA,IAChB,KAAA,IACA;GAAC,OAAO,UAAU;GAAG;GAAU,OAAO,UAAU;EAAC;CACvD,GACA,IACF;AAUJ;;;;;AAMA,SAAS,YAAY,QAAiB,OAAwB;CAC5D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,QAAQ,KAAK;CACjE,IAAI,OAAO,WAAW,YACpB,OAAO,gBAAgB,QAAsC,KAAK;CAEpE,MAAM,IAAI,UAEJ,6EAEN;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,QAAiC,OAAuC;CACtF,MAAM,GAAG,QAAQ,WAAW,OAAO,CAAC,WAAW,CAAC;CAEhD,OAAO,cACU;EACb,MAAM,SAAkB,MAAM;EAC9B,OAAO,cAAc,YAAY,QAAQ,IAAI,CAAC;CAChD,GACA,EAAE,aAAa,KAAK,CACtB;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,WACA,QAAgB,CAAC,GACF;CACf,OAAO,QACL,WACE,EACE,IAAI,YAAe;EACjB,OAAO,UAAU;CACnB,EACF,GACA,KACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":[],"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":";;;;;;;;;AAkDA,MAAM,cAAc;;;;;;;;AA8CpB,SAAS,aAAa,KAAa,OAAwB;CACzD,IAAI,CAAC,YAAY,KAAK,GAAG,GACvB,MAAM,IAAI,UAAoB,+BAAsD;CAMpF,OAAO,WACL,KACA,aACM;EACJ,MAAM,EAAE,aAAa;EAErB,IAAI,aAAa,KAAA,KAAa,kBAAkB,GAAG,GAAG,OAAO;EAC7D,OAAO;GAAC,OAAO,UAAU;GAAG;GAAU,OAAO,UAAU;EAAC;CAC1D,GACA,IACF;AAQJ;;;;;AAMA,SAAS,YAAY,QAAiB,OAAwB;CAC5D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,QAAQ,KAAK;CACjE,IAAI,OAAO,WAAW,YACpB,OAAO,gBAAgB,QAAsC,KAAK;CAEpE,MAAM,IAAI,UAEJ,6EAEN;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,QAAiC,OAAuC;CACtF,MAAM,GAAG,QAAQ,WAAW,OAAO,CAAC,WAAW,CAAC;CAEhD,OAAO,cACU;EACb,MAAM,SAAkB,MAAM;EAC9B,OAAO,cAAc,YAAY,QAAQ,IAAI,CAAC;CAChD,GACA,EAAE,aAAa,KAAK,CACtB;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,WACA,QAAgB,CAAC,GACF;CACf,OAAO,QACL,WACE,EACE,IAAI,YAAe;EACjB,OAAO,UAAU;CACnB,EACF,GACA,KACF,CACF;AACF"}
|
|
@@ -3,7 +3,7 @@ import { attachHotModules, createHotLink } from "./hot-link.js";
|
|
|
3
3
|
import { rootErrorsOf } from "./root-errors.js";
|
|
4
4
|
import { catchError, createRoot, getOwner, onCleanup, untrack, useMemo, useSignal } from "@shadow-js/core";
|
|
5
5
|
import { createSignalNode, handleError, readSignal, writeSignal } from "@shadow-js/core/extend";
|
|
6
|
-
|
|
6
|
+
// src/control-flow/error-boundary.ts
|
|
7
7
|
function ErrorBoundary(props) {
|
|
8
8
|
const failureCell = createSignalNode(void 0, Object.is);
|
|
9
9
|
/** Where an error of this boundary's own fallback goes: the boundary that encloses it. */
|
|
@@ -109,7 +109,6 @@ function ErrorBoundary(props) {
|
|
|
109
109
|
});
|
|
110
110
|
return body;
|
|
111
111
|
}
|
|
112
|
-
//#endregion
|
|
113
112
|
export { ErrorBoundary };
|
|
114
113
|
|
|
115
114
|
//# sourceMappingURL=error-boundary.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { mapArray, untrack } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/control-flow/for.ts
|
|
3
3
|
/**
|
|
4
4
|
* Calls the row callback. `props.children` is read untracked, once per row.
|
|
5
5
|
* @internal
|
|
@@ -17,7 +17,6 @@ function For(props) {
|
|
|
17
17
|
fallback
|
|
18
18
|
});
|
|
19
19
|
}
|
|
20
|
-
//#endregion
|
|
21
20
|
export { For };
|
|
22
21
|
|
|
23
22
|
//# sourceMappingURL=for.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/control-flow/fragment.ts
|
|
2
2
|
/**
|
|
3
3
|
* A no-op wrapper: returns `props.children` untouched, so the children are created by the caller's
|
|
4
4
|
* getter exactly as if no wrapper existed. Use it to group several children under one element.
|
|
@@ -25,7 +25,6 @@
|
|
|
25
25
|
function Fragment(props) {
|
|
26
26
|
return props.children;
|
|
27
27
|
}
|
|
28
|
-
//#endregion
|
|
29
28
|
export { Fragment };
|
|
30
29
|
|
|
31
30
|
//# sourceMappingURL=fragment.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getOwner } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/control-flow/hot-link.ts
|
|
3
3
|
/**
|
|
4
4
|
* The hot-update link between an error boundary and the modules its children were built from. Dev
|
|
5
5
|
* only: the callers reach this code behind `__DEV__`, so production bundles never include it.
|
|
@@ -51,7 +51,6 @@ function createHotLink(onUpdate) {
|
|
|
51
51
|
disarm
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
|
-
//#endregion
|
|
55
54
|
export { attachHotModules, createHotLink };
|
|
56
55
|
|
|
57
56
|
//# sourceMappingURL=hot-link.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { indexArray, untrack } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/control-flow/index-list.ts
|
|
3
3
|
/**
|
|
4
4
|
* Renders one row per position. Rows are created and removed only when the length changes; the
|
|
5
5
|
* row at position `i` stays, and its item accessor follows the value at `i`. Use it for
|
|
@@ -25,7 +25,6 @@ import { indexArray, untrack } from "@shadow-js/core";
|
|
|
25
25
|
function Index(props) {
|
|
26
26
|
return indexArray(() => props.each, (item, index) => untrack(() => props.children)(item, index), { fallback: () => props.fallback });
|
|
27
27
|
}
|
|
28
|
-
//#endregion
|
|
29
28
|
export { Index };
|
|
30
29
|
|
|
31
30
|
//# sourceMappingURL=index-list.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { untrack, useMemo, useResource } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/control-flow/lazy.ts
|
|
3
3
|
/**
|
|
4
4
|
* Defines a component whose code is loaded on first render. While loading, the nearest
|
|
5
5
|
* `<Suspense>` shows its fallback; a failed load throws to the nearest `<ErrorBoundary>` and the
|
|
@@ -58,7 +58,6 @@ function lazy(loader) {
|
|
|
58
58
|
Lazy.preload = load;
|
|
59
59
|
return Lazy;
|
|
60
60
|
}
|
|
61
|
-
//#endregion
|
|
62
61
|
export { lazy };
|
|
63
62
|
|
|
64
63
|
//# sourceMappingURL=lazy.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { nextKey, withScope } from "../internal/hydration-scope.js";
|
|
2
2
|
import { ssrRaw } from "../server/element.js";
|
|
3
|
-
|
|
3
|
+
// src/control-flow/no-hydration.ts
|
|
4
4
|
/**
|
|
5
5
|
* Content the browser never hydrates: the server renders it without hydration keys, and while the
|
|
6
6
|
* page hydrates the browser leaves that markup exactly as it is (no code runs for it, no event
|
|
@@ -34,7 +34,6 @@ function NoHydration(props) {
|
|
|
34
34
|
];
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
-
//#endregion
|
|
38
37
|
export { NoHydration };
|
|
39
38
|
|
|
40
39
|
//# sourceMappingURL=no-hydration.js.map
|
|
@@ -4,7 +4,7 @@ import { bindRegion, createRegion, removeRegion } from "../insert.js";
|
|
|
4
4
|
import { PortalContext } from "../internal/portal-context.js";
|
|
5
5
|
import { renderServerPortal } from "../server/portals.js";
|
|
6
6
|
import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from "@shadow-js/core";
|
|
7
|
-
|
|
7
|
+
// src/control-flow/portal.ts
|
|
8
8
|
/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */
|
|
9
9
|
function appendMoved(target, node) {
|
|
10
10
|
if (typeof target.moveBefore === "function") target.moveBefore(node, null);
|
|
@@ -115,6 +115,8 @@ function Portal(props) {
|
|
|
115
115
|
}, ({ host, shadow }) => {
|
|
116
116
|
if (host === null) {
|
|
117
117
|
unmount();
|
|
118
|
+
for (const node of adopted ?? []) node.parentNode?.removeChild(node);
|
|
119
|
+
adopted = void 0;
|
|
118
120
|
if (!warned) {
|
|
119
121
|
warned = true;
|
|
120
122
|
console.warn("[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.");
|
|
@@ -128,7 +130,6 @@ function Portal(props) {
|
|
|
128
130
|
onCleanup(unmount);
|
|
129
131
|
return null;
|
|
130
132
|
}
|
|
131
|
-
//#endregion
|
|
132
133
|
export { Portal };
|
|
133
134
|
|
|
134
135
|
//# sourceMappingURL=portal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"portal.js","names":[],"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":";;;;;;;;AAiEA,SAAS,YAAY,QAAc,MAAkB;CACnD,IAAI,OAAQ,OAAgC,eAAe,YACzD,OAAwB,WAAW,MAAM,IAAI;MAE7C,OAAO,YAAY,IAAI;AAE3B;;AAGA,SAAS,aAAa,MAA2B;CAC/C,OAAO,KAAK,cAAc,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAC9D;;AAGA,SAAS,aAAa,OAA6C;CACjE,IAAI,UAAU,KAAA,GAAW,OAAO,SAAS;CAEzC,QADc,OAAO,UAAU,aAAa,MAAM,IAAI,UACtC;AAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,OAAO,OAA0B;CAI/C,MAAM,MAAM,QAAQ;CAGpB,MAAM,OAAO,WAAW,aAAa;CACrC,IAAI,YAAY,SAAS,MAAM;EAC7B,IAAI,MAAM,cAAc,MAAM,mBAAmB,WAAW,MAAM,UAAU,IAAI;EAChF,OAAO;CACT;CACA,IAAI;CACJ,IAAI,SAAS;CAEb,IAAI,UAA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AAM;GACjB,QAAQ;GACR,IAAe,CAAC,QAAQ;IACtB,SAAS;IACT,QAAQ,KACN,kFACF;GACF;GACA;EACF;EACA,MAAM,SAAe,SAAS,aAAa,IAAI,IAAI;EACnD,IAAI,YAAY,KAAA,KAAa,QAAQ,SAAS,QAAQ;EACtD,OAAO,MAAM;CACf,CACF;CACA,UAAU,OAAO;CACjB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"portal.js","names":[],"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":";;;;;;;;AAiEA,SAAS,YAAY,QAAc,MAAkB;CACnD,IAAI,OAAQ,OAAgC,eAAe,YACzD,OAAwB,WAAW,MAAM,IAAI;MAE7C,OAAO,YAAY,IAAI;AAE3B;;AAGA,SAAS,aAAa,MAA2B;CAC/C,OAAO,KAAK,cAAc,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAC9D;;AAGA,SAAS,aAAa,OAA6C;CACjE,IAAI,UAAU,KAAA,GAAW,OAAO,SAAS;CAEzC,QADc,OAAO,UAAU,aAAa,MAAM,IAAI,UACtC;AAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,OAAO,OAA0B;CAI/C,MAAM,MAAM,QAAQ;CAGpB,MAAM,OAAO,WAAW,aAAa;CACrC,IAAI,YAAY,SAAS,MAAM;EAC7B,IAAI,MAAM,cAAc,MAAM,mBAAmB,WAAW,MAAM,UAAU,IAAI;EAChF,OAAO;CACT;CACA,IAAI;CACJ,IAAI,SAAS;CAEb,IAAI,UAA8B,OAAO,QAAQ,YAAY,GAAG;;CAGhE,MAAM,gBAAsB;EAC1B,MAAM,UAAU;EAChB,IAAI,YAAY,KAAA,GAAW;EAC3B,UAAU,KAAA;EACV,QAAQ,YAAY;EACpB,aAAa,QAAQ,MAAM;CAC7B;;CAGA,MAAM,aAAa,MAAY,SAAiB,SAA6B;EAC3E,MAAM,SAAS,aAAa,MAAM,MAAM,OAAO;EAU/C,OAAO;GAAE;GAAM;GAAQ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;CACf,CACF;CACA,UAAU,OAAO;CACjB,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getOwner } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/control-flow/root-errors.ts
|
|
3
3
|
/**
|
|
4
4
|
* The key the reporters are stored under in an owner's context map. A symbol the context map inherits
|
|
5
5
|
* (as a Provider's value is inherited), so every node below the root sees it, detached roots included.
|
|
@@ -27,7 +27,6 @@ function attachRootErrors(options) {
|
|
|
27
27
|
function rootErrorsOf(owner) {
|
|
28
28
|
return owner?.context?.[ROOT_ERRORS];
|
|
29
29
|
}
|
|
30
|
-
//#endregion
|
|
31
30
|
export { attachRootErrors, rootErrorsOf };
|
|
32
31
|
|
|
33
32
|
//# sourceMappingURL=root-errors.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createBranches } from "./branch.js";
|
|
2
|
-
|
|
2
|
+
// src/control-flow/show.ts
|
|
3
3
|
function Show(props) {
|
|
4
4
|
return createBranches("Show", () => {
|
|
5
5
|
const when = props.when;
|
|
@@ -12,7 +12,6 @@ function Show(props) {
|
|
|
12
12
|
};
|
|
13
13
|
}, () => props.fallback);
|
|
14
14
|
}
|
|
15
|
-
//#endregion
|
|
16
15
|
export { Show };
|
|
17
16
|
|
|
18
17
|
//# sourceMappingURL=show.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createContext, onCleanup } from "@shadow-js/core";
|
|
2
2
|
import { createSignalNode, readSignal, writeSignal } from "@shadow-js/core/extend";
|
|
3
|
-
|
|
3
|
+
// src/control-flow/suspense-list.ts
|
|
4
4
|
/** The enclosing list, or null. @internal */
|
|
5
5
|
const SuspenseListContext = /* @__PURE__ */ createContext(null, { name: "SuspenseList" });
|
|
6
6
|
/**
|
|
@@ -94,7 +94,6 @@ function SuspenseList(props) {
|
|
|
94
94
|
}
|
|
95
95
|
});
|
|
96
96
|
}
|
|
97
|
-
//#endregion
|
|
98
97
|
export { SuspenseList, SuspenseListContext };
|
|
99
98
|
|
|
100
99
|
//# sourceMappingURL=suspense-list.js.map
|
|
@@ -4,7 +4,7 @@ import { ssrRaw } from "../server/element.js";
|
|
|
4
4
|
import { StreamContext } from "../internal/stream-context.js";
|
|
5
5
|
import { SuspenseContext, getOwner, runWithOwner, useContext } from "@shadow-js/core";
|
|
6
6
|
import { createOwner, createSignalNode, readSignal, transitionHooks, writeSignal } from "@shadow-js/core/extend";
|
|
7
|
-
|
|
7
|
+
// src/control-flow/suspense.ts
|
|
8
8
|
/**
|
|
9
9
|
* A counter the resources of one boundary report to (see {@link SuspenseTracker}), and the hold a
|
|
10
10
|
* transition takes on the boundary. A transition that reads pending data while the boundary shows
|
|
@@ -113,7 +113,6 @@ function suspenseOnServer(props, key, count, content) {
|
|
|
113
113
|
ssrRaw("<!--]-->")
|
|
114
114
|
];
|
|
115
115
|
}
|
|
116
|
-
//#endregion
|
|
117
116
|
export { Suspense };
|
|
118
117
|
|
|
119
118
|
//# sourceMappingURL=suspense.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createBranches } from "./branch.js";
|
|
2
2
|
import { children } from "@shadow-js/core";
|
|
3
|
-
|
|
3
|
+
// src/control-flow/switch.ts
|
|
4
4
|
/**
|
|
5
5
|
* Describes one branch of a {@link Switch}. It returns its props unchanged.
|
|
6
6
|
*
|
|
@@ -84,7 +84,6 @@ function Switch(props) {
|
|
|
84
84
|
};
|
|
85
85
|
}, () => props.fallback);
|
|
86
86
|
}
|
|
87
|
-
//#endregion
|
|
88
87
|
export { Match, Switch };
|
|
89
88
|
|
|
90
89
|
//# sourceMappingURL=switch.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useMemo } from "@shadow-js/core";
|
|
2
|
-
|
|
2
|
+
// src/derived.ts
|
|
3
3
|
/**
|
|
4
4
|
* Wraps a computation as a {@link Derived} value that recomputes only when the signals it reads
|
|
5
5
|
* change. The compiler emits it for `const x = <expression reading signals>` inside components; it
|
|
@@ -28,7 +28,6 @@ function derived(compute) {
|
|
|
28
28
|
Object.defineProperty(read, "value", { get: memo });
|
|
29
29
|
return read;
|
|
30
30
|
}
|
|
31
|
-
//#endregion
|
|
32
31
|
export { derived };
|
|
33
32
|
|
|
34
33
|
//# sourceMappingURL=derived.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { isTextOnlyElement } from "./server/raw-text.js";
|
|
1
2
|
import { ssrElement, ssrRaw } from "./server/element.js";
|
|
2
3
|
import "@shadow-js/core";
|
|
3
|
-
|
|
4
|
+
// src/element.ts
|
|
4
5
|
/**
|
|
5
6
|
* The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,
|
|
6
7
|
* and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common
|
|
@@ -53,14 +54,14 @@ function element(tag, props) {
|
|
|
53
54
|
const read = props;
|
|
54
55
|
return ssrElement(tag, props, () => {
|
|
55
56
|
const children = read["children"];
|
|
56
|
-
|
|
57
|
+
if (children === void 0 || isTextOnlyElement(tag)) return children;
|
|
58
|
+
return [
|
|
57
59
|
ssrRaw("<!--[-->"),
|
|
58
60
|
children,
|
|
59
61
|
ssrRaw("<!--]-->")
|
|
60
62
|
];
|
|
61
63
|
}, true);
|
|
62
64
|
}
|
|
63
|
-
//#endregion
|
|
64
65
|
export { element };
|
|
65
66
|
|
|
66
67
|
//# sourceMappingURL=element.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":[],"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":[],"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":";;;;;;;;;;;;;;AAqBA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEpB,SAAgB,QAAQ,KAAa,OAAwB;CAC3D,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,IAAI,YAAY,MAAM,UAClD,MAAM,IAAI,UAAoB,+BAAsD;CAEtF,MAAM,OAAO;CAGX,OAAO,WACL,KACA,aACM;EACJ,MAAM,WAAW,KAAK;EAEtB,IAAI,aAAa,KAAA,KAAa,kBAAkB,GAAG,GAAG,OAAO;EAC7D,OAAO;GAAC,OAAO,UAAU;GAAG;GAAU,OAAO,UAAU;EAAC;CAC1D,GACA,IACF;AAgCJ"}
|