@shadow-js/web 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/dev/attributes.d.ts +10 -3
  3. package/dist/dev/attributes.js +27 -49
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +6 -2
  6. package/dist/dev/class-style.js +24 -7
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.d.ts +11 -2
  9. package/dist/dev/control-flow/dynamic.js +56 -39
  10. package/dist/dev/control-flow/dynamic.js.map +1 -1
  11. package/dist/dev/control-flow/portal.js +2 -0
  12. package/dist/dev/control-flow/portal.js.map +1 -1
  13. package/dist/dev/element.js +1 -1
  14. package/dist/dev/element.js.map +1 -1
  15. package/dist/dev/events.js +15 -44
  16. package/dist/dev/events.js.map +1 -1
  17. package/dist/dev/insert.d.ts +15 -5
  18. package/dist/dev/insert.js +35 -13
  19. package/dist/dev/insert.js.map +1 -1
  20. package/dist/dev/internal/claim.d.ts +2 -1
  21. package/dist/dev/internal/claim.js +18 -2
  22. package/dist/dev/internal/claim.js.map +1 -1
  23. package/dist/dev/internal/diagnostics.d.ts +7 -3
  24. package/dist/dev/internal/diagnostics.js +14 -4
  25. package/dist/dev/internal/diagnostics.js.map +1 -1
  26. package/dist/dev/internal/early-events.js +20 -2
  27. package/dist/dev/internal/early-events.js.map +1 -1
  28. package/dist/dev/internal/react-names.js +25 -61
  29. package/dist/dev/internal/react-names.js.map +1 -1
  30. package/dist/dev/internal/reconcile.js +3 -6
  31. package/dist/dev/internal/reconcile.js.map +1 -1
  32. package/dist/dev/jsx/global.d.ts +5 -2
  33. package/dist/dev/jsx/html.d.ts +1 -0
  34. package/dist/dev/resource-hints.js +4 -2
  35. package/dist/dev/resource-hints.js.map +1 -1
  36. package/dist/dev/select-value.js +5 -15
  37. package/dist/dev/select-value.js.map +1 -1
  38. package/dist/dev/server/attributes.d.ts +3 -0
  39. package/dist/dev/server/attributes.js +5 -1
  40. package/dist/dev/server/attributes.js.map +1 -1
  41. package/dist/dev/server/element.js +8 -4
  42. package/dist/dev/server/element.js.map +1 -1
  43. package/dist/dev/server/errors.js +7 -1
  44. package/dist/dev/server/errors.js.map +1 -1
  45. package/dist/dev/server/escape.js +14 -6
  46. package/dist/dev/server/escape.js.map +1 -1
  47. package/dist/dev/server/form-controls.js +5 -2
  48. package/dist/dev/server/form-controls.js.map +1 -1
  49. package/dist/dev/server/index.d.ts +2 -1
  50. package/dist/dev/server/index.js +2 -1
  51. package/dist/dev/server/raw-text.d.ts +28 -0
  52. package/dist/dev/server/raw-text.js +66 -0
  53. package/dist/dev/server/raw-text.js.map +1 -0
  54. package/dist/dev/server/render.d.ts +2 -1
  55. package/dist/dev/server/render.js +2 -2
  56. package/dist/dev/server/render.js.map +1 -1
  57. package/dist/dev/server/stream.d.ts +1 -1
  58. package/dist/dev/server/stream.js +2 -2
  59. package/dist/dev/server/stream.js.map +1 -1
  60. package/dist/dev/server.d.ts +2 -1
  61. package/dist/dev/server.js +2 -1
  62. package/dist/dev/spread.js +7 -54
  63. package/dist/dev/spread.js.map +1 -1
  64. package/dist/prod/attributes.js +1 -1
  65. package/dist/prod/attributes.js.map +1 -1
  66. package/dist/prod/class-style.js +1 -1
  67. package/dist/prod/class-style.js.map +1 -1
  68. package/dist/prod/control-flow/dynamic.js +1 -1
  69. package/dist/prod/control-flow/dynamic.js.map +1 -1
  70. package/dist/prod/control-flow/portal.js +1 -1
  71. package/dist/prod/control-flow/portal.js.map +1 -1
  72. package/dist/prod/element.js +1 -1
  73. package/dist/prod/element.js.map +1 -1
  74. package/dist/prod/events.js +1 -1
  75. package/dist/prod/events.js.map +1 -1
  76. package/dist/prod/insert.js +1 -1
  77. package/dist/prod/insert.js.map +1 -1
  78. package/dist/prod/internal/claim.js +1 -1
  79. package/dist/prod/internal/claim.js.map +1 -1
  80. package/dist/prod/internal/diagnostics.js +1 -1
  81. package/dist/prod/internal/diagnostics.js.map +1 -1
  82. package/dist/prod/internal/early-events.js +1 -1
  83. package/dist/prod/internal/early-events.js.map +1 -1
  84. package/dist/prod/internal/react-names.js +1 -1
  85. package/dist/prod/internal/react-names.js.map +1 -1
  86. package/dist/prod/internal/reconcile.js +1 -1
  87. package/dist/prod/internal/reconcile.js.map +1 -1
  88. package/dist/prod/resource-hints.js +1 -1
  89. package/dist/prod/resource-hints.js.map +1 -1
  90. package/dist/prod/select-value.js +1 -1
  91. package/dist/prod/select-value.js.map +1 -1
  92. package/dist/prod/server/attributes.js +1 -1
  93. package/dist/prod/server/attributes.js.map +1 -1
  94. package/dist/prod/server/element.js +1 -1
  95. package/dist/prod/server/element.js.map +1 -1
  96. package/dist/prod/server/errors.js +1 -1
  97. package/dist/prod/server/errors.js.map +1 -1
  98. package/dist/prod/server/escape.js +1 -1
  99. package/dist/prod/server/escape.js.map +1 -1
  100. package/dist/prod/server/form-controls.js +2 -2
  101. package/dist/prod/server/form-controls.js.map +1 -1
  102. package/dist/prod/server/index.js +1 -1
  103. package/dist/prod/server/raw-text.js +2 -0
  104. package/dist/prod/server/raw-text.js.map +1 -0
  105. package/dist/prod/server/render.js +1 -1
  106. package/dist/prod/server/render.js.map +1 -1
  107. package/dist/prod/server/stream.js +1 -1
  108. package/dist/prod/server/stream.js.map +1 -1
  109. package/dist/prod/server.js +1 -1
  110. package/dist/prod/spread.js +1 -1
  111. package/dist/prod/spread.js.map +1 -1
  112. package/dist/server/attributes.js +1 -1
  113. package/dist/server/attributes.js.map +1 -1
  114. package/dist/server/class-style.js +1 -1
  115. package/dist/server/class-style.js.map +1 -1
  116. package/dist/server/control-flow/dynamic.js +1 -1
  117. package/dist/server/control-flow/dynamic.js.map +1 -1
  118. package/dist/server/control-flow/portal.js +1 -1
  119. package/dist/server/control-flow/portal.js.map +1 -1
  120. package/dist/server/element.js +1 -1
  121. package/dist/server/element.js.map +1 -1
  122. package/dist/server/events.js +1 -1
  123. package/dist/server/events.js.map +1 -1
  124. package/dist/server/insert.js +1 -1
  125. package/dist/server/insert.js.map +1 -1
  126. package/dist/server/internal/claim.js +1 -1
  127. package/dist/server/internal/claim.js.map +1 -1
  128. package/dist/server/internal/diagnostics.js +1 -1
  129. package/dist/server/internal/diagnostics.js.map +1 -1
  130. package/dist/server/internal/early-events.js +1 -1
  131. package/dist/server/internal/early-events.js.map +1 -1
  132. package/dist/server/internal/react-names.js +1 -1
  133. package/dist/server/internal/react-names.js.map +1 -1
  134. package/dist/server/internal/reconcile.js +1 -1
  135. package/dist/server/internal/reconcile.js.map +1 -1
  136. package/dist/server/resource-hints.js +1 -1
  137. package/dist/server/resource-hints.js.map +1 -1
  138. package/dist/server/select-value.js +1 -1
  139. package/dist/server/select-value.js.map +1 -1
  140. package/dist/server/server/attributes.js +1 -1
  141. package/dist/server/server/attributes.js.map +1 -1
  142. package/dist/server/server/element.js +1 -1
  143. package/dist/server/server/element.js.map +1 -1
  144. package/dist/server/server/errors.js +1 -1
  145. package/dist/server/server/errors.js.map +1 -1
  146. package/dist/server/server/escape.js +1 -1
  147. package/dist/server/server/escape.js.map +1 -1
  148. package/dist/server/server/form-controls.js +2 -2
  149. package/dist/server/server/form-controls.js.map +1 -1
  150. package/dist/server/server/index.js +1 -1
  151. package/dist/server/server/raw-text.js +2 -0
  152. package/dist/server/server/raw-text.js.map +1 -0
  153. package/dist/server/server/render.js +1 -1
  154. package/dist/server/server/render.js.map +1 -1
  155. package/dist/server/server/stream.js +1 -1
  156. package/dist/server/server/stream.js.map +1 -1
  157. package/dist/server/server.js +1 -1
  158. package/dist/server/spread.js +1 -1
  159. package/dist/server/spread.js.map +1 -1
  160. package/dist/server-dev/attributes.js +27 -49
  161. package/dist/server-dev/attributes.js.map +1 -1
  162. package/dist/server-dev/class-style.js +24 -7
  163. package/dist/server-dev/class-style.js.map +1 -1
  164. package/dist/server-dev/control-flow/dynamic.js +22 -10
  165. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  166. package/dist/server-dev/control-flow/portal.js +2 -0
  167. package/dist/server-dev/control-flow/portal.js.map +1 -1
  168. package/dist/server-dev/element.js +3 -1
  169. package/dist/server-dev/element.js.map +1 -1
  170. package/dist/server-dev/events.js +15 -44
  171. package/dist/server-dev/events.js.map +1 -1
  172. package/dist/server-dev/insert.js +35 -13
  173. package/dist/server-dev/insert.js.map +1 -1
  174. package/dist/server-dev/internal/claim.js +18 -2
  175. package/dist/server-dev/internal/claim.js.map +1 -1
  176. package/dist/server-dev/internal/diagnostics.js +14 -4
  177. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  178. package/dist/server-dev/internal/early-events.js +20 -2
  179. package/dist/server-dev/internal/early-events.js.map +1 -1
  180. package/dist/server-dev/internal/react-names.js +25 -61
  181. package/dist/server-dev/internal/react-names.js.map +1 -1
  182. package/dist/server-dev/internal/reconcile.js +3 -6
  183. package/dist/server-dev/internal/reconcile.js.map +1 -1
  184. package/dist/server-dev/resource-hints.js +4 -2
  185. package/dist/server-dev/resource-hints.js.map +1 -1
  186. package/dist/server-dev/select-value.js +5 -15
  187. package/dist/server-dev/select-value.js.map +1 -1
  188. package/dist/server-dev/server/attributes.js +5 -1
  189. package/dist/server-dev/server/attributes.js.map +1 -1
  190. package/dist/server-dev/server/element.js +8 -4
  191. package/dist/server-dev/server/element.js.map +1 -1
  192. package/dist/server-dev/server/errors.js +7 -1
  193. package/dist/server-dev/server/errors.js.map +1 -1
  194. package/dist/server-dev/server/escape.js +14 -6
  195. package/dist/server-dev/server/escape.js.map +1 -1
  196. package/dist/server-dev/server/form-controls.js +5 -2
  197. package/dist/server-dev/server/form-controls.js.map +1 -1
  198. package/dist/server-dev/server/index.js +2 -1
  199. package/dist/server-dev/server/raw-text.js +86 -0
  200. package/dist/server-dev/server/raw-text.js.map +1 -0
  201. package/dist/server-dev/server/render.js +2 -2
  202. package/dist/server-dev/server/render.js.map +1 -1
  203. package/dist/server-dev/server/stream.js +2 -2
  204. package/dist/server-dev/server/stream.js.map +1 -1
  205. package/dist/server-dev/server.js +2 -1
  206. package/dist/server-dev/spread.js +7 -54
  207. package/dist/server-dev/spread.js.map +1 -1
  208. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","names":["TAG_PATTERN","element","tag","read","props","ssrElement","children","\"children\"","ssrRaw"],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n return children === undefined\n ? undefined\n : [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\") ref(el);\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":"A,qFAoBA,MAAMA,EAAc,qBAiEpB,SAAgBC,EAAQ,EAAa,EAAwB,CAC3D,GAAI,CAACD,EAAY,KAAKE,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAMC,EAAOC,EAGX,OAAOC,EACLH,EACAE,MACM,CACJ,IAAME,EAAWH,EAAKI,SACtB,OAAOD,IAAa,IAAA,GAChB,IAAA,GACA,CAACE,EAAO,UAAU,EAAGF,EAAUE,EAAO,UAAU,CAAC,CACvD,EACA,EACF,CAgCJ,C"}
