@shadow-js/web 1.0.6 → 1.1.1

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.
Files changed (222) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/dev/attributes.d.ts +1 -2
  4. package/dist/dev/autofocus.d.ts +1 -2
  5. package/dist/dev/class-style.d.ts +1 -2
  6. package/dist/dev/component.d.ts +1 -2
  7. package/dist/dev/control-flow/activity.d.ts +1 -2
  8. package/dist/dev/control-flow/client-only.d.ts +1 -2
  9. package/dist/dev/control-flow/dynamic.d.ts +1 -2
  10. package/dist/dev/control-flow/error-boundary.d.ts +1 -2
  11. package/dist/dev/control-flow/for.d.ts +1 -2
  12. package/dist/dev/control-flow/fragment.d.ts +1 -2
  13. package/dist/dev/control-flow/index-list.d.ts +1 -2
  14. package/dist/dev/control-flow/lazy.d.ts +1 -2
  15. package/dist/dev/control-flow/no-hydration.d.ts +1 -2
  16. package/dist/dev/control-flow/portal.d.ts +1 -2
  17. package/dist/dev/control-flow/portal.js.map +1 -1
  18. package/dist/dev/control-flow/root-errors.d.ts +2 -3
  19. package/dist/dev/control-flow/show.d.ts +1 -2
  20. package/dist/dev/control-flow/suspense-list.d.ts +2 -3
  21. package/dist/dev/control-flow/suspense.d.ts +1 -2
  22. package/dist/dev/control-flow/switch.d.ts +1 -2
  23. package/dist/dev/derived.d.ts +1 -2
  24. package/dist/dev/element.d.ts +1 -2
  25. package/dist/dev/events.d.ts +1 -2
  26. package/dist/dev/extend.d.ts +9 -0
  27. package/dist/dev/head/components.d.ts +1 -2
  28. package/dist/dev/head/server-head.d.ts +2 -3
  29. package/dist/dev/head/use-head.d.ts +1 -2
  30. package/dist/dev/head/validate.d.ts +1 -2
  31. package/dist/dev/hmr.d.ts +1 -2
  32. package/dist/dev/hmr.js.map +1 -1
  33. package/dist/dev/hydration.d.ts +1 -2
  34. package/dist/dev/insert.d.ts +1 -2
  35. package/dist/dev/insert.js.map +1 -1
  36. package/dist/dev/internal/claim.d.ts +1 -2
  37. package/dist/dev/internal/diagnostics.d.ts +1 -2
  38. package/dist/dev/internal/hydration-hooks.d.ts +1 -2
  39. package/dist/dev/internal/hydration-scope.d.ts +1 -2
  40. package/dist/dev/internal/names.d.ts +1 -2
  41. package/dist/dev/internal/portal-context.d.ts +1 -2
  42. package/dist/dev/internal/reconcile.d.ts +1 -2
  43. package/dist/dev/internal/reconcile.js.map +1 -1
  44. package/dist/dev/internal/stream-context.d.ts +1 -2
  45. package/dist/dev/jsx/aria.d.ts +7 -2
  46. package/dist/dev/jsx/component.d.ts +7 -2
  47. package/dist/dev/jsx/events.d.ts +1 -2
  48. package/dist/dev/jsx/global.d.ts +11 -2
  49. package/dist/dev/jsx/html.d.ts +8 -2
  50. package/dist/dev/jsx/intrinsic.d.ts +10 -2
  51. package/dist/dev/jsx/mathml.d.ts +8 -2
  52. package/dist/dev/jsx/svg.d.ts +13 -2
  53. package/dist/dev/jsx/types.d.ts +1 -2
  54. package/dist/dev/jsx-dev-runtime.d.ts +6 -0
  55. package/dist/dev/jsx-runtime.d.ts +13 -2
  56. package/dist/dev/reactive.d.ts +1 -2
  57. package/dist/dev/render.d.ts +1 -2
  58. package/dist/dev/resource-hints.d.ts +1 -2
  59. package/dist/dev/select-value.d.ts +1 -2
  60. package/dist/dev/server/attributes.d.ts +1 -2
  61. package/dist/dev/server/class-style.d.ts +1 -2
  62. package/dist/dev/server/component.d.ts +1 -2
  63. package/dist/dev/server/derived.d.ts +1 -2
  64. package/dist/dev/server/element.d.ts +1 -2
  65. package/dist/dev/server/errors.js.map +1 -1
  66. package/dist/dev/server/escape.d.ts +1 -2
  67. package/dist/dev/server/form-controls.d.ts +1 -2
  68. package/dist/dev/server/hydration-script.d.ts +1 -2
  69. package/dist/dev/server/index.d.ts +7 -2
  70. package/dist/dev/server/index.js +2 -2
  71. package/dist/dev/server/node.d.ts +1 -2
  72. package/dist/dev/server/node.js.map +1 -1
  73. package/dist/dev/server/portals.d.ts +1 -2
  74. package/dist/dev/server/portals.js.map +1 -1
  75. package/dist/dev/server/raw-text.d.ts +1 -2
  76. package/dist/dev/server/render.d.ts +1 -2
  77. package/dist/dev/server/serialize.d.ts +1 -2
  78. package/dist/dev/server/stream.d.ts +1 -2
  79. package/dist/dev/server/stream.js.map +1 -1
  80. package/dist/dev/server.d.ts +1 -0
  81. package/dist/dev/spread.d.ts +1 -2
  82. package/dist/dev/template.d.ts +1 -2
  83. package/dist/dev/view-transition.d.ts +1 -2
  84. package/dist/prod/attributes.js.map +1 -1
  85. package/dist/prod/autofocus.js.map +1 -1
  86. package/dist/prod/class-style.js.map +1 -1
  87. package/dist/prod/component.js.map +1 -1
  88. package/dist/prod/control-flow/activity.js.map +1 -1
  89. package/dist/prod/control-flow/branch.js.map +1 -1
  90. package/dist/prod/control-flow/client-only.js.map +1 -1
  91. package/dist/prod/control-flow/dynamic.js.map +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/for.js.map +1 -1
  94. package/dist/prod/control-flow/fragment.js.map +1 -1
  95. package/dist/prod/control-flow/hot-link.js.map +1 -1
  96. package/dist/prod/control-flow/index-list.js.map +1 -1
  97. package/dist/prod/control-flow/lazy.js.map +1 -1
  98. package/dist/prod/control-flow/no-hydration.js.map +1 -1
  99. package/dist/prod/control-flow/portal.js.map +1 -1
  100. package/dist/prod/control-flow/root-errors.js.map +1 -1
  101. package/dist/prod/control-flow/show.js.map +1 -1
  102. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  103. package/dist/prod/control-flow/suspense.js.map +1 -1
  104. package/dist/prod/control-flow/switch.js.map +1 -1
  105. package/dist/prod/derived.js.map +1 -1
  106. package/dist/prod/element.js.map +1 -1
  107. package/dist/prod/events.js.map +1 -1
  108. package/dist/prod/head/components.js.map +1 -1
  109. package/dist/prod/head/registry.js.map +1 -1
  110. package/dist/prod/head/server-head.js.map +1 -1
  111. package/dist/prod/head/sink.js.map +1 -1
  112. package/dist/prod/head/use-head.js.map +1 -1
  113. package/dist/prod/head/validate.js.map +1 -1
  114. package/dist/prod/hmr.js.map +1 -1
  115. package/dist/prod/hydration.js.map +1 -1
  116. package/dist/prod/insert.js.map +1 -1
  117. package/dist/prod/internal/accessor.js.map +1 -1
  118. package/dist/prod/internal/claim.js.map +1 -1
  119. package/dist/prod/internal/css-units.js.map +1 -1
  120. package/dist/prod/internal/diagnostics.js.map +1 -1
  121. package/dist/prod/internal/early-events.js.map +1 -1
  122. package/dist/prod/internal/hydration-hooks.js.map +1 -1
  123. package/dist/prod/internal/hydration-scope.js.map +1 -1
  124. package/dist/prod/internal/portal-context.js.map +1 -1
  125. package/dist/prod/internal/react-names.js.map +1 -1
  126. package/dist/prod/internal/reconcile.js.map +1 -1
  127. package/dist/prod/internal/stream-context.js.map +1 -1
  128. package/dist/prod/reactive.js.map +1 -1
  129. package/dist/prod/render.js.map +1 -1
  130. package/dist/prod/resource-hints.js.map +1 -1
  131. package/dist/prod/select-value.js.map +1 -1
  132. package/dist/prod/server/attributes.js.map +1 -1
  133. package/dist/prod/server/class-style.js.map +1 -1
  134. package/dist/prod/server/component.js.map +1 -1
  135. package/dist/prod/server/derived.js.map +1 -1
  136. package/dist/prod/server/element.js.map +1 -1
  137. package/dist/prod/server/errors.js.map +1 -1
  138. package/dist/prod/server/escape.js.map +1 -1
  139. package/dist/prod/server/form-controls.js.map +1 -1
  140. package/dist/prod/server/hydration-script.js.map +1 -1
  141. package/dist/prod/server/node.js.map +1 -1
  142. package/dist/prod/server/portals.js.map +1 -1
  143. package/dist/prod/server/raw-text.js.map +1 -1
  144. package/dist/prod/server/render.js.map +1 -1
  145. package/dist/prod/server/serialize.js.map +1 -1
  146. package/dist/prod/server/stream.js.map +1 -1
  147. package/dist/prod/spread.js.map +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js.map +1 -1
  150. package/dist/server/attributes.js.map +1 -1
  151. package/dist/server/autofocus.js.map +1 -1
  152. package/dist/server/class-style.js.map +1 -1
  153. package/dist/server/component.js.map +1 -1
  154. package/dist/server/control-flow/activity.js.map +1 -1
  155. package/dist/server/control-flow/branch.js.map +1 -1
  156. package/dist/server/control-flow/client-only.js.map +1 -1
  157. package/dist/server/control-flow/dynamic.js.map +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/for.js.map +1 -1
  160. package/dist/server/control-flow/fragment.js.map +1 -1
  161. package/dist/server/control-flow/index-list.js.map +1 -1
  162. package/dist/server/control-flow/lazy.js.map +1 -1
  163. package/dist/server/control-flow/no-hydration.js.map +1 -1
  164. package/dist/server/control-flow/portal.js.map +1 -1
  165. package/dist/server/control-flow/root-errors.js.map +1 -1
  166. package/dist/server/control-flow/show.js.map +1 -1
  167. package/dist/server/control-flow/suspense-list.js.map +1 -1
  168. package/dist/server/control-flow/suspense.js.map +1 -1
  169. package/dist/server/control-flow/switch.js.map +1 -1
  170. package/dist/server/derived.js.map +1 -1
  171. package/dist/server/element.js.map +1 -1
  172. package/dist/server/events.js.map +1 -1
  173. package/dist/server/head/components.js.map +1 -1
  174. package/dist/server/head/registry.js.map +1 -1
  175. package/dist/server/head/server-head.js.map +1 -1
  176. package/dist/server/head/sink.js.map +1 -1
  177. package/dist/server/head/use-head.js.map +1 -1
  178. package/dist/server/head/validate.js.map +1 -1
  179. package/dist/server/hydration.js.map +1 -1
  180. package/dist/server/insert.js.map +1 -1
  181. package/dist/server/internal/accessor.js.map +1 -1
  182. package/dist/server/internal/claim.js.map +1 -1
  183. package/dist/server/internal/css-units.js.map +1 -1
  184. package/dist/server/internal/diagnostics.js.map +1 -1
  185. package/dist/server/internal/early-events.js.map +1 -1
  186. package/dist/server/internal/hydration-hooks.js.map +1 -1
  187. package/dist/server/internal/hydration-scope.js.map +1 -1
  188. package/dist/server/internal/portal-context.js.map +1 -1
  189. package/dist/server/internal/react-names.js.map +1 -1
  190. package/dist/server/internal/reconcile.js.map +1 -1
  191. package/dist/server/internal/stream-context.js.map +1 -1
  192. package/dist/server/reactive.js.map +1 -1
  193. package/dist/server/render.js.map +1 -1
  194. package/dist/server/resource-hints.js.map +1 -1
  195. package/dist/server/select-value.js.map +1 -1
  196. package/dist/server/server/attributes.js.map +1 -1
  197. package/dist/server/server/class-style.js.map +1 -1
  198. package/dist/server/server/component.js.map +1 -1
  199. package/dist/server/server/derived.js.map +1 -1
  200. package/dist/server/server/element.js.map +1 -1
  201. package/dist/server/server/errors.js.map +1 -1
  202. package/dist/server/server/escape.js.map +1 -1
  203. package/dist/server/server/form-controls.js.map +1 -1
  204. package/dist/server/server/hydration-script.js.map +1 -1
  205. package/dist/server/server/node.js.map +1 -1
  206. package/dist/server/server/portals.js.map +1 -1
  207. package/dist/server/server/raw-text.js.map +1 -1
  208. package/dist/server/server/render.js.map +1 -1
  209. package/dist/server/server/serialize.js.map +1 -1
  210. package/dist/server/server/stream.js.map +1 -1
  211. package/dist/server/spread.js.map +1 -1
  212. package/dist/server/template.js.map +1 -1
  213. package/dist/server/view-transition.js.map +1 -1
  214. package/dist/server-dev/control-flow/portal.js.map +1 -1
  215. package/dist/server-dev/insert.js.map +1 -1
  216. package/dist/server-dev/internal/reconcile.js.map +1 -1
  217. package/dist/server-dev/server/errors.js.map +1 -1
  218. package/dist/server-dev/server/index.js +2 -2
  219. package/dist/server-dev/server/node.js.map +1 -1
  220. package/dist/server-dev/server/portals.js.map +1 -1
  221. package/dist/server-dev/server/stream.js.map +1 -1
  222. package/package.json +6 -6
@@ -20,5 +20,4 @@
20
20
  * document.body.append(card);
21
21
  * @since 1.0.0
22
22
  */
