@shadow-js/web 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/dev/attributes.js.map +1 -1
  3. package/dist/dev/class-style.d.ts +10 -5
  4. package/dist/dev/class-style.js +47 -47
  5. package/dist/dev/class-style.js.map +1 -1
  6. package/dist/dev/control-flow/dynamic.js +2 -2
  7. package/dist/dev/control-flow/dynamic.js.map +1 -1
  8. package/dist/dev/control-flow/error-boundary.js +2 -2
  9. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  10. package/dist/dev/control-flow/portal.d.ts +2 -2
  11. package/dist/dev/control-flow/portal.js +15 -13
  12. package/dist/dev/control-flow/portal.js.map +1 -1
  13. package/dist/dev/control-flow/suspense-list.js +2 -2
  14. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  15. package/dist/dev/control-flow/suspense.js +2 -2
  16. package/dist/dev/control-flow/suspense.js.map +1 -1
  17. package/dist/dev/element.js +5 -2
  18. package/dist/dev/element.js.map +1 -1
  19. package/dist/dev/extend.d.ts +2 -2
  20. package/dist/dev/extend.js +2 -2
  21. package/dist/dev/insert.d.ts +11 -0
  22. package/dist/dev/insert.js +50 -33
  23. package/dist/dev/insert.js.map +1 -1
  24. package/dist/dev/internal/accessor.js +56 -0
  25. package/dist/dev/internal/accessor.js.map +1 -0
  26. package/dist/dev/internal/claim.js +0 -1
  27. package/dist/dev/internal/claim.js.map +1 -1
  28. package/dist/dev/internal/css-units.js +2 -2
  29. package/dist/dev/internal/css-units.js.map +1 -1
  30. package/dist/dev/internal/portal-context.d.ts +9 -0
  31. package/dist/dev/internal/portal-context.js.map +1 -1
  32. package/dist/dev/internal/react-names.js +22 -12
  33. package/dist/dev/internal/react-names.js.map +1 -1
  34. package/dist/dev/internal/reconcile.js +4 -6
  35. package/dist/dev/internal/reconcile.js.map +1 -1
  36. package/dist/dev/server/attributes.js +1 -31
  37. package/dist/dev/server/attributes.js.map +1 -1
  38. package/dist/dev/server/element.js +5 -6
  39. package/dist/dev/server/element.js.map +1 -1
  40. package/dist/dev/server/index.js +1 -1
  41. package/dist/dev/server/portals.js +3 -0
  42. package/dist/dev/server/portals.js.map +1 -1
  43. package/dist/dev/server/render.js +1 -1
  44. package/dist/dev/server/stream.js +1 -1
  45. package/dist/dev/server.js +1 -1
  46. package/dist/dev/spread.js +49 -27
  47. package/dist/dev/spread.js.map +1 -1
  48. package/dist/dev/template.js +1 -3
  49. package/dist/dev/template.js.map +1 -1
  50. package/dist/dev/view-transition.js +12 -4
  51. package/dist/dev/view-transition.js.map +1 -1
  52. package/dist/prod/attributes.js +1 -1
  53. package/dist/prod/attributes.js.map +1 -1
  54. package/dist/prod/class-style.js +1 -1
  55. package/dist/prod/class-style.js.map +1 -1
  56. package/dist/prod/control-flow/dynamic.js +1 -1
  57. package/dist/prod/control-flow/dynamic.js.map +1 -1
  58. package/dist/prod/control-flow/error-boundary.js +1 -1
  59. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  60. package/dist/prod/control-flow/portal.js +1 -1
  61. package/dist/prod/control-flow/portal.js.map +1 -1
  62. package/dist/prod/control-flow/suspense-list.js +1 -1
  63. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  64. package/dist/prod/control-flow/suspense.js +1 -1
  65. package/dist/prod/control-flow/suspense.js.map +1 -1
  66. package/dist/prod/element.js +1 -1
  67. package/dist/prod/element.js.map +1 -1
  68. package/dist/prod/extend.js +1 -1
  69. package/dist/prod/insert.js +1 -1
  70. package/dist/prod/insert.js.map +1 -1
  71. package/dist/prod/internal/accessor.js +2 -0
  72. package/dist/prod/internal/accessor.js.map +1 -0
  73. package/dist/prod/internal/claim.js +1 -1
  74. package/dist/prod/internal/claim.js.map +1 -1
  75. package/dist/prod/internal/css-units.js +1 -1
  76. package/dist/prod/internal/css-units.js.map +1 -1
  77. package/dist/prod/internal/portal-context.js.map +1 -1
  78. package/dist/prod/internal/react-names.js +1 -1
  79. package/dist/prod/internal/react-names.js.map +1 -1
  80. package/dist/prod/internal/reconcile.js +1 -1
  81. package/dist/prod/internal/reconcile.js.map +1 -1
  82. package/dist/prod/server/attributes.js +1 -1
  83. package/dist/prod/server/attributes.js.map +1 -1
  84. package/dist/prod/server/element.js +1 -1
  85. package/dist/prod/server/element.js.map +1 -1
  86. package/dist/prod/server/index.js +1 -1
  87. package/dist/prod/server/portals.js +1 -1
  88. package/dist/prod/server/portals.js.map +1 -1
  89. package/dist/prod/server/render.js +1 -1
  90. package/dist/prod/server/stream.js +1 -1
  91. package/dist/prod/server.js +1 -1
  92. package/dist/prod/spread.js +1 -1
  93. package/dist/prod/spread.js.map +1 -1
  94. package/dist/prod/template.js +1 -1
  95. package/dist/prod/template.js.map +1 -1
  96. package/dist/prod/view-transition.js +1 -1
  97. package/dist/prod/view-transition.js.map +1 -1
  98. package/dist/server/attributes.js +1 -1
  99. package/dist/server/attributes.js.map +1 -1
  100. package/dist/server/class-style.js +1 -1
  101. package/dist/server/class-style.js.map +1 -1
  102. package/dist/server/control-flow/dynamic.js.map +1 -1
  103. package/dist/server/control-flow/error-boundary.js +1 -1
  104. package/dist/server/control-flow/error-boundary.js.map +1 -1
  105. package/dist/server/control-flow/portal.js +1 -1
  106. package/dist/server/control-flow/portal.js.map +1 -1
  107. package/dist/server/control-flow/suspense-list.js +1 -1
  108. package/dist/server/control-flow/suspense-list.js.map +1 -1
  109. package/dist/server/control-flow/suspense.js +1 -1
  110. package/dist/server/control-flow/suspense.js.map +1 -1
  111. package/dist/server/element.js.map +1 -1
  112. package/dist/server/extend.js +1 -1
  113. package/dist/server/insert.js +1 -1
  114. package/dist/server/insert.js.map +1 -1
  115. package/dist/server/internal/accessor.js +2 -0
  116. package/dist/server/internal/accessor.js.map +1 -0
  117. package/dist/server/internal/claim.js +1 -1
  118. package/dist/server/internal/claim.js.map +1 -1
  119. package/dist/server/internal/css-units.js +1 -1
  120. package/dist/server/internal/css-units.js.map +1 -1
  121. package/dist/server/internal/portal-context.js.map +1 -1
  122. package/dist/server/internal/react-names.js +1 -1
  123. package/dist/server/internal/react-names.js.map +1 -1
  124. package/dist/server/internal/reconcile.js +1 -1
  125. package/dist/server/internal/reconcile.js.map +1 -1
  126. package/dist/server/server/attributes.js +1 -1
  127. package/dist/server/server/attributes.js.map +1 -1
  128. package/dist/server/server/element.js +1 -1
  129. package/dist/server/server/element.js.map +1 -1
  130. package/dist/server/server/index.js +1 -1
  131. package/dist/server/server/portals.js +1 -1
  132. package/dist/server/server/portals.js.map +1 -1
  133. package/dist/server/server/render.js +1 -1
  134. package/dist/server/server/stream.js +1 -1
  135. package/dist/server/server.js +1 -1
  136. package/dist/server/spread.js +1 -1
  137. package/dist/server/spread.js.map +1 -1
  138. package/dist/server/template.js +1 -1
  139. package/dist/server/template.js.map +1 -1
  140. package/dist/server/view-transition.js.map +1 -1
  141. package/dist/server-dev/attributes.js.map +1 -1
  142. package/dist/server-dev/class-style.js +47 -47
  143. package/dist/server-dev/class-style.js.map +1 -1
  144. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  145. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  146. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  147. package/dist/server-dev/control-flow/portal.js +15 -13
  148. package/dist/server-dev/control-flow/portal.js.map +1 -1
  149. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  150. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  151. package/dist/server-dev/control-flow/suspense.js +2 -2
  152. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  153. package/dist/server-dev/element.js.map +1 -1
  154. package/dist/server-dev/extend.js +2 -2
  155. package/dist/server-dev/insert.js +50 -33
  156. package/dist/server-dev/insert.js.map +1 -1
  157. package/dist/server-dev/internal/accessor.js +56 -0
  158. package/dist/server-dev/internal/accessor.js.map +1 -0
  159. package/dist/server-dev/internal/claim.js +0 -1
  160. package/dist/server-dev/internal/claim.js.map +1 -1
  161. package/dist/server-dev/internal/css-units.js +2 -2
  162. package/dist/server-dev/internal/css-units.js.map +1 -1
  163. package/dist/server-dev/internal/portal-context.js.map +1 -1
  164. package/dist/server-dev/internal/react-names.js +22 -12
  165. package/dist/server-dev/internal/react-names.js.map +1 -1
  166. package/dist/server-dev/internal/reconcile.js +4 -6
  167. package/dist/server-dev/internal/reconcile.js.map +1 -1
  168. package/dist/server-dev/server/attributes.js +1 -31
  169. package/dist/server-dev/server/attributes.js.map +1 -1
  170. package/dist/server-dev/server/element.js +5 -6
  171. package/dist/server-dev/server/element.js.map +1 -1
  172. package/dist/server-dev/server/index.js +1 -1
  173. package/dist/server-dev/server/portals.js +3 -0
  174. package/dist/server-dev/server/portals.js.map +1 -1
  175. package/dist/server-dev/server/render.js +1 -1
  176. package/dist/server-dev/server/stream.js +1 -1
  177. package/dist/server-dev/server.js +1 -1
  178. package/dist/server-dev/spread.js +35 -26
  179. package/dist/server-dev/spread.js.map +1 -1
  180. package/dist/server-dev/template.js +1 -3
  181. package/dist/server-dev/template.js.map +1 -1
  182. package/dist/server-dev/view-transition.js.map +1 -1
  183. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","names":[],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n const event = eventNameOf(key);\n if (event !== undefined) {\n bindListener(el, event, read[key]);\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEpB,SAAgB,QAAQ,KAAa,OAAwB;CAC3D,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,IAAI,YAAY,MAAM,UAClD,MAAM,IAAI,UAAoB,+BAAsD;CAEtF,MAAM,OAAO;CAGX,OAAO,WACL,KACA,aACM;EACJ,MAAM,WAAW,KAAK;EAEtB,IAAI,aAAa,KAAA,KAAa,kBAAkB,GAAG,GAAG,OAAO;EAC7D,OAAO;GAAC,OAAO,UAAU;GAAG;GAAU,OAAO,UAAU;EAAC;CAC1D,GACA,IACF;AAgCJ"}
