@shadow-js/web 1.1.0 → 1.1.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 +12 -0
- package/README.md +3 -1
- package/dist/dev/attributes.d.ts +1 -2
- package/dist/dev/autofocus.d.ts +1 -2
- package/dist/dev/class-style.d.ts +1 -2
- package/dist/dev/component.d.ts +1 -2
- package/dist/dev/control-flow/activity.d.ts +1 -2
- package/dist/dev/control-flow/client-only.d.ts +1 -2
- package/dist/dev/control-flow/dynamic.d.ts +1 -2
- package/dist/dev/control-flow/error-boundary.d.ts +1 -2
- package/dist/dev/control-flow/for.d.ts +1 -2
- package/dist/dev/control-flow/fragment.d.ts +1 -2
- package/dist/dev/control-flow/index-list.d.ts +1 -2
- package/dist/dev/control-flow/lazy.d.ts +1 -2
- package/dist/dev/control-flow/no-hydration.d.ts +1 -2
- package/dist/dev/control-flow/portal.d.ts +1 -2
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/root-errors.d.ts +2 -3
- package/dist/dev/control-flow/show.d.ts +1 -2
- package/dist/dev/control-flow/suspense-list.d.ts +2 -3
- package/dist/dev/control-flow/suspense.d.ts +1 -2
- package/dist/dev/control-flow/switch.d.ts +1 -2
- package/dist/dev/derived.d.ts +1 -2
- package/dist/dev/element.d.ts +1 -2
- package/dist/dev/events.d.ts +1 -2
- package/dist/dev/extend.d.ts +9 -0
- package/dist/dev/head/components.d.ts +1 -2
- package/dist/dev/head/server-head.d.ts +2 -3
- package/dist/dev/head/use-head.d.ts +1 -2
- package/dist/dev/head/validate.d.ts +1 -2
- package/dist/dev/hmr.d.ts +1 -2
- package/dist/dev/hmr.js.map +1 -1
- package/dist/dev/hydration.d.ts +1 -2
- package/dist/dev/insert.d.ts +1 -2
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +1 -2
- package/dist/dev/internal/diagnostics.d.ts +1 -2
- package/dist/dev/internal/hydration-hooks.d.ts +1 -2
- package/dist/dev/internal/hydration-scope.d.ts +1 -2
- package/dist/dev/internal/names.d.ts +1 -2
- package/dist/dev/internal/portal-context.d.ts +1 -2
- package/dist/dev/internal/reconcile.d.ts +1 -2
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/internal/stream-context.d.ts +1 -2
- package/dist/dev/jsx/aria.d.ts +7 -2
- package/dist/dev/jsx/component.d.ts +7 -2
- package/dist/dev/jsx/events.d.ts +1 -2
- package/dist/dev/jsx/global.d.ts +11 -2
- package/dist/dev/jsx/html.d.ts +8 -2
- package/dist/dev/jsx/intrinsic.d.ts +10 -2
- package/dist/dev/jsx/mathml.d.ts +8 -2
- package/dist/dev/jsx/svg.d.ts +13 -2
- package/dist/dev/jsx/types.d.ts +1 -2
- package/dist/dev/jsx-dev-runtime.d.ts +6 -0
- package/dist/dev/jsx-runtime.d.ts +13 -2
- package/dist/dev/reactive.d.ts +1 -2
- package/dist/dev/render.d.ts +1 -2
- package/dist/dev/resource-hints.d.ts +1 -2
- package/dist/dev/select-value.d.ts +1 -2
- package/dist/dev/server/attributes.d.ts +1 -2
- package/dist/dev/server/class-style.d.ts +1 -2
- package/dist/dev/server/component.d.ts +1 -2
- package/dist/dev/server/derived.d.ts +1 -2
- package/dist/dev/server/element.d.ts +1 -2
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.d.ts +1 -2
- package/dist/dev/server/form-controls.d.ts +1 -2
- package/dist/dev/server/hydration-script.d.ts +1 -2
- package/dist/dev/server/index.d.ts +7 -2
- package/dist/dev/server/index.js +2 -2
- package/dist/dev/server/node.d.ts +1 -2
- package/dist/dev/server/node.js.map +1 -1
- package/dist/dev/server/portals.d.ts +1 -2
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/raw-text.d.ts +1 -2
- package/dist/dev/server/render.d.ts +1 -2
- package/dist/dev/server/serialize.d.ts +1 -2
- package/dist/dev/server/stream.d.ts +1 -2
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +1 -0
- package/dist/dev/spread.d.ts +1 -2
- package/dist/dev/template.d.ts +1 -2
- package/dist/dev/view-transition.d.ts +1 -2
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/autofocus.js.map +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/component.js.map +1 -1
- package/dist/prod/control-flow/activity.js.map +1 -1
- package/dist/prod/control-flow/branch.js.map +1 -1
- package/dist/prod/control-flow/client-only.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/for.js.map +1 -1
- package/dist/prod/control-flow/fragment.js.map +1 -1
- package/dist/prod/control-flow/hot-link.js.map +1 -1
- package/dist/prod/control-flow/index-list.js.map +1 -1
- package/dist/prod/control-flow/lazy.js.map +1 -1
- package/dist/prod/control-flow/no-hydration.js.map +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/root-errors.js.map +1 -1
- package/dist/prod/control-flow/show.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js.map +1 -1
- package/dist/prod/control-flow/switch.js.map +1 -1
- package/dist/prod/derived.js.map +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/head/components.js.map +1 -1
- package/dist/prod/head/registry.js.map +1 -1
- package/dist/prod/head/server-head.js.map +1 -1
- package/dist/prod/head/sink.js.map +1 -1
- package/dist/prod/head/use-head.js.map +1 -1
- package/dist/prod/head/validate.js.map +1 -1
- package/dist/prod/hmr.js.map +1 -1
- package/dist/prod/hydration.js.map +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js.map +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js.map +1 -1
- package/dist/prod/internal/hydration-hooks.js.map +1 -1
- package/dist/prod/internal/hydration-scope.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/internal/stream-context.js.map +1 -1
- package/dist/prod/reactive.js.map +1 -1
- package/dist/prod/render.js.map +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/class-style.js.map +1 -1
- package/dist/prod/server/component.js.map +1 -1
- package/dist/prod/server/derived.js.map +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/hydration-script.js.map +1 -1
- package/dist/prod/server/node.js.map +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/raw-text.js.map +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/serialize.js.map +1 -1
- package/dist/prod/server/stream.js.map +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js.map +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/autofocus.js.map +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/component.js.map +1 -1
- package/dist/server/control-flow/activity.js.map +1 -1
- package/dist/server/control-flow/branch.js.map +1 -1
- package/dist/server/control-flow/client-only.js.map +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/for.js.map +1 -1
- package/dist/server/control-flow/fragment.js.map +1 -1
- package/dist/server/control-flow/index-list.js.map +1 -1
- package/dist/server/control-flow/lazy.js.map +1 -1
- package/dist/server/control-flow/no-hydration.js.map +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/root-errors.js.map +1 -1
- package/dist/server/control-flow/show.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js.map +1 -1
- package/dist/server/control-flow/switch.js.map +1 -1
- package/dist/server/derived.js.map +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/head/components.js.map +1 -1
- package/dist/server/head/registry.js.map +1 -1
- package/dist/server/head/server-head.js.map +1 -1
- package/dist/server/head/sink.js.map +1 -1
- package/dist/server/head/use-head.js.map +1 -1
- package/dist/server/head/validate.js.map +1 -1
- package/dist/server/hydration.js.map +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js.map +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js.map +1 -1
- package/dist/server/internal/hydration-hooks.js.map +1 -1
- package/dist/server/internal/hydration-scope.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/internal/stream-context.js.map +1 -1
- package/dist/server/reactive.js.map +1 -1
- package/dist/server/render.js.map +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/class-style.js.map +1 -1
- package/dist/server/server/component.js.map +1 -1
- package/dist/server/server/derived.js.map +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/hydration-script.js.map +1 -1
- package/dist/server/server/node.js.map +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/raw-text.js.map +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/serialize.js.map +1 -1
- package/dist/server/server/stream.js.map +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js.map +1 -1
- package/dist/server/view-transition.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/index.js +2 -2
- package/dist/server-dev/server/node.js.map +1 -1
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/stream.js.map +1 -1
- package/package.json +6 -6
package/dist/prod/spread.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spread.js","names":["FORBIDDEN_NAMES","runRefCleanup","cleanup","state","untrack","applyKey","key","value","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","plainText","setSelectValue","LIVE_PROPERTIES","isMeasure","liveDiffers","STRING_PROPERTIES","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","spread","props","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","spreadProps","textarea","onCleanup","useRenderEffect","entries","hasValue","IGNORED_KEYS","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el && !isMeasure(el, key)) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True for the `value` of a `progress`, `meter` or `li`: a number property that turns `undefined` into `0` and\n * writes `value=\"0\"`, where the server leaves the attribute out (an indeterminate bar, an unnumbered item). It is written as\n * an attribute, which `setAttribute` removes for `null` and `undefined`, like the compiler does.\n */\nfunction isMeasure(el: Element, key: string): boolean {\n // The tag, not `instanceof`: a class of this window is not the class of an iframe's element, and a minimal DOM may\n // not define `HTMLMeterElement` at all.\n return (\n key === \"value\" &&\n (el.localName === \"progress\" || el.localName === \"meter\" || el.localName === \"li\")\n );\n}\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el) || isMeasure(el, key)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMA,EAAkB,wCAexB,SAASC,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,MAClBD,IAAY,IAAA,KAChB,EAAM,MAAQ,IAAA,GACdE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIC,IAAQ,MAGV,IADAL,EAAcE,CAAK,EACf,OAAOI,GAAU,WAAY,CAC/B,IAAMC,EAAUD,EACVL,EAAUE,MAAcI,EAAQC,CAAE,CAAC,EACrC,OAAOP,GAAY,aAAY,EAAM,MAAQA,EACnD,OAGF,GAAII,IAAQ,YACLH,EAAM,UACT,EAAM,QAAU,GAChBO,EAAUD,EAAIF,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BK,EAAWF,EAAIF,EAAOK,CAAG,OAG3B,GAAIN,IAAQ,QACV,EAAM,OAASO,EAAMJ,EAAgCF,EAAOJ,EAAM,MAAM,OAG1E,GAAIG,IAAQ,YACV,EAAM,OAASQ,EAAUL,EAAIM,EAASR,CAAK,EAAGJ,EAAM,MAAM,OAG5D,GAAIG,EAAI,OAAS,GAAKA,EAAI,WAAW,IAAI,EAAG,CAC1CH,EAAM,OAAO,IAAIG,CAAG,CAAC,GAAG,EACxBH,EAAM,OAAO,OAAOG,CAAG,EAEvB,IAA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AO7B,CAAG,CAAC,CAAC,GAG7C,OADI+C,GAAY,CAACD,EAAQ,MAAM,CAAC9C,KAASA,IAAQ,OAAO,GAAG8C,EAAQ,KAAK,CAAC,QAAS7C,CAAK,CAAC,EACjF6C,CACT,EAGC,GAAY,CACX,IAAMG,kBAAU,IAAI,IACpB,IAAK,GAAM,CAACjD,EAAKC,KAAU6C,EACzBG,EAAQ,IAAIjD,CAAG,EAEbH,EAAM,OAAO,IAAIG,CAAG,GACpB,OAAO,GAAGH,EAAM,OAAO,IAAIG,CAAG,EAAGC,CAAK,GACtC,CAACkB,EAAYhB,EAAIH,EAAKC,EAAOsC,CAAK,IAGpC1C,EAAM,OAAO,IAAIG,EAAKC,CAAK,EAC3BF,EAASI,EAAIH,EAAKC,EAAOJ,EAAO0C,CAAK,GAEvC,IAAK,IAAMvC,IAAO,CAAC,GAAGH,EAAM,OAAO,KAAK,CAAC,EACnCoD,EAAQ,IAAIjD,CAAG,IACnBH,EAAM,OAAO,OAAOG,CAAG,EAGvBD,EAASI,EAAIH,EAAK,IAAA,GAAWH,EAAO0C,CAAK,EAE7C,CACF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"spread.js","names":["setAttribute","setAttributeNS","setBoolAttribute","autoFocus","applyClass","asRecord","classList","style","bindEvent","bindRegion","createRegion","watchCommits","claims","IGNORED_KEYS","attributeName","eventPlan","isFlagAttribute","plainText","setSelectValue","onCleanup","untrack","useRenderEffect","FORBIDDEN_NAMES","runRefCleanup","state","cleanup","applyKey","el","key","value","svg","callRef","plan","handler","unbind","LIVE_PROPERTIES","isMeasure","liveDiffers","STRING_PROPERTIES","wire","live","spread","props","isSVG","skipChildren","read","newState","initial","region","followOptions","applyProps","spreadProps","textarea","entries","hasValue","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el && !isMeasure(el, key)) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True for the `value` of a `progress`, `meter` or `li`: a number property that turns `undefined` into `0` and\n * writes `value=\"0\"`, where the server leaves the attribute out (an indeterminate bar, an unnumbered item). It is written as\n * an attribute, which `setAttribute` removes for `null` and `undefined`, like the compiler does.\n */\nfunction isMeasure(el: Element, key: string): boolean {\n // The tag, not `instanceof`: a class of this window is not the class of an iframe's element, and a minimal DOM may\n // not define `HTMLMeterElement` at all.\n return (\n key === \"value\" &&\n (el.localName === \"progress\" || el.localName === \"meter\" || el.localName === \"li\")\n );\n}\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el) || isMeasure(el, key)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMsB,EAAkB,wCAexB,SAASC,EAAcC,EAA0B,CAC/C,IAAMC,EAAUD,EAAM,MAClBC,IAAY,IAAA,KAChBD,EAAM,MAAQ,IAAA,GACdJ,EAAQK,CAAO,EACjB,CAGA,SAASC,EACPC,EACAC,EACAC,EACAL,EACAM,EACM,CACN,GAAIF,IAAQ,MAGV,IADAL,EAAcC,CAAK,EACf,OAAOK,GAAU,WAAY,CAC/B,IAAME,EAAUF,EACVJ,EAAUL,MAAcW,EAAQJ,CAAE,CAAC,EACrC,OAAOF,GAAY,aAAYD,EAAM,MAAQC,EACnD,OAGF,GAAIG,IAAQ,YACLJ,EAAM,UACTA,EAAM,QAAU,GAChBrB,EAAUwB,EAAIE,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BxB,EAAWuB,EAAIE,EAAOC,CAAG,OAG3B,GAAIF,IAAQ,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W,GACf,IAAK,IAAM1B,KAAO,OAAO,KAAKc,CAAK,EAC7BpB,EAAgB,KAAKM,EAAI,MAAMA,EAAI,QAAQ,GAAG,EAAI,CAAC,CAAC,GAAKf,EAAa,KAAKe,CAAG,IAE9EA,IAAQ,WAGNwB,IACFvB,EAAQ,QAAQ,IAAIa,EAAOd,CAAG,EAC9B0B,EAAW,IAIfD,EAAQ,KAAK,CAACzB,EAAK,QAAQ,IAAIc,EAAOd,CAAG,CAAC,CAAC,GAG7C,OADI0B,GAAY,CAACD,EAAQ,MAAM,CAACzB,KAASA,IAAQ,OAAO,GAAGyB,EAAQ,KAAK,CAAC,QAASxB,CAAK,CAAC,EACjFwB,CACT,EAGCA,GAAY,CACX,IAAME,kBAAU,IAAI,IACpB,IAAK,GAAM,CAAC3B,EAAKC,KAAUwB,EACzBE,EAAQ,IAAI3B,CAAG,EAEbJ,EAAM,OAAO,IAAII,CAAG,GACpB,OAAO,GAAGJ,EAAM,OAAO,IAAII,CAAG,EAAGC,CAAK,GACtC,CAACQ,EAAYV,EAAIC,EAAKC,EAAOc,CAAK,IAGpCnB,EAAM,OAAO,IAAII,EAAKC,CAAK,EAC3BH,EAASC,EAAIC,EAAKC,EAAOL,EAAOmB,CAAK,GAEvC,IAAK,IAAMf,IAAO,CAAC,GAAGJ,EAAM,OAAO,KAAK,CAAC,EACnC+B,EAAQ,IAAI3B,CAAG,IACnBJ,EAAM,OAAO,OAAOI,CAAG,EAGvBF,EAASC,EAAIC,EAAK,IAAA,GAAWJ,EAAOmB,CAAK,EAE7C,CACF,CACF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.js","names":["
|
|
1
|
+
{"version":3,"file":"template.js","names":["claims","nextKey","MATHML_NS","inNamespace","source","namespace","doc","copyOf","element","copy","attribute","root","stack","from","to","child","parse","html","flags","holder","wrapper","template","importNode","roots","node","claimed","parsed","only","fragment"],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const [from, to] = stack.pop() as [Element, Element];\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":"A,+JAmCA,SAASG,EAAYC,EAAiBC,EAA4B,CAChE,IAAMC,EAAM,SACNC,EAAUC,GAA8B,CAC5C,IAAMC,EAAOH,EAAI,gBAAgBD,EAAWG,EAAQ,SAAS,EAC7D,IAAK,IAAME,KAAa,MAAM,KAAKF,EAAQ,UAAU,EACnDC,EAAK,aAAaC,EAAU,KAAMA,EAAU,KAAK,EAEnD,OAAOD,CACT,EACME,EAAOJ,EAAOH,CAAM,EACpBQ,EAAmC,CAAC,CAACR,EAAQO,CAAI,CAAC,EACxD,KAAOC,EAAM,OAAS,GAAG,CACvB,GAAM,CAACC,EAAMC,GAAMF,EAAM,IAAI,EAC7B,IAAK,IAAMG,KAAS,MAAM,KAAKF,EAA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CAAI,CAAC,EAC1D,OAAOiB,CACT,CACF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-transition.js","names":["
|
|
1
|
+
{"version":3,"file":"view-transition.js","names":["watchCommits","flushSync","untrack","useEffect","useId","startViewTransition","update","options","doc","error","failure","callback","types","ViewTransition","props","built","ready","contentValue","start","end","generated","name","transitionClass","apply","element","firstElementBetween","setOrClear","parent","node","property","value"],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\nimport { watchCommits } from \"./insert\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists. The content can change later\n // (a Show that opens, a fallback replaced by content) and the first element is then another one:\n // the name is applied again after each commit to the parent's regions, where that change lands.\n useEffect(() => {\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n const transitionClass = props.class;\n const apply = (): void => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", transitionClass);\n };\n apply();\n const parent = start.parentNode;\n if (parent !== null) watchCommits(parent, apply);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":"A,8HAmDA,SAAgBK,EACdC,EACAC,EACe,CACf,IAAMC,EAAM,OAAO,SAAa,IAAc,IAAA,GAAa,SAC3D,GAAIA,IAAQ,IAAA,IAAa,OAAOA,EAAI,qBAAwB,WAAY,CACtE,GAAI,CACFP,EA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WAAa,EAAG,OAAOA,EAElC,OAAO,IACT,CAEA,SAASF,EAAWF,EAAsBK,EAAkBC,EAAiC,CACvFA,IAAU,IAAA,IAAaA,IAAU,GAAIN,EAAQ,MAAM,eAAeK,CAAQ,EACzEL,EAAQ,MAAM,YAAYK,EAAUC,CAAK,CAChD,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","text","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAY,EAAwB,CAE3C,OAAOJ,EAAoB,KACzBK,EACG,QAAQ,WAAY,EAAE,CAAC,CACvB,KAAK,CAAC,CACN,YAAY,CACjB,CACF,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYL,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKS,CAAS,EAE3BA,IAAc,SAAWF,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKD,CAAW,EAAIA,EAAYC,CAAK,EAF1C,EAG9C,CAGA,SAASG,EAAc,EAAmB,EAA+B,CAIvE,OAHIH,GAAU,KAAoC,KAC9CA,IAAU,GAAcN,EAAc,KAAKQ,CAAS,EAAI,QAAU,KAClEF,IAAU,GAAaN,EAAc,KAAKQ,CAAS,EAAI,OAAS,GAC7D,OAAOF,CAAK,CACrB,CAGA,SAASI,EAAU,EAA2B,CAC5C,IAAMC,EAAQC,EAAU,QAAQ,GAAG,EACnC,OAAOD,IAAU,GAAKC,EAAYA,EAAU,MAAMD,EAAQ,CAAC,CAC7D,CAGA,SAASE,EAAO,EAAa,EAA0B,EAAmB,EAAsB,CAC9F,IAAML,EAAYI,EAAU,YAAY,EAClCE,EAAOL,EAAcD,EAAWF,CAAK,EACvCQ,IAAS,KACPC,IAAc,KAAMC,EAAG,gBAAgBJ,CAAS,EAC/CI,EAAG,kBAAkBD,EAAWL,EAAUE,CAAS,CAAC,EAKvD,OAAO,KAAKJ,CAAS,GAErBD,EAAqBC,EAAWM,CAAI,IAKpCC,IAAc,KACZC,EAAG,aAAaJ,CAAS,IAAME,GAAME,EAAG,aAAaJ,EAAWE,CAAI,EAC/DE,EAAG,eAAeD,EAAWL,EAAUE,CAAS,CAAC,IAAME,GAChEE,EAAG,eAAeD,EAAWH,EAAWE,CAAI,EAEhD,CA+BA,SAAgBG,EAAa,EAAa,EAAc,EAAsB,CAC5Ef,EAAoBC,CAAI,EACxBU,EAAOG,EAAI,KAAMb,EAAMG,CAAK,CAC9B,CAuBA,SAAgBY,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGhB,EAAoBC,CAAI,EACxBU,EAAOG,EAAID,IAAc,GAAK,KAAOA,EAAWZ,EAAMG,CAAK,CAC7D,CAoBA,SAAgBa,EAAiB,EAAa,EAAc,EAAsB,CAChFjB,EAAoBC,CAAI,EACxBa,EAAG,gBAAgBb,EAAM,EAAQG,CAAM,CACzC,C"}
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["invalidAttributeName","ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","qualified","colon","commit","el","namespace","text","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMC,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoBC,EAAoB,CACtD,GAAI,CAACL,EAAe,KAAKK,CAAI,EAAG,MAAMN,EAAqBM,CAAI,CACjE,CAGA,SAASC,EAAYC,EAAwB,CAE3C,OAAOJ,EAAoB,KACzBI,EACG,QAAQ,WAAY,EAAE,CAAC,CACvB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,EAAOC,EAAIC,IAAc,GAAK,KAAOA,EAAWX,EAAME,CAAK,CAC7D,CAoBA,SAAgBa,EAAiBL,EAAaV,EAAcE,EAAsB,CAChFH,EAAoBC,CAAI,EACxBU,EAAG,gBAAgBV,EAAM,EAAQE,CAAM,CACzC,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autofocus.js","names":["
|
|
1
|
+
{"version":3,"file":"autofocus.js","names":["onMount","isHydrating","autoFocus","el","enabled","hydrating","doc","active","free"],"sources":["../../src/autofocus.ts"],"sourcesContent":["import { onMount } from \"@shadow-js/core\";\nimport { isHydrating } from \"@shadow-js/core/extend\";\n\n/**\n * Focuses an element written with `autoFocus` (React parity) once it is inserted into the document\n * by a client render or update. The compiler calls this for an `autoFocus` attribute and for\n * `autoFocus` keys of a spread, so an app that never uses `autoFocus` never reaches this code. Call it\n * yourself only for elements you create by hand, inside an owner (a component or a root): the focus\n * is requested with `onMount`, so development builds warn with `NO_OWNER_EFFECT` without one.\n *\n * The rules, which match React's for `autoFocus`:\n * - Once per element: the focus is requested when the element is created, after the owner has been\n * flushed. Moving the element later (a keyed reorder) does not focus it again.\n * - An element that is not connected when its owner flushes (a detached root) is not focused.\n * - During hydration the server markup already carries `autofocus`, so the element focuses only when\n * nothing else has the focus (the document's active element is the body or null). A user's focus\n * is never taken away by hydration.\n *\n * @param el The element. Only `HTMLElement` and `SVGElement` are focused; for any other element, and\n * for one that cannot take focus, the call does nothing.\n * @param enabled The `autoFocus` value: falsy values (`false`, `undefined`, `\"\"`, `0`) do nothing.\n * @example\n * import { autoFocus, render } from \"@shadow-js/web\";\n *\n * render(() => {\n * const input = document.createElement(\"input\");\n * autoFocus(input, true); // focused once the root has mounted it\n * return input;\n * }, document.body);\n * @since 1.0.0\n */\nexport function autoFocus(el: Element, enabled: unknown): void {\n if (!enabled) return;\n const hydrating = isHydrating();\n onMount(() => {\n const doc = el.ownerDocument;\n const active = doc.activeElement;\n // Hydration focuses only when nothing has the focus: the body or no element.\n const free = !hydrating || active === null || active === doc.body;\n if (el.isConnected && free && (el instanceof HTMLElement || el instanceof SVGElement)) {\n el.focus();\n }\n });\n}\n"],"mappings":"A,+FA+BA,SAAgBE,EAAUC,EAAaC,EAAwB,CAC7D,GAAI,CAACA,EAAS,OACd,IAAMC,EAAYJ,EAAY,EAC9BD,MAAc,CACZ,IAAMM,EAAMH,EAAG,cACTI,EAASD,EAAI,cAEbE,EAAO,CAACH,GAAaE,IAAW,MAAQA,IAAWD,EAAI,KACzDH,EAAG,aAAeK,IAASL,aAAc,aAAeA,aAAc,aACxEA,EAAG,MAAM,CAEb,CAAC,CACH,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-style.js","names":["collectClasses","item","leaves","root","parts","record","key","unwrap","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","source","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved","declared","part"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAK,IAAMC,KAAQC,EAAOC,EAAM,oBAAK,EACnC,GAAI,OAAOF,GAAS,SACdA,IAAS,IAAIG,EAAM,KAAKH,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA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,SAAW,IAAIA,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAIF,IAAMoC,EAAoC,CAAC,EAC3C,IAAK,IAAM/B,KAAO,OAAO,KAAKL,CAAI,EAAG,CACnC,IAAMqC,EAAO/B,EAAQN,EAAiCK,EAAI,EACtDgC,GAAS,MAA8BA,IAAS,KAAO,EAAShC,GAAOgC,EAC7E,CACAH,EAAMtB,EAAIwB,EAAU,CAAC,CAAC,CACxB,CACF,CACA,OAAOD,CACT,CACA,IAAMd,EAAgC,CAAE,GAAIc,CAAqC,EACjF,IAAK,IAAM9B,KAAO,OAAO,KAAKgB,CAAI,EAAG,EAAKhB,GAAOC,EAAOe,EAAKhB,EAAI,EACjE,IAAMiB,EAASN,EAASO,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMhB,KAAOmB,EACZ,OAAO,GAAGF,EAAOjB,GAAMgB,EAAKhB,EAAI,GACpC0B,EAAiBnB,EAAIP,EAAKgB,EAAKhB,EAAI,EAErC,OAAOgB,CACT,C"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":["leaves","unwrap","cssValueText","HTML_NS","collectClasses","root","parts","item","record","key","classText","input","value","applyClass","el","svg","text","className","asRecord","enabled","map","classList","prev","source","next","before","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","style","resolved","declared","part"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASI,EAAeC,EAAeC,EAAuB,CAE5D,IAAK,IAAMC,KAAQP,EAAOK,EAAM,oBAAK,EACnC,GAAI,OAAOE,GAAS,SACdA,IAAS,IAAID,EAAM,KAAKC,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA,CAAI,GAAGD,EAAM,KAAK,OAAOC,CAAI,CAAC,OACzD,GAAqB,OAAOA,GAAS,UAAjCA,EAA2C,CACpD,IAAMC,EAASD,EACf,IAAK,IAAME,KAAO,OAAO,KAAKD,CAAM,EAC9BP,EAAOO,EAAOC,EAAI,GAAKA,IAAQ,IAAIH,EAAM,KAAKG,CAAG,CAEzD,CAEJ,CAGA,SAASC,EAAUC,EAA+B,CAChD,IAAMC,EAAQX,EAAOU,CAAK,EAC1B,GAAI,OAAOC,GAAU,SAAU,OAAOA,EACtC,GAAIA,GAAU,MAA+BA,IAAU,GAAO,OAAO,KACrE,IAAMN,EAAkB,CAAC,EAEzB,OADAF,EAAeQ,EAAON,CAAK,EACpBA,EAAM,KAAK,GAAG,CACvB,CAOA,SAAgBO,EAAWC,EAAaF,EAAgBG,EAAoB,CAC1E,IAAMC,EAAON,EAAUE,CAAK,EACxBI,IAAS,KACXF,EAAG,gBAAgB,OAAO,EAGxBC,EACED,EAAG,aAAa,OAAO,IAAME,GAAMF,EAAG,aAAa,QAASE,CAAI,EAC3DF,EAAG,YAAcE,IAC1BF,EAAG,UAAYE,EAEnB,CAyBA,SAAgBC,EAAUH,EAAaF,EAAsB,CAC3DC,EAAWC,EAAIF,EAAO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IAAMf,KAAOiB,EACZ,OAAO,GAAGD,EAAOhB,GAAMe,EAAKf,EAAI,GACpCwB,EAAiBnB,EAAIL,EAAKe,EAAKf,EAAI,EAErC,OAAOe,CACT,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component.js","names":["
|
|
1
|
+
{"version":3,"file":"component.js","names":["currentScope","enterComponent","createOwner","runInScope","createComponent","component","props","name","owner"],"sources":["../../src/component.ts"],"sourcesContent":["import {\n addCleanup,\n createOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n runInScope,\n} from \"@shadow-js/core/extend\";\nimport { currentScope, enterComponent } from \"./internal/hydration-scope\";\n\n/** Dev-only: the name each component was created with, for devtools. Weak, so components are not kept alive. */\nconst componentNames = new WeakMap<object, string>();\n\n/**\n * Calls a component untracked, under a new owner that is a child of the current one: cleanups and\n * effects it creates are disposed with the enclosing scope. The name, given in development builds,\n * is recorded for devtools.\n *\n * @param component The component function.\n * @param props The props object (usually with getters for reactive props).\n * @param name Optional devtools name.\n * @returns Whatever the component returns.\n * @example\n * import { createComponent } from \"@shadow-js/web\";\n *\n * function Counter(props: { start: number }) {\n * return `Count: ${props.start}`;\n * }\n *\n * const view = createComponent(Counter, { start: 0 }, \"Counter\");\n * @since 1.0.0\n */\nexport function createComponent<P>(\n component: (props: P) => unknown,\n props: P,\n name?: string,\n): unknown {\n if (__DEV__ && name !== undefined) componentNames.set(component, name);\n return enterComponent(() => {\n // Every component runs under an owner of its own: devtools attribute updates to it, and\n // `useId` uses its hydration-scope key as a prefix, so ids agree between server and browser\n // even though the browser creates more owners (effects) than the server does.\n const owner = createOwner();\n owner.idPrefix = currentScope()?.id;\n // One scope switch (owner in, listener off): deep component trees are bounded by the call stack.\n const result = runInScope({ owner, listener: null }, () => component(props));\n if (__DEV__) {\n devtoolsReport(\n DEVTOOLS_EVENT.COMPONENT_MOUNTED,\n owner,\n componentNames.get(component),\n result,\n );\n addCleanup(owner, () => devtoolsReport(DEVTOOLS_EVENT.COMPONENT_UNMOUNTED, owner));\n }\n return result;\n });\n}\n\n/**\n * The devtools name recorded for a component in development builds, if any.\n * @internal\n */\nexport function componentName(component: object): string | undefined {\n return componentNames.get(component);\n}\n"],"mappings":"A,sJA+BA,SAAgBI,EACdC,EACAC,EACAC,EACS,CAET,OAAON,MAAqB,CAI1B,IAAMO,EAAQN,EAAY,EAa1B,MAZAM,GAAM,SAAWR,EAAa,CAAC,EAAE,GAElBG,EAAW,CAAEK,QAAO,SAAU,IAAK,MAASH,EAAUC,CAAK,CAU9D,CACd,CAAC,CACH,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity.js","names":["Activity","props"],"sources":["../../../src/control-flow/activity.ts"],"sourcesContent":["import {\n type Accessor,\n runWithOwner,\n untrack,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n\n/**\n * `visible` shows the children; `hidden` keeps them alive (state, DOM and focus) but out of sight.\n * @since 1.0.0\n */\nexport type ActivityMode = \"visible\" | \"hidden\";\n\n/**\n * Props of {@link Activity}.\n * @since 1.0.0\n */\nexport interface ActivityProps {\n /**\n * `\"visible\"` shows the children; `\"hidden\"` keeps them alive but out of sight. Changing it\n * does not rebuild the children and may be reactive.\n * @default \"visible\"\n */\n readonly mode?: ActivityMode;\n /**\n * The content. Built once, when the parent first renders the Activity.\n * @default undefined (the Activity renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** What a hidden Activity changed in the DOM, so showing it restores exactly that. */\ninterface Stash {\n readonly elements: Array<readonly [HTMLElement, string]>;\n readonly texts: Array<{ readonly text: Text; readonly parent: Node; readonly next: Node | null }>;\n readonly scrolls: Array<readonly [Element, number, number]>;\n readonly focus: Element | null;\n}\n\n/**\n * Hides the nodes between two anchors without removing them. Top-level elements get\n * `display: none` (their own state, subtree and listeners are untouched). Top-level text nodes are\n * detached (a text node cannot be hidden) and put back in order when shown. Scroll offsets and the\n * focused element are remembered, because `display: none` loses both.\n */\nfunction stashBetween(start: Node, end: Node): Stash | undefined {\n const parent = start.parentNode;\n if (parent === null) return undefined;\n const elements: Array<readonly [HTMLElement, string]> = [];\n const texts: Stash[\"texts\"][number][] = [];\n const scrolls: Array<readonly [Element, number, number]> = [];\n const active = document.activeElement;\n let focus: Element | null = null;\n let node: Node | null = start.nextSibling;\n while (node !== null && node !== end) {\n const next: Node | null = node.nextSibling;\n if (node.nodeType === 1) {\n const element = node as HTMLElement;\n elements.push([element, element.style.display]);\n element.style.display = \"none\";\n for (const scrollable of [element, ...Array.from(element.querySelectorAll(\"*\"))]) {\n if (scrollable.scrollTop !== 0 || scrollable.scrollLeft !== 0) {\n scrolls.push([scrollable, scrollable.scrollTop, scrollable.scrollLeft]);\n }\n }\n if (active !== null && element.contains(active)) focus = active;\n } else if (node.nodeType === 3) {\n texts.push({ text: node as Text, parent, next });\n parent.removeChild(node);\n }\n node = next;\n }\n return { elements, texts, scrolls, focus };\n}\n\n/** Puts back what {@link stashBetween} changed. Texts are restored last-to-first, so each finds its next. */\nfunction restore(stash: Stash, end: Node): void {\n for (let i = stash.texts.length - 1; i >= 0; i -= 1) {\n const entry = stash.texts[i];\n if (entry === undefined || entry.text.parentNode !== null) continue;\n const before = entry.next !== null && entry.next.parentNode === entry.parent ? entry.next : end;\n entry.parent.insertBefore(entry.text, before);\n }\n for (const [element, display] of stash.elements) element.style.display = display;\n for (const [element, top, left] of stash.scrolls) {\n element.scrollTop = top;\n element.scrollLeft = left;\n }\n const focus = stash.focus;\n if (focus instanceof HTMLElement && focus.isConnected) focus.focus({ preventScroll: true });\n}\n\n/**\n * Keeps its children alive while hidden: `mode=\"hidden\"` removes them from sight but keeps their state,\n * their DOM nodes and their focus and scroll position. Hidden content is paused: its effects run their\n * cleanups and wait, its memos keep their last value, and its DOM does not update. Updates that arrive\n * while hidden are applied once, when the content is shown again.\n *\n * Use it for tabs, wizards and routes you want back instantly. A hidden Activity mounted hidden renders\n * its DOM once (so it is ready to show) and runs no effects until it is shown. The server renders the\n * children without hiding them; the client hides them once it hydrates.\n *\n * @param props See {@link ActivityProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Activity } from \"@shadow-js/web\";\n *\n * function Chat() {\n * return <p>Chat</p>;\n * }\n *\n * function Tabs() {\n * const [tab] = useSignal(\"chat\");\n * return (\n * <Activity mode={tab() === \"chat\" ? \"visible\" : \"hidden\"}>\n * <Chat />\n * </Activity>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Activity(props: ActivityProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // The content lives under its own owner, so pausing it reaches every effect and memo it created.\n const content = createOwner();\n // Built when the parent first reads it, not here: the server builds children at the same point of the\n // render, which keeps hydration keys equal on both sides.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = runWithOwner(content, () => untrack(() => props.children));\n }\n return built;\n };\n // Empty text anchors bound the content: the DOM range the visibility code hides and shows.\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const [hidden, setHidden] = useSignal(false);\n let paused = false;\n // Pausing happens in the render phase, before the content's own effects can run.\n useRenderEffect(\n () => props.mode === \"hidden\",\n (isHidden) => {\n if (isHidden === paused) return;\n paused = isHidden;\n if (isHidden) pauseOwner(content);\n else resumeOwner(content);\n setHidden(isHidden);\n },\n );\n // Runs after the DOM is committed (a user effect), so the nodes it hides exist.\n let stash: Stash | undefined;\n useEffect(() => {\n if (hidden()) {\n if (stash === undefined) stash = stashBetween(start, end);\n } else if (stash !== undefined) {\n const previous = stash;\n stash = undefined;\n restore(previous, end);\n }\n });\n return () => [start, contentValue(), end];\n}\n"],"mappings":"A,uDA8HA,SAAgBA,
|
|
1
|
+
{"version":3,"file":"activity.js","names":["Activity","props"],"sources":["../../../src/control-flow/activity.ts"],"sourcesContent":["import {\n type Accessor,\n runWithOwner,\n untrack,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n\n/**\n * `visible` shows the children; `hidden` keeps them alive (state, DOM and focus) but out of sight.\n * @since 1.0.0\n */\nexport type ActivityMode = \"visible\" | \"hidden\";\n\n/**\n * Props of {@link Activity}.\n * @since 1.0.0\n */\nexport interface ActivityProps {\n /**\n * `\"visible\"` shows the children; `\"hidden\"` keeps them alive but out of sight. Changing it\n * does not rebuild the children and may be reactive.\n * @default \"visible\"\n */\n readonly mode?: ActivityMode;\n /**\n * The content. Built once, when the parent first renders the Activity.\n * @default undefined (the Activity renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** What a hidden Activity changed in the DOM, so showing it restores exactly that. */\ninterface Stash {\n readonly elements: Array<readonly [HTMLElement, string]>;\n readonly texts: Array<{ readonly text: Text; readonly parent: Node; readonly next: Node | null }>;\n readonly scrolls: Array<readonly [Element, number, number]>;\n readonly focus: Element | null;\n}\n\n/**\n * Hides the nodes between two anchors without removing them. Top-level elements get\n * `display: none` (their own state, subtree and listeners are untouched). Top-level text nodes are\n * detached (a text node cannot be hidden) and put back in order when shown. Scroll offsets and the\n * focused element are remembered, because `display: none` loses both.\n */\nfunction stashBetween(start: Node, end: Node): Stash | undefined {\n const parent = start.parentNode;\n if (parent === null) return undefined;\n const elements: Array<readonly [HTMLElement, string]> = [];\n const texts: Stash[\"texts\"][number][] = [];\n const scrolls: Array<readonly [Element, number, number]> = [];\n const active = document.activeElement;\n let focus: Element | null = null;\n let node: Node | null = start.nextSibling;\n while (node !== null && node !== end) {\n const next: Node | null = node.nextSibling;\n if (node.nodeType === 1) {\n const element = node as HTMLElement;\n elements.push([element, element.style.display]);\n element.style.display = \"none\";\n for (const scrollable of [element, ...Array.from(element.querySelectorAll(\"*\"))]) {\n if (scrollable.scrollTop !== 0 || scrollable.scrollLeft !== 0) {\n scrolls.push([scrollable, scrollable.scrollTop, scrollable.scrollLeft]);\n }\n }\n if (active !== null && element.contains(active)) focus = active;\n } else if (node.nodeType === 3) {\n texts.push({ text: node as Text, parent, next });\n parent.removeChild(node);\n }\n node = next;\n }\n return { elements, texts, scrolls, focus };\n}\n\n/** Puts back what {@link stashBetween} changed. Texts are restored last-to-first, so each finds its next. */\nfunction restore(stash: Stash, end: Node): void {\n for (let i = stash.texts.length - 1; i >= 0; i -= 1) {\n const entry = stash.texts[i];\n if (entry === undefined || entry.text.parentNode !== null) continue;\n const before = entry.next !== null && entry.next.parentNode === entry.parent ? entry.next : end;\n entry.parent.insertBefore(entry.text, before);\n }\n for (const [element, display] of stash.elements) element.style.display = display;\n for (const [element, top, left] of stash.scrolls) {\n element.scrollTop = top;\n element.scrollLeft = left;\n }\n const focus = stash.focus;\n if (focus instanceof HTMLElement && focus.isConnected) focus.focus({ preventScroll: true });\n}\n\n/**\n * Keeps its children alive while hidden: `mode=\"hidden\"` removes them from sight but keeps their state,\n * their DOM nodes and their focus and scroll position. Hidden content is paused: its effects run their\n * cleanups and wait, its memos keep their last value, and its DOM does not update. Updates that arrive\n * while hidden are applied once, when the content is shown again.\n *\n * Use it for tabs, wizards and routes you want back instantly. A hidden Activity mounted hidden renders\n * its DOM once (so it is ready to show) and runs no effects until it is shown. The server renders the\n * children without hiding them; the client hides them once it hydrates.\n *\n * @param props See {@link ActivityProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Activity } from \"@shadow-js/web\";\n *\n * function Chat() {\n * return <p>Chat</p>;\n * }\n *\n * function Tabs() {\n * const [tab] = useSignal(\"chat\");\n * return (\n * <Activity mode={tab() === \"chat\" ? \"visible\" : \"hidden\"}>\n * <Chat />\n * </Activity>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Activity(props: ActivityProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // The content lives under its own owner, so pausing it reaches every effect and memo it created.\n const content = createOwner();\n // Built when the parent first reads it, not here: the server builds children at the same point of the\n // render, which keeps hydration keys equal on both sides.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = runWithOwner(content, () => untrack(() => props.children));\n }\n return built;\n };\n // Empty text anchors bound the content: the DOM range the visibility code hides and shows.\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const [hidden, setHidden] = useSignal(false);\n let paused = false;\n // Pausing happens in the render phase, before the content's own effects can run.\n useRenderEffect(\n () => props.mode === \"hidden\",\n (isHidden) => {\n if (isHidden === paused) return;\n paused = isHidden;\n if (isHidden) pauseOwner(content);\n else resumeOwner(content);\n setHidden(isHidden);\n },\n );\n // Runs after the DOM is committed (a user effect), so the nodes it hides exist.\n let stash: Stash | undefined;\n useEffect(() => {\n if (hidden()) {\n if (stash === undefined) stash = stashBetween(start, end);\n } else if (stash !== undefined) {\n const previous = stash;\n stash = undefined;\n restore(previous, end);\n }\n });\n return () => [start, contentValue(), end];\n}\n"],"mappings":"A,uDA8HA,SAAgBA,EAASC,EAAyC,CAChD,UAAaA,EAAM,QA0CrC,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch.js","names":["
|
|
1
|
+
{"version":3,"file":"branch.js","names":["createRoot","getOwner","onCleanup","untrack","useMemo","transitionHooks","sameChoice","a","b","createBranches","name","select","fallback","latest","state","swap","owner","selection","next","live","accessorFor","owned","current","produce","choice","eager","body","callback","result"],"sources":["../../../src/control-flow/branch.ts"],"sourcesContent":["import { type Accessor, createRoot, getOwner, onCleanup, untrack, useMemo } from \"@shadow-js/core\";\nimport {\n type SlotBranch,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n transitionHooks,\n} from \"@shadow-js/core/extend\";\n\n/**\n * Branch index meaning \"no branch is selected\": the fallback is shown.\n * @internal\n */\nexport const FALLBACK = -1;\n\n/**\n * One selection made by a control-flow component.\n *\n * - `index` names the chosen branch, or {@link FALLBACK}.\n * - `keyed` and `when` decide whether a change of selection rebuilds the branch.\n * - `read` reads the condition reactively; the callback child's accessor argument uses it.\n * - `body` reads the branch's children getter. It is read tracked: a compiled `children` getter\n * that is a plain reactive expression (`{count()}`) must update the output. Creating child JSX\n * reads nothing here, because components and bindings track inside their own computations.\n *\n * @internal\n * @since 1.0.0\n */\nexport interface Choice {\n /** The chosen branch: a zero-based position, or {@link FALLBACK} when no branch is chosen. */\n readonly index: number;\n /** True when a change of `when` (by identity) rebuilds the branch even if `index` is the same. */\n readonly keyed: boolean;\n /** The value of the condition at selection time; a keyed callback child receives it. */\n readonly when: unknown;\n /** Reads the current value of the condition, tracked; backs the callback child's accessor. */\n readonly read: () => unknown;\n /** Reads the chosen branch's children (content, an accessor, or a callback), tracked. */\n readonly body: () => unknown;\n}\n\n/** Bookkeeping for the branch that is on screen. */\ntype Rendered = SlotOwned;\n\n/** A branch on screen, or one a transition builds (see the transition layer in core's concurrency.ts). */\ntype Live = SlotBranch<Choice>;\n\n/**\n * Whether two selections describe the same rendered output. Non-keyed branches only care about\n * which branch is chosen, which is the same as comparing truthiness of the condition. Keyed\n * branches also rebuild when the condition's identity changes. The fallback never rebuilds.\n */\nfunction sameChoice(a: Choice, b: Choice): boolean {\n if (a.index !== b.index) return false;\n return a.index === FALLBACK || !a.keyed || a.when === b.when;\n}\n\n/**\n * Builds the accessor behind `Show` and `Switch`. The selection memo decides which branch is chosen;\n * the output memo commits it.\n *\n * Ordinary changes build the branch inside the output memo: the memo's teardown removes the previous\n * branch first. A change made during a transition, while a branch is on screen, is handled by the\n * transition layer (core's `slotSwap`, reached through `transitionHooks`), created by the first such change: it builds the\n * new branch under a hold and commits it once its reads have settled. Until then the shown branch stays\n * on screen, its DOM untouched, and nothing is built twice. Apps that never change a shown branch in a\n * transition never create that layer.\n *\n * Teardown ordering: the owner of a branch is marked `disposing` before it is torn down, so a cleanup\n * that reads the callback's accessor learns that the branch is going away and gets the last truthy\n * value instead of a stale-accessor error.\n *\n * @param name Component name used in diagnostics.\n * @param select Tracked selection; runs inside the selection memo.\n * @param fallback Reads the fallback lazily, untracked, only when it is shown.\n * @returns The output accessor.\n * @throws TypeError (production message `SHADOW_STALE_ACCESSOR`) from the accessor handed to a\n * callback child, when it is read after its branch was replaced.\n * @internal\n * @since 1.0.0\n */\nexport function createBranches(\n name: string,\n select: () => Choice,\n fallback: () => unknown,\n): Accessor<unknown> {\n /** Selection computed most recently; its `read` is always current, unlike the held value. */\n let latest: Choice | undefined;\n /** The branch on screen, and what the output last returned. The transition layer reads and writes it. */\n const state: SlotState<Choice> = { live: undefined };\n /** The transition layer, created by the first transition that replaces the branch on screen. */\n let swap: SlotSwap<Choice> | undefined;\n /** The slot's owner: the transition layer's holder for the branches it builds lives under it. */\n const owner = getOwner();\n\n const pick = (): Choice => {\n const next = select();\n latest = next;\n const live: Live | undefined = state.live;\n if (live !== undefined && next.index === live.owned.index) live.owned.value = next.when;\n return next;\n };\n const selection = useMemo<Choice>(pick, { equals: sameChoice });\n\n const accessorFor = (owned: Rendered): (() => unknown) => {\n return () => {\n if (owned.disposing) return owned.value;\n const current = untrack(selection);\n if (current.index !== owned.index) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS ${name}: stale accessor. The branch was replaced; read the accessor only while its condition is truthy.`\n : \"SHADOW_STALE_ACCESSOR\",\n );\n }\n return (latest ?? current).read();\n };\n };\n\n /**\n * The value a branch (or the fallback) produces. `eager` evaluates a zero-argument accessor now (a\n * transition build needs to see whether a read was held); otherwise it is evaluated when rendered.\n */\n const produce = (choice: Choice, owned: Rendered, eager: boolean): unknown => {\n if (choice.index === FALLBACK) return untrack(fallback);\n const body = choice.body();\n if (typeof body !== \"function\") return body;\n // A zero-argument function is an accessor. Returned as it is, the renderer would call it in an\n // effect outside this branch, so an error it throws would escape the boundary around the Show\n // (STATUS: ErrorBoundary does not catch a Show function child). A memo owned here evaluates it\n // inside the branch, where the nearest error handler applies.\n if (body.length === 0) {\n // Lazy outside a transition: the parent evaluates it when it renders, so a deep chain of\n // branches is built in that render rather than inside this one.\n return useMemo<unknown>(() => (body as () => unknown)(), {\n allowWrites: true,\n lazy: !eager,\n });\n }\n const callback = body as (value: unknown) => unknown;\n return untrack(() => callback(choice.keyed ? choice.when : accessorFor(owned)));\n };\n\n return useMemo<unknown>(\n () => {\n const choice = selection();\n if (swap === undefined && state.live !== undefined) {\n swap = transitionHooks()?.slotSwap(state, produce, sameChoice, owner);\n }\n if (swap?.step(choice)) return state.live?.result;\n\n // The usual path: the previous branch was torn down by this memo (its teardown marked it disposing;\n // the flag is cleared again, so a stale accessor throws). Build the next one here.\n if (state.live !== undefined) state.live.owned.disposing = false;\n state.live = undefined;\n const owned: Rendered = { index: choice.index, value: choice.when, disposing: false };\n const result = produce(choice, owned, false);\n // Created last, so it is the newest child: the memo's teardown marks the branch first.\n createRoot(() => {\n onCleanup(() => {\n owned.disposing = true;\n });\n });\n state.live = { choice, owned, result };\n return result;\n },\n { allowWrites: true },\n );\n}\n"],"mappings":"A,6JAoDA,SAASM,EAAWC,EAAWC,EAAoB,CAEjD,OADID,EAAE,QAAUC,EAAE,MACXD,EAAE,QAAA,IAAsB,CAACA,EAAE,OAASA,EAAE,OAASC,EAAE,KADxB,EAElC,CA0BA,SAAgBC,EACdC,EACAC,EACAC,EACmB,CAEnB,IAAIC,EAEEC,EAA2B,CAAE,KAAM,IAAA,EAAU,EAE/CC,EAEEC,EAAQf,EAAS,EASjBgB,EAAYb,MAPS,CACzB,IAAMc,EAAOP,EAAO,EACpBE,EAASK,EACT,IAAMC,EAAyBL,EAAM,KAErC,OADIK,IAAS,IAAA,IAAaD,EAAK,QAAUC,EAAK,MAAM,QAAOA,EAAK,MAAM,MAAQD,EAAK,MAC5EA,CACT,EACwC,CAAE,OAAQZ,CAAW,CAAC,EAExDc,EAAeC,OACN,CACX,GAAIA,EAAM,UAAW,OAAOA,EAAM,MAClC,IAAMC,EAAUnB,EAAQc,CAAS,EACjC,GAAIK,EAAQ,QAAUD,EAAM,MAC1B,MAAU,UAGJ,uBACN,EAEF,OAAQR,GAAUS,EAAA,CAAS,KAAK,CAClC,EAOIC,GAAWC,EAAgBH,EAAiBI,IAA4B,CAC5E,GAAID,EAAO,QAAA,GAAoB,OAAOrB,EAAQS,CAAQ,EACtD,IAAMc,EAAOF,EAAO,KAAK,EACzB,GAAI,OAAOE,GAAS,WAAY,OAAOA,EAKvC,GAAIA,EAAK,SAAW,EAGlB,OAAOtB,MAAwBsB,EAAuB,EAAG,CACvD,YAAa,GACb,KAAM,CAACD,CACT,CAAC,EAEH,IAAME,EAAWD,EACjB,OAAOvB,MAAcwB,EAASH,EAAO,MAAQA,EAAO,KAAOJ,EAAYC,CAAK,CAAC,CAAC,CAChF,EAEA,OAAOjB,MACC,CACJ,IAAMoB,EAASP,EAAU,EAIzB,GAHIF,IAAS,IAAA,IAAaD,EAAM,OAAS,IAAA,KACvCC,EAAOV,EAAgB,CAAC,EAAE,SAASS,EAAOS,EAASjB,EAAYU,CAAK,GAElED,GAAM,KAAKS,CAAM,EAAG,OAAOV,EAAM,MAAM,OAIvCA,EAAM,OAAS,IAAA,KAAWA,EAAM,KAAK,MAAM,UAAY,IAC3DA,EAAM,KAAO,IAAA,GACb,IAAMO,EAAkB,CAAE,MAAOG,EAAO,MAAO,MAAOA,EAAO,KAAM,UAAW,EAAM,EAC9EI,EAASL,EAAQC,EAAQH,EAAO,EAAK,EAQ3C,OANArB,MAAiB,CACfE,MAAgB,CACdmB,EAAM,UAAY,EACpB,CAAC,CACH,CAAC,EACDP,EAAM,KAAO,CAAEU,SAAQH,QAAOO,QAAO,EAC9BA,CACT,EACA,CAAE,YAAa,EAAK,CACtB,CACF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-only.js","names":["
|
|
1
|
+
{"version":3,"file":"client-only.js","names":["Show","onMount","useSignal","ClientOnly","props","mounted","setMounted"],"sources":["../../../src/control-flow/client-only.ts"],"sourcesContent":["import { type Accessor, onMount, useSignal } from \"@shadow-js/core\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { Show } from \"./show\";\n\n/**\n * Props of {@link ClientOnly}.\n * @since 1.0.0\n */\nexport interface ClientOnlyProps {\n /**\n * Rendered on the server and while the page hydrates, until the browser has mounted.\n * @default undefined (nothing is rendered until mount)\n */\n readonly fallback?: JsxChild;\n /**\n * Rendered in the browser only, after mount.\n * @default undefined (nothing is rendered after mount either)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * Renders `children` in the browser only. The server (and the first client pass, which must match\n * the server's markup) renders `fallback`; once mounted, the children replace it. Use it for\n * content that depends on browser state: `window`, `localStorage`, media queries, charts.\n *\n * @param props See {@link ClientOnlyProps}.\n * @returns An accessor of the current content: the fallback until mount, then the children.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ClientOnly } from \"@shadow-js/web\";\n *\n * function Chart(props: { data: number[] }) {\n * return <canvas data-points={props.data.length} />;\n * }\n *\n * function Report() {\n * const [rows] = useSignal([1, 2, 3]);\n * return (\n * <ClientOnly fallback={<p>Loading chart...</p>}>\n * <Chart data={rows()} />\n * </ClientOnly>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function ClientOnly(props: ClientOnlyProps): Accessor<unknown> {\n const [mounted, setMounted] = useSignal(false);\n // Never runs on the server, so the server always renders the fallback.\n onMount(() => {\n setMounted(true);\n });\n return Show({\n get when() {\n return mounted();\n },\n get fallback() {\n return props.fallback;\n },\n get children() {\n return props.children;\n },\n });\n}\n"],"mappings":"A,0FA+CA,SAAgBG,EAAWC,EAA2C,CACpE,GAAM,CAACC,EAASC,GAAcJ,EAAU,EAAK,EAK7C,OAHAD,MAAc,CACZK,EAAW,EAAI,CACjB,CAAC,EACMN,EAAK,CACV,IAAI,MAAO,CACT,OAAOK,EAAQ,CACjB,EACA,IAAI,UAAW,CACb,OAAOD,EAAM,QACf,EACA,IAAI,UAAW,CACb,OAAOA,EAAM,QACf,CACF,CAAC,CACH,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":["TAG_PATTERN","buildElement","tag","ssrElement","props","children","isTextOnlyElement","ssrRaw","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spreadProps } 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 spreadProps(el, props, el.namespaceURI === SVG_NS);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,iQAkDA,MAAMA,EAAc,gCA8CpB,SAASC,EAAa,EAAa,EAAwB,CACzD,GAAI,CAACD,EAAY,KAAKE,CAAG,EACvB,MAAU,UAAsD,oBAAoB,EAMpF,OAAOC,EACLD,EACAE,MACM,CACJ,GAAM,CAAE,YAAaA,EAGrB,OADIC,IAAa,IAAA,IAAaC,EAAkBJ,CAAG,EAAUG,EACtD,CAACE,EAAO,UAAU,EAAGF,EAAUE,EAAO,UAAU,CAAC,CAC1D,EACA,EACF,CAQJ,CAMA,SAASC,EAAY,EAAiB,EAAwB,CAC5D,GAAI,CAACC,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOR,EAAaQ,EAAQL,CAAK,EACjE,GAAI,OAAOK,GAAW,WACpB,OAAOC,EAAgBD,EAAsCL,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CA8CA,SAAgBO,EAAiC,EAAuC,CACtF,GAAM,EAAGC,GAAQC,EAAWT,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOU,MACU,CACb,IAAML,EAAkBL,EAAM,UAC9B,OAAOW,MAAcP,EAAYC,EAAQG,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAd,CACF,CACF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":["createComponent","ssrElement","ssrRaw","isTextOnlyElement","mergeProps","splitProps","untrack","useMemo","TAG_PATTERN","buildElement","tag","props","children","buildTarget","target","Dynamic","rest","createDynamic","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spreadProps } 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 spreadProps(el, props, el.namespaceURI === SVG_NS);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,iQAkDA,MAAMQ,EAAc,gCA8CpB,SAASC,EAAaC,EAAaC,EAAwB,CACzD,GAAI,CAACH,EAAY,KAAKE,CAAG,EACvB,MAAU,UAAsD,oBAAoB,EAMpF,OAAOT,EACLS,EACAC,MACM,CACJ,GAAM,CAAEC,YAAaD,EAGrB,OADIC,IAAa,IAAA,IAAaT,EAAkBO,CAAG,EAAUE,EACtD,CAACV,EAAO,UAAU,EAAGU,EAAUV,EAAO,UAAU,CAAC,CAC1D,EACA,EACF,CAQJ,CAMA,SAASW,EAAYC,EAAiBH,EAAwB,CAC5D,GAAI,CAACG,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOL,EAAaK,EAAQH,CAAK,EACjE,GAAI,OAAOG,GAAW,WACpB,OAAOd,EAAgBc,EAAsCH,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CA8CA,SAAgBI,EAAiCJ,EAAuC,CACtF,GAAM,EAAGK,GAAQX,EAAWM,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOJ,MACU,CACb,IAAMO,EAAkBH,EAAM,UAC9B,OAAOL,MAAcO,EAAYC,EAAQE,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBC,EACdC,EACAP,EAAgB,CAAC,EACF,CACf,OAAOI,EACLX,EACE,CACE,IAAI,WAAe,CACjB,OAAOc,EAAU,CACnB,CACF,EACAP,CACF,CACF,CACF,C"}
|