23
- export declare function template(html: string, flags?: number): () => Node;
24
- //# sourceMappingURL=template.d.ts.map
23
+ export declare function template(html: string, flags?: number): () => Node;
@@ -91,5 +91,4 @@ export interface ViewTransitionProps {
91
91
  * @see startViewTransition
92
92
  * @since 1.0.0
93
93
  */
94
- export declare function ViewTransition(props: ViewTransitionProps): Accessor<unknown>;
95
- //# sourceMappingURL=view-transition.d.ts.map
94
+ export declare function ViewTransition(props: ViewTransitionProps): Accessor<unknown>;
@@ -1 +1 @@
1
- {"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","text","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAY,EAAwB,CAE3C,OAAOJ,EAAoB,KACzBK,EACG,QAAQ,WAAY,EAAE,CAAC,CACvB,KAAK,CAAC,CACN,YAAY,CACjB,CACF,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYL,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKS,CAAS,EAE3BA,IAAc,SAAWF,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKD,CAAW,EAAIA,EAAYC,CAAK,EAF1C,EAG9C,CAGA,SAASG,EAAc,EAAmB,EAA+B,CAIvE,OAHIH,GAAU,KAAoC,KAC9CA,IAAU,GAAcN,EAAc,KAAKQ,CAAS,EAAI,QAAU,KAClEF,IAAU,GAAaN,EAAc,KAAKQ,CAAS,EAAI,OAAS,GAC7D,OAAOF,CAAK,CACrB,CAGA,SAASI,EAAU,EAA2B,CAC5C,IAAMC,EAAQC,EAAU,QAAQ,GAAG,EACnC,OAAOD,IAAU,GAAKC,EAAYA,EAAU,MAAMD,EAAQ,CAAC,CAC7D,CAGA,SAASE,EAAO,EAAa,EAA0B,EAAmB,EAAsB,CAC9F,IAAML,EAAYI,EAAU,YAAY,EAClCE,EAAOL,EAAcD,EAAWF,CAAK,EACvCQ,IAAS,KACPC,IAAc,KAAMC,EAAG,gBAAgBJ,CAAS,EAC/CI,EAAG,kBAAkBD,EAAWL,EAAUE,CAAS,CAAC,EAKvD,OAAO,KAAKJ,CAAS,GAErBD,EAAqBC,EAAWM,CAAI,IAKpCC,IAAc,KACZC,EAAG,aAAaJ,CAAS,IAAME,GAAME,EAAG,aAAaJ,EAAWE,CAAI,EAC/DE,EAAG,eAAeD,EAAWL,EAAUE,CAAS,CAAC,IAAME,GAChEE,EAAG,eAAeD,EAAWH,EAAWE,CAAI,EAEhD,CA+BA,SAAgBG,EAAa,EAAa,EAAc,EAAsB,CAC5Ef,EAAoBC,CAAI,EACxBU,EAAOG,EAAI,KAAMb,EAAMG,CAAK,CAC9B,CAuBA,SAAgBY,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGhB,EAAoBC,CAAI,EACxBU,EAAOG,EAAID,IAAc,GAAK,KAAOA,EAAWZ,EAAMG,CAAK,CAC7D,CAoBA,SAAgBa,EAAiB,EAAa,EAAc,EAAsB,CAChFjB,EAAoBC,CAAI,EACxBa,EAAG,gBAAgBb,EAAM,EAAQG,CAAM,CACzC,C"}
1
+ {"version":3,"file":"attributes.js","names":["invalidAttributeName","ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","qualified","colon","commit","el","namespace","text","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMC,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoBC,EAAoB,CACtD,GAAI,CAACL,EAAe,KAAKK,CAAI,EAAG,MAAMN,EAAqBM,CAAI,CACjE,CAGA,SAASC,EAAYC,EAAwB,CAE3C,OAAOJ,EAAoB,KACzBI,EACG,QAAQ,WAAY,EAAE,CAAC,CACvB,KAAK,CAAC,CACN,YAAY,CACjB,CACF,CAwBA,SAAgBC,EAAqBH,EAAcE,EAAwB,CACzE,IAAME,EAAYJ,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKQ,CAAS,EAE3BA,IAAc,SAAWF,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKD,CAAW,EAAIA,EAAYC,CAAK,EAF1C,EAG9C,CAGA,SAASG,EAAcD,EAAmBF,EAA+B,CAIvE,OAHIA,GAAU,KAAoC,KAC9CA,IAAU,GAAcL,EAAc,KAAKO,CAAS,EAAI,QAAU,KAClEF,IAAU,GAAaL,EAAc,KAAKO,CAAS,EAAI,OAAS,GAC7D,OAAOF,CAAK,CACrB,CAGA,SAASI,EAAUC,EAA2B,CAC5C,IAAMC,EAAQD,EAAU,QAAQ,GAAG,EACnC,OAAOC,IAAU,GAAKD,EAAYA,EAAU,MAAMC,EAAQ,CAAC,CAC7D,CAGA,SAASC,EAAOC,EAAaC,EAA0BJ,EAAmBL,EAAsB,CAC9F,IAAME,EAAYG,EAAU,YAAY,EAClCK,EAAOP,EAAcD,EAAWF,CAAK,EACvCU,IAAS,KACPD,IAAc,KAAMD,EAAG,gBAAgBH,CAAS,EAC/CG,EAAG,kBAAkBC,EAAWL,EAAUC,CAAS,CAAC,EAKvD,OAAO,KAAKH,CAAS,GAErBD,EAAqBC,EAAWQ,CAAI,IAKpCD,IAAc,KACZD,EAAG,aAAaH,CAAS,IAAMK,GAAMF,EAAG,aAAaH,EAAWK,CAAI,EAC/DF,EAAG,eAAeC,EAAWL,EAAUC,CAAS,CAAC,IAAMK,GAChEF,EAAG,eAAeC,EAAWJ,EAAWK,CAAI,EAEhD,CA+BA,SAAgBC,EAAaH,EAAaV,EAAcE,EAAsB,CAC5EH,EAAoBC,CAAI,EACxBS,EAAOC,EAAI,KAAMV,EAAME,CAAK,CAC9B,CAuBA,SAAgBY,EAAeJ,EAAaC,EAAmBX,EAAcE,EAAsB,CACjGH,EAAoBC,CAAI,EACxBS,EAAOC,EAAIC,IAAc,GAAK,KAAOA,EAAWX,EAAME,CAAK,CAC7D,CAoBA,SAAgBa,EAAiBL,EAAaV,EAAcE,EAAsB,CAChFH,EAAoBC,CAAI,EACxBU,EAAG,gBAAgBV,EAAM,EAAQE,CAAM,CACzC,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"autofocus.js","names":["autoFocus","enabled","hydrating","isHydrating","onMount","doc","el","active","free"],"sources":["../../src/autofocus.ts"],"sourcesContent":["import { onMount } from \"@shadow-js/core\";\nimport { isHydrating } from \"@shadow-js/core/extend\";\n\n/**\n * Focuses an element written with `autoFocus` (React parity) once it is inserted into the document\n * by a client render or update. The compiler calls this for an `autoFocus` attribute and for\n * `autoFocus` keys of a spread, so an app that never uses `autoFocus` never reaches this code. Call it\n * yourself only for elements you create by hand, inside an owner (a component or a root): the focus\n * is requested with `onMount`, so development builds warn with `NO_OWNER_EFFECT` without one.\n *\n * The rules, which match React's for `autoFocus`:\n * - Once per element: the focus is requested when the element is created, after the owner has been\n * flushed. Moving the element later (a keyed reorder) does not focus it again.\n * - An element that is not connected when its owner flushes (a detached root) is not focused.\n * - During hydration the server markup already carries `autofocus`, so the element focuses only when\n * nothing else has the focus (the document's active element is the body or null). A user's focus\n * is never taken away by hydration.\n *\n * @param el The element. Only `HTMLElement` and `SVGElement` are focused; for any other element, and\n * for one that cannot take focus, the call does nothing.\n * @param enabled The `autoFocus` value: falsy values (`false`, `undefined`, `\"\"`, `0`) do nothing.\n * @example\n * import { autoFocus, render } from \"@shadow-js/web\";\n *\n * render(() => {\n * const input = document.createElement(\"input\");\n * autoFocus(input, true); // focused once the root has mounted it\n * return input;\n * }, document.body);\n * @since 1.0.0\n */\nexport function autoFocus(el: Element, enabled: unknown): void {\n if (!enabled) return;\n const hydrating = isHydrating();\n onMount(() => {\n const doc = el.ownerDocument;\n const active = doc.activeElement;\n // Hydration focuses only when nothing has the focus: the body or no element.\n const free = !hydrating || active === null || active === doc.body;\n if (el.isConnected && free && (el instanceof HTMLElement || el instanceof SVGElement)) {\n el.focus();\n }\n });\n}\n"],"mappings":"A,+FA+BA,SAAgBA,EAAU,EAAa,EAAwB,CAC7D,GAAI,CAACC,EAAS,OACd,IAAMC,EAAYC,EAAY,EAC9BC,MAAc,CACZ,IAAMC,EAAMC,EAAG,cACTC,EAASF,EAAI,cAEbG,EAAO,CAACN,GAAaK,IAAW,MAAQA,IAAWF,EAAI,KACzDC,EAAG,aAAeE,IAASF,aAAc,aAAeA,aAAc,aACxEA,EAAG,MAAM,CAEb,CAAC,CACH,C"}
1
+ {"version":3,"file":"autofocus.js","names":["onMount","isHydrating","autoFocus","el","enabled","hydrating","doc","active","free"],"sources":["../../src/autofocus.ts"],"sourcesContent":["import { onMount } from \"@shadow-js/core\";\nimport { isHydrating } from \"@shadow-js/core/extend\";\n\n/**\n * Focuses an element written with `autoFocus` (React parity) once it is inserted into the document\n * by a client render or update. The compiler calls this for an `autoFocus` attribute and for\n * `autoFocus` keys of a spread, so an app that never uses `autoFocus` never reaches this code. Call it\n * yourself only for elements you create by hand, inside an owner (a component or a root): the focus\n * is requested with `onMount`, so development builds warn with `NO_OWNER_EFFECT` without one.\n *\n * The rules, which match React's for `autoFocus`:\n * - Once per element: the focus is requested when the element is created, after the owner has been\n * flushed. Moving the element later (a keyed reorder) does not focus it again.\n * - An element that is not connected when its owner flushes (a detached root) is not focused.\n * - During hydration the server markup already carries `autofocus`, so the element focuses only when\n * nothing else has the focus (the document's active element is the body or null). A user's focus\n * is never taken away by hydration.\n *\n * @param el The element. Only `HTMLElement` and `SVGElement` are focused; for any other element, and\n * for one that cannot take focus, the call does nothing.\n * @param enabled The `autoFocus` value: falsy values (`false`, `undefined`, `\"\"`, `0`) do nothing.\n * @example\n * import { autoFocus, render } from \"@shadow-js/web\";\n *\n * render(() => {\n * const input = document.createElement(\"input\");\n * autoFocus(input, true); // focused once the root has mounted it\n * return input;\n * }, document.body);\n * @since 1.0.0\n */\nexport function autoFocus(el: Element, enabled: unknown): void {\n if (!enabled) return;\n const hydrating = isHydrating();\n onMount(() => {\n const doc = el.ownerDocument;\n const active = doc.activeElement;\n // Hydration focuses only when nothing has the focus: the body or no element.\n const free = !hydrating || active === null || active === doc.body;\n if (el.isConnected && free && (el instanceof HTMLElement || el instanceof SVGElement)) {\n el.focus();\n }\n });\n}\n"],"mappings":"A,+FA+BA,SAAgBE,EAAUC,EAAaC,EAAwB,CAC7D,GAAI,CAACA,EAAS,OACd,IAAMC,EAAYJ,EAAY,EAC9BD,MAAc,CACZ,IAAMM,EAAMH,EAAG,cACTI,EAASD,EAAI,cAEbE,EAAO,CAACH,GAAaE,IAAW,MAAQA,IAAWD,EAAI,KACzDH,EAAG,aAAeK,IAASL,aAAc,aAAeA,aAAc,aACxEA,EAAG,MAAM,CAEb,CAAC,CACH,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"class-style.js","names":["collectClasses","item","leaves","root","parts","record","key","unwrap","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","source","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved","declared","part"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAK,IAAMC,KAAQC,EAAOC,EAAM,oBAAK,EACnC,GAAI,OAAOF,GAAS,SACdA,IAAS,IAAIG,EAAM,KAAKH,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA,CAAI,GAAGG,EAAM,KAAK,OAAOH,CAAI,CAAC,OACzD,GAAqB,OAAOA,GAAS,UAAjCA,EAA2C,CACpD,IAAMI,EAASJ,EACf,IAAK,IAAMK,KAAO,OAAO,KAAKD,CAAM,EAC9BE,EAAOF,EAAOC,EAAI,GAAKA,IAAQ,IAAIF,EAAM,KAAKE,CAAG,CAEzD,CAEJ,CAGA,SAASE,EAAU,EAA+B,CAChD,IAAMC,EAAQF,EAAOG,CAAK,EAC1B,GAAI,OAAOD,GAAU,SAAU,OAAOA,EACtC,GAAIA,GAAU,MAA+BA,IAAU,GAAO,OAAO,KACrE,IAAML,EAAkB,CAAC,EAEzB,OADAJ,EAAeS,EAAOL,CAAK,EACpBA,EAAM,KAAK,GAAG,CACvB,CAOA,SAAgBO,EAAW,EAAa,EAAgB,EAAoB,CAC1E,IAAMC,EAAOJ,EAAUC,CAAK,EACxBG,IAAS,KACXC,EAAG,gBAAgB,OAAO,EAGxBC,EACED,EAAG,aAAa,OAAO,IAAMD,GAAMC,EAAG,aAAa,QAASD,CAAI,EAC3DC,EAAG,YAAcD,IAC1B,EAAG,UAAYA,EAEnB,CAyBA,SAAgBG,EAAU,EAAa,EAAsB,CAC3DJ,EAAWE,EAAIJ,EAAOI,EAAG,eAAiBG,CAAO,CACnD,CAGA,SAAgBC,EAAS,EAAqD,CAC5E,GAAsB,OAAOR,GAAU,UAAnCA,GAA+C,OAAM,QAAQA,CAAK,EACtE,OAAOA,CACT,CAGA,SAASS,EAAQ,EAA8B,EAAsB,CACnE,OAAO,OAAO,OAAOC,EAAKb,CAAG,GAAK,EAAQa,EAAIb,EAChD,CAwBA,SAAgBc,EACd,EACA,EACA,EACyB,CAEzB,IAAMC,EAASZ,GAAS,CAAC,EACrBa,EAAOD,EACX,IAAK,IAAMf,KAAO,OAAO,KAAKe,CAAM,EAC9B,OAAOA,EAAOf,IAAS,aACvBgB,IAASD,IAAQ,EAAO,CAAE,GAAGA,CAAO,GACxC,EAAKf,GAAOC,EAAOc,EAAOf,EAAI,GAEhC,IAAMiB,EAAkCC,GAAQ,CAAC,EAC3CC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMhB,KAAOmB,EAAM,CAGtB,IAAMC,EAAMR,EAAQI,EAAMhB,CAAG,EAE7B,GAAIoB,IADQR,EAAQK,EAAQjB,CACd,EACd,IAAK,IAAMqB,KAASrB,EAAI,MAAM,KAAK,EAC7BqB,IAAU,IAAId,EAAG,UAAU,OAAOc,EAAOD,CAAG,CAEpD,CACA,OAAOJ,CACT,CAOA,SAAgBM,EAAc,EAAsB,CAClD,GAAIC,EAAK,WAAW,IAAI,EAAG,OAAOA,EAClC,IAAMC,EAAQD,EAAK,QAAQ,SAAW,GAAW,IAAIE,EAAO,YAAY,GAAG,EAC3E,OAAOD,EAAM,WAAW,KAAK,EAAI,IAAIA,IAAUA,CACjD,CAsBA,SAAgBE,EAAiB,EAA8B,EAAc,EAAsB,CACjG,IAAMC,EAAWL,EAAcC,CAAI,EAC/BpB,GAAU,MAA+BA,IAAU,GACrDI,EAAG,MAAM,eAAeoB,CAAQ,EAEhCpB,EAAG,MAAM,YAAYoB,EAAUC,EAAaD,EAAUxB,CAAK,CAAC,CAEhE,CA4BA,SAAgB0B,EAAM,EAA8B,EAAgB,EAAyB,CAC3F,IAAMC,EAAW7B,EAAOE,CAAK,EAC7B,GAAI2B,GAAa,MAAkCA,IAAa,GAE9D,OADAvB,EAAG,gBAAgB,OAAO,EACnBuB,EAET,GAAI,OAAOA,GAAa,SAEtB,MADA,GAAG,MAAM,QAAU,OAAOA,CAAQ,EAC3BA,EAET,GAAI,MAAM,QAAQA,CAAQ,EAAG,CAG3B,EAAG,MAAM,QAAU,GACnB,IAAK,IAAMf,KAAUe,EAAU,CAC7B,IAAMnC,EAAOM,EAAOc,CAAM,EAC1B,GAAI,OAAOpB,GAAS,SAClB,EAAG,MAAM,SAAW,IAAIA,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAIF,IAAMoC,EAAoC,CAAC,EAC3C,IAAK,IAAM/B,KAAO,OAAO,KAAKL,CAAI,EAAG,CACnC,IAAMqC,EAAO/B,EAAQN,EAAiCK,EAAI,EACtDgC,GAAS,MAA8BA,IAAS,KAAO,EAAShC,GAAOgC,EAC7E,CACAH,EAAMtB,EAAIwB,EAAU,CAAC,CAAC,CACxB,CACF,CACA,OAAOD,CACT,CACA,IAAMd,EAAgC,CAAE,GAAIc,CAAqC,EACjF,IAAK,IAAM9B,KAAO,OAAO,KAAKgB,CAAI,EAAG,EAAKhB,GAAOC,EAAOe,EAAKhB,EAAI,EACjE,IAAMiB,EAASN,EAASO,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMhB,KAAOmB,EACZ,OAAO,GAAGF,EAAOjB,GAAMgB,EAAKhB,EAAI,GACpC0B,EAAiBnB,EAAIP,EAAKgB,EAAKhB,EAAI,EAErC,OAAOgB,CACT,C"}
1
+ {"version":3,"file":"class-style.js","names":["leaves","unwrap","cssValueText","HTML_NS","collectClasses","root","parts","item","record","key","classText","input","value","applyClass","el","svg","text","className","asRecord","enabled","map","classList","prev","source","next","before","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","style","resolved","declared","part"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASI,EAAeC,EAAeC,EAAuB,CAE5D,IAAK,IAAMC,KAAQP,EAAOK,EAAM,oBAAK,EACnC,GAAI,OAAOE,GAAS,SACdA,IAAS,IAAID,EAAM,KAAKC,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA,CAAI,GAAGD,EAAM,KAAK,OAAOC,CAAI,CAAC,OACzD,GAAqB,OAAOA,GAAS,UAAjCA,EAA2C,CACpD,IAAMC,EAASD,EACf,IAAK,IAAME,KAAO,OAAO,KAAKD,CAAM,EAC9BP,EAAOO,EAAOC,EAAI,GAAKA,IAAQ,IAAIH,EAAM,KAAKG,CAAG,CAEzD,CAEJ,CAGA,SAASC,EAAUC,EAA+B,CAChD,IAAMC,EAAQX,EAAOU,CAAK,EAC1B,GAAI,OAAOC,GAAU,SAAU,OAAOA,EACtC,GAAIA,GAAU,MAA+BA,IAAU,GAAO,OAAO,KACrE,IAAMN,EAAkB,CAAC,EAEzB,OADAF,EAAeQ,EAAON,CAAK,EACpBA,EAAM,KAAK,GAAG,CACvB,CAOA,SAAgBO,EAAWC,EAAaF,EAAgBG,EAAoB,CAC1E,IAAMC,EAAON,EAAUE,CAAK,EACxBI,IAAS,KACXF,EAAG,gBAAgB,OAAO,EAGxBC,EACED,EAAG,aAAa,OAAO,IAAME,GAAMF,EAAG,aAAa,QAASE,CAAI,EAC3DF,EAAG,YAAcE,IAC1BF,EAAG,UAAYE,EAEnB,CAyBA,SAAgBC,EAAUH,EAAaF,EAAsB,CAC3DC,EAAWC,EAAIF,EAAOE,EAAG,eAAiBX,CAAO,CACnD,CAGA,SAAgBe,EAASN,EAAqD,CAC5E,GAAsB,OAAOA,GAAU,UAAnCA,GAA+C,OAAM,QAAQA,CAAK,EACtE,OAAOA,CACT,CAGA,SAASO,EAAQC,EAA8BX,EAAsB,CACnE,OAAO,OAAO,OAAOW,EAAKX,CAAG,GAAK,EAAQW,EAAIX,EAChD,CAwBA,SAAgBY,EACdP,EACAF,EACAU,EACyB,CAEzB,IAAMC,EAASX,GAAS,CAAC,EACrBY,EAAOD,EACX,IAAK,IAAMd,KAAO,OAAO,KAAKc,CAAM,EAC9B,OAAOA,EAAOd,IAAS,aACvBe,IAASD,IAAQC,EAAO,CAAE,GAAGD,CAAO,GACxCC,EAAKf,GAAOR,EAAOsB,EAAOd,EAAI,GAEhC,IAAMgB,EAAkCH,GAAQ,CAAC,EAC3CI,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKD,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMf,KAAOiB,EAAM,CAGtB,IAAMC,EAAMR,EAAQK,EAAMf,CAAG,EAE7B,GAAIkB,IADQR,EAAQM,EAAQhB,CACd,EACd,IAAK,IAAMmB,KAASnB,EAAI,MAAM,KAAK,EAC7BmB,IAAU,IAAId,EAAG,UAAU,OAAOc,EAAOD,CAAG,CAEpD,CACA,OAAOH,CACT,CAOA,SAAgBK,EAAcC,EAAsB,CAClD,GAAIA,EAAK,WAAW,IAAI,EAAG,OAAOA,EAClC,IAAMC,EAAQD,EAAK,QAAQ,SAAWE,GAAW,IAAIA,EAAO,YAAY,GAAG,EAC3E,OAAOD,EAAM,WAAW,KAAK,EAAI,IAAIA,IAAUA,CACjD,CAsBA,SAAgBE,EAAiBnB,EAA8BgB,EAAclB,EAAsB,CACjG,IAAMsB,EAAWL,EAAcC,CAAI,EAC/BlB,GAAU,MAA+BA,IAAU,GACrDE,EAAG,MAAM,eAAeoB,CAAQ,EAEhCpB,EAAG,MAAM,YAAYoB,EAAUhC,EAAagC,EAAUtB,CAAK,CAAC,CAEhE,CA4BA,SAAgBuB,EAAMrB,EAA8BF,EAAgBU,EAAyB,CAC3F,IAAMc,EAAWnC,EAAOW,CAAK,EAC7B,GAAIwB,GAAa,MAAkCA,IAAa,GAE9D,OADAtB,EAAG,gBAAgB,OAAO,EACnBsB,EAET,GAAI,OAAOA,GAAa,SAEtB,MADAtB,GAAG,MAAM,QAAU,OAAOsB,CAAQ,EAC3BA,EAET,GAAI,MAAM,QAAQA,CAAQ,EAAG,CAG3BtB,EAAG,MAAM,QAAU,GACnB,IAAK,IAAMS,KAAUa,EAAU,CAC7B,IAAM7B,EAAON,EAAOsB,CAAM,EAC1B,GAAI,OAAOhB,GAAS,SAClBO,EAAG,MAAM,SAAW,IAAIP,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAIF,IAAM8B,EAAoC,CAAC,EAC3C,IAAK,IAAM5B,KAAO,OAAO,KAAKF,CAAI,EAAG,CACnC,IAAM+B,EAAOrC,EAAQM,EAAiCE,EAAI,EACtD6B,GAAS,MAA8BA,IAAS,KAAOD,EAAS5B,GAAO6B,EAC7E,CACAH,EAAMrB,EAAIuB,EAAU,CAAC,CAAC,CACxB,CACF,CACA,OAAOD,CACT,CACA,IAAMZ,EAAgC,CAAE,GAAIY,CAAqC,EACjF,IAAK,IAAM3B,KAAO,OAAO,KAAKe,CAAI,EAAGA,EAAKf,GAAOR,EAAOuB,EAAKf,EAAI,EACjE,IAAMgB,EAASP,EAASI,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAGR,EAAG,MAAM,QAAU,IACxE,IAAMY,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKD,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMf,KAAOiB,EACZ,OAAO,GAAGD,EAAOhB,GAAMe,EAAKf,EAAI,GACpCwB,EAAiBnB,EAAIL,EAAKe,EAAKf,EAAI,EAErC,OAAOe,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","names":["createComponent","enterComponent","owner","createOwner","currentScope","runInScope","component","props"],"sources":["../../src/component.ts"],"sourcesContent":["import {\n addCleanup,\n createOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n runInScope,\n} from \"@shadow-js/core/extend\";\nimport { currentScope, enterComponent } from \"./internal/hydration-scope\";\n\n/** Dev-only: the name each component was created with, for devtools. Weak, so components are not kept alive. */\nconst componentNames = new WeakMap<object, string>();\n\n/**\n * Calls a component untracked, under a new owner that is a child of the current one: cleanups and\n * effects it creates are disposed with the enclosing scope. The name, given in development builds,\n * is recorded for devtools.\n *\n * @param component The component function.\n * @param props The props object (usually with getters for reactive props).\n * @param name Optional devtools name.\n * @returns Whatever the component returns.\n * @example\n * import { createComponent } from \"@shadow-js/web\";\n *\n * function Counter(props: { start: number }) {\n * return `Count: ${props.start}`;\n * }\n *\n * const view = createComponent(Counter, { start: 0 }, \"Counter\");\n * @since 1.0.0\n */\nexport function createComponent<P>(\n component: (props: P) => unknown,\n props: P,\n name?: string,\n): unknown {\n if (__DEV__ && name !== undefined) componentNames.set(component, name);\n return enterComponent(() => {\n // Every component runs under an owner of its own: devtools attribute updates to it, and\n // `useId` uses its hydration-scope key as a prefix, so ids agree between server and browser\n // even though the browser creates more owners (effects) than the server does.\n const owner = createOwner();\n owner.idPrefix = currentScope()?.id;\n // One scope switch (owner in, listener off): deep component trees are bounded by the call stack.\n const result = runInScope({ owner, listener: null }, () => component(props));\n if (__DEV__) {\n devtoolsReport(\n DEVTOOLS_EVENT.COMPONENT_MOUNTED,\n owner,\n componentNames.get(component),\n result,\n );\n addCleanup(owner, () => devtoolsReport(DEVTOOLS_EVENT.COMPONENT_UNMOUNTED, owner));\n }\n return result;\n });\n}\n\n/**\n * The devtools name recorded for a component in development builds, if any.\n * @internal\n */\nexport function componentName(component: object): string | undefined {\n return componentNames.get(component);\n}\n"],"mappings":"A,sJA+BA,SAAgBA,EACd,EACA,EACA,EACS,CAET,OAAOC,MAAqB,CAI1B,IAAMC,EAAQC,EAAY,EAa1B,MAZA,GAAM,SAAWC,EAAa,CAAC,EAAE,GAElBC,EAAW,CAAE,QAAO,SAAU,IAAK,MAASC,EAAUC,CAAK,CAU9D,CACd,CAAC,CACH,C"}
1
+ {"version":3,"file":"component.js","names":["currentScope","enterComponent","createOwner","runInScope","createComponent","component","props","name","owner"],"sources":["../../src/component.ts"],"sourcesContent":["import {\n addCleanup,\n createOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n runInScope,\n} from \"@shadow-js/core/extend\";\nimport { currentScope, enterComponent } from \"./internal/hydration-scope\";\n\n/** Dev-only: the name each component was created with, for devtools. Weak, so components are not kept alive. */\nconst componentNames = new WeakMap<object, string>();\n\n/**\n * Calls a component untracked, under a new owner that is a child of the current one: cleanups and\n * effects it creates are disposed with the enclosing scope. The name, given in development builds,\n * is recorded for devtools.\n *\n * @param component The component function.\n * @param props The props object (usually with getters for reactive props).\n * @param name Optional devtools name.\n * @returns Whatever the component returns.\n * @example\n * import { createComponent } from \"@shadow-js/web\";\n *\n * function Counter(props: { start: number }) {\n * return `Count: ${props.start}`;\n * }\n *\n * const view = createComponent(Counter, { start: 0 }, \"Counter\");\n * @since 1.0.0\n */\nexport function createComponent<P>(\n component: (props: P) => unknown,\n props: P,\n name?: string,\n): unknown {\n if (__DEV__ && name !== undefined) componentNames.set(component, name);\n return enterComponent(() => {\n // Every component runs under an owner of its own: devtools attribute updates to it, and\n // `useId` uses its hydration-scope key as a prefix, so ids agree between server and browser\n // even though the browser creates more owners (effects) than the server does.\n const owner = createOwner();\n owner.idPrefix = currentScope()?.id;\n // One scope switch (owner in, listener off): deep component trees are bounded by the call stack.\n const result = runInScope({ owner, listener: null }, () => component(props));\n if (__DEV__) {\n devtoolsReport(\n DEVTOOLS_EVENT.COMPONENT_MOUNTED,\n owner,\n componentNames.get(component),\n result,\n );\n addCleanup(owner, () => devtoolsReport(DEVTOOLS_EVENT.COMPONENT_UNMOUNTED, owner));\n }\n return result;\n });\n}\n\n/**\n * The devtools name recorded for a component in development builds, if any.\n * @internal\n */\nexport function componentName(component: object): string | undefined {\n return componentNames.get(component);\n}\n"],"mappings":"A,sJA+BA,SAAgBI,EACdC,EACAC,EACAC,EACS,CAET,OAAON,MAAqB,CAI1B,IAAMO,EAAQN,EAAY,EAa1B,MAZAM,GAAM,SAAWR,EAAa,CAAC,EAAE,GAElBG,EAAW,CAAEK,QAAO,SAAU,IAAK,MAASH,EAAUC,CAAK,CAU9D,CACd,CAAC,CACH,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"activity.js","names":["stashBetween","parent","start","elements","texts","scrolls","active","focus","node","end","next","element","scrollable","restore","i","stash","entry","before","display","top","left","Activity","content","createOwner","built","ready","contentValue","runWithOwner","untrack","props","hidden","setHidden","useSignal","paused","useRenderEffect","isHidden","pauseOwner","resumeOwner","useEffect","previous"],"sources":["../../../src/control-flow/activity.ts"],"sourcesContent":["import {\n type Accessor,\n runWithOwner,\n untrack,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n\n/**\n * `visible` shows the children; `hidden` keeps them alive (state, DOM and focus) but out of sight.\n * @since 1.0.0\n */\nexport type ActivityMode = \"visible\" | \"hidden\";\n\n/**\n * Props of {@link Activity}.\n * @since 1.0.0\n */\nexport interface ActivityProps {\n /**\n * `\"visible\"` shows the children; `\"hidden\"` keeps them alive but out of sight. Changing it\n * does not rebuild the children and may be reactive.\n * @default \"visible\"\n */\n readonly mode?: ActivityMode;\n /**\n * The content. Built once, when the parent first renders the Activity.\n * @default undefined (the Activity renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** What a hidden Activity changed in the DOM, so showing it restores exactly that. */\ninterface Stash {\n readonly elements: Array<readonly [HTMLElement, string]>;\n readonly texts: Array<{ readonly text: Text; readonly parent: Node; readonly next: Node | null }>;\n readonly scrolls: Array<readonly [Element, number, number]>;\n readonly focus: Element | null;\n}\n\n/**\n * Hides the nodes between two anchors without removing them. Top-level elements get\n * `display: none` (their own state, subtree and listeners are untouched). Top-level text nodes are\n * detached (a text node cannot be hidden) and put back in order when shown. Scroll offsets and the\n * focused element are remembered, because `display: none` loses both.\n */\nfunction stashBetween(start: Node, end: Node): Stash | undefined {\n const parent = start.parentNode;\n if (parent === null) return undefined;\n const elements: Array<readonly [HTMLElement, string]> = [];\n const texts: Stash[\"texts\"][number][] = [];\n const scrolls: Array<readonly [Element, number, number]> = [];\n const active = document.activeElement;\n let focus: Element | null = null;\n let node: Node | null = start.nextSibling;\n while (node !== null && node !== end) {\n const next: Node | null = node.nextSibling;\n if (node.nodeType === 1) {\n const element = node as HTMLElement;\n elements.push([element, element.style.display]);\n element.style.display = \"none\";\n for (const scrollable of [element, ...Array.from(element.querySelectorAll(\"*\"))]) {\n if (scrollable.scrollTop !== 0 || scrollable.scrollLeft !== 0) {\n scrolls.push([scrollable, scrollable.scrollTop, scrollable.scrollLeft]);\n }\n }\n if (active !== null && element.contains(active)) focus = active;\n } else if (node.nodeType === 3) {\n texts.push({ text: node as Text, parent, next });\n parent.removeChild(node);\n }\n node = next;\n }\n return { elements, texts, scrolls, focus };\n}\n\n/** Puts back what {@link stashBetween} changed. Texts are restored last-to-first, so each finds its next. */\nfunction restore(stash: Stash, end: Node): void {\n for (let i = stash.texts.length - 1; i >= 0; i -= 1) {\n const entry = stash.texts[i];\n if (entry === undefined || entry.text.parentNode !== null) continue;\n const before = entry.next !== null && entry.next.parentNode === entry.parent ? entry.next : end;\n entry.parent.insertBefore(entry.text, before);\n }\n for (const [element, display] of stash.elements) element.style.display = display;\n for (const [element, top, left] of stash.scrolls) {\n element.scrollTop = top;\n element.scrollLeft = left;\n }\n const focus = stash.focus;\n if (focus instanceof HTMLElement && focus.isConnected) focus.focus({ preventScroll: true });\n}\n\n/**\n * Keeps its children alive while hidden: `mode=\"hidden\"` removes them from sight but keeps their state,\n * their DOM nodes and their focus and scroll position. Hidden content is paused: its effects run their\n * cleanups and wait, its memos keep their last value, and its DOM does not update. Updates that arrive\n * while hidden are applied once, when the content is shown again.\n *\n * Use it for tabs, wizards and routes you want back instantly. A hidden Activity mounted hidden renders\n * its DOM once (so it is ready to show) and runs no effects until it is shown. The server renders the\n * children without hiding them; the client hides them once it hydrates.\n *\n * @param props See {@link ActivityProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Activity } from \"@shadow-js/web\";\n *\n * function Chat() {\n * return <p>Chat</p>;\n * }\n *\n * function Tabs() {\n * const [tab] = useSignal(\"chat\");\n * return (\n * <Activity mode={tab() === \"chat\" ? \"visible\" : \"hidden\"}>\n * <Chat />\n * </Activity>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Activity(props: ActivityProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // The content lives under its own owner, so pausing it reaches every effect and memo it created.\n const content = createOwner();\n // Built when the parent first reads it, not here: the server builds children at the same point of the\n // render, which keeps hydration keys equal on both sides.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = runWithOwner(content, () => untrack(() => props.children));\n }\n return built;\n };\n // Empty text anchors bound the content: the DOM range the visibility code hides and shows.\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const [hidden, setHidden] = useSignal(false);\n let paused = false;\n // Pausing happens in the render phase, before the content's own effects can run.\n useRenderEffect(\n () => props.mode === \"hidden\",\n (isHidden) => {\n if (isHidden === paused) return;\n paused = isHidden;\n if (isHidden) pauseOwner(content);\n else resumeOwner(content);\n setHidden(isHidden);\n },\n );\n // Runs after the DOM is committed (a user effect), so the nodes it hides exist.\n let stash: Stash | undefined;\n useEffect(() => {\n if (hidden()) {\n if (stash === undefined) stash = stashBetween(start, end);\n } else if (stash !== undefined) {\n const previous = stash;\n stash = undefined;\n restore(previous, end);\n }\n });\n return () => [start, contentValue(), end];\n}\n"],"mappings":"A,qMAgDA,SAASA,EAAa,EAAa,EAA8B,CAC/D,IAAMC,EAASC,EAAM,WACrB,GAAID,IAAW,KAAM,OACrB,IAAME,EAAkD,CAAC,EACnDC,EAAkC,CAAC,EACnCC,EAAqD,CAAC,EACtDC,EAAS,SAAS,cACpBC,EAAwB,KACxBC,EAAoBN,EAAM,YAC9B,KAAOM,IAAS,MAAQA,IAASC,GAAK,CACpC,IAAMC,EAAoBF,EAAK,YAC/B,GAAIA,EAAK,WAAa,EAAG,CACvB,IAAMG,EAAUH,EAChBL,EAAS,KAAK,CAACQ,EAASA,EAAQ,MAAM,OAAO,CAAC,EAC9C,EAAQ,MAAM,QAAU,OACxB,IAAK,IAAMC,IAAc,CAACD,EAAS,GAAG,MAAM,KAAKA,EAAQ,iBAAiB,GAAG,CAAC,CAAC,GACzEC,EAAW,YAAc,GAAKA,EAAW,aAAe,IAC1DP,EAAQ,KAAK,CAACO,EAAYA,EAAW,UAAWA,EAAW,UAAU,CAAC,EAGtEN,IAAW,MAAQK,EAAQ,SAASL,CAAM,IAAG,EAAQA,EAC3D,MAAWE,EAAK,WAAa,IAC3BJ,EAAM,KAAK,CAAE,KAAMI,EAAc,SAAQ,MAAK,CAAC,EAC/CP,EAAO,YAAYO,CAAI,GAEzB,EAAOE,CACT,CACA,MAAO,CAAE,WAAU,QAAO,UAAS,OAAM,CAC3C,CAGA,SAASG,EAAQ,EAAc,EAAiB,CAC9C,IAAK,IAAIC,EAAIC,EAAM,MAAM,OAAS,EAAGD,GAAK,EAAG,IAAQ,CACnD,IAAME,EAAQD,EAAM,MAAMD,GAC1B,GAAIE,IAAU,IAAA,IAAaA,EAAM,KAAK,aAAe,KAAM,SAC3D,IAAMC,EAASD,EAAM,OAAS,MAAQA,EAAM,KAAK,aAAeA,EAAM,OAASA,EAAM,KAAOP,EAC5FO,EAAM,OAAO,aAAaA,EAAM,KAAMC,CAAM,CAC9C,CACA,IAAK,GAAM,CAACN,EAASO,KAAYH,EAAM,SAAU,EAAQ,MAAM,QAAUG,EACzE,IAAK,GAAM,CAACP,EAASQ,EAAKC,KAASL,EAAM,QACvC,EAAQ,UAAYI,EACpB,EAAQ,WAAaC,EAEvB,IAAMb,EAAQQ,EAAM,MAChBR,aAAiB,aAAeA,EAAM,aAAaA,EAAM,MAAM,CAAE,cAAe,EAAK,CAAC,CAC5F,CAiCA,SAAgBc,EAAS,EAAyC,CAGhE,IAAMC,EAAUC,EAAY,EAGxBC,EACAC,EAAQ,GACNC,OACCD,IACH,EAAQ,GACR,EAAQE,EAAaL,MAAeM,MAAcC,EAAM,QAAQ,CAAC,GAE5DL,GAGHtB,EAAQ,SAAS,eAAe,EAAE,EAClCO,EAAM,SAAS,eAAe,EAAE,EAChC,CAACqB,EAAQC,GAAaC,EAAU,EAAK,EACvCC,EAAS,GAEbC,MACQL,EAAM,OAAS,SACpB,GAAa,CACRM,IAAaF,IACjB,EAASE,EACLA,EAAUC,EAAWd,CAAO,EAC3Be,EAAYf,CAAO,EACxBS,EAAUI,CAAQ,EACpB,CACF,EAEA,IAAIpB,EAUJ,OATAuB,MAAgB,CACd,GAAIR,EAAO,EACLf,IAAU,IAAA,KAAW,EAAQf,EAAaE,EAAOO,CAAG,QACnD,GAAIM,IAAU,IAAA,GAAW,CAC9B,IAAMwB,EAAWxB,EACjB,EAAQ,IAAA,GACRF,EAAQ0B,EAAU9B,CAAG,CACvB,CACF,CAAC,MACY,CAACP,EAAOwB,EAAa,EAAGjB,CAAG,CAC1C,C"}
1
+ {"version":3,"file":"activity.js","names":["runWithOwner","untrack","useEffect","useRenderEffect","useSignal","createOwner","pauseOwner","resumeOwner","stashBetween","start","end","parent","elements","texts","scrolls","active","focus","node","next","element","scrollable","restore","stash","i","entry","before","display","top","left","Activity","props","content","built","ready","contentValue","hidden","setHidden","paused","isHidden","previous"],"sources":["../../../src/control-flow/activity.ts"],"sourcesContent":["import {\n type Accessor,\n runWithOwner,\n untrack,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n\n/**\n * `visible` shows the children; `hidden` keeps them alive (state, DOM and focus) but out of sight.\n * @since 1.0.0\n */\nexport type ActivityMode = \"visible\" | \"hidden\";\n\n/**\n * Props of {@link Activity}.\n * @since 1.0.0\n */\nexport interface ActivityProps {\n /**\n * `\"visible\"` shows the children; `\"hidden\"` keeps them alive but out of sight. Changing it\n * does not rebuild the children and may be reactive.\n * @default \"visible\"\n */\n readonly mode?: ActivityMode;\n /**\n * The content. Built once, when the parent first renders the Activity.\n * @default undefined (the Activity renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** What a hidden Activity changed in the DOM, so showing it restores exactly that. */\ninterface Stash {\n readonly elements: Array<readonly [HTMLElement, string]>;\n readonly texts: Array<{ readonly text: Text; readonly parent: Node; readonly next: Node | null }>;\n readonly scrolls: Array<readonly [Element, number, number]>;\n readonly focus: Element | null;\n}\n\n/**\n * Hides the nodes between two anchors without removing them. Top-level elements get\n * `display: none` (their own state, subtree and listeners are untouched). Top-level text nodes are\n * detached (a text node cannot be hidden) and put back in order when shown. Scroll offsets and the\n * focused element are remembered, because `display: none` loses both.\n */\nfunction stashBetween(start: Node, end: Node): Stash | undefined {\n const parent = start.parentNode;\n if (parent === null) return undefined;\n const elements: Array<readonly [HTMLElement, string]> = [];\n const texts: Stash[\"texts\"][number][] = [];\n const scrolls: Array<readonly [Element, number, number]> = [];\n const active = document.activeElement;\n let focus: Element | null = null;\n let node: Node | null = start.nextSibling;\n while (node !== null && node !== end) {\n const next: Node | null = node.nextSibling;\n if (node.nodeType === 1) {\n const element = node as HTMLElement;\n elements.push([element, element.style.display]);\n element.style.display = \"none\";\n for (const scrollable of [element, ...Array.from(element.querySelectorAll(\"*\"))]) {\n if (scrollable.scrollTop !== 0 || scrollable.scrollLeft !== 0) {\n scrolls.push([scrollable, scrollable.scrollTop, scrollable.scrollLeft]);\n }\n }\n if (active !== null && element.contains(active)) focus = active;\n } else if (node.nodeType === 3) {\n texts.push({ text: node as Text, parent, next });\n parent.removeChild(node);\n }\n node = next;\n }\n return { elements, texts, scrolls, focus };\n}\n\n/** Puts back what {@link stashBetween} changed. Texts are restored last-to-first, so each finds its next. */\nfunction restore(stash: Stash, end: Node): void {\n for (let i = stash.texts.length - 1; i >= 0; i -= 1) {\n const entry = stash.texts[i];\n if (entry === undefined || entry.text.parentNode !== null) continue;\n const before = entry.next !== null && entry.next.parentNode === entry.parent ? entry.next : end;\n entry.parent.insertBefore(entry.text, before);\n }\n for (const [element, display] of stash.elements) element.style.display = display;\n for (const [element, top, left] of stash.scrolls) {\n element.scrollTop = top;\n element.scrollLeft = left;\n }\n const focus = stash.focus;\n if (focus instanceof HTMLElement && focus.isConnected) focus.focus({ preventScroll: true });\n}\n\n/**\n * Keeps its children alive while hidden: `mode=\"hidden\"` removes them from sight but keeps their state,\n * their DOM nodes and their focus and scroll position. Hidden content is paused: its effects run their\n * cleanups and wait, its memos keep their last value, and its DOM does not update. Updates that arrive\n * while hidden are applied once, when the content is shown again.\n *\n * Use it for tabs, wizards and routes you want back instantly. A hidden Activity mounted hidden renders\n * its DOM once (so it is ready to show) and runs no effects until it is shown. The server renders the\n * children without hiding them; the client hides them once it hydrates.\n *\n * @param props See {@link ActivityProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Activity } from \"@shadow-js/web\";\n *\n * function Chat() {\n * return <p>Chat</p>;\n * }\n *\n * function Tabs() {\n * const [tab] = useSignal(\"chat\");\n * return (\n * <Activity mode={tab() === \"chat\" ? \"visible\" : \"hidden\"}>\n * <Chat />\n * </Activity>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Activity(props: ActivityProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // The content lives under its own owner, so pausing it reaches every effect and memo it created.\n const content = createOwner();\n // Built when the parent first reads it, not here: the server builds children at the same point of the\n // render, which keeps hydration keys equal on both sides.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = runWithOwner(content, () => untrack(() => props.children));\n }\n return built;\n };\n // Empty text anchors bound the content: the DOM range the visibility code hides and shows.\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const [hidden, setHidden] = useSignal(false);\n let paused = false;\n // Pausing happens in the render phase, before the content's own effects can run.\n useRenderEffect(\n () => props.mode === \"hidden\",\n (isHidden) => {\n if (isHidden === paused) return;\n paused = isHidden;\n if (isHidden) pauseOwner(content);\n else resumeOwner(content);\n setHidden(isHidden);\n },\n );\n // Runs after the DOM is committed (a user effect), so the nodes it hides exist.\n let stash: Stash | undefined;\n useEffect(() => {\n if (hidden()) {\n if (stash === undefined) stash = stashBetween(start, end);\n } else if (stash !== undefined) {\n const previous = stash;\n stash = undefined;\n restore(previous, end);\n }\n });\n return () => [start, contentValue(), end];\n}\n"],"mappings":"A,qMAgDA,SAASQ,EAAaC,EAAaC,EAA8B,CAC/D,IAAMC,EAASF,EAAM,WACrB,GAAIE,IAAW,KAAM,OACrB,IAAMC,EAAkD,CAAC,EACnDC,EAAkC,CAAC,EACnCC,EAAqD,CAAC,EACtDC,EAAS,SAAS,cACpBC,EAAwB,KACxBC,EAAoBR,EAAM,YAC9B,KAAOQ,IAAS,MAAQA,IAASP,GAAK,CACpC,IAAMQ,EAAoBD,EAAK,YAC/B,GAAIA,EAAK,WAAa,EAAG,CACvB,IAAME,EAAUF,EAChBL,EAAS,KAAK,CAACO,EAASA,EAAQ,MAAM,OAAO,CAAC,EAC9CA,EAAQ,MAAM,QAAU,OACxB,IAAK,IAAMC,IAAc,CAACD,EAAS,GAAG,MAAM,KAAKA,EAAQ,iBAAiB,GAAG,CAAC,CAAC,GACzEC,EAAW,YAAc,GAAKA,EAAW,aAAe,IAC1DN,EAAQ,KAAK,CAACM,EAAYA,EAAW,UAAWA,EAAW,UAAU,CAAC,EAGtEL,IAAW,MAAQI,EAAQ,SAASJ,CAAM,IAAGC,EAAQD,EAC3D,MAAWE,EAAK,WAAa,IAC3BJ,EAAM,KAAK,CAAE,KAAMI,EAAcN,SAAQO,MAAK,CAAC,EAC/CP,EAAO,YAAYM,CAAI,GAEzBA,EAAOC,CACT,CACA,MAAO,CAAEN,WAAUC,QAAOC,UAASE,OAAM,CAC3C,CAGA,SAASK,EAAQC,EAAcZ,EAAiB,CAC9C,IAAK,IAAIa,EAAID,EAAM,MAAM,OAAS,EAAGC,GAAK,EAAGA,IAAQ,CACnD,IAAMC,EAAQF,EAAM,MAAMC,GAC1B,GAAIC,IAAU,IAAA,IAAaA,EAAM,KAAK,aAAe,KAAM,SAC3D,IAAMC,EAASD,EAAM,OAAS,MAAQA,EAAM,KAAK,aAAeA,EAAM,OAASA,EAAM,KAAOd,EAC5Fc,EAAM,OAAO,aAAaA,EAAM,KAAMC,CAAM,CAC9C,CACA,IAAK,GAAM,CAACN,EAASO,KAAYJ,EAAM,SAAUH,EAAQ,MAAM,QAAUO,EACzE,IAAK,GAAM,CAACP,EAASQ,EAAKC,KAASN,EAAM,QACvCH,EAAQ,UAAYQ,EACpBR,EAAQ,WAAaS,EAEvB,IAAMZ,EAAQM,EAAM,MAChBN,aAAiB,aAAeA,EAAM,aAAaA,EAAM,MAAM,CAAE,cAAe,EAAK,CAAC,CAC5F,CAiCA,SAAgBa,EAASC,EAAyC,CAGhE,IAAMC,EAAU1B,EAAY,EAGxB2B,EACAC,EAAQ,GACNC,OACCD,IACHA,EAAQ,GACRD,EAAQhC,EAAa+B,MAAe9B,MAAc6B,EAAM,QAAQ,CAAC,GAE5DE,GAGHvB,EAAQ,SAAS,eAAe,EAAE,EAClCC,EAAM,SAAS,eAAe,EAAE,EAChC,CAACyB,EAAQC,GAAahC,EAAU,EAAK,EACvCiC,EAAS,GAEblC,MACQ2B,EAAM,OAAS,SACpBQ,GAAa,CACRA,IAAaD,IACjBA,EAASC,EACLA,EAAUhC,EAAWyB,CAAO,EAC3BxB,EAAYwB,CAAO,EACxBK,EAAUE,CAAQ,EACpB,CACF,EAEA,IAAIhB,EAUJ,OATApB,MAAgB,CACd,GAAIiC,EAAO,EACLb,IAAU,IAAA,KAAWA,EAAQd,EAAaC,EAAOC,CAAG,QACnD,GAAIY,IAAU,IAAA,GAAW,CAC9B,IAAMiB,EAAWjB,EACjBA,EAAQ,IAAA,GACRD,EAAQkB,EAAU7B,CAAG,CACvB,CACF,CAAC,MACY,CAACD,EAAOyB,EAAa,EAAGxB,CAAG,CAC1C,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"branch.js","names":["sameChoice","a","b","createBranches","latest","state","swap","owner","getOwner","selection","useMemo","next","select","live","accessorFor","owned","current","untrack","produce","choice","fallback","body","eager","callback","transitionHooks","result","createRoot","onCleanup"],"sources":["../../../src/control-flow/branch.ts"],"sourcesContent":["import { type Accessor, createRoot, getOwner, onCleanup, untrack, useMemo } from \"@shadow-js/core\";\nimport {\n type SlotBranch,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n transitionHooks,\n} from \"@shadow-js/core/extend\";\n\n/**\n * Branch index meaning \"no branch is selected\": the fallback is shown.\n * @internal\n */\nexport const FALLBACK = -1;\n\n/**\n * One selection made by a control-flow component.\n *\n * - `index` names the chosen branch, or {@link FALLBACK}.\n * - `keyed` and `when` decide whether a change of selection rebuilds the branch.\n * - `read` reads the condition reactively; the callback child's accessor argument uses it.\n * - `body` reads the branch's children getter. It is read tracked: a compiled `children` getter\n * that is a plain reactive expression (`{count()}`) must update the output. Creating child JSX\n * reads nothing here, because components and bindings track inside their own computations.\n *\n * @internal\n * @since 1.0.0\n */\nexport interface Choice {\n /** The chosen branch: a zero-based position, or {@link FALLBACK} when no branch is chosen. */\n readonly index: number;\n /** True when a change of `when` (by identity) rebuilds the branch even if `index` is the same. */\n readonly keyed: boolean;\n /** The value of the condition at selection time; a keyed callback child receives it. */\n readonly when: unknown;\n /** Reads the current value of the condition, tracked; backs the callback child's accessor. */\n readonly read: () => unknown;\n /** Reads the chosen branch's children (content, an accessor, or a callback), tracked. */\n readonly body: () => unknown;\n}\n\n/** Bookkeeping for the branch that is on screen. */\ntype Rendered = SlotOwned;\n\n/** A branch on screen, or one a transition builds (see the transition layer in core's concurrency.ts). */\ntype Live = SlotBranch<Choice>;\n\n/**\n * Whether two selections describe the same rendered output. Non-keyed branches only care about\n * which branch is chosen, which is the same as comparing truthiness of the condition. Keyed\n * branches also rebuild when the condition's identity changes. The fallback never rebuilds.\n */\nfunction sameChoice(a: Choice, b: Choice): boolean {\n if (a.index !== b.index) return false;\n return a.index === FALLBACK || !a.keyed || a.when === b.when;\n}\n\n/**\n * Builds the accessor behind `Show` and `Switch`. The selection memo decides which branch is chosen;\n * the output memo commits it.\n *\n * Ordinary changes build the branch inside the output memo: the memo's teardown removes the previous\n * branch first. A change made during a transition, while a branch is on screen, is handled by the\n * transition layer (core's `slotSwap`, reached through `transitionHooks`), created by the first such change: it builds the\n * new branch under a hold and commits it once its reads have settled. Until then the shown branch stays\n * on screen, its DOM untouched, and nothing is built twice. Apps that never change a shown branch in a\n * transition never create that layer.\n *\n * Teardown ordering: the owner of a branch is marked `disposing` before it is torn down, so a cleanup\n * that reads the callback's accessor learns that the branch is going away and gets the last truthy\n * value instead of a stale-accessor error.\n *\n * @param name Component name used in diagnostics.\n * @param select Tracked selection; runs inside the selection memo.\n * @param fallback Reads the fallback lazily, untracked, only when it is shown.\n * @returns The output accessor.\n * @throws TypeError (production message `SHADOW_STALE_ACCESSOR`) from the accessor handed to a\n * callback child, when it is read after its branch was replaced.\n * @internal\n * @since 1.0.0\n */\nexport function createBranches(\n name: string,\n select: () => Choice,\n fallback: () => unknown,\n): Accessor<unknown> {\n /** Selection computed most recently; its `read` is always current, unlike the held value. */\n let latest: Choice | undefined;\n /** The branch on screen, and what the output last returned. The transition layer reads and writes it. */\n const state: SlotState<Choice> = { live: undefined };\n /** The transition layer, created by the first transition that replaces the branch on screen. */\n let swap: SlotSwap<Choice> | undefined;\n /** The slot's owner: the transition layer's holder for the branches it builds lives under it. */\n const owner = getOwner();\n\n const pick = (): Choice => {\n const next = select();\n latest = next;\n const live: Live | undefined = state.live;\n if (live !== undefined && next.index === live.owned.index) live.owned.value = next.when;\n return next;\n };\n const selection = useMemo<Choice>(pick, { equals: sameChoice });\n\n const accessorFor = (owned: Rendered): (() => unknown) => {\n return () => {\n if (owned.disposing) return owned.value;\n const current = untrack(selection);\n if (current.index !== owned.index) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS ${name}: stale accessor. The branch was replaced; read the accessor only while its condition is truthy.`\n : \"SHADOW_STALE_ACCESSOR\",\n );\n }\n return (latest ?? current).read();\n };\n };\n\n /**\n * The value a branch (or the fallback) produces. `eager` evaluates a zero-argument accessor now (a\n * transition build needs to see whether a read was held); otherwise it is evaluated when rendered.\n */\n const produce = (choice: Choice, owned: Rendered, eager: boolean): unknown => {\n if (choice.index === FALLBACK) return untrack(fallback);\n const body = choice.body();\n if (typeof body !== \"function\") return body;\n // A zero-argument function is an accessor. Returned as it is, the renderer would call it in an\n // effect outside this branch, so an error it throws would escape the boundary around the Show\n // (STATUS: ErrorBoundary does not catch a Show function child). A memo owned here evaluates it\n // inside the branch, where the nearest error handler applies.\n if (body.length === 0) {\n // Lazy outside a transition: the parent evaluates it when it renders, so a deep chain of\n // branches is built in that render rather than inside this one.\n return useMemo<unknown>(() => (body as () => unknown)(), {\n allowWrites: true,\n lazy: !eager,\n });\n }\n const callback = body as (value: unknown) => unknown;\n return untrack(() => callback(choice.keyed ? choice.when : accessorFor(owned)));\n };\n\n return useMemo<unknown>(\n () => {\n const choice = selection();\n if (swap === undefined && state.live !== undefined) {\n swap = transitionHooks()?.slotSwap(state, produce, sameChoice, owner);\n }\n if (swap?.step(choice)) return state.live?.result;\n\n // The usual path: the previous branch was torn down by this memo (its teardown marked it disposing;\n // the flag is cleared again, so a stale accessor throws). Build the next one here.\n if (state.live !== undefined) state.live.owned.disposing = false;\n state.live = undefined;\n const owned: Rendered = { index: choice.index, value: choice.when, disposing: false };\n const result = produce(choice, owned, false);\n // Created last, so it is the newest child: the memo's teardown marks the branch first.\n createRoot(() => {\n onCleanup(() => {\n owned.disposing = true;\n });\n });\n state.live = { choice, owned, result };\n return result;\n },\n { allowWrites: true },\n );\n}\n"],"mappings":"A,6JAoDA,SAASA,EAAW,EAAW,EAAoB,CAEjD,OADIC,EAAE,QAAUC,EAAE,MACXD,EAAE,QAAA,IAAsB,CAACA,EAAE,OAASA,EAAE,OAASC,EAAE,KADxB,EAElC,CA0BA,SAAgBC,EACd,EACA,EACA,EACmB,CAEnB,IAAIC,EAEEC,EAA2B,CAAE,KAAM,IAAA,EAAU,EAE/CC,EAEEC,EAAQC,EAAS,EASjBC,EAAYC,MAPS,CACzB,IAAMC,EAAOC,EAAO,EACpB,EAASD,EACT,IAAME,EAAyBR,EAAM,KAErC,OADIQ,IAAS,IAAA,IAAaF,EAAK,QAAUE,EAAK,MAAM,QAAO,EAAK,MAAM,MAAQF,EAAK,MAC5EA,CACT,EACwC,CAAE,OAAQX,CAAW,CAAC,EAExDc,EAAe,OACN,CACX,GAAIC,EAAM,UAAW,OAAOA,EAAM,MAClC,IAAMC,EAAUC,EAAQR,CAAS,EACjC,GAAIO,EAAQ,QAAUD,EAAM,MAC1B,MAAU,UAGJ,uBACN,EAEF,OAAQX,GAAUY,EAAA,CAAS,KAAK,CAClC,EAOIE,GAAW,EAAgB,EAAiB,IAA4B,CAC5E,GAAIC,EAAO,QAAA,GAAoB,OAAOF,EAAQG,CAAQ,EACtD,IAAMC,EAAOF,EAAO,KAAK,EACzB,GAAI,OAAOE,GAAS,WAAY,OAAOA,EAKvC,GAAIA,EAAK,SAAW,EAGlB,OAAOX,MAAwBW,EAAuB,EAAG,CACvD,YAAa,GACb,KAAM,CAACC,CACT,CAAC,EAEH,IAAMC,EAAWF,EACjB,OAAOJ,MAAcM,EAASJ,EAAO,MAAQA,EAAO,KAAOL,EAAYC,CAAK,CAAC,CAAC,CAChF,EAEA,OAAOL,MACC,CACJ,IAAMS,EAASV,EAAU,EAIzB,GAHIH,IAAS,IAAA,IAAaD,EAAM,OAAS,IAAA,KACvC,EAAOmB,EAAgB,CAAC,EAAE,SAASnB,EAAOa,EAASlB,EAAYO,CAAK,GAElED,GAAM,KAAKa,CAAM,EAAG,OAAOd,EAAM,MAAM,OAIvCA,EAAM,OAAS,IAAA,KAAW,EAAM,KAAK,MAAM,UAAY,IAC3D,EAAM,KAAO,IAAA,GACb,IAAMU,EAAkB,CAAE,MAAOI,EAAO,MAAO,MAAOA,EAAO,KAAM,UAAW,EAAM,EAC9EM,EAASP,EAAQC,EAAQJ,EAAO,EAAK,EAQ3C,OANAW,MAAiB,CACfC,MAAgB,CACd,EAAM,UAAY,EACpB,CAAC,CACH,CAAC,EACD,EAAM,KAAO,CAAE,SAAQ,QAAO,QAAO,EAC9BF,CACT,EACA,CAAE,YAAa,EAAK,CACtB,CACF,C"}
1
+ {"version":3,"file":"branch.js","names":["createRoot","getOwner","onCleanup","untrack","useMemo","transitionHooks","sameChoice","a","b","createBranches","name","select","fallback","latest","state","swap","owner","selection","next","live","accessorFor","owned","current","produce","choice","eager","body","callback","result"],"sources":["../../../src/control-flow/branch.ts"],"sourcesContent":["import { type Accessor, createRoot, getOwner, onCleanup, untrack, useMemo } from \"@shadow-js/core\";\nimport {\n type SlotBranch,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n transitionHooks,\n} from \"@shadow-js/core/extend\";\n\n/**\n * Branch index meaning \"no branch is selected\": the fallback is shown.\n * @internal\n */\nexport const FALLBACK = -1;\n\n/**\n * One selection made by a control-flow component.\n *\n * - `index` names the chosen branch, or {@link FALLBACK}.\n * - `keyed` and `when` decide whether a change of selection rebuilds the branch.\n * - `read` reads the condition reactively; the callback child's accessor argument uses it.\n * - `body` reads the branch's children getter. It is read tracked: a compiled `children` getter\n * that is a plain reactive expression (`{count()}`) must update the output. Creating child JSX\n * reads nothing here, because components and bindings track inside their own computations.\n *\n * @internal\n * @since 1.0.0\n */\nexport interface Choice {\n /** The chosen branch: a zero-based position, or {@link FALLBACK} when no branch is chosen. */\n readonly index: number;\n /** True when a change of `when` (by identity) rebuilds the branch even if `index` is the same. */\n readonly keyed: boolean;\n /** The value of the condition at selection time; a keyed callback child receives it. */\n readonly when: unknown;\n /** Reads the current value of the condition, tracked; backs the callback child's accessor. */\n readonly read: () => unknown;\n /** Reads the chosen branch's children (content, an accessor, or a callback), tracked. */\n readonly body: () => unknown;\n}\n\n/** Bookkeeping for the branch that is on screen. */\ntype Rendered = SlotOwned;\n\n/** A branch on screen, or one a transition builds (see the transition layer in core's concurrency.ts). */\ntype Live = SlotBranch<Choice>;\n\n/**\n * Whether two selections describe the same rendered output. Non-keyed branches only care about\n * which branch is chosen, which is the same as comparing truthiness of the condition. Keyed\n * branches also rebuild when the condition's identity changes. The fallback never rebuilds.\n */\nfunction sameChoice(a: Choice, b: Choice): boolean {\n if (a.index !== b.index) return false;\n return a.index === FALLBACK || !a.keyed || a.when === b.when;\n}\n\n/**\n * Builds the accessor behind `Show` and `Switch`. The selection memo decides which branch is chosen;\n * the output memo commits it.\n *\n * Ordinary changes build the branch inside the output memo: the memo's teardown removes the previous\n * branch first. A change made during a transition, while a branch is on screen, is handled by the\n * transition layer (core's `slotSwap`, reached through `transitionHooks`), created by the first such change: it builds the\n * new branch under a hold and commits it once its reads have settled. Until then the shown branch stays\n * on screen, its DOM untouched, and nothing is built twice. Apps that never change a shown branch in a\n * transition never create that layer.\n *\n * Teardown ordering: the owner of a branch is marked `disposing` before it is torn down, so a cleanup\n * that reads the callback's accessor learns that the branch is going away and gets the last truthy\n * value instead of a stale-accessor error.\n *\n * @param name Component name used in diagnostics.\n * @param select Tracked selection; runs inside the selection memo.\n * @param fallback Reads the fallback lazily, untracked, only when it is shown.\n * @returns The output accessor.\n * @throws TypeError (production message `SHADOW_STALE_ACCESSOR`) from the accessor handed to a\n * callback child, when it is read after its branch was replaced.\n * @internal\n * @since 1.0.0\n */\nexport function createBranches(\n name: string,\n select: () => Choice,\n fallback: () => unknown,\n): Accessor<unknown> {\n /** Selection computed most recently; its `read` is always current, unlike the held value. */\n let latest: Choice | undefined;\n /** The branch on screen, and what the output last returned. The transition layer reads and writes it. */\n const state: SlotState<Choice> = { live: undefined };\n /** The transition layer, created by the first transition that replaces the branch on screen. */\n let swap: SlotSwap<Choice> | undefined;\n /** The slot's owner: the transition layer's holder for the branches it builds lives under it. */\n const owner = getOwner();\n\n const pick = (): Choice => {\n const next = select();\n latest = next;\n const live: Live | undefined = state.live;\n if (live !== undefined && next.index === live.owned.index) live.owned.value = next.when;\n return next;\n };\n const selection = useMemo<Choice>(pick, { equals: sameChoice });\n\n const accessorFor = (owned: Rendered): (() => unknown) => {\n return () => {\n if (owned.disposing) return owned.value;\n const current = untrack(selection);\n if (current.index !== owned.index) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS ${name}: stale accessor. The branch was replaced; read the accessor only while its condition is truthy.`\n : \"SHADOW_STALE_ACCESSOR\",\n );\n }\n return (latest ?? current).read();\n };\n };\n\n /**\n * The value a branch (or the fallback) produces. `eager` evaluates a zero-argument accessor now (a\n * transition build needs to see whether a read was held); otherwise it is evaluated when rendered.\n */\n const produce = (choice: Choice, owned: Rendered, eager: boolean): unknown => {\n if (choice.index === FALLBACK) return untrack(fallback);\n const body = choice.body();\n if (typeof body !== \"function\") return body;\n // A zero-argument function is an accessor. Returned as it is, the renderer would call it in an\n // effect outside this branch, so an error it throws would escape the boundary around the Show\n // (STATUS: ErrorBoundary does not catch a Show function child). A memo owned here evaluates it\n // inside the branch, where the nearest error handler applies.\n if (body.length === 0) {\n // Lazy outside a transition: the parent evaluates it when it renders, so a deep chain of\n // branches is built in that render rather than inside this one.\n return useMemo<unknown>(() => (body as () => unknown)(), {\n allowWrites: true,\n lazy: !eager,\n });\n }\n const callback = body as (value: unknown) => unknown;\n return untrack(() => callback(choice.keyed ? choice.when : accessorFor(owned)));\n };\n\n return useMemo<unknown>(\n () => {\n const choice = selection();\n if (swap === undefined && state.live !== undefined) {\n swap = transitionHooks()?.slotSwap(state, produce, sameChoice, owner);\n }\n if (swap?.step(choice)) return state.live?.result;\n\n // The usual path: the previous branch was torn down by this memo (its teardown marked it disposing;\n // the flag is cleared again, so a stale accessor throws). Build the next one here.\n if (state.live !== undefined) state.live.owned.disposing = false;\n state.live = undefined;\n const owned: Rendered = { index: choice.index, value: choice.when, disposing: false };\n const result = produce(choice, owned, false);\n // Created last, so it is the newest child: the memo's teardown marks the branch first.\n createRoot(() => {\n onCleanup(() => {\n owned.disposing = true;\n });\n });\n state.live = { choice, owned, result };\n return result;\n },\n { allowWrites: true },\n );\n}\n"],"mappings":"A,6JAoDA,SAASM,EAAWC,EAAWC,EAAoB,CAEjD,OADID,EAAE,QAAUC,EAAE,MACXD,EAAE,QAAA,IAAsB,CAACA,EAAE,OAASA,EAAE,OAASC,EAAE,KADxB,EAElC,CA0BA,SAAgBC,EACdC,EACAC,EACAC,EACmB,CAEnB,IAAIC,EAEEC,EAA2B,CAAE,KAAM,IAAA,EAAU,EAE/CC,EAEEC,EAAQf,EAAS,EASjBgB,EAAYb,MAPS,CACzB,IAAMc,EAAOP,EAAO,EACpBE,EAASK,EACT,IAAMC,EAAyBL,EAAM,KAErC,OADIK,IAAS,IAAA,IAAaD,EAAK,QAAUC,EAAK,MAAM,QAAOA,EAAK,MAAM,MAAQD,EAAK,MAC5EA,CACT,EACwC,CAAE,OAAQZ,CAAW,CAAC,EAExDc,EAAeC,OACN,CACX,GAAIA,EAAM,UAAW,OAAOA,EAAM,MAClC,IAAMC,EAAUnB,EAAQc,CAAS,EACjC,GAAIK,EAAQ,QAAUD,EAAM,MAC1B,MAAU,UAGJ,uBACN,EAEF,OAAQR,GAAUS,EAAA,CAAS,KAAK,CAClC,EAOIC,GAAWC,EAAgBH,EAAiBI,IAA4B,CAC5E,GAAID,EAAO,QAAA,GAAoB,OAAOrB,EAAQS,CAAQ,EACtD,IAAMc,EAAOF,EAAO,KAAK,EACzB,GAAI,OAAOE,GAAS,WAAY,OAAOA,EAKvC,GAAIA,EAAK,SAAW,EAGlB,OAAOtB,MAAwBsB,EAAuB,EAAG,CACvD,YAAa,GACb,KAAM,CAACD,CACT,CAAC,EAEH,IAAME,EAAWD,EACjB,OAAOvB,MAAcwB,EAASH,EAAO,MAAQA,EAAO,KAAOJ,EAAYC,CAAK,CAAC,CAAC,CAChF,EAEA,OAAOjB,MACC,CACJ,IAAMoB,EAASP,EAAU,EAIzB,GAHIF,IAAS,IAAA,IAAaD,EAAM,OAAS,IAAA,KACvCC,EAAOV,EAAgB,CAAC,EAAE,SAASS,EAAOS,EAASjB,EAAYU,CAAK,GAElED,GAAM,KAAKS,CAAM,EAAG,OAAOV,EAAM,MAAM,OAIvCA,EAAM,OAAS,IAAA,KAAWA,EAAM,KAAK,MAAM,UAAY,IAC3DA,EAAM,KAAO,IAAA,GACb,IAAMO,EAAkB,CAAE,MAAOG,EAAO,MAAO,MAAOA,EAAO,KAAM,UAAW,EAAM,EAC9EI,EAASL,EAAQC,EAAQH,EAAO,EAAK,EAQ3C,OANArB,MAAiB,CACfE,MAAgB,CACdmB,EAAM,UAAY,EACpB,CAAC,CACH,CAAC,EACDP,EAAM,KAAO,CAAEU,SAAQH,QAAOO,QAAO,EAC9BA,CACT,EACA,CAAE,YAAa,EAAK,CACtB,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"client-only.js","names":["ClientOnly","mounted","setMounted","useSignal","onMount","Show","props"],"sources":["../../../src/control-flow/client-only.ts"],"sourcesContent":["import { type Accessor, onMount, useSignal } from \"@shadow-js/core\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { Show } from \"./show\";\n\n/**\n * Props of {@link ClientOnly}.\n * @since 1.0.0\n */\nexport interface ClientOnlyProps {\n /**\n * Rendered on the server and while the page hydrates, until the browser has mounted.\n * @default undefined (nothing is rendered until mount)\n */\n readonly fallback?: JsxChild;\n /**\n * Rendered in the browser only, after mount.\n * @default undefined (nothing is rendered after mount either)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * Renders `children` in the browser only. The server (and the first client pass, which must match\n * the server's markup) renders `fallback`; once mounted, the children replace it. Use it for\n * content that depends on browser state: `window`, `localStorage`, media queries, charts.\n *\n * @param props See {@link ClientOnlyProps}.\n * @returns An accessor of the current content: the fallback until mount, then the children.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ClientOnly } from \"@shadow-js/web\";\n *\n * function Chart(props: { data: number[] }) {\n * return <canvas data-points={props.data.length} />;\n * }\n *\n * function Report() {\n * const [rows] = useSignal([1, 2, 3]);\n * return (\n * <ClientOnly fallback={<p>Loading chart...</p>}>\n * <Chart data={rows()} />\n * </ClientOnly>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function ClientOnly(props: ClientOnlyProps): Accessor<unknown> {\n const [mounted, setMounted] = useSignal(false);\n // Never runs on the server, so the server always renders the fallback.\n onMount(() => {\n setMounted(true);\n });\n return Show({\n get when() {\n return mounted();\n },\n get fallback() {\n return props.fallback;\n },\n get children() {\n return props.children;\n },\n });\n}\n"],"mappings":"A,0FA+CA,SAAgBA,EAAW,EAA2C,CACpE,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EAK7C,OAHAC,MAAc,CACZF,EAAW,EAAI,CACjB,CAAC,EACMG,EAAK,CACV,IAAI,MAAO,CACT,OAAOJ,EAAQ,CACjB,EACA,IAAI,UAAW,CACb,OAAOK,EAAM,QACf,EACA,IAAI,UAAW,CACb,OAAOA,EAAM,QACf,CACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"client-only.js","names":["Show","onMount","useSignal","ClientOnly","props","mounted","setMounted"],"sources":["../../../src/control-flow/client-only.ts"],"sourcesContent":["import { type Accessor, onMount, useSignal } from \"@shadow-js/core\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { Show } from \"./show\";\n\n/**\n * Props of {@link ClientOnly}.\n * @since 1.0.0\n */\nexport interface ClientOnlyProps {\n /**\n * Rendered on the server and while the page hydrates, until the browser has mounted.\n * @default undefined (nothing is rendered until mount)\n */\n readonly fallback?: JsxChild;\n /**\n * Rendered in the browser only, after mount.\n * @default undefined (nothing is rendered after mount either)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * Renders `children` in the browser only. The server (and the first client pass, which must match\n * the server's markup) renders `fallback`; once mounted, the children replace it. Use it for\n * content that depends on browser state: `window`, `localStorage`, media queries, charts.\n *\n * @param props See {@link ClientOnlyProps}.\n * @returns An accessor of the current content: the fallback until mount, then the children.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ClientOnly } from \"@shadow-js/web\";\n *\n * function Chart(props: { data: number[] }) {\n * return <canvas data-points={props.data.length} />;\n * }\n *\n * function Report() {\n * const [rows] = useSignal([1, 2, 3]);\n * return (\n * <ClientOnly fallback={<p>Loading chart...</p>}>\n * <Chart data={rows()} />\n * </ClientOnly>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function ClientOnly(props: ClientOnlyProps): Accessor<unknown> {\n const [mounted, setMounted] = useSignal(false);\n // Never runs on the server, so the server always renders the fallback.\n onMount(() => {\n setMounted(true);\n });\n return Show({\n get when() {\n return mounted();\n },\n get fallback() {\n return props.fallback;\n },\n get children() {\n return props.children;\n },\n });\n}\n"],"mappings":"A,0FA+CA,SAAgBG,EAAWC,EAA2C,CACpE,GAAM,CAACC,EAASC,GAAcJ,EAAU,EAAK,EAK7C,OAHAD,MAAc,CACZK,EAAW,EAAI,CACjB,CAAC,EACMN,EAAK,CACV,IAAI,MAAO,CACT,OAAOK,EAAQ,CACjB,EACA,IAAI,UAAW,CACb,OAAOD,EAAM,QACf,EACA,IAAI,UAAW,CACb,OAAOA,EAAM,QACf,CACF,CAAC,CACH,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic.js","names":["SVG_PATTERN","MATHML_TAGS","TAG_PATTERN","createTagged","lower","tag","MATHML_NS","el","SVG_NS","buildElement","claims","nextKey","spreadProps","props","region","createRegion","bindRegion","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spreadProps } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spreadProps(el, props, el.namespaceURI === SVG_NS);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,8ZAuCA,MAAMA,EACJ,gRAGIC,EACJ,oMAMIC,EAAc,gCA0BpB,SAASC,EAAa,EAAsB,CAC1C,IAAMC,EAAQC,EAAI,YAAY,EAC9B,GAAIJ,EAAY,KAAKG,CAAK,EAAG,OAAO,SAAS,gBAAgBE,EAAWF,CAAK,EAC7E,IAAMG,EAAK,SAAS,cAAcF,CAAG,EAOrC,OAJKE,EAAG,cAAgB,oBAAsBH,IAAU,SAAY,CAACJ,EAAY,KAAKI,CAAK,EAClFG,EAGF,SAAS,gBAAgBC,EAAQH,CAAG,CAC7C,CASA,SAASI,EAAa,EAAa,EAAwB,CACzD,GAAI,CAACP,EAAY,KAAKG,CAAG,EACvB,MAAU,UAAsD,oBAAoB,EAkBtF,IAAME,EAAKG,EAAO,QAAQ,aAAaC,EAAQ,CAAC,GAAKR,EAAaE,CAAG,EAErEO,EAAYL,EAAIM,EAAON,EAAG,eAAiBC,CAAM,EACjD,IAAMM,EAASC,EAAaR,EAAI,KAAMG,EAAO,QAAQ,WAAWH,EAAI,IAAI,CAAC,EAEzE,OADAS,EAAWF,MAAeD,EAAiC,QAAQ,EAC5DN,CACT,CAMA,SAASU,EAAY,EAAiB,EAAwB,CAC5D,GAAI,CAACC,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOT,EAAaS,EAAQL,CAAK,EACjE,GAAI,OAAOK,GAAW,WACpB,OAAOC,EAAgBD,EAAsCL,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CA8CA,SAAgBO,EAAiC,EAAuC,CACtF,GAAM,EAAGC,GAAQC,EAAWT,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOU,MACU,CACb,IAAML,EAAkBL,EAAM,UAC9B,OAAOW,MAAcP,EAAYC,EAAQG,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAd,CACF,CACF,CACF,C"}
1
+ {"version":3,"file":"dynamic.js","names":["createComponent","bindRegion","createRegion","claims","MATHML_NS","SVG_NS","nextKey","spreadProps","mergeProps","splitProps","untrack","useMemo","SVG_PATTERN","MATHML_TAGS","TAG_PATTERN","createTagged","tag","lower","el","buildElement","props","region","buildTarget","target","Dynamic","rest","createDynamic","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spreadProps } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spreadProps(el, props, el.namespaceURI === SVG_NS);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,8ZAuCA,MAAMY,EACJ,gRAGIC,EACJ,oMAMIC,EAAc,gCA0BpB,SAASC,EAAaC,EAAsB,CAC1C,IAAMC,EAAQD,EAAI,YAAY,EAC9B,GAAIH,EAAY,KAAKI,CAAK,EAAG,OAAO,SAAS,gBAAgBb,EAAWa,CAAK,EAC7E,IAAMC,EAAK,SAAS,cAAcF,CAAG,EAOrC,OAJKE,EAAG,cAAgB,oBAAsBD,IAAU,SAAY,CAACL,EAAY,KAAKK,CAAK,EAClFC,EAGF,SAAS,gBAAgBb,EAAQW,CAAG,CAC7C,CASA,SAASG,EAAaH,EAAaI,EAAwB,CACzD,GAAI,CAACN,EAAY,KAAKE,CAAG,EACvB,MAAU,UAAsD,oBAAoB,EAkBtF,IAAME,EAAKf,EAAO,QAAQ,aAAaG,EAAQ,CAAC,GAAKS,EAAaC,CAAG,EAErET,EAAYW,EAAIE,EAAOF,EAAG,eAAiBb,CAAM,EACjD,IAAMgB,EAASnB,EAAagB,EAAI,KAAMf,EAAO,QAAQ,WAAWe,EAAI,IAAI,CAAC,EAEzE,OADAjB,EAAWoB,MAAeD,EAAiC,QAAQ,EAC5DF,CACT,CAMA,SAASI,EAAYC,EAAiBH,EAAwB,CAC5D,GAAI,CAACG,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOJ,EAAaI,EAAQH,CAAK,EACjE,GAAI,OAAOG,GAAW,WACpB,OAAOvB,EAAgBuB,EAAsCH,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CA8CA,SAAgBI,EAAiCJ,EAAuC,CACtF,GAAM,EAAGK,GAAQhB,EAAWW,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOT,MACU,CACb,IAAMY,EAAkBH,EAAM,UAC9B,OAAOV,MAAcY,EAAYC,EAAQE,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBC,EACdC,EACAP,EAAgB,CAAC,EACF,CACf,OAAOI,EACLhB,EACE,CACE,IAAI,WAAe,CACjB,OAAOmB,EAAU,CACnB,CACF,EACAP,CACF,CACF,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"error-boundary.js","names":["ErrorBoundary","failureCell","SignalNode","parentOwner","getOwner","roots","rootErrorsOf","live","currentScope","origin","failure","readSignal","setFailure","writeSignal","next","version","setVersion","useSignal","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","props","untrack","thrown","handleError","build","current","scope","createRoot","catchError","creation","onCleanup","body","useMemo","withScope"],"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":"A,sWA0FA,SAAgBA,EAAc,EAAmD,CAG/E,IAAMC,EAAc,IAAIC,EAAgC,IAAA,GAAW,OAAO,EAAE,EAEtEC,EAAcC,EAAS,EAEvBC,EAAQC,EAAaH,CAAW,EAEhCI,EAAOC,EAAa,EACpBC,EACJF,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EG,MAAqCC,EAAWV,CAAW,EAC3DW,EAAc,GAAoC,CACtDC,EAAYZ,EAAaa,EAAM,CAAE,YAAa,EAAK,CAAC,CACtD,EAEM,CAACC,EAASC,GAAcC,EAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAExDC,EAAQ,GAERC,EAAO,GAEPC,EAEEC,MAAoB,CACnBH,IACLN,EAAW,IAAA,EAAS,EACpBI,EAAY,GAAUM,EAAQ,CAAC,EACjC,EAYMC,EAAU,GAAyB,CAClCL,IACLb,GAAO,gBAAgBmB,CAAK,EACxBL,EACEC,IAAY,IAAA,KAAW,EAAU,CAAE,OAAM,GAG/CR,EAAW,CAAE,OAAM,CAAC,EACtB,EAGMa,MAAyC,CAC7C,IAAMC,EAAWN,EAEjB,MADA,GAAU,IAAA,GACHM,CACT,EAEMC,EAAe,GAA4B,CAC/C,IAAMC,EAAWC,EAAM,SACvB,GAAI,OAAOD,GAAa,WAAY,OAAOA,EAC3C,GAAI,CACF,OAAOE,MACJF,EAA4DJ,EAAOH,CAAK,CAC3E,CACF,OAASU,EAAQ,CAGfC,EAAYD,EAAQ5B,CAAW,EAC/B,MACF,CACF,EAGM8B,MAAuB,CAC3B,EAAO,GACP,GAAI,CACFlB,EAAQ,EACR,IAAMmB,EAAUxB,EAAQ,GAAKe,EAAY,EACzC,GAAIS,IAAY,IAAA,GAEd,OAAOP,EAAYO,EAAQ,KAAK,EAIlC,IAAMC,EAAQC,EAAY,IAEjB,CACL,UACA,MAAOC,MAAiBP,MAAcD,EAAM,QAAQ,EAAGN,CAAM,CAC/D,EACD,EACKe,EAAWb,EAAY,EAO7B,OANIa,IAAa,IAAA,GAMVH,EAAM,OALXA,EAAM,QAAQ,EAEPR,EAAYW,EAAS,KAAK,EAIrC,QAAU,CAERF,MAAiB,CACfG,MAAgB,CACd,EAAO,EACT,CAAC,CACH,CAAC,EACD,EAAO,EACT,CAEF,EAIMC,EAAOC,MACJhC,IAAW,KAAOwB,EAAM,EAAIS,EAAU,CAAE,GAAGjC,CAAO,EAAGwB,CAAK,EACjE,CAAE,YAAa,EAAK,CACtB,EASA,OANAG,MAAiB,CACfG,MAAgB,CACd,EAAQ,EAEV,CAAC,CACH,CAAC,EACMC,CACT,C"}
1
+ {"version":3,"file":"error-boundary.js","names":["currentScope","withScope","rootErrorsOf","catchError","createRoot","getOwner","onCleanup","untrack","useMemo","useSignal","SignalNode","handleError","readSignal","writeSignal","ErrorBoundary","props","failureCell","parentOwner","roots","live","origin","failure","setFailure","next","version","setVersion","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","thrown","build","current","scope","dispose","creation","body"],"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":"A,sWA0FA,SAAgBc,EAAcC,EAAmD,CAG/E,IAAMC,EAAc,IAAIN,EAAgC,IAAA,GAAW,OAAO,EAAE,EAEtEO,EAAcZ,EAAS,EAEvBa,EAAQhB,EAAae,CAAW,EAEhCE,EAAOnB,EAAa,EACpBoB,EACJD,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EE,MAAqCT,EAAWI,CAAW,EAC3DM,EAAcC,GAAoC,CACtDV,EAAYG,EAAaO,EAAM,CAAE,YAAa,EAAK,CAAC,CACtD,EAEM,CAACC,EAASC,GAAchB,EAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAExDiB,EAAQ,GAERC,EAAO,GAEPC,EAEEC,MAAoB,CACnBH,IACLJ,EAAW,IAAA,EAAS,EACpBG,EAAYK,GAAUA,EAAQ,CAAC,EACjC,EAYMC,EAAUC,GAAyB,CAClCN,IACLR,GAAO,gBAAgBc,CAAK,EACxBL,EACEC,IAAY,IAAA,KAAWA,EAAU,CAAEI,OAAM,GAG/CV,EAAW,CAAEU,OAAM,CAAC,EACtB,EAGMC,MAAyC,CAC7C,IAAMC,EAAWN,EAEjB,MADAA,GAAU,IAAA,GACHM,CACT,EAEMC,EAAeH,GAA4B,CAC/C,IAAMI,EAAWrB,EAAM,SACvB,GAAI,OAAOqB,GAAa,WAAY,OAAOA,EAC3C,GAAI,CACF,OAAO7B,MACJ6B,EAA4DJ,EAAOH,CAAK,CAC3E,CACF,OAASQ,EAAQ,CAGf1B,EAAY0B,EAAQpB,CAAW,EAC/B,MACF,CACF,EAGMqB,MAAuB,CAC3BX,EAAO,GACP,GAAI,CACFH,EAAQ,EACR,IAAMe,EAAUlB,EAAQ,GAAKY,EAAY,EACzC,GAAIM,IAAY,IAAA,GAEd,OAAOJ,EAAYI,EAAQ,KAAK,EAIlC,IAAMC,EAAQpC,EAAYqC,IAEjB,CACLA,UACA,MAAOtC,MAAiBI,MAAcQ,EAAM,QAAQ,EAAGgB,CAAM,CAC/D,EACD,EACKW,EAAWT,EAAY,EAO7B,OANIS,IAAa,IAAA,GAMVF,EAAM,OALXA,EAAM,QAAQ,EAEPL,EAAYO,EAAS,KAAK,EAIrC,QAAU,CAERtC,MAAiB,CACfE,MAAgB,CACdqB,EAAO,EACT,CAAC,CACH,CAAC,EACDA,EAAO,EACT,CAEF,EAIMgB,EAAOnC,MACJY,IAAW,KAAOkB,EAAM,EAAIrC,EAAU,CAAE,GAAGmB,CAAO,EAAGkB,CAAK,EACjE,CAAE,YAAa,EAAK,CACtB,EASA,OANAlC,MAAiB,CACfE,MAAgB,CACdoB,EAAQ,EAEV,CAAC,CACH,CAAC,EACMiB,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"for.js","names":["renderRow","untrack","props","item","index","For","list","fallback","keyOf","mapArray"],"sources":["../../../src/control-flow/for.ts"],"sourcesContent":["import { type Accessor, mapArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link For} without `key`: rows are matched by item reference.\n * @since 1.0.0\n */\nexport interface ForUnkeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Absent in this form: rows are matched by item reference. Pass `key` to match by key.\n * No default: omit it for reference matching.\n */\n readonly key?: undefined;\n /** Called once per row, untracked. The callback receives the item value. */\n readonly children: (item: T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For} with `key`: rows are matched by `key(item)`.\n * @since 1.0.0\n */\nexport interface ForKeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /** Identifies each item. A new object under the same key updates the row's `item()`. */\n readonly key: (item: T) => unknown;\n /** Called once per row, untracked. The callback receives an accessor of the item. */\n readonly children: (item: () => T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For}.\n * @since 1.0.0\n */\nexport type ForProps<T> = ForUnkeyedProps<T> | ForKeyedProps<T>;\n\n/**\n * Calls the row callback. `props.children` is read untracked, once per row.\n * @internal\n */\nfunction renderRow(props: { readonly children: unknown }, item: unknown, index: () => number) {\n const render = untrack(() => props.children) as (item: unknown, index: () => number) => unknown;\n return render(item, index);\n}\n\n/**\n * Renders one row per item. Rows whose key survives an update keep their DOM and state; only\n * changed items create or dispose rows. The list is read lazily, inside the list memo.\n *\n * Whether rows are keyed is decided when `For` is created: it reads `key` once. When the list\n * is empty and `fallback` is not given, the result is `[undefined]`, which renders nothing.\n *\n * @param props See {@link ForUnkeyedProps} and {@link ForKeyedProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { For } from \"@shadow-js/web\";\n *\n * function TodoList() {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * return (\n * <ul>\n * <For each={todos()} key={(todo) => todo.id} fallback={<li>Nothing to do</li>}>\n * {(todo) => <li>{todo().title}</li>}\n * </For>\n * </ul>\n * );\n * }\n * @see Index\n * @since 1.0.0\n */\nexport function For<T>(props: ForKeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForUnkeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForProps<T>): Accessor<unknown[]> {\n const list = (): readonly T[] | null | undefined | false => props.each;\n const fallback = (): unknown => props.fallback;\n const keyOf = props.key;\n if (keyOf === undefined) {\n return mapArray(list, (item: T, index: () => number) => renderRow(props, item, index), {\n fallback,\n });\n }\n return mapArray(list, (item: () => T, index: () => number) => renderRow(props, item, index), {\n key: keyOf,\n fallback,\n });\n}\n"],"mappings":"A,wDAyDA,SAASA,EAAU,EAAuC,EAAe,EAAqB,CAE5F,OADeC,MAAcC,EAAM,QACvB,CAAC,CAACC,EAAMC,CAAK,CAC3B,CA8BA,SAAgBC,EAAO,EAAyC,CAC9D,IAAMC,MAAsDJ,EAAM,KAC5DK,MAA0BL,EAAM,SAChCM,EAAQN,EAAM,IAMpB,OALIM,IAAU,IAAA,GACLC,EAASH,GAAO,EAAS,IAAwBN,EAAUE,EAAOC,EAAMC,CAAK,EAAG,CACrF,UACF,CAAC,EAEIK,EAASH,GAAO,EAAe,IAAwBN,EAAUE,EAAOC,EAAMC,CAAK,EAAG,CAC3F,IAAKI,EACL,UACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"for.js","names":["mapArray","untrack","renderRow","props","item","index","For","list","fallback","keyOf"],"sources":["../../../src/control-flow/for.ts"],"sourcesContent":["import { type Accessor, mapArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link For} without `key`: rows are matched by item reference.\n * @since 1.0.0\n */\nexport interface ForUnkeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Absent in this form: rows are matched by item reference. Pass `key` to match by key.\n * No default: omit it for reference matching.\n */\n readonly key?: undefined;\n /** Called once per row, untracked. The callback receives the item value. */\n readonly children: (item: T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For} with `key`: rows are matched by `key(item)`.\n * @since 1.0.0\n */\nexport interface ForKeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /** Identifies each item. A new object under the same key updates the row's `item()`. */\n readonly key: (item: T) => unknown;\n /** Called once per row, untracked. The callback receives an accessor of the item. */\n readonly children: (item: () => T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For}.\n * @since 1.0.0\n */\nexport type ForProps<T> = ForUnkeyedProps<T> | ForKeyedProps<T>;\n\n/**\n * Calls the row callback. `props.children` is read untracked, once per row.\n * @internal\n */\nfunction renderRow(props: { readonly children: unknown }, item: unknown, index: () => number) {\n const render = untrack(() => props.children) as (item: unknown, index: () => number) => unknown;\n return render(item, index);\n}\n\n/**\n * Renders one row per item. Rows whose key survives an update keep their DOM and state; only\n * changed items create or dispose rows. The list is read lazily, inside the list memo.\n *\n * Whether rows are keyed is decided when `For` is created: it reads `key` once. When the list\n * is empty and `fallback` is not given, the result is `[undefined]`, which renders nothing.\n *\n * @param props See {@link ForUnkeyedProps} and {@link ForKeyedProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { For } from \"@shadow-js/web\";\n *\n * function TodoList() {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * return (\n * <ul>\n * <For each={todos()} key={(todo) => todo.id} fallback={<li>Nothing to do</li>}>\n * {(todo) => <li>{todo().title}</li>}\n * </For>\n * </ul>\n * );\n * }\n * @see Index\n * @since 1.0.0\n */\nexport function For<T>(props: ForKeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForUnkeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForProps<T>): Accessor<unknown[]> {\n const list = (): readonly T[] | null | undefined | false => props.each;\n const fallback = (): unknown => props.fallback;\n const keyOf = props.key;\n if (keyOf === undefined) {\n return mapArray(list, (item: T, index: () => number) => renderRow(props, item, index), {\n fallback,\n });\n }\n return mapArray(list, (item: () => T, index: () => number) => renderRow(props, item, index), {\n key: keyOf,\n fallback,\n });\n}\n"],"mappings":"A,wDAyDA,SAASE,EAAUC,EAAuCC,EAAeC,EAAqB,CAE5F,OADeJ,MAAcE,EAAM,QACvB,CAAC,CAACC,EAAMC,CAAK,CAC3B,CA8BA,SAAgBC,EAAOH,EAAyC,CAC9D,IAAMI,MAAsDJ,EAAM,KAC5DK,MAA0BL,EAAM,SAChCM,EAAQN,EAAM,IAMpB,OALIM,IAAU,IAAA,GACLT,EAASO,GAAOH,EAASC,IAAwBH,EAAUC,EAAOC,EAAMC,CAAK,EAAG,CACrFG,UACF,CAAC,EAEIR,EAASO,GAAOH,EAAeC,IAAwBH,EAAUC,EAAOC,EAAMC,CAAK,EAAG,CAC3F,IAAKI,EACLD,UACF,CAAC,CACH,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"fragment.js","names":["Fragment","props"],"sources":["../../../src/control-flow/fragment.ts"],"sourcesContent":["/**\n * Props of {@link Fragment}.\n * @since 1.0.0\n */\nexport interface FragmentProps {\n /**\n * The children to group.\n * @default undefined (the Fragment renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * A no-op wrapper: returns `props.children` untouched, so the children are created by the caller's\n * getter exactly as if no wrapper existed. Use it to group several children under one element.\n *\n * @param props The children to group.\n * @returns `props.children`, unchanged.\n * @example\n * import { Fragment } from \"@shadow-js/web\";\n *\n * function Header() {\n * return <h1>Title</h1>;\n * }\n *\n * function Page() {\n * return (\n * <Fragment>\n * <Header />\n * <p>Body</p>\n * </Fragment>\n * );\n * }\n * @since 1.0.0\n */\nexport function Fragment(props: FragmentProps): unknown {\n return props.children;\n}\n"],"mappings":"AAmCA,SAAgBA,EAAS,EAA+B,CACtD,OAAOC,EAAM,QACf,C"}
1
+ {"version":3,"file":"fragment.js","names":["Fragment","props"],"sources":["../../../src/control-flow/fragment.ts"],"sourcesContent":["/**\n * Props of {@link Fragment}.\n * @since 1.0.0\n */\nexport interface FragmentProps {\n /**\n * The children to group.\n * @default undefined (the Fragment renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * A no-op wrapper: returns `props.children` untouched, so the children are created by the caller's\n * getter exactly as if no wrapper existed. Use it to group several children under one element.\n *\n * @param props The children to group.\n * @returns `props.children`, unchanged.\n * @example\n * import { Fragment } from \"@shadow-js/web\";\n *\n * function Header() {\n * return <h1>Title</h1>;\n * }\n *\n * function Page() {\n * return (\n * <Fragment>\n * <Header />\n * <p>Body</p>\n * </Fragment>\n * );\n * }\n * @since 1.0.0\n */\nexport function Fragment(props: FragmentProps): unknown {\n return props.children;\n}\n"],"mappings":"AAmCA,SAAgBA,EAASC,EAA+B,CACtD,OAAOA,EAAM,QACf,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"hot-link.js","names":["HOT_MODULES","hotModulesOf","owner"],"sources":["../../../src/control-flow/hot-link.ts"],"sourcesContent":["import { getOwner, type Owner } from \"@shadow-js/core\";\nimport type { ModuleRegistry } from \"../hmr\";\n\n/**\n * The hot-update link between an error boundary and the modules its children were built from. Dev\n * only: the callers reach this code behind `__DEV__`, so production bundles never include it.\n *\n * A boundary that shows its fallback listens to those modules. When one of them is hot-replaced (the\n * edit is usually the fix), the boundary resets and builds its children again, so the user does not\n * have to press retry. The same module set is kept while the children are built: each component instance\n * adds its module to it when it is created (`hotModulesOf` in the proxy of `component()`).\n */\n\n/** The key the module set is stored under in the owner context of a boundary's children. */\nconst HOT_MODULES: symbol = /* @__PURE__ */ Symbol(\"HotModules\");\n\n/**\n * Makes `modules` the set of the root that is being created (called inside its `createRoot`): every\n * component created below that root adds its module to it.\n * @internal\n */\nexport function attachHotModules(modules: Set<ModuleRegistry>): void {\n const root = getOwner();\n if (root === null) return;\n const map = Object.create(root.context) as Record<symbol, unknown>;\n map[HOT_MODULES] = modules;\n root.context = map;\n}\n\n/**\n * The module set of the nearest boundary above `owner`, or undefined when there is none.\n * @internal\n */\nexport function hotModulesOf(owner: Owner | null): Set<ModuleRegistry> | undefined {\n return owner?.context?.[HOT_MODULES] as Set<ModuleRegistry> | undefined;\n}\n\n/**\n * The link of one boundary: the modules its children were last built from, and the listener armed on\n * them while the boundary shows its fallback.\n * @internal\n */\nexport interface HotLink {\n /** The modules of the last children build. Cleared by the boundary before each build. */\n readonly modules: Set<ModuleRegistry>;\n /** Listens to every module in `modules`: a hot update of one of them calls the boundary's `onUpdate`. */\n arm(): void;\n /** Stops listening (the children built, or the boundary was disposed). */\n disarm(): void;\n}\n\n/**\n * Creates the link of a boundary. `onUpdate` runs after a hot update of a module the boundary listens to,\n * once the update is applied.\n * @internal\n */\nexport function createHotLink(onUpdate: () => void): HotLink {\n const modules = new Set<ModuleRegistry>();\n let armed: ModuleRegistry[] = [];\n const listener = (): void => {\n onUpdate();\n };\n const disarm = (): void => {\n for (const registry of armed) registry.listeners.delete(listener);\n armed = [];\n };\n const arm = (): void => {\n disarm();\n for (const registry of modules) {\n registry.listeners.add(listener);\n armed.push(registry);\n }\n };\n return { modules, arm, disarm };\n}\n"],"mappings":"A,wBAcA,MAAMA,EAAsC,uBAAO,YAAY,EAmB/D,SAAgBC,EAAa,EAAsD,CACjF,OAAOC,GAAO,UAAUF,EAC1B,C"}
1
+ {"version":3,"file":"hot-link.js","names":["HOT_MODULES","hotModulesOf","owner"],"sources":["../../../src/control-flow/hot-link.ts"],"sourcesContent":["import { getOwner, type Owner } from \"@shadow-js/core\";\nimport type { ModuleRegistry } from \"../hmr\";\n\n/**\n * The hot-update link between an error boundary and the modules its children were built from. Dev\n * only: the callers reach this code behind `__DEV__`, so production bundles never include it.\n *\n * A boundary that shows its fallback listens to those modules. When one of them is hot-replaced (the\n * edit is usually the fix), the boundary resets and builds its children again, so the user does not\n * have to press retry. The same module set is kept while the children are built: each component instance\n * adds its module to it when it is created (`hotModulesOf` in the proxy of `component()`).\n */\n\n/** The key the module set is stored under in the owner context of a boundary's children. */\nconst HOT_MODULES: symbol = /* @__PURE__ */ Symbol(\"HotModules\");\n\n/**\n * Makes `modules` the set of the root that is being created (called inside its `createRoot`): every\n * component created below that root adds its module to it.\n * @internal\n */\nexport function attachHotModules(modules: Set<ModuleRegistry>): void {\n const root = getOwner();\n if (root === null) return;\n const map = Object.create(root.context) as Record<symbol, unknown>;\n map[HOT_MODULES] = modules;\n root.context = map;\n}\n\n/**\n * The module set of the nearest boundary above `owner`, or undefined when there is none.\n * @internal\n */\nexport function hotModulesOf(owner: Owner | null): Set<ModuleRegistry> | undefined {\n return owner?.context?.[HOT_MODULES] as Set<ModuleRegistry> | undefined;\n}\n\n/**\n * The link of one boundary: the modules its children were last built from, and the listener armed on\n * them while the boundary shows its fallback.\n * @internal\n */\nexport interface HotLink {\n /** The modules of the last children build. Cleared by the boundary before each build. */\n readonly modules: Set<ModuleRegistry>;\n /** Listens to every module in `modules`: a hot update of one of them calls the boundary's `onUpdate`. */\n arm(): void;\n /** Stops listening (the children built, or the boundary was disposed). */\n disarm(): void;\n}\n\n/**\n * Creates the link of a boundary. `onUpdate` runs after a hot update of a module the boundary listens to,\n * once the update is applied.\n * @internal\n */\nexport function createHotLink(onUpdate: () => void): HotLink {\n const modules = new Set<ModuleRegistry>();\n let armed: ModuleRegistry[] = [];\n const listener = (): void => {\n onUpdate();\n };\n const disarm = (): void => {\n for (const registry of armed) registry.listeners.delete(listener);\n armed = [];\n };\n const arm = (): void => {\n disarm();\n for (const registry of modules) {\n registry.listeners.add(listener);\n armed.push(registry);\n }\n };\n return { modules, arm, disarm };\n}\n"],"mappings":"A,wBAcA,MAAMA,EAAsC,uBAAO,YAAY,EAmB/D,SAAgBC,EAAaC,EAAsD,CACjF,OAAOA,GAAO,UAAUF,EAC1B,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"index-list.js","names":["Index","indexArray","props","untrack","item","index"],"sources":["../../../src/control-flow/index-list.ts"],"sourcesContent":["import { type Accessor, indexArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link Index}.\n * @since 1.0.0\n */\nexport interface IndexProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, so it\n * is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Called once per position, untracked. The item is an accessor that follows the value at this\n * position; the index is a plain number, because a position never changes.\n */\n readonly children: (item: () => T, index: number) => unknown;\n}\n\n/**\n * Renders one row per position. Rows are created and removed only when the length changes; the\n * row at position `i` stays, and its item accessor follows the value at `i`. Use it for\n * primitive lists where identity does not matter.\n *\n * @param props See {@link IndexProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Index } from \"@shadow-js/web\";\n *\n * function Cells() {\n * const [values] = useSignal([10, 20, 30]);\n * return (\n * <ul>\n * <Index each={values()}>{(value, index) => <li>{`${index}: ${value()}`}</li>}</Index>\n * </ul>\n * );\n * }\n * @see For\n * @since 1.0.0\n */\nexport function Index<T>(props: IndexProps<T>): Accessor<unknown[]> {\n return indexArray(\n () => props.each,\n (item: () => T, index: number) => untrack(() => props.children)(item, index),\n { fallback: () => props.fallback },\n );\n}\n"],"mappings":"A,0DA8CA,SAAgBA,EAAS,EAA2C,CAClE,OAAOC,MACCC,EAAM,MACX,EAAe,IAAkBC,MAAcD,EAAM,QAAQ,CAAC,CAACE,EAAMC,CAAK,EAC3E,CAAE,aAAgBH,EAAM,QAAS,CACnC,CACF,C"}
1
+ {"version":3,"file":"index-list.js","names":["indexArray","untrack","Index","props","item","index"],"sources":["../../../src/control-flow/index-list.ts"],"sourcesContent":["import { type Accessor, indexArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link Index}.\n * @since 1.0.0\n */\nexport interface IndexProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, so it\n * is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Called once per position, untracked. The item is an accessor that follows the value at this\n * position; the index is a plain number, because a position never changes.\n */\n readonly children: (item: () => T, index: number) => unknown;\n}\n\n/**\n * Renders one row per position. Rows are created and removed only when the length changes; the\n * row at position `i` stays, and its item accessor follows the value at `i`. Use it for\n * primitive lists where identity does not matter.\n *\n * @param props See {@link IndexProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Index } from \"@shadow-js/web\";\n *\n * function Cells() {\n * const [values] = useSignal([10, 20, 30]);\n * return (\n * <ul>\n * <Index each={values()}>{(value, index) => <li>{`${index}: ${value()}`}</li>}</Index>\n * </ul>\n * );\n * }\n * @see For\n * @since 1.0.0\n */\nexport function Index<T>(props: IndexProps<T>): Accessor<unknown[]> {\n return indexArray(\n () => props.each,\n (item: () => T, index: number) => untrack(() => props.children)(item, index),\n { fallback: () => props.fallback },\n );\n}\n"],"mappings":"A,0DA8CA,SAAgBE,EAASC,EAA2C,CAClE,OAAOH,MACCG,EAAM,MACXC,EAAeC,IAAkBJ,MAAcE,EAAM,QAAQ,CAAC,CAACC,EAAMC,CAAK,EAC3E,CAAE,aAAgBF,EAAM,QAAS,CACnC,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"lazy.js","names":["lazy","pending","loaded","load","loader","module","error","Lazy","component","useMemo","untrack","props","resource","useResource"],"sources":["../../../src/control-flow/lazy.ts"],"sourcesContent":["import { type Accessor, untrack, useMemo, useResource } from \"@shadow-js/core\";\n\ntype ComponentFunction<P> = (props: P) => unknown;\n\n/**\n * A component made by {@link lazy}: call it (or write it in JSX) like any component, and use\n * `preload` to start the load early.\n * @since 1.0.0\n */\nexport interface LazyComponent<P> {\n /**\n * Renders the loaded component with `props`. While the code is loading the result is empty and the\n * nearest `<Suspense>` shows its fallback; without a boundary nothing is rendered until the load\n * resolves.\n */\n (props: P): Accessor<unknown>;\n /**\n * Starts loading without rendering and resolves to the component. Calls share one load, so the\n * loader runs once. A failed load is not cached: the next call or render loads again.\n */\n preload(): Promise<ComponentFunction<P>>;\n}\n\n/**\n * Defines a component whose code is loaded on first render. While loading, the nearest\n * `<Suspense>` shows its fallback; a failed load throws to the nearest `<ErrorBoundary>` and the\n * next render retries.\n *\n * @param loader Returns a promise of a module whose `default` export is the component, such as\n * `() => import(\"./chart\")`. Called at most once while its load succeeds.\n * @returns A {@link LazyComponent}.\n * @throws Nothing synchronously. A rejected load surfaces as an error when the component's output\n * is read, so the nearest `<ErrorBoundary>` takes it; `preload()` rejects with the same error.\n * @example\n * import { lazy, Suspense } from \"@shadow-js/web\";\n *\n * function Chart(props: { title: string }) {\n * return <h2>{props.title}</h2>;\n * }\n *\n * // In an app the loader is `() => import(\"./chart\")`.\n * const LazyChart = lazy(() => Promise.resolve({ default: Chart }));\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <LazyChart title=\"Sales\" />\n * </Suspense>\n * );\n * }\n * @see Suspense\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function lazy<P>(\n loader: () => Promise<{ default: ComponentFunction<P> }>,\n): LazyComponent<P> {\n let pending: Promise<ComponentFunction<P>> | undefined;\n let loaded: ComponentFunction<P> | undefined;\n\n const load = (): Promise<ComponentFunction<P>> => {\n if (pending === undefined) {\n pending = loader().then(\n (module) => {\n loaded = module.default;\n return module.default;\n },\n (error: unknown) => {\n pending = undefined;\n throw error;\n },\n );\n }\n return pending;\n };\n\n const Lazy = ((props: P): Accessor<unknown> => {\n if (loaded !== undefined) {\n const component = loaded;\n return useMemo(() => untrack(() => component(props)), { allowWrites: true });\n }\n const resource = useResource(() => load());\n return useMemo(\n () => {\n const component = resource();\n return component === undefined ? undefined : untrack(() => component(props));\n },\n { allowWrites: true },\n );\n }) as LazyComponent<P>;\n Lazy.preload = load;\n return Lazy;\n}\n"],"mappings":"A,wEAsDA,SAAgBA,EACd,EACkB,CAClB,IAAIC,EACAC,EAEEC,OACAF,IAAY,IAAA,KACd,EAAUG,EAAO,CAAC,CAAC,KAChB,IACC,EAASC,EAAO,QACTA,EAAO,SAEf,GAAmB,CAElB,KADA,GAAU,IAAA,GACJC,CACR,CACF,GAEKL,GAGHM,GAAS,GAAgC,CAC7C,GAAIL,IAAW,IAAA,GAAW,CACxB,IAAMM,EAAYN,EAClB,OAAOO,MAAcC,MAAcF,EAAUG,CAAK,CAAC,EAAG,CAAE,YAAa,EAAK,CAAC,CAC7E,CACA,IAAMC,EAAWC,MAAkBV,EAAK,CAAC,EACzC,OAAOM,MACC,CACJ,IAAMD,EAAYI,EAAS,EAC3B,OAAOJ,IAAc,IAAA,GAAY,IAAA,GAAYE,MAAcF,EAAUG,CAAK,CAAC,CAC7E,EACA,CAAE,YAAa,EAAK,CACtB,CACF,GAEA,MADA,GAAK,QAAUR,EACRI,CACT,C"}
1
+ {"version":3,"file":"lazy.js","names":["untrack","useMemo","useResource","lazy","loader","pending","loaded","load","module","error","Lazy","props","component","resource"],"sources":["../../../src/control-flow/lazy.ts"],"sourcesContent":["import { type Accessor, untrack, useMemo, useResource } from \"@shadow-js/core\";\n\ntype ComponentFunction<P> = (props: P) => unknown;\n\n/**\n * A component made by {@link lazy}: call it (or write it in JSX) like any component, and use\n * `preload` to start the load early.\n * @since 1.0.0\n */\nexport interface LazyComponent<P> {\n /**\n * Renders the loaded component with `props`. While the code is loading the result is empty and the\n * nearest `<Suspense>` shows its fallback; without a boundary nothing is rendered until the load\n * resolves.\n */\n (props: P): Accessor<unknown>;\n /**\n * Starts loading without rendering and resolves to the component. Calls share one load, so the\n * loader runs once. A failed load is not cached: the next call or render loads again.\n */\n preload(): Promise<ComponentFunction<P>>;\n}\n\n/**\n * Defines a component whose code is loaded on first render. While loading, the nearest\n * `<Suspense>` shows its fallback; a failed load throws to the nearest `<ErrorBoundary>` and the\n * next render retries.\n *\n * @param loader Returns a promise of a module whose `default` export is the component, such as\n * `() => import(\"./chart\")`. Called at most once while its load succeeds.\n * @returns A {@link LazyComponent}.\n * @throws Nothing synchronously. A rejected load surfaces as an error when the component's output\n * is read, so the nearest `<ErrorBoundary>` takes it; `preload()` rejects with the same error.\n * @example\n * import { lazy, Suspense } from \"@shadow-js/web\";\n *\n * function Chart(props: { title: string }) {\n * return <h2>{props.title}</h2>;\n * }\n *\n * // In an app the loader is `() => import(\"./chart\")`.\n * const LazyChart = lazy(() => Promise.resolve({ default: Chart }));\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <LazyChart title=\"Sales\" />\n * </Suspense>\n * );\n * }\n * @see Suspense\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function lazy<P>(\n loader: () => Promise<{ default: ComponentFunction<P> }>,\n): LazyComponent<P> {\n let pending: Promise<ComponentFunction<P>> | undefined;\n let loaded: ComponentFunction<P> | undefined;\n\n const load = (): Promise<ComponentFunction<P>> => {\n if (pending === undefined) {\n pending = loader().then(\n (module) => {\n loaded = module.default;\n return module.default;\n },\n (error: unknown) => {\n pending = undefined;\n throw error;\n },\n );\n }\n return pending;\n };\n\n const Lazy = ((props: P): Accessor<unknown> => {\n if (loaded !== undefined) {\n const component = loaded;\n return useMemo(() => untrack(() => component(props)), { allowWrites: true });\n }\n const resource = useResource(() => load());\n return useMemo(\n () => {\n const component = resource();\n return component === undefined ? undefined : untrack(() => component(props));\n },\n { allowWrites: true },\n );\n }) as LazyComponent<P>;\n Lazy.preload = load;\n return Lazy;\n}\n"],"mappings":"A,wEAsDA,SAAgBG,EACdC,EACkB,CAClB,IAAIC,EACAC,EAEEC,OACAF,IAAY,IAAA,KACdA,EAAUD,EAAO,CAAC,CAAC,KAChBI,IACCF,EAASE,EAAO,QACTA,EAAO,SAEfC,GAAmB,CAElB,KADAJ,GAAU,IAAA,GACJI,CACR,CACF,GAEKJ,GAGHK,GAASC,GAAgC,CAC7C,GAAIL,IAAW,IAAA,GAAW,CACxB,IAAMM,EAAYN,EAClB,OAAOL,MAAcD,MAAcY,EAAUD,CAAK,CAAC,EAAG,CAAE,YAAa,EAAK,CAAC,CAC7E,CACA,IAAME,EAAWX,MAAkBK,EAAK,CAAC,EACzC,OAAON,MACC,CACJ,IAAMW,EAAYC,EAAS,EAC3B,OAAOD,IAAc,IAAA,GAAY,IAAA,GAAYZ,MAAcY,EAAUD,CAAK,CAAC,CAC7E,EACA,CAAE,YAAa,EAAK,CACtB,CACF,GAEA,MADAD,GAAK,QAAUH,EACRG,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-hydration.js","names":["findStatic","key","regions","region","open","node","nodes","depth","i","data","NoHydration","nextKey","claims","kept","props"],"sources":["../../../src/control-flow/no-hydration.ts"],"sourcesContent":["import type { Accessor } from \"@shadow-js/core\";\nimport { claims, nextKey, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n\n/** The nodes between `<!--nh:KEY-->` and its `<!--/nh-->` in the lifted regions, or undefined when the server sent none. */\nfunction findStatic(\n key: string | undefined,\n regions: readonly (readonly Node[])[] | undefined,\n): Node[] | undefined {\n if (key === undefined || regions === undefined) return undefined;\n for (const region of regions) {\n const open = region.findIndex(\n (node) => node.nodeType === 8 && (node as Comment).data === `nh:${key}`,\n );\n if (open === -1) continue;\n const nodes: Node[] = [];\n let depth = 1;\n for (let i = open + 1; i < region.length; i += 1) {\n const node = region[i] as Node;\n if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data.startsWith(\"nh:\")) depth += 1;\n else if (data === \"/nh\" && --depth === 0) break;\n }\n nodes.push(node);\n }\n return nodes;\n }\n return undefined;\n}\n\n/**\n * Props of {@link NoHydration}.\n * @since 1.0.0\n */\nexport interface NoHydrationProps {\n /**\n * The static content. Rendered by the server without hydration keys and left untouched by the\n * browser's hydration pass.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Content the browser never hydrates: the server renders it without hydration keys, and while the\n * page hydrates the browser leaves that markup exactly as it is (no code runs for it, no event\n * handlers or reactivity are attached). Use it for static, heavy markup such as rendered\n * documentation or a long article. Rendered by the browser alone (a client-side navigation), its\n * children render normally.\n *\n * @param props See {@link NoHydrationProps}.\n * @returns An accessor of the content: the children, or the server's own nodes while the browser hydrates.\n * @example\n * import { NoHydration } from \"@shadow-js/web\";\n *\n * function Docs(props: { html: string }) {\n * return (\n * <NoHydration>\n * <article innerHTML={props.html} />\n * </NoHydration>\n * );\n * }\n * @see ClientOnly\n * @since 1.0.0\n */\nexport function NoHydration(props: NoHydrationProps): Accessor<unknown> {\n // The component has its own scope, so this key does not move the keys of its siblings.\n const key = nextKey();\n if (__SERVER__) {\n // No scope for the content: the keys of what is rendered inside are not handed out.\n const built = withScope(null, () => props.children);\n return () => [ssrRaw(`<!--nh:${key ?? \"\"}-->`), built, ssrRaw(\"<!--/nh-->\")];\n }\n if (claims.current.isClaiming()) {\n // Hydrating: the server's nodes between the markers are handed to the region as they are.\n const kept = findStatic(key, claims.current.liftedRegions());\n if (kept !== undefined) return () => kept;\n // No markers from the server (the root of the container): render on the client, claiming nothing.\n return () => claims.current.withoutClaiming(() => props.children);\n }\n return () => props.children;\n}\n"],"mappings":"A,iHAKA,SAASA,EACP,EACA,EACoB,CACpB,GAAIC,IAAQ,IAAA,IAAaC,IAAY,IAAA,GACrC,IAAK,IAAMC,KAAUD,EAAS,CAC5B,IAAME,EAAOD,EAAO,UACjB,GAASE,EAAK,WAAa,GAAMA,EAAiB,OAAS,MAAMJ,GACpE,EACA,GAAIG,IAAS,GAAI,SACjB,IAAME,EAAgB,CAAC,EACnBC,EAAQ,EACZ,IAAK,IAAIC,EAAIJ,EAAO,EAAGI,EAAIL,EAAO,OAAQ,GAAK,EAAG,CAChD,IAAME,EAAOF,EAAOK,GACpB,GAAIH,EAAK,WAAa,EAAG,CACvB,IAAMI,EAAQJ,EAAiB,KAC/B,GAAII,EAAK,WAAW,KAAK,EAAG,GAAS,OAChC,GAAIA,IAAS,OAAS,EAAEF,IAAU,EAAG,KAC5C,CACAD,EAAM,KAAKD,CAAI,CACjB,CACA,OAAOC,CACT,CAEF,CAqCA,SAAgBI,EAAY,EAA4C,CAEtE,IAAMT,EAAMU,EAAQ,EAMpB,GAAIC,EAAO,QAAQ,WAAW,EAAG,CAE/B,IAAMC,EAAOb,EAAWC,EAAKW,EAAO,QAAQ,cAAc,CAAC,EAG3D,OAFIC,IAAS,IAAA,OAEAD,EAAO,QAAQ,oBAAsBE,EAAM,QAAQ,MAF3BD,CAGvC,CACA,UAAaC,EAAM,QACrB,C"}
1
+ {"version":3,"file":"no-hydration.js","names":["claims","nextKey","findStatic","key","regions","region","open","node","nodes","depth","i","data","NoHydration","props","kept"],"sources":["../../../src/control-flow/no-hydration.ts"],"sourcesContent":["import type { Accessor } from \"@shadow-js/core\";\nimport { claims, nextKey, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n\n/** The nodes between `<!--nh:KEY-->` and its `<!--/nh-->` in the lifted regions, or undefined when the server sent none. */\nfunction findStatic(\n key: string | undefined,\n regions: readonly (readonly Node[])[] | undefined,\n): Node[] | undefined {\n if (key === undefined || regions === undefined) return undefined;\n for (const region of regions) {\n const open = region.findIndex(\n (node) => node.nodeType === 8 && (node as Comment).data === `nh:${key}`,\n );\n if (open === -1) continue;\n const nodes: Node[] = [];\n let depth = 1;\n for (let i = open + 1; i < region.length; i += 1) {\n const node = region[i] as Node;\n if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data.startsWith(\"nh:\")) depth += 1;\n else if (data === \"/nh\" && --depth === 0) break;\n }\n nodes.push(node);\n }\n return nodes;\n }\n return undefined;\n}\n\n/**\n * Props of {@link NoHydration}.\n * @since 1.0.0\n */\nexport interface NoHydrationProps {\n /**\n * The static content. Rendered by the server without hydration keys and left untouched by the\n * browser's hydration pass.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Content the browser never hydrates: the server renders it without hydration keys, and while the\n * page hydrates the browser leaves that markup exactly as it is (no code runs for it, no event\n * handlers or reactivity are attached). Use it for static, heavy markup such as rendered\n * documentation or a long article. Rendered by the browser alone (a client-side navigation), its\n * children render normally.\n *\n * @param props See {@link NoHydrationProps}.\n * @returns An accessor of the content: the children, or the server's own nodes while the browser hydrates.\n * @example\n * import { NoHydration } from \"@shadow-js/web\";\n *\n * function Docs(props: { html: string }) {\n * return (\n * <NoHydration>\n * <article innerHTML={props.html} />\n * </NoHydration>\n * );\n * }\n * @see ClientOnly\n * @since 1.0.0\n */\nexport function NoHydration(props: NoHydrationProps): Accessor<unknown> {\n // The component has its own scope, so this key does not move the keys of its siblings.\n const key = nextKey();\n if (__SERVER__) {\n // No scope for the content: the keys of what is rendered inside are not handed out.\n const built = withScope(null, () => props.children);\n return () => [ssrRaw(`<!--nh:${key ?? \"\"}-->`), built, ssrRaw(\"<!--/nh-->\")];\n }\n if (claims.current.isClaiming()) {\n // Hydrating: the server's nodes between the markers are handed to the region as they are.\n const kept = findStatic(key, claims.current.liftedRegions());\n if (kept !== undefined) return () => kept;\n // No markers from the server (the root of the container): render on the client, claiming nothing.\n return () => claims.current.withoutClaiming(() => props.children);\n }\n return () => props.children;\n}\n"],"mappings":"A,iHAKA,SAASE,EACPC,EACAC,EACoB,CACpB,GAAID,IAAQ,IAAA,IAAaC,IAAY,IAAA,GACrC,IAAK,IAAMC,KAAUD,EAAS,CAC5B,IAAME,EAAOD,EAAO,UACjBE,GAASA,EAAK,WAAa,GAAMA,EAAiB,OAAS,MAAMJ,GACpE,EACA,GAAIG,IAAS,GAAI,SACjB,IAAME,EAAgB,CAAC,EACnBC,EAAQ,EACZ,IAAK,IAAIC,EAAIJ,EAAO,EAAGI,EAAIL,EAAO,OAAQK,GAAK,EAAG,CAChD,IAAMH,EAAOF,EAAOK,GACpB,GAAIH,EAAK,WAAa,EAAG,CACvB,IAAMI,EAAQJ,EAAiB,KAC/B,GAAII,EAAK,WAAW,KAAK,EAAGF,GAAS,OAChC,GAAIE,IAAS,OAAS,EAAEF,IAAU,EAAG,KAC5C,CACAD,EAAM,KAAKD,CAAI,CACjB,CACA,OAAOC,CACT,CAEF,CAqCA,SAAgBI,EAAYC,EAA4C,CAEtE,IAAMV,EAAMF,EAAQ,EAMpB,GAAID,EAAO,QAAQ,WAAW,EAAG,CAE/B,IAAMc,EAAOZ,EAAWC,EAAKH,EAAO,QAAQ,cAAc,CAAC,EAG3D,OAFIc,IAAS,IAAA,OAEAd,EAAO,QAAQ,oBAAsBa,EAAM,QAAQ,MAF3BC,CAGvC,CACA,UAAaD,EAAM,QACrB,C"}