1
+ {"version":3,"file":"element.js","names":[],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setBoolAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { isFlagAttribute } from \"./internal/react-names\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n const event = eventNameOf(key);\n if (event !== undefined) {\n bindListener(el, event, read[key]);\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n // The server writes a boolean attribute by truthiness; the client does the same. A name\n // that is a flag has no React spelling, so lower case is its attribute name.\n const name = key.toLowerCase();\n if (isFlagAttribute(name, value)) setBoolAttribute(el, name, value);\n else setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEpB,SAAgB,QAAQ,KAAa,OAAwB;CAC3D,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,IAAI,YAAY,MAAM,UAClD,MAAM,IAAI,UAAoB,+BAAsD;CAEtF,MAAM,OAAO;CAGX,OAAO,WACL,KACA,aACM;EACJ,MAAM,WAAW,KAAK;EAEtB,IAAI,aAAa,KAAA,KAAa,kBAAkB,GAAG,GAAG,OAAO;EAC7D,OAAO;GAAC,OAAO,UAAU;GAAG;GAAU,OAAO,UAAU;EAAC;CAC1D,GACA,IACF;AAoCJ"}
@@ -5,8 +5,8 @@ import { childScope, createRootScope, currentScope, enterComponent, nextKey, res
5
5
  import { claimElement, claimPortal, isClaiming, takeRegion, withoutClaiming } from "./internal/claim.js";
6
6
  import { claims } from "./internal/hydration-hooks.js";
7
7
  import { reconcileNodes } from "./internal/reconcile.js";
8
- import { bindRegion, createRegion, removeRegion } from "./insert.js";
8
+ import { bindRegion, createRegion, moveRegion, removeRegion } from "./insert.js";
9
9
  import { element } from "./element.js";
10
10
  import { PortalContext } from "./internal/portal-context.js";
11
11
  import { StreamContext } from "./internal/stream-context.js";
12
- export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
12
+ export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, moveRegion, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
@@ -1,11 +1,10 @@
1
+ import { leaves } from "./internal/accessor.js";
1
2
  import { checkClaimedText } from "./internal/claim.js";
2
3
  import { claims } from "./internal/hydration-hooks.js";
3
4
  import { reconcileNodes } from "./internal/reconcile.js";
4
- import { useRenderEffect } from "@shadow-js/core";
5
+ import { onCleanup, useRenderEffect } from "@shadow-js/core";
5
6
  import { addCleanup, createComputation, currentOwner, disposeOwner, readComputation } from "@shadow-js/core/extend";
6
7
  // src/insert.ts
7
- /** Longest chain of accessors a single value may hold (a function returning a function ...). */
8
- const MAX_ACCESSOR_DEPTH = 1e4;
9
8
  /** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */
10
9
  const tails = /* @__PURE__ */ new WeakMap();
11
10
  /** The document a node belongs to (a Document is its own document). */
@@ -34,39 +33,23 @@ function pruneTexts(region, keep) {
34
33
  } else if (!keep.includes(texts)) region.texts = null;
35
34
  }