1
+ {"version":3,"file":"element.js","names":["TAG_PATTERN","element","tag","read","props","ssrElement","children","\"children\"","isTextOnlyElement","ssrRaw"],"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":"A,8IAqBA,MAAMA,EAAc,qBAiEpB,SAAgBC,EAAQ,EAAa,EAAwB,CAC3D,GAAI,CAACD,EAAY,KAAKE,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAMC,EAAOC,EAGX,OAAOC,EACLH,EACAE,MACM,CACJ,IAAME,EAAWH,EAAKI,SAGtB,OADID,IAAa,IAAA,IAAaE,EAAkBN,CAAG,EAAUI,EACtD,CAACG,EAAO,UAAU,EAAGH,EAAUG,EAAO,UAAU,CAAC,CAC1D,EACA,EACF,CAgCJ,C"}
@@ -1,2 +1,2 @@
1
- import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/* @__PURE__ */ new Set([`click`,`dblclick`,`input`,`keydown`,`keyup`,`keypress`,`pointerdown`,`pointerup`,`pointermove`,`mousedown`,`mouseup`,`mousemove`,`focusin`,`focusout`,`beforeinput`,`touchstart`,`touchend`,`touchmove`,`contextmenu`,`mouseover`,`mouseout`,`pointerover`,`pointerout`]),a=/* @__PURE__ */ new WeakMap;function o(e,t,n,i){Object.defineProperty(n,"currentTarget",{configurable:!0,get:()=>t});try{r(()=>e.fn.call(t,...i))}finally{Reflect.deleteProperty(n,`currentTarget`)}}function s(e,t){return Reflect.get(e,t)}function c(t){e(()=>l(t))}function l(e){let t=`$$${e.type}`,n=`${t}Data`,r=[];for(let i of e.composedPath()){if(e.cancelBubble)break;let a=s(i,t);if(typeof a!=`function`)continue;let c=s(i,n),l={fn:a,data:c,tuple:c!==void 0};try{o(l,i,e,l.tuple?[c,e]:[e])}catch(e){r.push(e)}}let[i]=r;if(r.length===1)throw i;if(r.length>1)throw AggregateError(r,`SHADOW_EVENT_ERRORS`)}function u(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function d(t,n,i,a){let o={capture:i.capture===!0||a};i.once!==void 0&&(o.once=i.once),i.passive!==void 0&&(o.passive=i.passive),i.signal!==void 0&&(o.signal=i.signal);let s=t=>{e(()=>r(()=>i.handleEvent(t)))};return t.addEventListener(n,s,o),()=>{t.removeEventListener(n,s,o)}}function f(e){if(typeof e==`function`)return{fn:e,data:void 0,tuple:!1};if(Array.isArray(e)&&typeof e[0]==`function`)return{fn:e[0],data:e[1],tuple:!0};throw TypeError(`SHADOW_EVENT_HANDLER`)}function p(...e){return function(t){for(let n of e)n.call(this,t)}}function m(e,t=globalThis.document){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n));for(let r of e)n.has(r)||(n.add(r),t.addEventListener(r,c))}function h(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,c);a.delete(e)}}function g(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function _(t,n,a,o,s=!1){if(a==null||a===!1)return;if(u(a))return d(t,n,a,s);let c=f(a),l=`$$${n}`;if(o&&!s&&i.has(n)&&Reflect.get(t,l)===void 0){m([n],g(t));let e=`${l}Data`;return Reflect.set(t,l,c.fn),c.tuple?Reflect.set(t,e,c.data):Reflect.deleteProperty(t,e),()=>{Reflect.get(t,l)===c.fn&&(Reflect.deleteProperty(t,l),Reflect.deleteProperty(t,e))}}let p=n=>{let i=c.tuple?[c.data,n]:[n];e(()=>r(()=>c.fn.call(t,...i)))};return t.addEventListener(n,p,s),()=>{t.removeEventListener(n,p,s)}}function v(e,r,i,a,o){let s=_(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{v as addEventListener,_ as bindEvent,p as chainEvents,h as clearDelegatedEvents,m as delegateEvents};
1
+ import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/,a=/* @__PURE__ */ new WeakMap;function o(e,t,n,i){Object.defineProperty(n,"currentTarget",{configurable:!0,get:()=>t});try{r(()=>e.call(t,...i))}finally{Reflect.deleteProperty(n,`currentTarget`)}}function s(t){e(()=>c(t))}function c(e){let t=`$$${e.type}`,n=`${t}Data`,r=[];for(let i of e.composedPath()){if(e.cancelBubble)break;let a=Reflect.get(i,t);if(typeof a!=`function`)continue;let s=Reflect.get(i,n);try{o(a,i,e,s===void 0?[e]:[s,e])}catch(e){r.push(e)}}let[i]=r;if(r.length===1)throw i;if(r.length>1)throw AggregateError(r,`SHADOW_EVENT_ERRORS`)}function l(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function u(t,n,i,a){let{once:o,passive:s,signal:c}=i,l={capture:i.capture===!0||a,once:o,passive:s,signal:c},u=t=>{e(()=>r(()=>i.handleEvent(t)))};return t.addEventListener(n,u,l),()=>{t.removeEventListener(n,u,l)}}function d(e){if(typeof e==`function`)return{fn:e,data:void 0,tuple:!1};if(Array.isArray(e)&&typeof e[0]==`function`)return{fn:e[0],data:e[1],tuple:!0};throw TypeError(`SHADOW_EVENT_HANDLER`)}function f(...e){return function(t){for(let n of e)n.call(this,t)}}function p(e,t=globalThis.document){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n));for(let r of e)n.has(r)||(n.add(r),t.addEventListener(r,s))}function m(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,s);a.delete(e)}}function h(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function g(t,n,a,o,s=!1){if(a==null||a===!1)return;if(l(a))return u(t,n,a,s);let c=d(a),f=`$$${n}`,m=!c.tuple||c.data!==void 0;if(o&&m&&!s&&i.test(n)&&Reflect.get(t,f)===void 0){p([n],h(t));let e=`${f}Data`;return Reflect.set(t,f,c.fn),c.tuple?Reflect.set(t,e,c.data):Reflect.deleteProperty(t,e),()=>{Reflect.get(t,f)===c.fn&&(Reflect.deleteProperty(t,f),Reflect.deleteProperty(t,e))}}let g=n=>{let i=c.tuple?[c.data,n]:[n];e(()=>r(()=>c.fn.call(t,...i)))};return t.addEventListener(n,g,s),()=>{t.removeEventListener(n,g,s)}}function _(e,r,i,a,o){let s=g(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{_ as addEventListener,g as bindEvent,f as chainEvents,m as clearDelegatedEvents,p as delegateEvents};
2
2
  //# sourceMappingURL=events.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":["holder","DELEGATED_EVENTS","installed","invoke","event","node","untrack","binding","args","expando","key","dispatchDelegated","batch","dispatchPath","dataKey","errors","fn","data","error","first","isListenerObject","handler","bindListenerObject","options","object","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS = new Set([\n \"click\",\n \"dblclick\",\n \"input\",\n \"keydown\",\n \"keyup\",\n \"keypress\",\n \"pointerdown\",\n \"pointerup\",\n \"pointermove\",\n \"mousedown\",\n \"mouseup\",\n \"mousemove\",\n \"focusin\",\n \"focusout\",\n \"beforeinput\",\n \"touchstart\",\n \"touchend\",\n \"touchmove\",\n \"contextmenu\",\n \"mouseover\",\n \"mouseout\",\n \"pointerover\",\n \"pointerout\",\n]);\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(binding: Binding, node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => binding.fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/** Reads a compiler-style expando (`node.$$click`), if present. */\nfunction expando(node: EventTarget, key: string): unknown {\n const holder: object = node;\n return Reflect.get(holder, key);\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = expando(node, key);\n if (typeof fn !== \"function\") continue;\n const data = expando(node, dataKey);\n const binding: Binding = {\n fn: fn as (this: EventTarget, ...args: unknown[]) => unknown,\n data,\n tuple: data !== undefined,\n };\n try {\n invoke(binding, node, event, binding.tuple ? [data, event] : [event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const options: AddEventListenerOptions = { capture: object.capture === true || capture };\n if (object.once !== undefined) options.once = object.once;\n if (object.passive !== undefined) options.passive = object.passive;\n if (object.signal !== undefined) options.signal = object.signal;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n if (delegate && !capture && DELEGATED_EVENTS.has(name) && Reflect.get(el, slot) === undefined) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMC,kBAAmB,IAAI,IAAI,CAC/B,QACA,WACA,QACA,UACA,QACA,WACA,cACA,YACA,cACA,YACA,UACA,YACA,UACA,WACA,cACA,aACA,WACA,YACA,cACA,YACA,WACA,cACA,YACF,CAAC,EAGKC,kBAAY,IAAI,QAUtB,SAASC,EAAO,EAAkB,EAAmB,EAAc,EAAuB,CACxF,OAAO,eAAeC,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWC,CAAK,CAAC,EACrF,GAAI,CACFC,MAAcC,EAAQ,GAAG,KAAKF,EAAM,GAAGG,CAAI,CAAC,CAC9C,QAAU,CACR,QAAQ,eAAeJ,EAAO,eAAe,CAC/C,CACF,CAGA,SAASK,EAAQ,EAAmB,EAAsB,CAExD,OAAO,QAAQ,IAAIT,EAAQU,CAAG,CAChC,CAMA,SAASC,EAAkB,EAAoB,CAG7CC,MAAYC,EAAaT,CAAK,CAAC,CACjC,CAEA,SAASS,EAAa,EAAoB,CACxC,IAAMH,EAAM,KAAKN,EAAM,OACjBU,EAAU,GAAGJ,EAAI,MACjBK,EAAoB,C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AACJ,CAAI,EAAGS,EAAmBV,CAAE,CAAC,EAC7C,IAAMb,EAAU,GAAG0B,EAAK,MAIxB,OAHA,QAAQ,IAAIb,EAAIa,EAAMjC,EAAQ,EAAE,EAC5BA,EAAQ,MAAO,QAAQ,IAAIoB,EAAIb,EAASP,EAAQ,IAAI,EACnD,QAAQ,eAAeoB,EAAIb,CAAO,MAC1B,CACP,QAAQ,IAAIa,EAAIa,CAAI,IAAMjC,EAAQ,KACpC,QAAQ,eAAeoB,EAAIa,CAAI,EAC/B,QAAQ,eAAeb,EAAIb,CAAO,EAEtC,CACF,CACA,IAAMY,EAAY,GAAuB,CACvC,IAAMlB,EAAkBD,EAAQ,MAAQ,CAACA,EAAQ,KAAMH,CAAK,EAAI,CAACA,CAAK,EACtEQ,MAAYN,MAAcC,EAAQ,GAAG,KAAKoB,EAAI,GAAGnB,CAAI,CAAC,CAAC,CACzD,EAEA,OADAmB,EAAG,iBAAiBC,EAAMF,EAAUD,CAAO,MAC9B,CACXE,EAAG,oBAAoBC,EAAMF,EAAUD,CAAO,CAChD,CACF,CA6BA,SAAgBiB,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASJ,EAAUZ,EAAIC,EAAMP,EAASoB,IAAa,GAAMhB,IAAY,EAAI,EAE3EkB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
1
+ {"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","invoke","event","node","untrack","fn","args","dispatchDelegated","batch","dispatchPath","key","dataKey","errors","data","error","first","isListenerObject","handler","bindListenerObject","object","options","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","binding","slot","plain","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(fn: Binding[\"fn\"], node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n invoke(fn as Binding[\"fn\"], node, event, data === undefined ? [event] : [data, event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n const options = {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n const plain = !binding.tuple || binding.data !== undefined;\n if (\n delegate &&\n plain &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAO,EAAmB,EAAmB,EAAc,EAAuB,CACzF,OAAO,eAAeC,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWC,CAAK,CAAC,EACrF,GAAI,CACFC,MAAcC,EAAG,KAAKF,EAAM,GAAGG,CAAI,CAAC,CACtC,QAAU,CACR,QAAQ,eAAeJ,EAAO,eAAe,CAC/C,CACF,CAMA,SAASK,EAAkB,EAAoB,CAG7CC,MAAYC,EAAaP,CAAK,CAAC,CACjC,CAEA,SAASO,EAAa,EAAoB,CACxC,IAAMC,EAAM,KAAKR,EAAM,OACjBS,EAAU,GAAGD,EAAI,MACjBE,EAAoB,CAAC,EAC3B,IAAK,IAAMT,KAAQD,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB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IAAI,EACnD,QAAQ,eAAeb,EAAIZ,CAAO,MAC1B,CACP,QAAQ,IAAIY,EAAIc,CAAI,IAAMD,EAAQ,KACpC,QAAQ,eAAeb,EAAIc,CAAI,EAC/B,QAAQ,eAAed,EAAIZ,CAAO,EAEtC,CACF,CACA,IAAMW,EAAY,GAAuB,CACvC,IAAMhB,EAAkB8B,EAAQ,MAAQ,CAACA,EAAQ,KAAMlC,CAAK,EAAI,CAACA,CAAK,EACtEM,MAAYJ,MAAcgC,EAAQ,GAAG,KAAKb,EAAI,GAAGjB,CAAI,CAAC,CAAC,CACzD,EAEA,OADAiB,EAAG,iBAAiBC,EAAMF,EAAUD,CAAO,MAC9B,CACXE,EAAG,oBAAoBC,EAAMF,EAAUD,CAAO,CAChD,CACF,CA6BA,SAAgBmB,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASN,EAAUZ,EAAIC,EAAMP,EAASsB,IAAa,GAAMlB,IAAY,EAAI,EAE3EoB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
@@ -1,2 +1,2 @@
1
- import{claims as e}from"./internal/hydration-hooks.js";import{reconcileNodes as t}from"./internal/reconcile.js";import{useRenderEffect as n}from"@shadow-js/core";import{createComputation as r,currentOwner as i,disposeOwner as a,readComputation as o}from"@shadow-js/core/extend";function s(e){return e instanceof Document?e:e.ownerDocument??document}function c(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function l(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function u(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}function d(e,t=e=>e()){let n=[],r=[[e]],i=[0],a=/* @__PURE__ */ new Set;for(;r.length>0;){let e=r.length-1,o=r[e],s=i[e]??0;if(o===void 0||s>=o.length){let e=r.pop();e!==void 0&&a.delete(e),i.pop();continue}i[e]=s+1;let c=o[s];for(let e=0;typeof c==`function`;e+=1){if(e>=1e4)throw TypeError(`SHADOW_INSERT_DEPTH`);c=t(c)}if(c!=null&&typeof c!=`boolean`){if(typeof c==`string`)n.push(c);else if(typeof c==`number`)n.push(String(c));else if(c instanceof DocumentFragment)for(let e of c.childNodes)n.push(e);else if(c instanceof Node)n.push(c);else if(Array.isArray(c)){if(a.has(c))throw TypeError(`SHADOW_INSERT_CYCLE`);a.add(c),r.push(c),i.push(0)}else n.push(String(c))}}return n}function f(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!c(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function p(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&c(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=f(e);let t=o.get(n)?.pop();t===void 0&&(t=s(e.parent).createTextNode(n),l(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function m(e,t){if(e.anchor!==null)return e.anchor;let n=t.at(-1);if(n!==void 0)return n.nextSibling;let r=e.marker;return r===null?e.parent.firstChild:r.parentNode===e.parent?r.nextSibling:null}function h(e,n){let r=e.parent,i=e.nodes.filter(e=>e.parentNode===r),a=m(e,i),o=i[0];n.length===0&&o!==void 0&&(e.marker=o.previousSibling),t(r,i,n,a),e.nodes=n,u(e,n)}function g(e,t){h(e,p(e,t))}function _(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=typeof t==`string`?t:String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&c(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=s(e.parent).createTextNode(r);l(e,t),e.parent.insertBefore(t,m(e,n)),e.nodes=[t];return}}g(e,d(t))}function v(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i of d(t))typeof i==`string`||r.has(i)||i.parentNode!==e||(r.add(i),n.push(i));return n}function y(e,t,n){let r=n===void 0?[]:v(e,n),i={parent:e,anchor:t,marker:r.length>0?r[0]?.previousSibling??null:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&l(i,e);return i}function b(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop()??[];for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function x(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;return{begin(){n=/* @__PURE__ */ new Set},call(i){n.add(i);let a=t.get(i);return a===void 0&&(a=r({kind:`memo`,fn:()=>i(),allowWrites:!0,owner:e}),t.set(i,a)),o(a)},prune(){for(let[e,r]of t)n.has(e)||(t.delete(e),a(r))}}}function S(e,t){if(!b(t))return _(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n(typeof t==`function`?t:()=>t,t=>{if(r=t,b(t)){let r=x(i());n(()=>{r.begin();let e=d(t,r.call);return r.prune(),e},t=>{g(e,t)})}else _(e,t)}),r}function C(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function w(e,t){let n=s(e).createTextNode(``);return e.insertBefore(n,t),n}function T(t,n,r,i){let a=r??null;return S(y(t,a,i===void 0?e.current.takeRegion(t,a):i),n)}export{w as anchor,S as bindRegion,y as createRegion,T as insert,C as removeRegion};
1
+ import{claims as e}from"./internal/hydration-hooks.js";import{reconcileNodes as t}from"./internal/reconcile.js";import{useRenderEffect as n}from"@shadow-js/core";import{addCleanup as r,createComputation as i,currentOwner as a,disposeOwner as o,readComputation as s}from"@shadow-js/core/extend";const c=/* @__PURE__ */ new WeakMap;function l(e){return e instanceof Document?e:e.ownerDocument??document}function u(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function d(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function f(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}function p(e,t=e=>e()){let n=[],r=[[e]],i=[0],a=/* @__PURE__ */ new Set;for(;r.length>0;){let e=r.length-1,o=r[e],s=i[e]??0;if(o===void 0||s>=o.length){let e=r.pop();e!==void 0&&a.delete(e),i.pop();continue}i[e]=s+1;let c=o[s];for(let e=0;typeof c==`function`;e+=1){if(e>=1e4)throw TypeError(`SHADOW_INSERT_DEPTH`);c=t(c)}if(c!=null&&typeof c!=`boolean`){if(c instanceof DocumentFragment)for(let e of c.childNodes)n.push(e);else if(c instanceof Node)n.push(c);else if(Array.isArray(c)){if(a.has(c))throw TypeError(`SHADOW_INSERT_CYCLE`);a.add(c),r.push(c),i.push(0)}else n.push(String(c))}}return n}function m(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!u(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function h(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&u(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=m(e);let t=o.get(n)?.pop();t===void 0&&(t=l(e.parent).createTextNode(n),d(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function g(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}function _(e,n){let r=e.parent,i=e.nodes.filter(e=>e.parentNode===r),a=g(e,i.at(-1)),o=i[0];n.length===0&&o!==void 0&&(e.marker=o.previousSibling),t(r,i,n,a),e.nodes=n,f(e,n)}function v(e,t){_(e,h(e,t))}function y(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=typeof t==`string`?t:String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&u(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=l(e.parent).createTextNode(r);d(e,t),e.parent.insertBefore(t,g(e,void 0)),e.nodes=[t];return}}v(e,p(t))}function b(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i of p(t))typeof i==`string`||r.has(i)||i.parentNode!==e||(r.add(i),n.push(i));return n}function x(e,t,n){let r=n===void 0?[]:b(e,n),i={parent:e,anchor:t,marker:r.length>0?r[0]?.previousSibling??null:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&d(i,e);return i}function S(e){let t=e.parent,n=c.get(t);e.owner=a(),c.set(t,e);let i=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||g(n,n.nodes.at(-1))!==i)return;let o=D(t,i);n.anchor=e.marker=o,n.owner&&r(n.owner,()=>o.remove())}function C(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop()??[];for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function w(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;return{begin(){n=/* @__PURE__ */ new Set},call(r){n.add(r);let a=t.get(r);return a===void 0&&(a=i({kind:`memo`,fn:()=>r(),allowWrites:!0,owner:e}),t.set(r,a)),s(a)},prune(){for(let[e,r]of t)n.has(e)||(t.delete(e),o(r))}}}function T(e,t,r){if(!C(t))return y(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let i;return r===!0&&S(e),n(typeof t==`function`?t:()=>t,t=>{if(i=t,C(t)){let r=w(a());n(()=>{r.begin();let e=p(t,r.call);return r.prune(),e},t=>{v(e,t)})}else y(e,t)}),i}function E(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function D(e,t){let n=l(e).createTextNode(``);return e.insertBefore(n,t),n}function O(t,n,r,i){let a=r??null;return T(x(t,a,i===void 0?e.current.takeRegion(t,a):i),n,a===null)}export{D as anchor,T as bindRegion,x as createRegion,O as insert,E as removeRegion};
2
2
  //# sourceMappingURL=insert.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":["documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","flatten","fn","parts","frames","root","cursors","active","top","frame","cursor","done","item","depth","call","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","attached","marker","reconcileRegion","parent","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","containsFunction","stack","createCallCache","memos","touched","createComputation","readComputation","disposeOwner","bindRegion","value","latest","useRenderEffect","cache","currentOwner","removeRegion","anchor","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\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.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n readonly anchor: Node | null;\n marker: Node | 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 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 (typeof item === \"string\") parts.push(item);\n else if (typeof item === \"number\") parts.push(String(item));\n else 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));\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, or its marker. */\nfunction endOf(region: Region, attached: readonly Node[]): Node | null {\n if (region.anchor !== null) return region.anchor;\n const last = attached.at(-1);\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);\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, nodes));\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 = { parent, anchor: anchorNode, marker, nodes, texts: null };\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 * 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.\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\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.\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);\n}\n"],"mappings":"A,sRA0CA,SAASA,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IAAKA,EAAM,IAAIG,CAAI,EACpCH,IAAUG,IAAM,EAAO,sBAAQ,IAAI,IAAI,CAACH,EAAOG,CAAI,CAAC,EAC/D,CAGA,SAASC,EAAW,EAAgB,EAA6B,CAC/D,IAAMJ,EAAQC,EAAO,MACrB,GAAID,IAAU,KACd,IAAIA,aAAiB,IAAK,CACxB,IAAMK,EAAO,IAAI,IAAUC,CAAI,EAC/B,IAAK,IAAMH,KAAQH,EACZK,EAAK,IAAIF,CAAI,GAAGH,EAAM,OAAOG,CAAI,CAE1C,MAAYG,EAAK,SAASN,CAAK,IAAG,EAAO,MAAQ,KAAA,CACnD,CAMA,SAASO,EAAQ,EAAe,EAAwC,GAAOC,EAAG,EAAW,CAC3F,IAAMC,EAAgB,CAAC,EACjBC,EAAsB,CAAC,CAACC,CAAI,CAAC,EAC7BC,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOH,EAAO,OAAS,GAAG,CACxB,IAAMI,EAAMJ,EAAO,OAAS,EACtBK,EAAQL,EAAOI,GACfE,EAASJ,EAAQE,IAAQ,EAC/B,GAAIC,IAAU,IAAA,IAAaC,GAAUD,EAAM,OAAQ,CACjD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ert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","flatten","fn","parts","frames","root","cursors","active","top","frame","cursor","done","item","depth","call","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","reconcileRegion","parent","attached","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","createCallCache","memos","touched","createComputation","readComputation","disposeOwner","bindRegion","value","latest","ordered","useRenderEffect","cache","removeRegion","before","insert","resolvedAnchor","claims"],"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 = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":"A,sSAkBA,MA+BMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IAAKA,EAAM,IAAIG,CAAI,EACpCH,IAAUG,IAAM,EAAO,sBAAQ,IAAI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AAC,GAAGjE,EAAO,KAAK,EAAIiE,EAEjE,IAAIC,EA+BJ,OA9BIC,IAAY,IAAMjB,EAAWlD,CAAM,EAWvCoE,EAViB,OAAOH,GAAU,WAAcA,MAAgCA,EAUrD,GAAQ,CAEjC,GADA,EAAStB,EACLa,EAAiBb,CAAG,EAAG,CACzB,IAAM0B,EAAQX,EAAgBN,EAAa,CAAC,EAC5CgB,MACQ,CACJC,EAAM,MAAM,EACZ,IAAM7D,EAAQF,EAAQqC,EAAK0B,EAAM,IAAI,EAErC,OADAA,EAAM,MAAM,EACL7D,CACT,EACC,GAAU,CACTiC,EAAOzC,EAAQQ,CAAK,CACtB,CACF,CACF,MACEkC,EAAY1C,EAAQ2C,CAAG,CAE3B,CAAC,EACMuB,CACT,CAOA,SAAgBI,EAAa,EAAsB,CACjD,IAAK,IAAMzE,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgByD,EAAO,EAAc,EAA2B,CAC9D,IAAMpD,EAAON,EAAWuC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAajC,EAAMqE,CAAM,EACzBrE,CACT,CAwCA,SAAgBsE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiBxB,GAAc,KAIrC,OAAOe,EADQhB,EAAab,EAAQsC,EADlC1B,IAAY,IAAA,GAAY2B,EAAO,QAAQ,WAAWvC,EAAQsC,CAAc,EAAI1B,CAEvD,EAAGkB,EAAOQ,IAAmB,IAAI,CAC1D,C"}
@@ -1,2 +1,2 @@
1
- import"@shadow-js/core/extend";let e=null;function t(t,n){e={registry:t,recoverable:n,pending:/* @__PURE__ */ new WeakMap,lifted:[]}}function n(){e=null}function r(){return e!==null}function i(e,t){if(e.nodeType!==8)return!1;let n=e.data;return n===t||t===`[`&&n.startsWith(`[b:`)}function a(e,t,n){let r=[e];for(;r.length>0;){let e=r.pop();if(e===void 0)break;let a=e.firstChild;for(;a!==null;){let o=a.nextSibling;if(i(a,`[`)){let r=[],o=1,s=a.nextSibling;for(;s!==null;){if(i(s,`[`))o+=1;else if(i(s,`]`)&&(--o,o===0))break;r.push(s),s=s.nextSibling}let c=s===null?null:s.nextSibling;n.push(r);for(let t of r)e.removeChild(t);e.removeChild(a),s!==null&&e.removeChild(s);let l=t.get(e);l===void 0?t.set(e,[r]):l.push(r),a=c}else a.nodeType===1&&r.push(a),a=o}}e.normalize()}function o(t){let n=e;if(n===null||t===void 0)return null;let r=n.registry.get(t);return r===void 0?(n.recoverable?.(/* @__PURE__ */ Error(`SHADOW_HYDRATION_KEY_MISS`)),null):(n.registry.delete(t),r.removeAttribute(`data-hk`),a(r,n.pending,n.lifted),r)}function s(t,n){let r=e;if(r===null)return;let i=r.pending.get(t)?.shift();if(i!==void 0){for(let e of i)t.insertBefore(e,n);return i}}function c(){return e?.lifted}function l(t){let n=e;e=null;try{return t()}finally{e=n}}const u=`portal:`,d=`/portal:`;function f(t){let n=e;if(n===null||t===void 0||typeof document>`u`)return;let r=document.body;if(r===null)return;let i=Array.from(r.childNodes),a=i.findIndex(e=>m(e,u+t));if(a===-1)return;let o=i.findIndex((e,n)=>n>a&&m(e,d+t));if(o===-1)return;let s=[];for(let e of i.slice(a+1,o))e.nodeType===8&&h(e)?r.removeChild(e):s.push(e);for(let e of[i[a],i[o]])e!==void 0&&r.removeChild(e);for(let e of s){if(e.nodeType!==1)continue;let t=e,r=t.getAttribute(`data-hk`);r!==null&&n.registry.set(r,t);for(let e of Array.from(t.querySelectorAll(`[data-hk]`))){let t=e.getAttribute(`data-hk`);t!==null&&n.registry.set(t,e)}}return s}function p(e){let t=Array.from(e.childNodes);for(let n=0;n<t.length;n+=1){let r=t[n];if(r===void 0||r.nodeType!==8)continue;let i=r.data;if(!i.startsWith(u))continue;let a=t.findIndex((e,t)=>t>n&&m(e,d+i.slice(7))),o=a===-1?n:a;for(let r of t.slice(n,o+1))r.parentNode===e&&e.removeChild(r);n=o}}function m(e,t){return e.nodeType===8&&e.data===t}function h(e){return e.data===`[`||e.data===`]`}export{t as beginClaiming,o as claimElement,f as claimPortal,n as endClaiming,r as isClaiming,c as liftedRegions,p as releaseUnclaimedPortals,s as takeRegion,l as withoutClaiming};
1
+ import"@shadow-js/core/extend";let e=null;function t(t,n){e={registry:t,recoverable:n,pending:/* @__PURE__ */ new WeakMap,lifted:[]}}function n(){e=null}function r(){return e!==null}function i(e,t){if(e.nodeType!==8)return!1;let n=e.data;return n===t||t===`[`&&n.startsWith(`[b:`)}function a(e,t,n){let r=[e];for(;r.length>0;){let e=r.pop();if(e===void 0)break;let a=e.firstChild;for(;a!==null;){let o=a.nextSibling;if(i(a,`[`)){let r=[],o=1,s=a.nextSibling;for(;s!==null;){if(i(s,`[`))o+=1;else if(i(s,`]`)&&(--o,o===0))break;r.push(s),s=s.nextSibling}let c=s===null?null:s.nextSibling;n.push(r);for(let t of r)e.removeChild(t);e.removeChild(a),s!==null&&e.removeChild(s);let l=t.get(e);l===void 0?t.set(e,[r]):l.push(r),a=c}else a.nodeType===1&&r.push(a),a=o}}e.normalize()}function o(t){let n=e;if(n===null||t===void 0)return null;let r=n.registry.get(t);return r===void 0?(n.recoverable?.(/* @__PURE__ */ Error(`SHADOW_HYDRATION_KEY_MISS`)),null):(n.registry.delete(t),r.removeAttribute(`data-hk`),a(r,n.pending,n.lifted),r)}const s=/* @__PURE__ */ new Set([`script`,`style`,`title`,`textarea`]);function c(e){return e.nodeType===1&&s.has(e.localName)}function l(t,n){let r=e;if(r===null)return;let i=r.pending.get(t)?.shift();if(i===void 0)return c(t)?Array.from(t.childNodes):void 0;for(let e of i)t.insertBefore(e,n);return i}function u(){return e?.lifted}function d(t){let n=e;e=null;try{return t()}finally{e=n}}const f=`portal:`,p=`/portal:`;function m(t){let n=e;if(n===null||t===void 0||typeof document>`u`)return;let r=document.body;if(r===null)return;let i=Array.from(r.childNodes),a=i.findIndex(e=>g(e,f+t));if(a===-1)return;let o=i.findIndex((e,n)=>n>a&&g(e,p+t));if(o===-1)return;let s=[];for(let e of i.slice(a+1,o))e.nodeType===8&&_(e)?r.removeChild(e):s.push(e);for(let e of[i[a],i[o]])e!==void 0&&r.removeChild(e);for(let e of s){if(e.nodeType!==1)continue;let t=e,r=t.getAttribute(`data-hk`);r!==null&&n.registry.set(r,t);for(let e of Array.from(t.querySelectorAll(`[data-hk]`))){let t=e.getAttribute(`data-hk`);t!==null&&n.registry.set(t,e)}}return s}function h(e){let t=Array.from(e.childNodes);for(let n=0;n<t.length;n+=1){let r=t[n];if(r===void 0||r.nodeType!==8)continue;let i=r.data;if(!i.startsWith(f))continue;let a=t.findIndex((e,t)=>t>n&&g(e,p+i.slice(7))),o=a===-1?n:a;for(let r of t.slice(n,o+1))r.parentNode===e&&e.removeChild(r);n=o}}function g(e,t){return e.nodeType===8&&e.data===t}function _(e){return e.data===`[`||e.data===`]`}export{t as beginClaiming,o as claimElement,m as claimPortal,n as endClaiming,r as isClaiming,u as liftedRegions,h as releaseUnclaimedPortals,l as takeRegion,d as withoutClaiming};
2
2
  //# sourceMappingURL=claim.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"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/**\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).\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 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":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClC,EAAQ,IACV,CAkBA,SAAgBC,GAAsB,CACpC,OAAOH,IAAU,IACnB,CAEA,SAASI,EAAS,EAAY,EAAuB,CACnD,GAAIC,EAAK,WAAa,EAAG,MAAO,GAChC,IAAMC,EAAQD,EAAiB,KAE/B,OAAOC,IAASC,GAASA,IAAS,KAAOD,EAAK,WAAW,KAAK,CAChE,CAQA,SAASE,EAAQ,EAAe,EAAkC,EAAwB,CACxF,IAAMC,EAAmB,CAACC,CAAI,EAC9B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAASF,EAAM,IAAI,EACzB,GAAIE,IAAW,IAAA,GAAW,MAC1B,IAAIC,EAA0BD,EAAO,WACrC,KAAOC,IAAU,MAAM,CACrB,IAAMC,EAA8BD,EAAM,YAC1C,GAAIR,EAASQ,EAAO,GAAG,EAAG,CACxB,IAAME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,WAAW,CAAC,EAAG,CACrE,IAAMmB,EAAKD,EAAM,aAAa,SAAS,EACnCC,IAAO,MAAMrB,EAAQ,SAAS,IAAIqB,EAAID,CAAK,CACjD,CACF,CACA,OAAO5B,CACT,CAQA,SAAgB8B,EAAwB,EAAkB,CACxD,IAAMT,EAAQ,MAAM,KAAKD,EAAK,UAAU,EACxC,IAAK,IAAIE,EAAO,EAAGA,EAAOD,EAAM,OAAQ,GAAQ,EAAG,CACjD,IAAMU,EAAUV,EAAMC,GACtB,GAAIS,IAAY,IAAA,IAAaA,EAAQ,WAAa,EAAG,SACrD,IAAMtC,EAAQsC,EAAoB,KAClC,GAAI,CAACtC,EAAK,WAAWwB,CAAW,EAAG,SACnC,IAAMO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUhC,EAAM2B,EAAezB,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMuC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMjC,KAAQ8B,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvCzC,EAAK,aAAe6B,GAAMA,EAAK,YAAY7B,CAAI,EAErD,EAAOyC,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOhC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASiC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
1
+ {"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"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":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CA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MO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUlC,EAAM6B,EAAe3B,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMyC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMnC,KAAQgC,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvC3C,EAAK,aAAe+B,GAAMA,EAAK,YAAY/B,CAAI,EAErD,EAAO2C,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOlC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASmC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
@@ -1,2 +1,2 @@
1
- function e(e,t){}function t(e){return/* @__PURE__ */ TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: "${e}"`)}export{t as invalidAttributeName,e as warnOnce};
1
+ function e(e,t,n){}function t(e){return/* @__PURE__ */ TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: "${e}"`)}export{t as invalidAttributeName,e as warnOnce};
2
2
  //# sourceMappingURL=diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\";\n\nconst seen = new Set<WebWarningCode>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":"AAgCA,SAAgBA,EAAS,EAAsB,EAAsB,CAKrE,CAYA,SAAgBC,EAAqB,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCC,EAAK,EAAE,CAE/E,C"}
1
+ {"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one)\n * `SRCDOC_DYNAMIC` (a value computed at run time was written to `srcdoc`, an HTML sink) and\n * `DYNAMIC_SVG_CASE` (`Dynamic` was given an SVG element name in a case SVG does not spell it in).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\"\n | \"SRCDOC_DYNAMIC\"\n | \"DYNAMIC_SVG_CASE\";\n\n/** The codes reported, and the `code:key` pairs of the warnings that pass a key. */\nconst seen = new Set<string>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @param key Optional. With a key the warning is once per `code` and `key` instead of once per code, for a\n * warning about a name where each name deserves a report. Pass a bounded set of keys: each is remembered.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string, key?: string): void {\n if (!__DEV__) return;\n const id = key === undefined ? code : `${code}:${key}`;\n if (seen.has(id)) return;\n seen.add(id);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/**\n * The text of the `SRCDOC_DYNAMIC` warning, shared by the client and the server writer. `srcdoc` is a whole HTML\n * document the frame runs, so it has the trust of `innerHTML`, not of a URL: no scheme check applies to it.\n * @internal\n */\nexport const SRCDOC_DYNAMIC_DETAIL =\n 'A computed value was written to \"srcdoc\". It is an HTML document the frame runs, with the trust of innerHTML: sanitize it, and add the sandbox attribute to the frame.';\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":"AAuCA,SAAgBA,EAAS,EAAsB,EAAgB,EAAoB,CAMnF,CAoBA,SAAgBC,EAAqB,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCC,EAAK,EAAE,CAE/E,C"}
@@ -1,2 +1,2 @@
1
- const e=[`click`,`input`],t=`__SHADOWJS_EARLY__`,n=/^[a-z]+$/;function r(e){return`(function(){var d=document,n=`+JSON.stringify(e.filter(e=>n.test(e)))+`,q=[];function c(e){q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${t}={queue:q,names:n,listener:c};})();`}function i(){let e=Reflect.get(globalThis,t);if(typeof e!=`object`||!e)return;let n=Reflect.get(e,`queue`),r=Reflect.get(e,`names`),i=Reflect.get(e,`listener`);if(Array.isArray(n)&&Array.isArray(r)&&typeof i==`function`)return{queue:n.filter(e=>e instanceof Event),names:r.filter(e=>typeof e==`string`),listener:i}}function a(e){let t={bubbles:!0,cancelable:e.cancelable,composed:!0};return e instanceof MouseEvent?new MouseEvent(e.type,{...t,clientX:e.clientX,clientY:e.clientY,button:e.button,buttons:e.buttons,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey}):new Event(e.type,t)}function o(){let e=i();if(e!==void 0){Reflect.deleteProperty(globalThis,t);for(let t of e.names)document.removeEventListener(t,e.listener,!0);for(let t of e.queue){let e=t.target;e instanceof Node&&e.dispatchEvent(a(t))}}}export{e as DEFAULT_EARLY_EVENTS,t as EARLY_CAPTURE_KEY,r as captureScriptBody,o as replayEarlyEvents};
1
+ const e=[`click`,`input`],t=`__SHADOWJS_EARLY__`,n=/^[a-z]+$/;function r(e){return`(function(){var d=document,n=`+JSON.stringify(e.filter(e=>n.test(e)))+`,q=[];function c(e){if(q.length<100)q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${t}={queue:q,names:n,listener:c};})();`}function i(){let e=Reflect.get(globalThis,t);if(typeof e!=`object`||!e)return;let n=Reflect.get(e,`queue`),r=Reflect.get(e,`names`),i=Reflect.get(e,`listener`);if(Array.isArray(n)&&Array.isArray(r)&&typeof i==`function`)return{queue:n.filter(e=>e instanceof Event),names:r.filter(e=>typeof e==`string`),listener:i}}function a(e){let t={bubbles:!0,cancelable:e.cancelable,composed:!0};return e instanceof MouseEvent?new MouseEvent(e.type,{...t,clientX:e.clientX,clientY:e.clientY,button:e.button,buttons:e.buttons,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey}):new Event(e.type,t)}function o(){let e=i();if(e!==void 0){Reflect.deleteProperty(globalThis,t);for(let t of e.names)document.removeEventListener(t,e.listener,!0);for(let t of e.queue){let e=t.target;e instanceof Node&&e.dispatchEvent(s(a(t)))}}}function s(e){e.preventDefault();let t=!1;return Object.defineProperties(e,{defaultPrevented:{get:()=>t},preventDefault:{value:()=>{t=!0}}}),e}export{e as DEFAULT_EARLY_EVENTS,t as EARLY_CAPTURE_KEY,r as captureScriptBody,o as replayEarlyEvents};
2
2
  //# sourceMappingURL=early-events.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","init","event","replayEarlyEvents","capture","target"],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n \",q=[];function c(e){q.push(e)}\" +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(reissue(event));\n }\n}\n"],"mappings":"AASA,MAAaA,EAA0C,CAAC,QAAS,OAAO,EAG3DC,EAAoB,qBAG3BC,EAAa,WAQnB,SAAgBC,EAAkB,EAAkC,CAElE,MACE,gCAFW,KAAK,UAAUC,EAAM,OAAQ,GAASF,EAAW,KAAKG,CAAI,CAAC,CAGnE,EACH,mGAEUJ,EAAkB,oCAEhC,CASA,SAASK,GAAmC,CAC1C,IAAMC,EAAiB,QAAQ,IAAI,WAAYN,CAAiB,EAChE,GAAI,OAAOM,GAAU,WAAYA,EAAgB,OACjD,IAAMC,EAAiB,QAAQ,IAAID,EAAO,OAAO,EAC3CH,EAAiB,QAAQ,IAAIG,EAAO,OAAO,EAC3CE,EAAoB,QAAQ,IAAIF,EAAO,UAAU,EACvD,GAAK,MAAM,QAAQC,CAAK,GAAM,MAAM,QAAQJ,CAAK,GAAK,OAAOK,GAAa,WAK1E,MAAO,CAAE,MAFMD,EAAM,OAAQ,GAAwBE,aAAgB,KAEhD,EAAG,MADVN,EAAM,OAAQ,GAAyB,OAAOC,GAAS,QAClC,EAAa,UAAmC,CACrF,CAGA,SAASM,EAAQ,EAAqB,CACpC,IAAMC,EAAkB,CAAE,QAAS,GAAM,WAAYC,EAAM,WAAY,SAAU,EAAK,EActF,OAbIA,aAAiB,WACZ,IAAI,WAAWA,EAAM,KAAM,CAChC,GAAGD,EACH,QAASC,EAAM,QACf,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,QAASA,EAAM,QACf,SAAUA,EAAM,QAClB,CAAC,EAEI,IAAI,MAAMA,EAAM,KAAMD,CAAI,CACnC,CAOA,SAAgBE,GAA0B,CACxC,IAAMC,EAAUT,EAAY,EAC5B,GAAIS,IAAY,IAAA,GAChB,SAAQ,eAAe,WAAYd,CAAiB,EACpD,IAAK,IAAMI,KAAQU,EAAQ,MAAO,SAAS,oBAAoBV,EAAMU,EAAQ,SAAU,EAAI,EAC3F,IAAK,IAAMF,KAASE,EAAQ,MAAO,CACjC,IAAMC,EAASH,EAAM,OACjBG,aAAkB,MAAMA,EAAO,cAAcL,EAAQE,CAAK,CAAC,CACjE,CALoD,CAMtD,C"}
1
+ {"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","init","event","replayEarlyEvents","capture","target","withoutDefaultAction","prevented"],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/**\n * The most events the capture script keeps. A page whose bundle never loads would otherwise hold every\n * click and keystroke of the visit; the first ones are the ones worth replaying. @internal\n */\nexport const MAX_EARLY_EVENTS = 100;\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n `,q=[];function c(e){if(q.length<${MAX_EARLY_EVENTS})q.push(e)}` +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(withoutDefaultAction(reissue(event)));\n }\n}\n\n/**\n * The replayed event runs the page's handlers, not the browser's default action: the real event\n * already ran it when the user made it. A dispatched `click` on a link follows the link, so without\n * this a link was followed twice. The native flag is set right away, which cancels the default action,\n * and the handlers still see `defaultPrevented` as false (a router skips a click that is already\n * prevented) until one of them prevents it itself.\n */\nfunction withoutDefaultAction(event: Event): Event {\n event.preventDefault();\n let prevented = false;\n Object.defineProperties(event, {\n defaultPrevented: { get: () => prevented },\n preventDefault: {\n value: () => {\n prevented = true;\n },\n },\n });\n return event;\n}\n"],"mappings":"AASA,MAAaA,EAA0C,CAAC,QAAS,OAAO,EAG3DC,EAAoB,qBAS3BC,EAAa,WAQnB,SAAgBC,EAAkB,EAAkC,CAElE,MACE,gCAFW,KAAK,UAAUC,EAAM,OAAQ,GAASF,EAAW,KAAKG,CAAI,CAAC,CAGnE,EACH,mHAEUJ,EAAkB,oCAEhC,CASA,SAASK,GAAmC,CAC1C,IAAMC,EAAiB,QAAQ,IAAI,WAAYN,CAAiB,EAChE,GAAI,OAAOM,GAAU,WAAYA,EAAgB,OACjD,IAAMC,EAAiB,QAAQ,IAAID,EAAO,OAAO,EAC3CH,EAAiB,QAAQ,IAAIG,EAAO,OAAO,EAC3CE,EAAoB,QAAQ,IAAIF,EAAO,UAAU,EACvD,GAAK,MAAM,QAAQC,CAAK,GAAM,MAAM,QAAQJ,CAAK,GAAK,OAAOK,GAAa,WAK1E,MAAO,CAAE,MAFMD,EAAM,OAAQ,GAAwBE,aAAgB,KAEhD,EAAG,MADVN,EAAM,OAAQ,GAAyB,OAAOC,GAAS,QAClC,EAAa,UAAmC,CACrF,CAGA,SAASM,EAAQ,EAAqB,CACpC,IAAMC,EAAkB,CAAE,QAAS,GAAM,WAAYC,EAAM,WAAY,SAAU,EAAK,EActF,OAbIA,aAAiB,WACZ,IAAI,WAAWA,EAAM,KAAM,CAChC,GAAGD,EACH,QAASC,EAAM,QACf,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,QAASA,EAAM,QACf,SAAUA,EAAM,QAClB,CAAC,EAEI,IAAI,MAAMA,EAAM,KAAMD,CAAI,CACnC,CAOA,SAAgBE,GAA0B,CACxC,IAAMC,EAAUT,EAAY,EAC5B,GAAIS,IAAY,IAAA,GAChB,SAAQ,eAAe,WAAYd,CAAiB,EACpD,IAAK,IAAMI,KAAQU,EAAQ,MAAO,SAAS,oBAAoBV,EAAMU,EAAQ,SAAU,EAAI,EAC3F,IAAK,IAAMF,KAASE,EAAQ,MAAO,CACjC,IAAMC,EAASH,EAAM,OACjBG,aAAkB,MAAMA,EAAO,cAAcC,EAAqBN,EAAQE,CAAK,CAAC,CAAC,CACvF,CALoD,CAMtD,CASA,SAASI,EAAqB,EAAqB,CACjDJ,EAAM,eAAe,EACrB,IAAIK,EAAY,GAShB,OARA,OAAO,iBAAiBL,EAAO,CAC7B,iBAAkB,CAAE,QAAWK,CAAU,EACzC,eAAgB,CACd,UAAa,CACX,EAAY,EACd,CACF,CACF,CAAC,EACML,CACT,C"}
@@ -1,2 +1,2 @@
1
- const e=/^(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/,t=/* @__PURE__ */ new Set([`clipPathUnits`,`glyphRef`,`markerHeight`,`markerUnits`,`markerWidth`,`maskContentUnits`,`maskUnits`,`textLength`]);function n(n,i){if(n===`className`)return`class`;if(n===`htmlFor`)return`for`;if(n===`httpEquiv`)return`http-equiv`;if(n===`acceptCharset`)return`accept-charset`;if(!i)return n.toLowerCase();if(n.includes(`:`))return n;let a=/^xlink([A-Z].*)$/.exec(n);if(a!==null)return`xlink:${r(a[1]??``)}`;let o=/^xml([A-Z].*)$/.exec(n);return o===null?t.has(n)||!e.test(n)?n:n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`):`xml:${r(o[1]??``)}`}function r(e){return e.replace(/^[A-Z]/,e=>e.toLowerCase())}const i=/* @__PURE__ */ new Set([`key`,`suppressHydrationWarning`,`suppressContentEditableWarning`]),a=/* @__PURE__ */ new Set([`checkbox`,`radio`,`file`]);function o(e,t,n){let r=/^on[A-Z]/.test(e),i=r&&e.endsWith(`Capture`),o=e.slice(2,i?-7:void 0);if(!r)return{type:o.toLowerCase(),capture:!1,passive:!1};let s=o.toLowerCase();return s===`change`?{type:t===`textarea`||t===`input`&&(n===null||!a.has(n))?`input`:`change`,capture:i,passive:!1}:s===`focus`?{type:`focusin`,capture:i,passive:!1}:s===`blur`?{type:`focusout`,capture:i,passive:!1}:s===`doubleclick`?{type:`dblclick`,capture:i,passive:!1}:s===`wheel`?{type:`wheel`,capture:i,passive:!i}:{type:s,capture:i,passive:!1}}export{i as IGNORED_KEYS,n as attributeName,o as eventPlan};
1
+ const e=/^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/,t=/* @__PURE__ */ new Map([[`className`,`class`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`],[`acceptCharset`,`accept-charset`]]);function n(n,r){let i=t.get(n);if(i!==void 0)return i;if(!r)return n.toLowerCase();if(n.includes(`:`))return n;let a=/^(xlink|xml)([A-Z])(.*)$/.exec(n);return a===null?e.test(n)?n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`):n:`${a[1]}:${a[2]?.toLowerCase()}${a[3]}`}const r=/* @__PURE__ */ new Set([`key`,`suppressHydrationWarning`,`suppressContentEditableWarning`]),i=/* @__PURE__ */ new Map([[`focus`,`focusin`],[`blur`,`focusout`],[`doubleclick`,`dblclick`]]),a=/* @__PURE__ */ new Set([`checkbox`,`radio`,`file`]);function o(e,t,n){let r=/^on[A-Z]/.test(e),o=r&&e.endsWith(`Capture`),s=e.slice(2,o?-7:void 0).toLowerCase(),c=s;return r&&(c=s===`change`?t===`textarea`||t===`input`&&(n===null||!a.has(n))?`input`:`change`:i.get(s)??s),{type:c,capture:o,passive:r&&s===`wheel`&&!o}}export{r as IGNORED_KEYS,n as attributeName,o as eventPlan};
2
2
  //# sourceMappingURL=react-names.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","SVG_CAMEL_ATTRIBUTES","attributeName","name","svg","xlink","lowerFirst","xml","letter","text","IGNORED_KEYS","CHANGE_ON_TYPES","eventPlan","reactSpelling","attribute","capture","base","lower","tag","type"],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/**\n * SVG attributes that start with a property family but are not CSS properties (`clipPathUnits`,\n * `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_CAMEL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"clipPathUnits\",\n \"glyphRef\",\n \"markerHeight\",\n \"markerUnits\",\n \"markerWidth\",\n \"maskContentUnits\",\n \"maskUnits\",\n \"textLength\",\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n if (name === \"className\") return \"class\";\n if (name === \"htmlFor\") return \"for\";\n if (name === \"httpEquiv\") return \"http-equiv\";\n if (name === \"acceptCharset\") return \"accept-charset\";\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const xlink = /^xlink([A-Z].*)$/.exec(name);\n if (xlink !== null) return `xlink:${lowerFirst(xlink[1] ?? \"\")}`;\n const xml = /^xml([A-Z].*)$/.exec(name);\n if (xml !== null) return `xml:${lowerFirst(xml[1] ?? \"\")}`;\n if (SVG_CAMEL_ATTRIBUTES.has(name) || !SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\nfunction lowerFirst(text: string): string {\n return text.replace(/^[A-Z]/, (letter) => letter.toLowerCase());\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: ReadonlySet<string> = new Set([\n \"key\",\n \"suppressHydrationWarning\",\n \"suppressContentEditableWarning\",\n]);\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\nconst CHANGE_ON_TYPES: ReadonlySet<string> = new Set([\"checkbox\", \"radio\", \"file\"]);\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const base = attribute.slice(2, capture ? -\"Capture\".length : undefined);\n if (!reactSpelling) return { type: base.toLowerCase(), capture: false, passive: false };\n const lower = base.toLowerCase();\n if (lower === \"change\") {\n const perEdit =\n tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.has(type)));\n return { type: perEdit ? \"input\" : \"change\", capture, passive: false };\n }\n if (lower === \"focus\") return { type: \"focusin\", capture, passive: false };\n if (lower === \"blur\") return { type: \"focusout\", capture, passive: false };\n if (lower === \"doubleclick\") return { type: \"dblclick\", capture, passive: false };\n if (lower === \"wheel\") return { type: \"wheel\", capture, passive: !capture };\n return { type: lower, capture, passive: false };\n}\n"],"mappings":"AAeA,MAAMA,EACJ,2MAMIC,kBAA4C,IAAI,IAAI,CACxD,gBACA,WACA,eACA,cACA,cACA,mBACA,YACA,YACF,CAAC,EAQD,SAAgBC,EAAc,EAAc,EAAsB,CAChE,GAAIC,IAAS,YAAa,MAAO,QACjC,GAAIA,IAAS,UAAW,MAAO,MAC/B,GAAIA,IAAS,YAAa,MAAO,aACjC,GAAIA,IAAS,gBAAiB,MAAO,iBACrC,GAAI,CAACC,EAAK,OAAOD,EAAK,YAAY,EAClC,GAAIA,EAAK,SAAS,GAAG,EAAG,OAAOA,EAC/B,IAAME,EAAQ,mBAAmB,KAAKF,CAAI,EAC1C,GAAIE,IAAU,KAAM,MAAO,SAASC,EAAWD,EAAM,IAAM,EAAE,IAC7D,IAAME,EAAM,iBAAiB,KAAKJ,CAAI,EAGtC,OAFII,IAAQ,KACRN,EAAqB,IAAIE,CAAI,GAAK,CAACH,EAAoB,KAAKG,CAAI,EAAUA,EACvEA,EAAK,QAAQ,SAAW,GAAW,IAAIK,EAAO,YAAY,GAAG,EAF3C,OAAOF,EAAWC,EAAI,IAAM,EAAE,GAGzD,CAEA,SAASD,EAAW,EAAsB,CACxC,OAAOG,EAAK,QAAQ,SAAW,GAAWD,EAAO,YAAY,CAAC,CAChE,CAGA,MAAaE,kBAAoC,IAAI,IAAI,CACvD,MACA,2BACA,gCACF,CAAC,EASKC,kBAAuC,IAAI,IAAI,CAAC,WAAY,QAAS,MAAM,CAAC,EASlF,SAAgBC,EAAU,EAAmB,EAAa,EAAgC,CACxF,IAAMC,EAAgB,WAAW,KAAKC,CAAS,EACzCC,EAAUF,GAAiBC,EAAU,SAAS,SAAS,EACvDE,EAAOF,EAAU,MAAM,EAAGC,EAAU,GAAoB,IAAA,EAAS,EACvE,GAAI,CAACF,EAAe,MAAO,CAAE,KAAMG,EAAK,YAAY,EAAG,QAAS,GAAO,QAAS,EAAM,EACtF,IAAMC,EAAQD,EAAK,YAAY,EAU/B,OATIC,IAAU,SAGL,CAAE,KADPC,IAAQ,YAAeA,IAAQ,UAAYC,IAAS,MAAQ,CAACR,EAAgB,IAAIQ,CAAI,GAC9D,QAAU,SAAU,UAAS,QAAS,EAAM,EAEnEF,IAAU,QAAgB,CAAE,KAAM,UAAW,UAAS,QAAS,EAAM,EACrEA,IAAU,OAAe,CAAE,KAAM,WAAY,UAAS,QAAS,EAAM,EACrEA,IAAU,cAAsB,CAAE,KAAM,WAAY,UAAS,QAAS,EAAM,EAC5EA,IAAU,QAAgB,CAAE,KAAM,QAAS,UAAS,QAAS,CAACF,CAAQ,EACnE,CAAE,KAAME,EAAO,UAAS,QAAS,EAAM,CAChD,C"}
1
+ {"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","RENAMED","attributeName","renamed","name","svg","prefixed","letter","IGNORED_KEYS","REACT_EVENTS","CHANGE_ON_TYPES","eventPlan","reactSpelling","attribute","capture","lower","planned","tag","type"],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: ReadonlySet<string> = new Set([\n \"key\",\n \"suppressHydrationWarning\",\n \"suppressContentEditableWarning\",\n]);\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES: ReadonlySet<string> = new Set([\"checkbox\", \"radio\", \"file\"]);\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.has(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n"],"mappings":"AAgBA,MAAMA,EACJ,mSAGIC,kBAAuC,IAAI,IAAI,CACnD,CAAC,YAAa,OAAO,EACrB,CAAC,UAAW,KAAK,EACjB,CAAC,YAAa,YAAY,EAC1B,CAAC,gBAAiB,gBAAgB,CACpC,CAAC,EAQD,SAAgBC,EAAc,EAAc,EAAsB,CAChE,IAAMC,EAAUF,EAAQ,IAAIG,CAAI,EAChC,GAAID,IAAY,IAAA,GAAW,OAAOA,EAClC,GAAI,CAACE,EAAK,OAAOD,EAAK,YAAY,EAClC,GAAIA,EAAK,SAAS,GAAG,EAAG,OAAOA,EAC/B,IAAME,EAAW,2BAA2B,KAAKF,CAAI,EAGrD,OAFIE,IAAa,KACZN,EAAoB,KAAKI,CAAI,EAC3BA,EAAK,QAAQ,SAAW,GAAW,IAAIG,EAAO,YAAY,GAAG,EADxBH,EADd,GAAGE,EAAS,GAAG,GAAGA,EAAS,EAAE,EAAE,YAAY,IAAIA,EAAS,IAGxF,CAGA,MAAaE,kBAAoC,IAAI,IAAI,CACvD,MACA,2BACA,gCACF,CAAC,EAUKC,kBAA4C,IAAI,IAAI,CACxD,CAAC,QAAS,SAAS,EACnB,CAAC,OAAQ,UAAU,EACnB,CAAC,cAAe,UAAU,CAC5B,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CAAC,WAAY,QAAS,MAAM,CAAC,EASlF,SAAgBC,EAAU,EAAmB,EAAa,EAAgC,CACxF,IAAMC,EAAgB,WAAW,KAAKC,CAAS,EACzCC,EAAUF,GAAiBC,EAAU,SAAS,SAAS,EACvDE,EAAQF,EAAU,MAAM,EAAGC,EAAU,GAAoB,IAAA,EAAS,CAAC,CAAC,YAAY,EAClFE,EAAUD,EASd,OARIH,IACF,EACEG,IAAU,SACNE,IAAQ,YAAeA,IAAQ,UAAYC,IAAS,MAAQ,CAACR,EAAgB,IAAIQ,CAAI,GACnF,QACA,SACDT,EAAa,IAAIM,CAAK,GAAKA,GAE7B,CAAE,KAAMC,EAAS,UAAS,QAASJ,GAAiBG,IAAU,SAAW,CAACD,CAAQ,CAC3F,C"}
@@ -1,2 +1,2 @@
1
- function e(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function t(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t]??0,a=0,o=r.length;for(;a<o;){let t=a+o>>1;(e[r[t]??0]??0)<n?a=t+1:o=t}i[t]=a>0?r[a-1]??-1:-1,r[a]=t}let a=r.length>0?r[r.length-1]??-1:-1;for(;a!==-1;)n[(e[a]??0)-t]=1,a=i[a]??-1}function n(n,r,i,a){let o=r.length,s=i.length,c=0;for(;c<o&&c<s&&r[c]===i[c];)c+=1;let l=o,u=s;for(;l>c&&u>c&&r[l-1]===i[u-1];)--l,--u;if(l===c&&u===c)return;let d=u<s?i[u]??null:a;if(u===c){for(let t=c;t<l;t+=1)e(n,r[t]);return}let f=/* @__PURE__ */ new Map;for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&f.set(t,e)}let p=[];for(let t=c;t<l;t+=1){let i=r[t];if(i===void 0)continue;let a=f.get(i);a===void 0?e(n,i):p.push(a)}if(p.length===0){for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&n.insertBefore(t,d)}return}let m=new Uint8Array(u-c);t(p,c,m);let h=typeof n.moveBefore==`function`,g=d;for(let e=u-1;e>=c;--e){let t=i[e];t!==void 0&&(m[e-c]!==1&&(h&&t.parentNode===n?n.moveBefore(t,g):n.insertBefore(t,g)),g=t)}}export{n as reconcileNodes};
1
+ function e(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function t(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t]??0,a=0,o=r.length;for(;a<o;){let t=a+o>>1;(e[r[t]??0]??0)<n?a=t+1:o=t}i[t]=r[a-1]??-1,r[a]=t}let a=r.at(-1)??-1;for(;a!==-1;)n[(e[a]??0)-t]=1,a=i[a]??-1}function n(n,r,i,a){let o=r.length,s=i.length,c=0;for(;c<o&&c<s&&r[c]===i[c];)c+=1;let l=o,u=s;for(;l>c&&u>c&&r[l-1]===i[u-1];)--l,--u;if(l===c&&u===c)return;let d=u<s?i[u]??null:a;if(u===c){for(let t=c;t<l;t+=1)e(n,r[t]);return}let f=/* @__PURE__ */ new Map;for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&f.set(t,e)}let p=[];for(let t=c;t<l;t+=1){let i=r[t];if(i===void 0)continue;let a=f.get(i);a===void 0?e(n,i):p.push(a)}if(p.length===0){for(let e of i.slice(c,u))n.insertBefore(e,d);return}let m=new Uint8Array(u-c);t(p,c,m);let h=typeof n.moveBefore==`function`,g=d;for(let e=u-1;e>=c;--e){let t=i[e];t!==void 0&&(m[e-c]!==1&&(h&&t.parentNode===n?n.moveBefore(t,g):n.insertBefore(t,g)),g=t)}}export{n as reconcileNodes};
2
2
  //# sourceMappingURL=reconcile.js.map