@shadow-js/web 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +10 -5
- package/dist/dev/class-style.js +47 -47
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +2 -2
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.js +2 -2
- package/dist/dev/control-flow/error-boundary.js.map +1 -1
- package/dist/dev/control-flow/portal.d.ts +2 -2
- package/dist/dev/control-flow/portal.js +15 -13
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/suspense-list.js +2 -2
- package/dist/dev/control-flow/suspense-list.js.map +1 -1
- package/dist/dev/control-flow/suspense.js +2 -2
- package/dist/dev/control-flow/suspense.js.map +1 -1
- package/dist/dev/element.js +5 -2
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/extend.d.ts +2 -2
- package/dist/dev/extend.js +2 -2
- package/dist/dev/insert.d.ts +11 -0
- package/dist/dev/insert.js +50 -33
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/accessor.js +56 -0
- package/dist/dev/internal/accessor.js.map +1 -0
- package/dist/dev/internal/claim.js +0 -1
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +2 -2
- package/dist/dev/internal/css-units.js.map +1 -1
- package/dist/dev/internal/portal-context.d.ts +9 -0
- package/dist/dev/internal/portal-context.js.map +1 -1
- package/dist/dev/internal/react-names.js +22 -12
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +4 -6
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/server/attributes.js +1 -31
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +5 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/index.js +1 -1
- package/dist/dev/server/portals.js +3 -0
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/render.js +1 -1
- package/dist/dev/server/stream.js +1 -1
- package/dist/dev/server.js +1 -1
- package/dist/dev/spread.js +49 -27
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +1 -3
- package/dist/dev/template.js.map +1 -1
- package/dist/dev/view-transition.js +12 -4
- package/dist/dev/view-transition.js.map +1 -1
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js +1 -1
- package/dist/prod/control-flow/suspense.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/extend.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js +2 -0
- package/dist/prod/internal/accessor.js.map +1 -0
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js +1 -1
- package/dist/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js +1 -1
- package/dist/prod/view-transition.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/control-flow/suspense.js.map +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/extend.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js +2 -0
- package/dist/server/internal/accessor.js.map +1 -0
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js +1 -1
- package/dist/server/template.js.map +1 -1
- package/dist/server/view-transition.js.map +1 -1
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +47 -47
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +2 -2
- package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +15 -13
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/suspense-list.js +2 -2
- package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/control-flow/suspense.js.map +1 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/extend.js +2 -2
- package/dist/server-dev/insert.js +50 -33
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/accessor.js +56 -0
- package/dist/server-dev/internal/accessor.js.map +1 -0
- package/dist/server-dev/internal/claim.js +0 -1
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +2 -2
- package/dist/server-dev/internal/css-units.js.map +1 -1
- package/dist/server-dev/internal/portal-context.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +22 -12
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +4 -6
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/attributes.js +1 -31
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +5 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/index.js +1 -1
- package/dist/server-dev/server/portals.js +3 -0
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/render.js +1 -1
- package/dist/server-dev/server/stream.js +1 -1
- package/dist/server-dev/server.js +1 -1
- package/dist/server-dev/spread.js +35 -26
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -3
- package/dist/server-dev/template.js.map +1 -1
- package/dist/server-dev/view-transition.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.3
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- `ViewTransition` applies its name and class again when its content changes (a `Show` that opens, a fallback replaced by content), not only when `name` or `class` change.
|
|
8
|
+
- `insert` reads the children of a `DocumentFragment` once, so an array or accessor that holds the same fragment keeps its nodes when it runs again.
|
|
9
|
+
- `className`, `classList` and `style` call accessors (as array items, object values, style values and nested accessors) like the server does, so `["a", () => "b"]` is `a b` on both sides.
|
|
10
|
+
- `Portal` builds its children once and moves the same nodes and effects when a reactive `mount` changes, so an input keeps its text and a component is not disposed and rebuilt (`moveRegion` is added to `@shadow-js/web/extend`).
|
|
11
|
+
- `ssrElement` writes the extra line break after `<pre>` and `<listing>` (as it already did for `<textarea>`) when the content starts with one, so the parser does not drop it.
|
|
12
|
+
- Boolean attributes written from a props object (`spread`, `element`) follow the rule the server uses: `disabled: 0`, `hidden: ""` or `required: NaN` write no attribute, so hydration no longer gives a disabled button the server did not render (`hidden="until-found"` stays a keyword).
|
|
13
|
+
- A `<select>` driven by `spread` keeps its `value` when its `children` options change: the value is applied again after each commit of the options, as the compiled path does.
|
|
14
|
+
- `<Dynamic component="select" value={...}>` selects its value once its options exist and again whenever new options replace the old ones; it used to show the first option.
|
|
15
|
+
- Client bundles that use `Portal` no longer carry the server markup writer, and props spreads and `Dynamic` are smaller.
|
|
16
|
+
|
|
3
17
|
## 1.0.2
|
|
4
18
|
|
|
5
19
|
### Fixed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":[],"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/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\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 return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\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 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}\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ACF;CAGA,IAAI,OAAO,KAAK,SAAS,GAAG;CAC5B,IAAe,cAAc,UAAU,SAAS,kBAAkB,qBAAqB;CACvF,IAAI,qBAAqB,WAAW,IAAI,GAAG;EACzC,SAAS,sBAAsB,gCAAgC,UAAU,aAAa;EACtF;CACF;CACA,IAAI,cAAc,MACZ;MAAA,GAAG,aAAa,SAAS,MAAM,MAAM,GAAG,aAAa,WAAW,IAAI;CAAA,OACnE,IAAI,GAAG,eAAe,WAAW,UAAU,SAAS,CAAC,MAAM,MAChE,GAAG,eAAe,WAAW,WAAW,IAAI;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,aAAa,IAAa,MAAc,OAAsB;CAC5E,oBAAoB,IAAI;CACxB,OAAO,IAAI,MAAM,MAAM,KAAK;AAC9B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,IAAa,WAAmB,MAAc,OAAsB;CACjG,oBAAoB,IAAI;CACxB,OAAO,IAAI,cAAc,KAAK,OAAO,WAAW,MAAM,KAAK;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,IAAa,MAAc,OAAsB;CAChF,oBAAoB,IAAI;CACxB,GAAG,gBAAgB,MAAM,QAAQ,KAAK,CAAC;AACzC"}
|
|
1
|
+
{"version":3,"file":"attributes.js","names":[],"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/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\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 return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\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":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iBAAiB;;;;;AAMvB,MAAM,gBAAgB;;AAGtB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;AAGA,SAAS,YAAY,OAAwB;CAC3C,OAAO,oBAAoB,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;AAC3E;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,qBAAqB,MAA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B,IAAI;CACxB,OAAO,IAAI,MAAM,MAAM,KAAK;AAC9B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,IAAa,WAAmB,MAAc,OAAsB;CACjG,oBAAoB,IAAI;CACxB,OAAO,IAAI,cAAc,KAAK,OAAO,WAAW,MAAM,KAAK;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,IAAa,MAAc,OAAsB;CAChF,oBAAoB,IAAI;CACxB,GAAG,gBAAgB,MAAM,QAAQ,KAAK,CAAC;AACzC"}
|
|
@@ -7,9 +7,11 @@
|
|
|
7
7
|
* @param el Target element.
|
|
8
8
|
* @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,
|
|
9
9
|
* numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,
|
|
10
|
-
* joined with spaces. `null`, `undefined` and `false` remove the attribute.
|
|
10
|
+
* joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside
|
|
11
|
+
* arrays and as object values, are called (as on the server); the signals they read are tracked by
|
|
12
|
+
* the effect that applies the class.
|
|
11
13
|
* @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested
|
|
12
|
-
* array).
|
|
14
|
+
* array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.
|
|
13
15
|
* @example
|
|
14
16
|
* import { className } from "@shadow-js/web";
|
|
15
17
|
*
|
|
@@ -27,10 +29,12 @@ export declare function className(el: Element, value: unknown): void;
|
|
|
27
29
|
* disappeared from `value` are switched off.
|
|
28
30
|
*
|
|
29
31
|
* @param el Target element.
|
|
30
|
-
* @param value Map from class names to truthiness
|
|
32
|
+
* @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`
|
|
33
|
+
* switches off every class `prev` had on.
|
|
31
34
|
* @param prev The map returned by the previous call. Undefined (the first call) means no class was
|
|
32
35
|
* on yet.
|
|
33
|
-
* @returns The map now in effect (`value`, or `{}` for undefined
|
|
36
|
+
* @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved
|
|
37
|
+
* when `value` has any), to pass back as `prev` next time.
|
|
34
38
|
* @example
|
|
35
39
|
* import { classList } from "@shadow-js/web";
|
|
36
40
|
*
|
|
@@ -71,7 +75,8 @@ export declare function setStyleProperty(el: HTMLElement | SVGElement, name: str
|
|
|
71
75
|
* @param value An object of properties (camelCase, kebab-case or custom names). A string replaces
|
|
72
76
|
* `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `""`
|
|
73
77
|
* items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it
|
|
74
|
-
* on the server. `null`, `undefined` and `false` remove the `style` attribute.
|
|
78
|
+
* on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,
|
|
79
|
+
* array items and property values) are called, as on the server.
|
|
75
80
|
* @param prev The value returned by the previous call. Undefined (the first call) diffs against an
|
|
76
81
|
* empty style. When it is a string or an array, `cssText` is cleared before the object is written.
|
|
77
82
|
* @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise
|
package/dist/dev/class-style.js
CHANGED
|
@@ -1,40 +1,31 @@
|
|
|
1
|
+
import { leaves, unwrap } from "./internal/accessor.js";
|
|
1
2
|
import { cssValueText } from "./internal/css-units.js";
|
|
2
3
|
import { HTML_NS } from "./internal/names.js";
|
|
3
4
|
// src/class-style.ts
|
|
5
|
+
/** `map` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied. */
|
|
6
|
+
function resolveMap(map) {
|
|
7
|
+
let out = map;
|
|
8
|
+
for (const key of Object.keys(map)) {
|
|
9
|
+
if (typeof map[key] !== "function") continue;
|
|
10
|
+
if (out === map) out = { ...map };
|
|
11
|
+
out[key] = unwrap(map[key]);
|
|
12
|
+
}
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
4
15
|
/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */
|
|
5
16
|
function collectClasses(root, parts) {
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
if (frame === void 0 || cursor >= frame.length) {
|
|
14
|
-
const done = frames.pop();
|
|
15
|
-
if (done !== void 0) active.delete(done);
|
|
16
|
-
cursors.pop();
|
|
17
|
-
continue;
|
|
18
|
-
}
|
|
19
|
-
cursors[top] = cursor + 1;
|
|
20
|
-
const item = frame[cursor];
|
|
21
|
-
if (Array.isArray(item)) {
|
|
22
|
-
if (active.has(item)) throw new TypeError("className(): a class array contains itself.");
|
|
23
|
-
active.add(item);
|
|
24
|
-
frames.push(item);
|
|
25
|
-
cursors.push(0);
|
|
26
|
-
} else if (typeof item === "string") {
|
|
27
|
-
if (item !== "") parts.push(item);
|
|
28
|
-
} else if (typeof item === "number") {
|
|
29
|
-
if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));
|
|
30
|
-
} else if (item !== null && typeof item === "object") {
|
|
31
|
-
const record = item;
|
|
32
|
-
for (const key of Object.keys(record)) if (record[key] && key !== "") parts.push(key);
|
|
33
|
-
}
|
|
17
|
+
for (const item of leaves(root, "className(): a class array contains itself.")) if (typeof item === "string") {
|
|
18
|
+
if (item !== "") parts.push(item);
|
|
19
|
+
} else if (typeof item === "number") {
|
|
20
|
+
if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));
|
|
21
|
+
} else if (item !== null && typeof item === "object") {
|
|
22
|
+
const record = item;
|
|
23
|
+
for (const key of Object.keys(record)) if (unwrap(record[key]) && key !== "") parts.push(key);
|
|
34
24
|
}
|
|
35
25
|
}
|
|
36
26
|
/** Class text for `value`, or null when the class attribute must be removed. */
|
|
37
|
-
function classText(
|
|
27
|
+
function classText(input) {
|
|
28
|
+
const value = unwrap(input);
|
|
38
29
|
if (typeof value === "string") return value;
|
|
39
30
|
if (value === null || value === void 0 || value === false) return null;
|
|
40
31
|
const parts = [];
|
|
@@ -65,9 +56,11 @@ function applyClass(el, value, svg) {
|
|
|
65
56
|
* @param el Target element.
|
|
66
57
|
* @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,
|
|
67
58
|
* numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,
|
|
68
|
-
* joined with spaces. `null`, `undefined` and `false` remove the attribute.
|
|
59
|
+
* joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside
|
|
60
|
+
* arrays and as object values, are called (as on the server); the signals they read are tracked by
|
|
61
|
+
* the effect that applies the class.
|
|
69
62
|
* @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested
|
|
70
|
-
* array).
|
|
63
|
+
* array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.
|
|
71
64
|
* @example
|
|
72
65
|
* import { className } from "@shadow-js/web";
|
|
73
66
|
*
|
|
@@ -96,10 +89,12 @@ function enabled(map, key) {
|
|
|
96
89
|
* disappeared from `value` are switched off.
|
|
97
90
|
*
|
|
98
91
|
* @param el Target element.
|
|
99
|
-
* @param value Map from class names to truthiness
|
|
92
|
+
* @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`
|
|
93
|
+
* switches off every class `prev` had on.
|
|
100
94
|
* @param prev The map returned by the previous call. Undefined (the first call) means no class was
|
|
101
95
|
* on yet.
|
|
102
|
-
* @returns The map now in effect (`value`, or `{}` for undefined
|
|
96
|
+
* @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved
|
|
97
|
+
* when `value` has any), to pass back as `prev` next time.
|
|
103
98
|
* @example
|
|
104
99
|
* import { classList } from "@shadow-js/web";
|
|
105
100
|
*
|
|
@@ -110,7 +105,7 @@ function enabled(map, key) {
|
|
|
110
105
|
* @since 1.0.0
|
|
111
106
|
*/
|
|
112
107
|
function classList(el, value, prev) {
|
|
113
|
-
const next = value ?? {};
|
|
108
|
+
const next = resolveMap(value ?? {});
|
|
114
109
|
const before = prev ?? {};
|
|
115
110
|
const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
|
|
116
111
|
for (const key of keys) {
|
|
@@ -164,7 +159,8 @@ function setStyleProperty(el, name, value) {
|
|
|
164
159
|
* @param value An object of properties (camelCase, kebab-case or custom names). A string replaces
|
|
165
160
|
* `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `""`
|
|
166
161
|
* items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it
|
|
167
|
-
* on the server. `null`, `undefined` and `false` remove the `style` attribute.
|
|
162
|
+
* on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,
|
|
163
|
+
* array items and property values) are called, as on the server.
|
|
168
164
|
* @param prev The value returned by the previous call. Undefined (the first call) diffs against an
|
|
169
165
|
* empty style. When it is a string or an array, `cssText` is cleared before the object is written.
|
|
170
166
|
* @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise
|
|
@@ -181,24 +177,28 @@ function setStyleProperty(el, name, value) {
|
|
|
181
177
|
* @since 1.0.0
|
|
182
178
|
*/
|
|
183
179
|
function style(el, value, prev) {
|
|
184
|
-
|
|
180
|
+
const resolved = unwrap(value);
|
|
181
|
+
if (resolved === null || resolved === void 0 || resolved === false) {
|
|
185
182
|
el.removeAttribute("style");
|
|
186
|
-
return
|
|
183
|
+
return resolved;
|
|
187
184
|
}
|
|
188
|
-
if (typeof
|
|
189
|
-
el.style.cssText = String(
|
|
190
|
-
return
|
|
185
|
+
if (typeof resolved !== "object") {
|
|
186
|
+
el.style.cssText = String(resolved);
|
|
187
|
+
return resolved;
|
|
191
188
|
}
|
|
192
|
-
if (Array.isArray(
|
|
189
|
+
if (Array.isArray(resolved)) {
|
|
193
190
|
el.style.cssText = "";
|
|
194
|
-
for (const
|
|
195
|
-
|
|
196
|
-
if (typeof item
|
|
197
|
-
|
|
191
|
+
for (const source of resolved) {
|
|
192
|
+
const item = unwrap(source);
|
|
193
|
+
if (typeof item === "string") el.style.cssText += `;${item}`;
|
|
194
|
+
else if (item !== null && item !== void 0 && item !== false) {
|
|
195
|
+
if (typeof item !== "object" || Array.isArray(item)) throw new TypeError("style(): an array holds only strings and objects.");
|
|
196
|
+
style(el, item, {});
|
|
197
|
+
}
|
|
198
198
|
}
|
|
199
|
-
return
|
|
199
|
+
return resolved;
|
|
200
200
|
}
|
|
201
|
-
const next = { ...
|
|
201
|
+
const next = resolveMap({ ...resolved });
|
|
202
202
|
const before = asRecord(prev) ?? {};
|
|
203
203
|
if (typeof prev === "string" || Array.isArray(prev)) el.style.cssText = "";
|
|
204
204
|
const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-style.js","names":[],"sources":["../../src/class-style.ts"],"sourcesContent":["import { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n // Explicit frames instead of recursion: array nesting depth is controlled by the user.\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = frame[cursor];\n if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(\n __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\",\n );\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (record[key] && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array).\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness. `undefined` switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next: Record<string, unknown> = value ?? {};\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n if (value === null || value === undefined || value === false) {\n el.removeAttribute(\"style\");\n return value;\n }\n if (typeof value !== \"object\") {\n el.style.cssText = String(value);\n return value;\n }\n if (Array.isArray(value)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const item of value) {\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return value;\n }\n const next = { ...(value as Record<string, unknown>) };\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":";;;;AAIA,SAAS,eAAe,MAAe,OAAuB;CAE5D,MAAM,SAAsB,CAAC,CAAC,IAAI,CAAC;CACnC,MAAM,UAAoB,CAAC,CAAC;CAC5B,MAAM,yBAAS,IAAI,IAAe;CAClC,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,SAAS,QAAQ,QAAQ;EAC/B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,QAAQ;GACjD,MAAM,OAAO,OAAO,IAAI;GACxB,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,IAAI;GAC1C,QAAQ,IAAI;GACZ;EACF;EACA,QAAQ,OAAO,SAAS;EACxB,MAAM,OAAO,MAAM;EACnB,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,IAAI,OAAO,IAAI,IAAI,GACjB,MAAM,IAAI,UACE,6CACZ;GACF,OAAO,IAAI,IAAI;GACf,OAAO,KAAK,IAAI;GAChB,QAAQ,KAAK,CAAC;EAChB,OAAO,IAAI,OAAO,SAAS,UACrB;OAAA,SAAS,IAAI,MAAM,KAAK,IAAI;EAAA,OAC3B,IAAI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AI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAChD,MAAM,IAAI,UACE,mDACZ;GAEF,MAAM,IAAI,MAAM,CAAC,CAAC;EACpB;EAEF,OAAO;CACT;CACA,MAAM,OAAO,EAAE,GAAI,MAAkC;CACrD,MAAM,SAAS,SAAS,IAAI,KAAK,CAAC;CAElC,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,GAAG,MAAM,UAAU;CACxE,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,GAAG;EACvC,iBAAiB,IAAI,KAAK,KAAK,IAAI;CACrC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":[],"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/** `map` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied. */\nfunction resolveMap(map: Record<string, unknown>): Record<string, unknown> {\n let out = map;\n for (const key of Object.keys(map)) {\n if (typeof map[key] !== \"function\") continue;\n if (out === map) out = { ...map };\n out[key] = unwrap(map[key]);\n }\n return out;\n}\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 const next = resolveMap(value ?? {});\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. 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 style(el, item, {});\n }\n }\n return resolved;\n }\n const next = resolveMap({ ...(resolved as Record<string, unknown>) });\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":";;;;;AAKA,SAAS,WAAW,KAAuD;CACzE,IAAI,MAAM;CACV,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAAG;EAClC,IAAI,OAAO,IAAI,SAAS,YAAY;EACpC,IAAI,QAAQ,KAAK,MAAM,EAAE,GAAG,IAAI;EAChC,IAAI,OAAO,OAAO,IAAI,IAAI;CAC5B;CACA,OAAO;AACT;;AAGA,SAAS,eAAe,MAAe,OAAuB;CAE5D,KAAK,MAAM,QAAQ,OAAO,MAAM,6CAAK,GACnC,IAAI,OAAO,SAAS,UACd;MAAA,SAAS,IAAI,MAAM,KAAK,IAAI;CAAA,OAC3B,IAAI,OAAO,SAAS,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IAAI,OAAO,SAAS,UAClB,GAAG,MAAM,WAAW,IAAI;QACnB,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,SAAS,OAAO;IAChE,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAChD,MAAM,IAAI,UACE,mDACZ;IAEF,MAAM,IAAI,MAAM,CAAC,CAAC;GACpB;EACF;EACA,OAAO;CACT;CACA,MAAM,OAAO,WAAW,EAAE,GAAI,SAAqC,CAAC;CACpE,MAAM,SAAS,SAAS,IAAI,KAAK,CAAC;CAElC,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,GAAG,MAAM,UAAU;CACxE,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,GAAG;EACvC,iBAAiB,IAAI,KAAK,KAAK,IAAI;CACrC;CACA,OAAO;AACT"}
|
|
@@ -4,7 +4,7 @@ import { nextKey } from "../internal/hydration-scope.js";
|
|
|
4
4
|
import { createComponent } from "../component.js";
|
|
5
5
|
import { claims } from "../internal/hydration-hooks.js";
|
|
6
6
|
import { bindRegion, createRegion } from "../insert.js";
|
|
7
|
-
import {
|
|
7
|
+
import { spreadProps } from "../spread.js";
|
|
8
8
|
import { mergeProps, splitProps, untrack, useMemo } from "@shadow-js/core";
|
|
9
9
|
// src/control-flow/dynamic.ts
|
|
10
10
|
/**
|
|
@@ -55,7 +55,7 @@ function createTagged(tag) {
|
|
|
55
55
|
function buildElement(tag, props) {
|
|
56
56
|
if (!TAG_PATTERN.test(tag)) throw new TypeError("ShadowJS Dynamic: invalid tag");
|
|
57
57
|
const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);
|
|
58
|
-
|
|
58
|
+
spreadProps(el, props, el.namespaceURI === SVG_NS);
|
|
59
59
|
const region = createRegion(el, null, claims.current.takeRegion(el, null));
|
|
60
60
|
bindRegion(region, () => props.children);
|
|
61
61
|
return el;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":[],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spread } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spread(el, props, el.namespaceURI === SVG_NS, true);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,cACJ;;AAGF,MAAM,cACJ;;;;;AAMF,MAAM,cAAc;;;;;;AAOpB,SAAS,YAAY,KAAa,OAAqB;CACrD,MAAM,YACJ,+YACG,MAAM,GAAG,CAAC,CACV,MAAM,SAAS,KAAK,YAAY,MAAM,KAAK;CAChD,IAAI,cAAc,KAAA,KAAa,cAAc,KAAK;CAClD,SACE,oBACA,oCAAoC,IAAI,iDAAiD,UAAU,qCAAqC,IAAI,2CAA2C,UAAU,KACjM,KACF;AACF;;;;;;;AAQA,SAAS,aAAa,KAAsB;CAC1C,MAAM,QAAQ,IAAI,YAAY;CAC9B,IAAI,YAAY,KAAK,KAAK,GAAG,OAAO,SAAS,gBAAgB,WAAW,KAAK;CAC7E,MAAM,KAAK,SAAS,cAAc,GAAG;CAGrC,IAAK,GAAG,gBAAgB,sBAAsB,UAAU,WAAY,CAAC,YAAY,KAAK,KAAK,GACzF,OAAO;CAEI,YAAY,KAAK,KAAK;CACnC,OAAO,SAAS,gBAAgB,QAAQ,GAAG;AAC7C;;;;;;;;AASA,SAAS,aAAa,KAAa,OAAwB;CACzD,IAAI,CAAC,YAAY,KAAK,GAAG,GACvB,MAAM,IAAI,UAAoB,+BAAsD;CAkBtF,MAAM,KAAK,OAAO,QAAQ,aAAa,QAAQ,CAAC,KAAK,aAAa,GAAG;CAErE,OAAO,IAAI,OAAO,GAAG,iBAAiB,QAAQ,IAAI;CAClD,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO,QAAQ,WAAW,IAAI,IAAI,CAAC;CACzE,WAAW,cAAe,MAAiC,QAAQ;CACnE,OAAO;AACT;;;;;AAMA,SAAS,YAAY,QAAiB,OAAwB;CAC5D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,QAAQ,KAAK;CACjE,IAAI,OAAO,WAAW,YACpB,OAAO,gBAAgB,QAAsC,KAAK;CAEpE,MAAM,IAAI,UAEJ,6EAEN;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,QAAiC,OAAuC;CACtF,MAAM,GAAG,QAAQ,WAAW,OAAO,CAAC,WAAW,CAAC;CAEhD,OAAO,cACU;EACb,MAAM,SAAkB,MAAM;EAC9B,OAAO,cAAc,YAAY,QAAQ,IAAI,CAAC;CAChD,GACA,EAAE,aAAa,KAAK,CACtB;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,WACA,QAAgB,CAAC,GACF;CACf,OAAO,QACL,WACE,EACE,IAAI,YAAe;EACjB,OAAO,UAAU;CACnB,EACF,GACA,KACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":[],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { 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":";;;;;;;;;;;;;;;AAuCA,MAAM,cACJ;;AAGF,MAAM,cACJ;;;;;AAMF,MAAM,cAAc;;;;;;AAOpB,SAAS,YAAY,KAAa,OAAqB;CACrD,MAAM,YACJ,+YACG,MAAM,GAAG,CAAC,CACV,MAAM,SAAS,KAAK,YAAY,MAAM,KAAK;CAChD,IAAI,cAAc,KAAA,KAAa,cAAc,KAAK;CAClD,SACE,oBACA,oCAAoC,IAAI,iDAAiD,UAAU,qCAAqC,IAAI,2CAA2C,UAAU,KACjM,KACF;AACF;;;;;;;AAQA,SAAS,aAAa,KAAsB;CAC1C,MAAM,QAAQ,IAAI,YAAY;CAC9B,IAAI,YAAY,KAAK,KAAK,GAAG,OAAO,SAAS,gBAAgB,WAAW,KAAK;CAC7E,MAAM,KAAK,SAAS,cAAc,GAAG;CAGrC,IAAK,GAAG,gBAAgB,sBAAsB,UAAU,WAAY,CAAC,YAAY,KAAK,KAAK,GACzF,OAAO;CAEI,YAAY,KAAK,KAAK;CACnC,OAAO,SAAS,gBAAgB,QAAQ,GAAG;AAC7C;;;;;;;;AASA,SAAS,aAAa,KAAa,OAAwB;CACzD,IAAI,CAAC,YAAY,KAAK,GAAG,GACvB,MAAM,IAAI,UAAoB,+BAAsD;CAkBtF,MAAM,KAAK,OAAO,QAAQ,aAAa,QAAQ,CAAC,KAAK,aAAa,GAAG;CAErE,YAAY,IAAI,OAAO,GAAG,iBAAiB,MAAM;CACjD,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO,QAAQ,WAAW,IAAI,IAAI,CAAC;CACzE,WAAW,cAAe,MAAiC,QAAQ;CACnE,OAAO;AACT;;;;;AAMA,SAAS,YAAY,QAAiB,OAAwB;CAC5D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,QAAQ,KAAK;CACjE,IAAI,OAAO,WAAW,YACpB,OAAO,gBAAgB,QAAsC,KAAK;CAEpE,MAAM,IAAI,UAEJ,6EAEN;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,QAAiC,OAAuC;CACtF,MAAM,GAAG,QAAQ,WAAW,OAAO,CAAC,WAAW,CAAC;CAEhD,OAAO,cACU;EACb,MAAM,SAAkB,MAAM;EAC9B,OAAO,cAAc,YAAY,QAAQ,IAAI,CAAC;CAChD,GACA,EAAE,aAAa,KAAK,CACtB;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,WACA,QAAgB,CAAC,GACF;CACf,OAAO,QACL,WACE,EACE,IAAI,YAAe;EACjB,OAAO,UAAU;CACnB,EACF,GACA,KACF,CACF;AACF"}
|
|
@@ -2,10 +2,10 @@ import { currentScope, withScope } from "../internal/hydration-scope.js";
|
|
|
2
2
|
import { attachHotModules, createHotLink } from "./hot-link.js";
|
|
3
3
|
import { rootErrorsOf } from "./root-errors.js";
|
|
4
4
|
import { catchError, createRoot, getOwner, onCleanup, untrack, useMemo, useSignal } from "@shadow-js/core";
|
|
5
|
-
import {
|
|
5
|
+
import { SignalNode, handleError, readSignal, writeSignal } from "@shadow-js/core/extend";
|
|
6
6
|
// src/control-flow/error-boundary.ts
|
|
7
7
|
function ErrorBoundary(props) {
|
|
8
|
-
const failureCell =
|
|
8
|
+
const failureCell = new SignalNode(void 0, Object.is);
|
|
9
9
|
/** Where an error of this boundary's own fallback goes: the boundary that encloses it. */
|
|
10
10
|
const parentOwner = getOwner();
|
|
11
11
|
const roots = rootErrorsOf(parentOwner);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-boundary.js","names":[],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createSignalNode, handleError, readSignal, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = createSignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":";;;;;;AA0FA,SAAgB,cAAc,OAAmD;CAG/E,MAAM,cAAc,iBAAsC,KAAA,GAAW,OAAO,EAAE;;CAE9E,MAAM,cAAc,SAAS;CAE7B,MAAM,QAAQ,aAAa,WAAW;;CAEtC,MAAM,OAAO,aAAa;CAC1B,MAAM,SACJ,SAAS,OAAO,OAAO;EAAE,IAAI,KAAK;EAAI,OAAO,KAAK;EAAO,WAAW,KAAK;CAAU;CACrF,MAAM,gBAAqC,WAAW,WAAW;CACjE,MAAM,cAAc,SAAoC;EACtD,YAAY,aAAa,MAAM,EAAE,aAAa,KAAK,CAAC;CACtD;;CAEA,MAAM,CAAC,SAAS,cAAc,UAAU,GAAG,EAAE,QAAQ,MAAM,CAAC;;CAE5D,IAAI,QAAQ;;CAEZ,IAAI,OAAO;;CAEX,IAAI;CAEJ,MAAM,cAAoB;EACxB,IAAI,CAAC,OAAO;EACZ,WAAW,KAAA,CAAS;EACpB,YAAY,UAAU,QAAQ,CAAC;CACjC;;;;;CAMA,MAAM,MACF,oBAAoB;EAClB,MAAM;CACR,CAAC;CAGL,MAAM,UAAU,UAAyB;EACvC,IAAI,CAAC,OAAO;EACZ,OAAO,gBAAgB,KAAK;EAC5B,IAAI,MAAM;GACR,IAAI,YAAY,KAAA,GAAW,UAAU,EAAE,MAAM;GAC7C;EACF;EACA,WAAW,EAAE,MAAM,CAAC;CACtB;;CAGA,MAAM,oBAAyC;EAC7C,MAAM,WAAW;EACjB,UAAU,KAAA;EACV,OAAO;CACT;CAEA,MAAM,eAAe,UAA4B;EAC/C,MAAM,WAAW,MAAM;EACvB,IAAI,OAAO,aAAa,YAAY,OAAO;EAC3C,IAAI;GACF,OAAO,cACJ,SAA4D,OAAO,KAAK,CAC3E;EACF,SAAS,QAAQ;GAGf,YAAY,QAAQ,WAAW;GAC/B;EACF;CACF;;CAGA,MAAM,cAAuB;EAC3B,OAAO;EACP,IAAI;GACF,QAAQ;GACR,MAAM,UAAU,QAAQ,KAAK,YAAY;GACzC,IAAI,YAAY,KAAA,GAAW;IACzB,KAAK,IAAI;IACT,OAAO,YAAY,QAAQ,KAAK;GAClC;GAEA,KAAK,QAAQ,MAAM;GACnB,MAAM,QAAQ,YAAY,YAAY;IACpC,IAAI,QAAQ,KAAA,GAAW,iBAAiB,IAAI,OAAO;IACnD,OAAO;KACL;KACA,OAAO,iBAAiB,cAAc,MAAM,QAAQ,GAAG,MAAM;IAC/D;GACF,CAAC;GACD,MAAM,WAAW,YAAY;GAC7B,IAAI,aAAa,KAAA,GAAW;IAC1B,MAAM,QAAQ;IACd,KAAK,IAAI;IACT,OAAO,YAAY,SAAS,KAAK;GACnC;GACA,KAAK,OAAO;GACZ,OAAO,MAAM;EACf,UAAU;GAER,iBAAiB;IACf,gBAAgB;KACd,OAAO;IACT,CAAC;GACH,CAAC;GACD,OAAO;EACT;CAEF;CAIA,MAAM,OAAO,cACJ,WAAW,OAAO,MAAM,IAAI,UAAU,EAAE,GAAG,OAAO,GAAG,KAAK,GACjE,EAAE,aAAa,KAAK,CACtB;CAGA,iBAAiB;EACf,gBAAgB;GACd,QAAQ;GACR,KAAK,OAAO;EACd,CAAC;CACH,CAAC;CACD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"error-boundary.js","names":[],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { handleError, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = new SignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":";;;;;;AA0FA,SAAgB,cAAc,OAAmD;CAG/E,MAAM,cAAc,IAAI,WAAgC,KAAA,GAAW,OAAO,EAAE;;CAE5E,MAAM,cAAc,SAAS;CAE7B,MAAM,QAAQ,aAAa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IAAI,QAAQ,KAAA,GAAW,iBAAiB,IAAI,OAAO;IACnD,OAAO;KACL;KACA,OAAO,iBAAiB,cAAc,MAAM,QAAQ,GAAG,MAAM;IAC/D;GACF,CAAC;GACD,MAAM,WAAW,YAAY;GAC7B,IAAI,aAAa,KAAA,GAAW;IAC1B,MAAM,QAAQ;IACd,KAAK,IAAI;IACT,OAAO,YAAY,SAAS,KAAK;GACnC;GACA,KAAK,OAAO;GACZ,OAAO,MAAM;EACf,UAAU;GAER,iBAAiB;IACf,gBAAgB;KACd,OAAO;IACT,CAAC;GACH,CAAC;GACD,OAAO;EACT;CAEF;CAIA,MAAM,OAAO,cACJ,WAAW,OAAO,MAAM,IAAI,UAAU,EAAE,GAAG,OAAO,GAAG,KAAK,GACjE,EAAE,aAAa,KAAK,CACtB;CAGA,iBAAiB;EACf,gBAAgB;GACd,QAAQ;GACR,KAAK,OAAO;EACd,CAAC;CACH,CAAC;CACD,OAAO;AACT"}
|
|
@@ -32,8 +32,8 @@ export interface PortalProps {
|
|
|
32
32
|
* Renders `children` into another part of the document, without a wrapper: the content nodes are
|
|
33
33
|
* inserted directly into the mount element (or its shadow root). Nothing is left at the call site.
|
|
34
34
|
* Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the
|
|
35
|
-
* mount stay. A reactive `mount` moves the content
|
|
36
|
-
* move.
|
|
35
|
+
* mount stay. A reactive `mount` moves the content: the children are built once, and
|
|
36
|
+
* their nodes and effects keep their identity while they move.
|
|
37
37
|
*
|
|
38
38
|
* On the server the content is rendered into the render's `portals` collector (see
|
|
39
39
|
* `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { childScope, nextKey, withScope } from "../internal/hydration-scope.js";
|
|
2
2
|
import { claims } from "../internal/hydration-hooks.js";
|
|
3
|
-
import { bindRegion, createRegion, removeRegion } from "../insert.js";
|
|
3
|
+
import { bindRegion, createRegion, moveRegion, removeRegion } from "../insert.js";
|
|
4
4
|
import { PortalContext } from "../internal/portal-context.js";
|
|
5
|
-
import {
|
|
6
|
-
import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from "@shadow-js/core";
|
|
5
|
+
import { createRoot, getOwner, isServer, onCleanup, runWithOwner, useContext, useRenderEffect } from "@shadow-js/core";
|
|
7
6
|
// src/control-flow/portal.ts
|
|
8
7
|
/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */
|
|
9
8
|
function appendMoved(target, node) {
|
|
@@ -23,8 +22,8 @@ function resolveMount(mount) {
|
|
|
23
22
|
* Renders `children` into another part of the document, without a wrapper: the content nodes are
|
|
24
23
|
* inserted directly into the mount element (or its shadow root). Nothing is left at the call site.
|
|
25
24
|
* Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the
|
|
26
|
-
* mount stay. A reactive `mount` moves the content
|
|
27
|
-
* move.
|
|
25
|
+
* mount stay. A reactive `mount` moves the content: the children are built once, and
|
|
26
|
+
* their nodes and effects keep their identity while they move.
|
|
28
27
|
*
|
|
29
28
|
* On the server the content is rendered into the render's `portals` collector (see
|
|
30
29
|
* `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates
|
|
@@ -58,9 +57,10 @@ function Portal(props) {
|
|
|
58
57
|
const key = nextKey();
|
|
59
58
|
const sink = useContext(PortalContext);
|
|
60
59
|
if (isServer || sink !== null) {
|
|
61
|
-
if (props.useShadow !== true)
|
|
60
|
+
if (props.useShadow !== true) sink?.render?.(key, () => props.children);
|
|
62
61
|
return null;
|
|
63
62
|
}
|
|
63
|
+
const owner = getOwner();
|
|
64
64
|
let mounted;
|
|
65
65
|
let warned = false;
|
|
66
66
|
let adopted = claims.current.claimPortal(key);
|
|
@@ -78,7 +78,7 @@ function Portal(props) {
|
|
|
78
78
|
return {
|
|
79
79
|
host,
|
|
80
80
|
region,
|
|
81
|
-
stopEffects: createRoot((dispose) => {
|
|
81
|
+
stopEffects: runWithOwner(owner, () => createRoot((dispose) => {
|
|
82
82
|
const bind = () => {
|
|
83
83
|
bindRegion(region, () => props.children);
|
|
84
84
|
};
|
|
@@ -86,10 +86,10 @@ function Portal(props) {
|
|
|
86
86
|
else if (mode === "claimed") withScope(childScope(key), bind);
|
|
87
87
|
else claims.current.withoutClaiming(() => withScope(childScope(key), bind));
|
|
88
88
|
return dispose;
|
|
89
|
-
})
|
|
89
|
+
}))
|
|
90
90
|
};
|
|
91
91
|
};
|
|
92
|
-
/**
|
|
92
|
+
/** Mounts the content in `target` the first time, and moves it there afterward. */
|
|
93
93
|
const moveTo = (target) => {
|
|
94
94
|
const previous = mounted;
|
|
95
95
|
if (previous === void 0) {
|
|
@@ -102,10 +102,12 @@ function Portal(props) {
|
|
|
102
102
|
mounted = mountInto(target, initial, mode);
|
|
103
103
|
return;
|
|
104
104
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
105
|
+
moveRegion(previous.region, target, (node) => appendMoved(target, node));
|
|
106
|
+
mounted = {
|
|
107
|
+
host: target,
|
|
108
|
+
region: previous.region,
|
|
109
|
+
stopEffects: previous.stopEffects
|
|
110
|
+
};
|
|
109
111
|
};
|
|
110
112
|
useRenderEffect(() => {
|
|
111
113
|
return {
|