36
35
  /**
36
+ * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect
37
+ * that runs again flattens the same fragment value once more: it must still give those nodes.
38
+ */
39
+ const fragmentChildren = /* @__PURE__ */ new WeakMap();
40
+ /**
37
41
  * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)
38
42
  * through `call`, which runs inside the render effect that owns the value, so reads are tracked.
39
43
  */
40
- function flatten(root, call = (fn) => fn()) {
44
+ function flatten(root, call) {
41
45
  const parts = [];
42
- const frames = [[root]];
43
- const cursors = [0];
44
- const active = /* @__PURE__ */ new Set();
45
- while (frames.length > 0) {
46
- const top = frames.length - 1;
47
- const frame = frames[top];
48
- const cursor = cursors[top] ?? 0;
49
- if (frame === void 0 || cursor >= frame.length) {
50
- const done = frames.pop();
51
- if (done !== void 0) active.delete(done);
52
- cursors.pop();
53
- continue;
54
- }
55
- cursors[top] = cursor + 1;
56
- let item = frame[cursor];
57
- for (let depth = 0; typeof item === "function"; depth += 1) {
58
- if (depth >= MAX_ACCESSOR_DEPTH) throw new TypeError("insert(): accessor chain is too deep.");
59
- item = call(item);
60
- }
46
+ for (const item of leaves(root, "insert(): a value contains itself.", call)) {
61
47
  if (item === null || item === void 0 || typeof item === "boolean") continue;
62
- if (item instanceof DocumentFragment) for (const child of item.childNodes) parts.push(child);
63
- else if (item instanceof Node) parts.push(item);
64
- else if (Array.isArray(item)) {
65
- if (active.has(item)) throw new TypeError("insert(): a value contains itself.");
66
- active.add(item);
67
- frames.push(item);
68
- cursors.push(0);
69
- } else parts.push(String(item));
48
+ if (item instanceof DocumentFragment) {
49
+ const kids = fragmentChildren.get(item) ?? [...item.childNodes];
50
+ fragmentChildren.set(item, kids);
51
+ for (const child of kids) parts.push(child);
52
+ } else parts.push(item instanceof Node ? item : String(item));
70
53
  }
71
54
  return parts;
72
55
  }
@@ -122,6 +105,21 @@ function endOf(region, last) {
122
105
  if (marker.parentNode !== region.parent) return null;
123
106
  return marker.nextSibling;
124
107
  }
108
+ /** Callbacks to run after a region of a parent has committed (see `watchCommits`). */
109
+ const commitWatchers = /* @__PURE__ */ new WeakMap();
110
+ /**
111
+ * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the
112
+ * parent holds (a name on the first element of a content region) can follow a change of content.
113
+ * The watch ends with the owner that is current when this is called.
114
+ * @internal
115
+ */
116
+ function watchCommits(parent, run) {
117
+ const set = commitWatchers.get(parent) ?? /* @__PURE__ */ new Set();
118
+ commitWatchers.set(parent, set.add(run));
119
+ onCleanup(() => {
120
+ set.delete(run);
121
+ });
122
+ }
125
123
  /** Makes the DOM show `next` for this region. */
126
124
  function reconcileRegion(region, next) {
127
125
  const parent = region.parent;
@@ -132,6 +130,9 @@ function reconcileRegion(region, next) {
132
130
  reconcileNodes(parent, attached, next, end);
133
131
  region.nodes = next;
134
132
  pruneTexts(region, next);
133
+ commitWatchers.get(parent)?.forEach((run) => {
134
+ run();
135
+ });
135
136
  }
136
137
  /** Applies a flattened value to a region. */
137
138
  function commit(region, parts) {
@@ -223,7 +224,7 @@ function containsFunction(root) {
223
224
  const stack = [root];
224
225
  const seen = /* @__PURE__ */ new Set([root]);
225
226
  while (stack.length > 0) {
226
- const frame = stack.pop() ?? [];
227
+ const frame = stack.pop();
227
228
  for (const item of frame) {
228
229
  if (typeof item === "function") return true;
229
230
  if (Array.isArray(item) && !seen.has(item)) {
@@ -301,6 +302,22 @@ function bindRegion(region, value, ordered) {
301
302
  return latest;
302
303
  }
303
304
  /**
305
+ * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts
306
+ * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so
307
+ * what it shows is not built again. Only for a region without an anchor.
308
+ * @param region The region to move.
309
+ * @param parent The node that receives the region's nodes.
310
+ * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).
311
+ * @since 1.0.3
312
+ * @internal
313
+ */
314
+ function moveRegion(region, parent, move) {
315
+ const attached = region.nodes.filter((node) => node.parentNode === region.parent);
316
+ for (const node of attached) move(node);
317
+ region.parent = parent;
318
+ region.marker = attached[0]?.previousSibling ?? parent.lastChild;
319
+ }
320
+ /**
304
321
  * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not
305
322
  * touched.
306
323
  * @internal
@@ -373,6 +390,6 @@ function insert(parent, value, anchorNode, initial) {
373
390
  const resolvedAnchor = anchorNode ?? null;
374
391
  return bindRegion(createRegion(parent, resolvedAnchor, initial === void 0 ? claims.current.takeRegion(parent, resolvedAnchor) : initial), value, resolvedAnchor === null);
375
392
  }
376
- export { anchor, bindRegion, createRegion, insert, removeRegion };
393
+ export { anchor, bindRegion, createRegion, insert, moveRegion, removeRegion, watchCommits };
377
394
 
378
395
  //# sourceMappingURL=insert.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call: (fn: () => unknown) => unknown = (fn) => fn()): Part[] {\n const parts: Part[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n let item: unknown = frame[cursor];\n for (let depth = 0; typeof item === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__ ? \"insert(): accessor chain is too deep.\" : \"SHADOW_INSERT_DEPTH\",\n );\n item = call(item as () => unknown);\n }\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n for (const child of item.childNodes) parts.push(child);\n } else if (item instanceof Node) parts.push(item);\n else if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(__DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\");\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else parts.push(String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() ?? [];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region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AO,OACxB,IAAI,KAAK,eAAe,OAAO,QAAQ,OAAO,OAAO,YAAY,IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
1
+ {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n for (const node of attached) move(node);\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;MAC9B,IAAI,iBAAiB,KAAK,MAAM,IAAI,IAAI;MACxC,IAAI,UAAU,MAAM,OAAO,wBAAQ,IAAI,IAAI,CAAC,OAAO,IAAI,CAAC;AAC/D;;AAGA,SAAS,WAAW,QAAgB,MAA6B;CAC/D,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM;CACpB,IAAI,iBAAiB,KAAK;EACxB,MAAM,OAAO,IAAI,IAAU,IAAI;EAC/B,KAAK,MAAM,QAAQ,OACjB,IAAI,CAAC,KAAK,IAAI,IAAI,GAAG,MAAM,OAAO,IAAI;CAE1C,OAAO,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ;AACnD;;;;;AAMA,MAAM,mCAAmB,IAAI,QAAkC;;;;;AAM/D,SAAS,QAAQ,MAAe,MAA+C;CAC7E,MAAM,QAAgB,CAAC;CAEvB,KAAK,MAAM,QAAQ,OAAO,MAAM,sCAAO,IAAI,GAAG;EAC5C,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,OAAO,SAAS,WAAW;EACtE,IAAI,gBAAgB,kBAAkB;GACpC,MAAM,O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gB,aAAa,QAAsB;CACjD,KAAK,MAAM,QAAQ,OAAO,OACxB,IAAI,KAAK,eAAe,OAAO,QAAQ,OAAO,OAAO,YAAY,IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
@@ -0,0 +1,56 @@
1
+ // src/internal/accessor.ts
2
+ /** Longest chain of accessors a single value may hold (a function returning a function ...). */
3
+ const MAX_ACCESSOR_DEPTH = 1e4;
4
+ /**
5
+ * Calls `value` while it is a function, so an accessor that returns an accessor is followed to the
6
+ * value at its end. `call` runs each function (default: a plain call); `insert` passes one that
7
+ * memoizes. Class and style values use the default, inside the effect that applies them, so the
8
+ * signals an accessor reads are tracked by it.
9
+ * @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.
10
+ * @internal
11
+ */
12
+ function unwrap(value, call = (fn) => fn()) {
13
+ for (let depth = 0; typeof value === "function"; depth += 1) {
14
+ if (depth >= MAX_ACCESSOR_DEPTH) throw new TypeError("An accessor returns accessors more than 10,000 levels deep.");
15
+ value = call(value);
16
+ }
17
+ return value;
18
+ }
19
+ /**
20
+ * The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is
21
+ * the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.
22
+ * `insert` and the class writer share it.
23
+ * @param root The value; an array is entered, any other value is a leaf.
24
+ * @param cycle The message of the `TypeError` thrown when an array contains itself.
25
+ * @param call Passed to {@link unwrap}.
26
+ * @internal
27
+ */
28
+ function leaves(root, cycle, call) {
29
+ const found = [];
30
+ const frames = [[root]];
31
+ const cursors = [0];
32
+ const active = /* @__PURE__ */ new Set();
33
+ while (frames.length > 0) {
34
+ const top = frames.length - 1;
35
+ const frame = frames[top];
36
+ const cursor = cursors[top];
37
+ if (cursor >= frame.length) {
38
+ active.delete(frames.pop());
39
+ cursors.pop();
40
+ continue;
41
+ }
42
+ cursors[top] = cursor + 1;
43
+ const item = unwrap(frame[cursor], call);
44
+ if (!Array.isArray(item)) found.push(item);
45
+ else if (active.has(item)) throw new TypeError(cycle);
46
+ else {
47
+ active.add(item);
48
+ frames.push(item);
49
+ cursors.push(0);
50
+ }
51
+ }
52
+ return found;
53
+ }
54
+ export { leaves, unwrap };
55
+
56
+ //# sourceMappingURL=accessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accessor.js","names":[],"sources":["../../../src/internal/accessor.ts"],"sourcesContent":["/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * Calls `value` while it is a function, so an accessor that returns an accessor is followed to the\n * value at its end. `call` runs each function (default: a plain call); `insert` passes one that\n * memoizes. Class and style values use the default, inside the effect that applies them, so the\n * signals an accessor reads are tracked by it.\n * @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.\n * @internal\n */\nexport function unwrap(\n value: unknown,\n call: (fn: () => unknown) => unknown = (fn) => fn(),\n): unknown {\n for (let depth = 0; typeof value === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__\n ? \"An accessor returns accessors more than 10,000 levels deep.\"\n : \"SHADOW_INSERT_DEPTH\",\n );\n value = call(value as () => unknown);\n }\n return value;\n}\n\n/**\n * The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is\n * the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.\n * `insert` and the class writer share it.\n * @param root The value; an array is entered, any other value is a leaf.\n * @param cycle The message of the `TypeError` thrown when an array contains itself.\n * @param call Passed to {@link unwrap}.\n * @internal\n */\nexport function leaves(\n root: unknown,\n cycle: string,\n call?: (fn: () => unknown) => unknown,\n): unknown[] {\n const found: unknown[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top] as unknown[];\n const cursor = cursors[top] as number;\n if (cursor >= frame.length) {\n active.delete(frames.pop() as unknown[]);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = unwrap(frame[cursor], call);\n if (!Array.isArray(item)) found.push(item);\n else if (active.has(item)) throw new TypeError(cycle);\n else {\n active.add(item);\n frames.push(item);\n cursors.push(0);\n }\n }\n return found;\n}\n"],"mappings":";;AACA,MAAM,qBAAqB;;;;;;;;;AAU3B,SAAgB,OACd,OACA,QAAwC,OAAO,GAAG,GACzC;CACT,KAAK,IAAI,QAAQ,GAAG,OAAO,UAAU,YAAY,SAAS,GAAG;EAC3D,IAAI,SAAS,oBACX,MAAM,IAAI,UAEJ,6DAEN;EACF,QAAQ,KAAK,KAAsB;CACrC;CACA,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,OACd,MACA,OACA,MACW;CACX,MAAM,QAAmB,CAAC;CAC1B,MAAM,SAAsB,CAAC,CAAC,IAAI,CAAC;CACnC,MAAM,UAAoB,CAAC,CAAC;CAC5B,MAAM,yBAAS,IAAI,IAAe;CAClC,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,SAAS,QAAQ;EACvB,IAAI,UAAU,MAAM,QAAQ;GAC1B,OAAO,OAAO,OAAO,IAAI,CAAc;GACvC,QAAQ,IAAI;GACZ;EACF;EACA,QAAQ,OAAO,SAAS;EACxB,MAAM,OAAO,OAAO,MAAM,SAAS,IAAI;EACvC,IAAI,CAAC,MAAM,QAAQ,IAAI,GAAG,MAAM,KAAK,IAAI;OACpC,IAAI,OAAO,IAAI,IAAI,GAAG,MAAM,IAAI,UAAU,KAAK;OAC/C;GACH,OAAO,IAAI,IAAI;GACf,OAAO,KAAK,IAAI;GAChB,QAAQ,KAAK,CAAC;EAChB;CACF;CACA,OAAO;AACT"}
@@ -48,7 +48,6 @@ function prepare(root, pending, lifted) {
48
48
  const stack = [root];
49
49
  while (stack.length > 0) {
50
50
  const parent = stack.pop();
51
- if (parent === void 0) break;
52
51
  let child = parent.firstChild;
53
52
  while (child !== null) {
54
53
  const following = child.nextSibling;
@@ -1 +1 @@
1
- {"version":3,"file":"claim.js","names":[],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop();\n if (parent === undefined) break;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `&lt;` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":";;AAcA,IAAI,QAA+B;;AAGnC,SAAgB,cACd,UACA,aACM;CACN,QAAQ;EAAE;EAAU;EAAa,yBAAS,IAAI,QAAQ;EAAG,QAAQ,CAAC;CAAE;AACtE;;AAGA,SAAgB,cAAoB;CAClC,QAAQ;AACV;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAsB;CACpC,OAAO,UAAU;AACnB;AAEA,SAAS,SAAS,MAAY,MAAuB;CACnD,IAAI,KAAK,aAAa,GAAG,OAAO;CAChC,MAAM,OAAQ,KAAiB;CAE/B,OAAO,SAAS,QAAS,SAAS,OAAO,KAAK,WAAW,KAAK;AAChE;;;;;;;AAQA,SAAS,QAAQ,MAAe,SAAkC,QAAwB;CACxF,MAAM,QAAmB,CAAC,IAAI;CAC9B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,SAAS,MAAM,IAAI;EACzB,IAAI,WAAW,KAAA,GAAW;EAC1B,IAAI,QAA0B,OAAO;EACrC,OAAO,UAAU,MAAM;GACrB,MAAM,YAA8B,MAAM;GAC1C,IAAI,SAAS,OAAO,GAAG,GAAG;IACxB,MAAM,UAAkB,CAAC;IACzB,IAAI,QAAQ;IACZ,IAAI,SAA2B,MAAM;IACrC,OAAO,WAAW,MAAM;KACtB,IAAI,SAAS,QAAQ,GAAG,GAAG,SAAS;UAC/B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M,WACjB,MAAM,UACL,QAAQ,QAAQ,UAAU,MAAM,eAAe,KAAK,MAAM,CAAkB,CAAC,CACjF;EACA,MAAM,OAAO,UAAU,KAAK,OAAO;EACnC,KAAK,MAAM,QAAQ,MAAM,MAAM,MAAM,OAAO,CAAC,GAC3C,IAAI,KAAK,eAAe,MAAM,KAAK,YAAY,IAAI;EAErD,OAAO;CACT;AACF;AAEA,SAAS,UAAU,MAAY,MAAuB;CACpD,OAAO,KAAK,aAAa,KAAM,KAAiB,SAAS;AAC3D;AAEA,SAAS,eAAe,SAA2B;CACjD,OAAO,QAAQ,SAAS,OAAO,QAAQ,SAAS;AAClD"}
1
+ {"version":3,"file":"claim.js","names":[],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop() as Element;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `&lt;` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":";;AAcA,IAAI,QAA+B;;AAGnC,SAAgB,cACd,UACA,aACM;CACN,QAAQ;EAAE;EAAU;EAAa,yBAAS,IAAI,QAAQ;EAAG,QAAQ,CAAC;CAAE;AACtE;;AAGA,SAAgB,cAAoB;CAClC,QAAQ;AACV;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAsB;CACpC,OAAO,UAAU;AACnB;AAEA,SAAS,SAAS,MAAY,MAAuB;CACnD,IAAI,KAAK,aAAa,GAAG,OAAO;CAChC,MAAM,OAAQ,KAAiB;CAE/B,OAAO,SAAS,QAAS,SAAS,OAAO,KAAK,WAAW,KAAK;AAChE;;;;;;;AAQA,SAAS,QAAQ,MAAe,SAAkC,QAAwB;CACxF,MAAM,QAAmB,CAAC,IAAI;CAC9B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,SAAS,MAAM,IAAI;EACzB,IAAI,QAA0B,OAAO;EACrC,OAAO,UAAU,MAAM;GACrB,MAAM,YAA8B,MAAM;GAC1C,IAAI,SAAS,OAAO,GAAG,GAAG;IACxB,MAAM,UAAkB,CAAC;IACzB,IAAI,QAAQ;IACZ,IAAI,SAA2B,MAAM;IACrC,OAAO,WAAW,MAAM;KACtB,IAAI,SAAS,QAAQ,GAAG,GAAG,SAAS;UAC/B,IAAI,SAAS,QAAQ,GAAG,GAAG;MAC9B,SAAS;MACT,IAAI,UAAU,GAAG;KACnB;KACA,QAAQ,KAAK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M,OAAO,UAAU,KAAK,OAAO;EACnC,KAAK,MAAM,QAAQ,MAAM,MAAM,MAAM,OAAO,CAAC,GAC3C,IAAI,KAAK,eAAe,MAAM,KAAK,YAAY,IAAI;EAErD,OAAO;CACT;AACF;AAEA,SAAS,UAAU,MAAY,MAAuB;CACpD,OAAO,KAAK,aAAa,KAAM,KAAiB,SAAS;AAC3D;AAEA,SAAS,eAAe,SAA2B;CACjD,OAAO,QAAQ,SAAS,OAAO,QAAQ,SAAS;AAClD"}
@@ -7,7 +7,7 @@
7
7
  * stylesheet writer are the only importers, so it is linked only where a style is written.
8
8
  * @internal
9
9
  */
10
- const UNITLESS = new Set("animation-iteration-count aspect-ratio border-image-outset border-image-slice border-image-width box-flex box-flex-group box-ordinal-group column-count columns flex flex-grow flex-positive flex-shrink flex-negative flex-order grid-area grid-row grid-row-end grid-row-span grid-row-start grid-column grid-column-end grid-column-span grid-column-start font-weight line-clamp line-height opacity order orphans scale tab-size widows z-index zoom fill-opacity flood-opacity stop-opacity stroke-dasharray stroke-dashoffset stroke-miterlimit stroke-opacity stroke-width".split(" "));
10
+ const UNITLESS = /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;
11
11
  /**
12
12
  * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a
13
13
  * custom property (`--x`) or unitless; every other value is `String(value)`.
@@ -18,7 +18,7 @@ const UNITLESS = new Set("animation-iteration-count aspect-ratio border-image-ou
18
18
  function cssValueText(property, value) {
19
19
  if (typeof value !== "number" || value === 0 || property.startsWith("--")) return String(value);
20
20
  const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
21
- return UNITLESS.has(bare) ? String(value) : `${value}px`;
21
+ return UNITLESS.test(bare) ? String(value) : `${value}px`;
22
22
  }
23
23
  export { cssValueText };
24
24
 
@@ -1 +1 @@
1
- {"version":3,"file":"css-units.js","names":[],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS: ReadonlySet<string> = new Set(\n (\n \"animation-iteration-count aspect-ratio border-image-outset border-image-slice \" +\n \"border-image-width box-flex box-flex-group box-ordinal-group column-count columns flex \" +\n \"flex-grow flex-positive flex-shrink flex-negative flex-order grid-area grid-row grid-row-end \" +\n \"grid-row-span grid-row-start grid-column grid-column-end grid-column-span grid-column-start \" +\n \"font-weight line-clamp line-height opacity order orphans scale tab-size widows z-index zoom \" +\n \"fill-opacity flood-opacity stop-opacity stroke-dasharray stroke-dashoffset stroke-miterlimit \" +\n \"stroke-opacity stroke-width\"\n ).split(\" \"),\n);\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.has(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,WAAgC,IAAI,IAEtC,qjBAOA,MAAM,GAAG,CACb;;;;;;;;AASA,SAAgB,aAAa,UAAkB,OAAwB;CACrE,IAAI,OAAO,UAAU,YAAY,UAAU,KAAK,SAAS,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK;CAC9F,MAAM,OAAO,SAAS,QAAQ,0BAA0B,EAAE;CAC1D,OAAO,SAAS,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,GAAG,MAAM;AACvD"}
1
+ {"version":3,"file":"css-units.js","names":[],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS =\n /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.test(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,WACJ;;;;;;;;AASF,SAAgB,aAAa,UAAkB,OAAwB;CACrE,IAAI,OAAO,UAAU,YAAY,UAAU,KAAK,SAAS,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK;CAC9F,MAAM,OAAO,SAAS,QAAQ,0BAA0B,EAAE;CAC1D,OAAO,SAAS,KAAK,IAAI,IAAI,OAAO,KAAK,IAAI,GAAG,MAAM;AACxD"}
@@ -1 +1 @@
1
- {"version":3,"file":"portal-context.js","names":[],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,gBACK,8BAAiC,MAAM,EACrD,MAAM,SACR,CAAC"}
1
+ {"version":3,"file":"portal-context.js","names":[],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n /**\n * Renders a `Portal`'s content into this sink under hydration key `key`. The collectors the\n * renderers provide have it; `Portal` calls it instead of importing the markup writer, so the\n * browser bundle of an app that uses `Portal` does not carry server rendering code. A sink without\n * it receives nothing from `Portal`.\n * @param key The portal's key, `undefined` when the render has no scope (nothing is written).\n * @param children Reads the content: a thunk, because it must be built inside the portal's scope.\n */\n render?(key: string | undefined, children: () => unknown): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,gBACK,8BAAiC,MAAM,EACrD,MAAM,SACR,CAAC"}