@shadow-js/web 1.0.2 → 1.0.4

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 (195) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -3
  3. package/dist/dev/attributes.js +1 -5
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +10 -5
  6. package/dist/dev/class-style.js +44 -47
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.js +2 -2
  9. package/dist/dev/control-flow/dynamic.js.map +1 -1
  10. package/dist/dev/control-flow/error-boundary.js +2 -2
  11. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  12. package/dist/dev/control-flow/portal.d.ts +2 -2
  13. package/dist/dev/control-flow/portal.js +15 -13
  14. package/dist/dev/control-flow/portal.js.map +1 -1
  15. package/dist/dev/control-flow/suspense-list.js +2 -2
  16. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  17. package/dist/dev/control-flow/suspense.js +2 -2
  18. package/dist/dev/control-flow/suspense.js.map +1 -1
  19. package/dist/dev/element.js +13 -27
  20. package/dist/dev/element.js.map +1 -1
  21. package/dist/dev/events.js +64 -80
  22. package/dist/dev/events.js.map +1 -1
  23. package/dist/dev/extend.d.ts +2 -2
  24. package/dist/dev/extend.js +2 -2
  25. package/dist/dev/insert.d.ts +11 -0
  26. package/dist/dev/insert.js +99 -100
  27. package/dist/dev/insert.js.map +1 -1
  28. package/dist/dev/internal/accessor.js +56 -0
  29. package/dist/dev/internal/accessor.js.map +1 -0
  30. package/dist/dev/internal/claim.js +0 -1
  31. package/dist/dev/internal/claim.js.map +1 -1
  32. package/dist/dev/internal/css-units.js +2 -2
  33. package/dist/dev/internal/css-units.js.map +1 -1
  34. package/dist/dev/internal/portal-context.d.ts +9 -0
  35. package/dist/dev/internal/portal-context.js.map +1 -1
  36. package/dist/dev/internal/react-names.js +22 -12
  37. package/dist/dev/internal/react-names.js.map +1 -1
  38. package/dist/dev/internal/reconcile.d.ts +2 -1
  39. package/dist/dev/internal/reconcile.js +23 -8
  40. package/dist/dev/internal/reconcile.js.map +1 -1
  41. package/dist/dev/server/attributes.js +1 -31
  42. package/dist/dev/server/attributes.js.map +1 -1
  43. package/dist/dev/server/element.js +5 -6
  44. package/dist/dev/server/element.js.map +1 -1
  45. package/dist/dev/server/index.js +1 -1
  46. package/dist/dev/server/portals.js +3 -0
  47. package/dist/dev/server/portals.js.map +1 -1
  48. package/dist/dev/server/render.js +1 -1
  49. package/dist/dev/server/stream.js +1 -1
  50. package/dist/dev/server.js +1 -1
  51. package/dist/dev/spread.js +95 -106
  52. package/dist/dev/spread.js.map +1 -1
  53. package/dist/dev/template.js +1 -3
  54. package/dist/dev/template.js.map +1 -1
  55. package/dist/dev/view-transition.js +12 -4
  56. package/dist/dev/view-transition.js.map +1 -1
  57. package/dist/prod/attributes.js +1 -1
  58. package/dist/prod/attributes.js.map +1 -1
  59. package/dist/prod/class-style.js +1 -1
  60. package/dist/prod/class-style.js.map +1 -1
  61. package/dist/prod/control-flow/dynamic.js +1 -1
  62. package/dist/prod/control-flow/dynamic.js.map +1 -1
  63. package/dist/prod/control-flow/error-boundary.js +1 -1
  64. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  65. package/dist/prod/control-flow/portal.js +1 -1
  66. package/dist/prod/control-flow/portal.js.map +1 -1
  67. package/dist/prod/control-flow/suspense-list.js +1 -1
  68. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  69. package/dist/prod/control-flow/suspense.js +1 -1
  70. package/dist/prod/control-flow/suspense.js.map +1 -1
  71. package/dist/prod/element.js +1 -1
  72. package/dist/prod/element.js.map +1 -1
  73. package/dist/prod/events.js +1 -1
  74. package/dist/prod/events.js.map +1 -1
  75. package/dist/prod/extend.js +1 -1
  76. package/dist/prod/insert.js +1 -1
  77. package/dist/prod/insert.js.map +1 -1
  78. package/dist/prod/internal/accessor.js +2 -0
  79. package/dist/prod/internal/accessor.js.map +1 -0
  80. package/dist/prod/internal/claim.js +1 -1
  81. package/dist/prod/internal/claim.js.map +1 -1
  82. package/dist/prod/internal/css-units.js +1 -1
  83. package/dist/prod/internal/css-units.js.map +1 -1
  84. package/dist/prod/internal/portal-context.js.map +1 -1
  85. package/dist/prod/internal/react-names.js +1 -1
  86. package/dist/prod/internal/react-names.js.map +1 -1
  87. package/dist/prod/internal/reconcile.js +1 -1
  88. package/dist/prod/internal/reconcile.js.map +1 -1
  89. package/dist/prod/server/attributes.js +1 -1
  90. package/dist/prod/server/attributes.js.map +1 -1
  91. package/dist/prod/server/element.js +1 -1
  92. package/dist/prod/server/element.js.map +1 -1
  93. package/dist/prod/server/index.js +1 -1
  94. package/dist/prod/server/portals.js +1 -1
  95. package/dist/prod/server/portals.js.map +1 -1
  96. package/dist/prod/server/render.js +1 -1
  97. package/dist/prod/server/stream.js +1 -1
  98. package/dist/prod/server.js +1 -1
  99. package/dist/prod/spread.js +1 -1
  100. package/dist/prod/spread.js.map +1 -1
  101. package/dist/prod/template.js +1 -1
  102. package/dist/prod/template.js.map +1 -1
  103. package/dist/prod/view-transition.js +1 -1
  104. package/dist/prod/view-transition.js.map +1 -1
  105. package/dist/server/attributes.js +1 -1
  106. package/dist/server/attributes.js.map +1 -1
  107. package/dist/server/class-style.js +1 -1
  108. package/dist/server/class-style.js.map +1 -1
  109. package/dist/server/control-flow/dynamic.js.map +1 -1
  110. package/dist/server/control-flow/error-boundary.js +1 -1
  111. package/dist/server/control-flow/error-boundary.js.map +1 -1
  112. package/dist/server/control-flow/portal.js +1 -1
  113. package/dist/server/control-flow/portal.js.map +1 -1
  114. package/dist/server/control-flow/suspense-list.js +1 -1
  115. package/dist/server/control-flow/suspense-list.js.map +1 -1
  116. package/dist/server/control-flow/suspense.js +1 -1
  117. package/dist/server/control-flow/suspense.js.map +1 -1
  118. package/dist/server/element.js.map +1 -1
  119. package/dist/server/events.js +1 -1
  120. package/dist/server/events.js.map +1 -1
  121. package/dist/server/extend.js +1 -1
  122. package/dist/server/insert.js +1 -1
  123. package/dist/server/insert.js.map +1 -1
  124. package/dist/server/internal/accessor.js +2 -0
  125. package/dist/server/internal/accessor.js.map +1 -0
  126. package/dist/server/internal/claim.js +1 -1
  127. package/dist/server/internal/claim.js.map +1 -1
  128. package/dist/server/internal/css-units.js +1 -1
  129. package/dist/server/internal/css-units.js.map +1 -1
  130. package/dist/server/internal/portal-context.js.map +1 -1
  131. package/dist/server/internal/react-names.js +1 -1
  132. package/dist/server/internal/react-names.js.map +1 -1
  133. package/dist/server/internal/reconcile.js +1 -1
  134. package/dist/server/internal/reconcile.js.map +1 -1
  135. package/dist/server/server/attributes.js +1 -1
  136. package/dist/server/server/attributes.js.map +1 -1
  137. package/dist/server/server/element.js +1 -1
  138. package/dist/server/server/element.js.map +1 -1
  139. package/dist/server/server/index.js +1 -1
  140. package/dist/server/server/portals.js +1 -1
  141. package/dist/server/server/portals.js.map +1 -1
  142. package/dist/server/server/render.js +1 -1
  143. package/dist/server/server/stream.js +1 -1
  144. package/dist/server/server.js +1 -1
  145. package/dist/server/spread.js +1 -1
  146. package/dist/server/spread.js.map +1 -1
  147. package/dist/server/template.js +1 -1
  148. package/dist/server/template.js.map +1 -1
  149. package/dist/server/view-transition.js.map +1 -1
  150. package/dist/server-dev/attributes.js +1 -5
  151. package/dist/server-dev/attributes.js.map +1 -1
  152. package/dist/server-dev/class-style.js +44 -47
  153. package/dist/server-dev/class-style.js.map +1 -1
  154. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  155. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  156. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  157. package/dist/server-dev/control-flow/portal.js +15 -13
  158. package/dist/server-dev/control-flow/portal.js.map +1 -1
  159. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  160. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  161. package/dist/server-dev/control-flow/suspense.js +2 -2
  162. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  163. package/dist/server-dev/element.js.map +1 -1
  164. package/dist/server-dev/events.js +64 -80
  165. package/dist/server-dev/events.js.map +1 -1
  166. package/dist/server-dev/extend.js +2 -2
  167. package/dist/server-dev/insert.js +99 -100
  168. package/dist/server-dev/insert.js.map +1 -1
  169. package/dist/server-dev/internal/accessor.js +56 -0
  170. package/dist/server-dev/internal/accessor.js.map +1 -0
  171. package/dist/server-dev/internal/claim.js +0 -1
  172. package/dist/server-dev/internal/claim.js.map +1 -1
  173. package/dist/server-dev/internal/css-units.js +2 -2
  174. package/dist/server-dev/internal/css-units.js.map +1 -1
  175. package/dist/server-dev/internal/portal-context.js.map +1 -1
  176. package/dist/server-dev/internal/react-names.js +22 -12
  177. package/dist/server-dev/internal/react-names.js.map +1 -1
  178. package/dist/server-dev/internal/reconcile.js +23 -8
  179. package/dist/server-dev/internal/reconcile.js.map +1 -1
  180. package/dist/server-dev/server/attributes.js +1 -31
  181. package/dist/server-dev/server/attributes.js.map +1 -1
  182. package/dist/server-dev/server/element.js +5 -6
  183. package/dist/server-dev/server/element.js.map +1 -1
  184. package/dist/server-dev/server/index.js +1 -1
  185. package/dist/server-dev/server/portals.js +3 -0
  186. package/dist/server-dev/server/portals.js.map +1 -1
  187. package/dist/server-dev/server/render.js +1 -1
  188. package/dist/server-dev/server/stream.js +1 -1
  189. package/dist/server-dev/server.js +1 -1
  190. package/dist/server-dev/spread.js +81 -105
  191. package/dist/server-dev/spread.js.map +1 -1
  192. package/dist/server-dev/template.js +1 -3
  193. package/dist/server-dev/template.js.map +1 -1
  194. package/dist/server-dev/view-transition.js.map +1 -1
  195. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"class-style.js","names":["collectClasses","frames","root","cursors","active","top","frame","cursor","done","item","parts","record","key","classText","value","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n // Explicit frames instead of recursion: array nesting depth is controlled by the user.\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = frame[cursor];\n if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(\n __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\",\n );\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (record[key] && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array).\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness. `undefined` switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next: Record<string, unknown> = value ?? {};\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n if (value === null || value === undefined || value === false) {\n el.removeAttribute(\"style\");\n return value;\n }\n if (typeof value !== \"object\") {\n el.style.cssText = String(value);\n return value;\n }\n if (Array.isArray(value)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const item of value) {\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return value;\n }\n const next = { ...(value as Record<string, unknown>) };\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if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iB,EAA8B,EAAc,EAAsB,CACjG,IAAMC,EAAWL,EAAcC,CAAI,EAC/BlB,GAAU,MAA+BA,IAAU,GACrDG,EAAG,MAAM,eAAemB,CAAQ,EAEhCnB,EAAG,MAAM,YAAYmB,EAAUC,EAAaD,EAAUtB,CAAK,CAAC,CAEhE,CA2BA,SAAgBwB,EAAM,EAA8B,EAAgB,EAAyB,CAC3F,GAAIxB,GAAU,MAA+BA,IAAU,GAErD,OADAG,EAAG,gBAAgB,OAAO,EACnBH,EAET,GAAI,OAAOA,GAAU,SAEnB,MADA,GAAG,MAAM,QAAU,OAAOA,CAAK,EACxBA,EAET,GAAI,MAAM,QAAQA,CAAK,EAAG,CAGxB,EAAG,MAAM,QAAU,GACnB,IAAK,IAAML,KAAQK,EACjB,GAAI,OAAOL,GAAS,SAClB,EAAG,MAAM,SAAW,IAAIA,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAEF6B,EAAMrB,EAAIR,EAAM,CAAC,CAAC,CACpB,CAEF,OAAOK,CACT,CACA,IAAMW,EAAO,CAAE,GAAIX,CAAkC,EAC/CY,EAASL,EAASM,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMb,KAAOgB,EACZ,OAAO,GAAGF,EAAOd,GAAMa,EAAKb,EAAI,GACpCuB,EAAiBlB,EAAIL,EAAKa,EAAKb,EAAI,EAErC,OAAOa,CACT,C"}
1
+ {"version":3,"file":"class-style.js","names":["collectClasses","item","leaves","root","parts","record","key","unwrap","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","source","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAK,IAAMC,KAAQC,EAAOC,EAAM,oBAAK,EACnC,GAAI,OAAOF,GAAS,SACdA,IAAS,IAAIG,EAAM,KAAKH,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA,CAAI,GAAGG,EAAM,KAAK,OAAOH,CAAI,CAAC,OACzD,GAAqB,OAAOA,GAAS,UAAjCA,EAA2C,CACpD,IAAMI,EAASJ,EACf,IAAK,IAAMK,KAAO,OAAO,KAAKD,CAAM,EAC9BE,EAAOF,EAAOC,EAAI,GAAKA,IAAQ,IAAIF,EAAM,KAAKE,CAAG,CAEzD,CAEJ,CAGA,SAASE,EAAU,EAA+B,CAChD,IAAMC,EAAQF,EAAOG,CAAK,EAC1B,GAAI,OAAOD,GAAU,SAAU,OAAOA,EACtC,GAAIA,GAAU,MAA+BA,IAAU,GAAO,OAAO,KACrE,IAAML,EAAkB,CAAC,EAEzB,OADAJ,EAAeS,EAAOL,CAAK,EACpBA,EAAM,KAAK,GAAG,CACvB,CAOA,SAAgBO,EAAW,EAAa,EAAgB,EAAoB,CAC1E,IAAMC,EAAOJ,EAAUC,CAAK,EACxBG,IAAS,KACXC,EAAG,gBAAgB,OAAO,EAGxBC,EACED,EAAG,aAAa,OAAO,IAAMD,GAAMC,EAAG,aAAa,QAASD,CAAI,EAC3DC,EAAG,YAAcD,IAC1B,EAAG,UAAYA,EAEnB,CAyBA,SAAgBG,EAAU,EAAa,E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NS as e,SVG_NS as t}from"../internal/names.js";import{nextKey as n}from"../internal/hydration-scope.js";import{createComponent as r}from"../component.js";import{claims as i}from"../internal/hydration-hooks.js";import{bindRegion as a,createRegion as o}from"../insert.js";import{spread as s}from"../spread.js";import{mergeProps as c,splitProps as l,untrack as u,useMemo as d}from"@shadow-js/core";const f=/^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/,p=/^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/,m=/^(?!script$)[a-z][a-z0-9-]*$/i;function h(n){let r=n.toLowerCase();if(p.test(r))return document.createElementNS(e,r);let i=document.createElement(n);return i.constructor!==HTMLUnknownElement&&r!==`image`||!f.test(r)?i:document.createElementNS(t,n)}function g(e,r){if(!m.test(e))throw TypeError(`SHADOW_DYNAMIC_TAG`);let c=i.current.claimElement(n())??h(e);s(c,r,c.namespaceURI===t,!0);let l=o(c,null,i.current.takeRegion(c,null));return a(l,()=>r.children),c}function _(e,t){if(!e)return null;if(typeof e==`string`)return g(e,t);if(typeof e==`function`)return r(e,t);throw TypeError(`SHADOW_DYNAMIC_COMPONENT`)}function v(e){let[,t]=l(e,[`component`]);return d(()=>{let n=e.component;return u(()=>_(n,t))},{allowWrites:!0})}function y(e,t={}){return v(c({get component(){return e()}},t))}export{v as Dynamic,y as createDynamic};
1
+ import{MATHML_NS as e,SVG_NS as t}from"../internal/names.js";import{nextKey as n}from"../internal/hydration-scope.js";import{createComponent as r}from"../component.js";import{claims as i}from"../internal/hydration-hooks.js";import{bindRegion as a,createRegion as o}from"../insert.js";import{spreadProps as s}from"../spread.js";import{mergeProps as c,splitProps as l,untrack as u,useMemo as d}from"@shadow-js/core";const f=/^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/,p=/^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/,m=/^(?!script$)[a-z][a-z0-9-]*$/i;function h(n){let r=n.toLowerCase();if(p.test(r))return document.createElementNS(e,r);let i=document.createElement(n);return i.constructor!==HTMLUnknownElement&&r!==`image`||!f.test(r)?i:document.createElementNS(t,n)}function g(e,r){if(!m.test(e))throw TypeError(`SHADOW_DYNAMIC_TAG`);let c=i.current.claimElement(n())??h(e);s(c,r,c.namespaceURI===t);let l=o(c,null,i.current.takeRegion(c,null));return a(l,()=>r.children),c}function _(e,t){if(!e)return null;if(typeof e==`string`)return g(e,t);if(typeof e==`function`)return r(e,t);throw TypeError(`SHADOW_DYNAMIC_COMPONENT`)}function v(e){let[,t]=l(e,[`component`]);return d(()=>{let n=e.component;return u(()=>_(n,t))},{allowWrites:!0})}function y(e,t={}){return v(c({get component(){return e()}},t))}export{v as Dynamic,y as createDynamic};
2
2
  //# sourceMappingURL=dynamic.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic.js","names":["SVG_PATTERN","MATHML_TAGS","TAG_PATTERN","createTagged","lower","tag","MATHML_NS","el","SVG_NS","buildElement","claims","nextKey","spread","props","region","createRegion","bindRegion","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spread } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spread(el, props, el.namespaceURI === SVG_NS, true);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): () => unknown {\n return Dynamic(\n mergeProps(\n {\n get component(): C {\n return component();\n },\n },\n props,\n ) as DynamicProps<C>,\n );\n}\n"],"mappings":"A,yZAuCA,MAAMA,EACJ,gRAGIC,EACJ,oMAMIC,EAAc,gCA0BpB,SAASC,EAAa,EAAsB,CAC1C,IAAMC,EAAQC,EAAI,YAAY,EAC9B,GAAIJ,EAAY,KAAKG,CAAK,EAAG,OAAO,SAAS,gBAAgBE,EAAWF,CAAK,EAC7E,IAAMG,EAAK,SAAS,cAAcF,CAAG,EAOrC,OAJKE,EAAG,cAAgB,oBAAsBH,IAAU,SAAY,CAACJ,EAAY,KAAKI,CAAK,EAClFG,EAGF,SAAS,gBAAgBC,EAAQH,CAAG,CAC7C,CASA,SAASI,EAAa,EAAa,EAAwB,CACzD,GAAI,CAACP,EAAY,KAAKG,CAAG,EACvB,MAAU,UAAsD,oBAAoB,EAkBtF,IAAME,EAAKG,EAAO,QAAQ,aAAaC,EAAQ,CAAC,GAAKR,EAAaE,CAAG,EAErEO,EAAOL,EAAIM,EAAON,EAAG,eAAiBC,EAAQ,EAAI,EAClD,IAAMM,EAASC,EAAaR,EAAI,KAAMG,EAAO,QAAQ,WAAWH,EAAI,IAAI,CAAC,EAEzE,OADAS,EAAWF,MAAeD,EAAiC,QAAQ,EAC5DN,CACT,CAMA,SAASU,EAAY,EAAiB,EAAwB,CAC5D,GAAI,CAACC,EAAQ,OAAO,KACpB,GAAI,OAAOA,GAAW,SAAU,OAAOT,EAAaS,EAAQL,CAAK,EACjE,GAAI,OAAOK,GAAW,WACpB,OAAOC,EAAgBD,EAAsCL,CAAK,EAEpE,MAAU,UAGJ,0BACN,CACF,CA8CA,SAAgBO,EAAiC,EAAuC,CACtF,GAAM,EAAGC,GAAQC,EAAWT,EAAO,CAAC,WAAW,CAAC,EAEhD,OAAOU,MACU,CACb,IAAML,EAAkBL,EAAM,UAC9B,OAAOW,MAAcP,EAAYC,EAAQG,CAAI,CAAC,CAChD,EACA,CAAE,YAAa,EAAK,CACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAd,CACF,CACF,CACF,C"}
1
+ {"version":3,"file":"dynamic.js","names":["SVG_PATTERN","MATHML_TAGS","TAG_PATTERN","createTagged","lower","tag","MATHML_NS","el","SVG_NS","buildElement","claims","nextKey","spreadProps","props","region","createRegion","bindRegion","buildTarget","target","createComponent","Dynamic","rest","splitProps","useMemo","untrack","createDynamic","mergeProps","component"],"sources":["../../../src/control-flow/dynamic.ts"],"sourcesContent":["import { mergeProps, splitProps, untrack, useMemo } from \"@shadow-js/core\";\nimport { createComponent } from \"../component\";\nimport { bindRegion, claims, createRegion, MATHML_NS, nextKey, SVG_NS, warnOnce } from \"../extend\";\nimport { ssrElement, ssrRaw } from \"../server/element\";\nimport { isTextOnlyElement } from \"../server/raw-text\";\nimport { spreadProps } from \"../spread\";\n\n/**\n * A component function or a tag name, as {@link Dynamic} accepts it. The props of a function are\n * checked by the caller.\n * @since 1.0.0\n */\nexport type DynamicComponent = string | ((props: never) => unknown);\n\n/**\n * Everything `component` may be: a component, a tag name, or `undefined`, `null` or `false`, which\n * render nothing.\n * @since 1.0.0\n */\nexport type DynamicTarget = DynamicComponent | undefined | null | false;\n\n/**\n * Props of {@link Dynamic}: `component` plus the props of whatever it renders. Every other prop\n * passes through, reactive getters included.\n * @since 1.0.0\n */\nexport interface DynamicProps<C extends DynamicTarget = DynamicTarget> {\n /** The component to render, a tag name, or a falsy value for nothing. */\n readonly component: C;\n /** Any other prop is passed to the rendered component or set on the element, still reactive. */\n readonly [prop: string]: unknown;\n}\n\n/**\n * The SVG element names (lowercase) HTML does not define: the names a tag takes the SVG namespace for. A pattern\n * rather than a question to the platform because it answers the same in every DOM (browsers, happy-dom, jsdom,\n * which has no interface per SVG element) and never parses HTML, so a page that enforces Trusted Types is never\n * asked for a sink. `fe[bcdfgimopst]...` is every filter primitive (`feBlend` to `feTurbulence`).\n */\nconst SVG_PATTERN =\n /^(svg|g|path|circle|ellipse|line|poly(gon|line)|rect|text(path)?|tspan|defs|desc|discard|metadata|use|symbol|marker|switch|view|set|mpath|image|stop|mask|pattern|clippath|filter|foreignobject|animate(motion|transform)?|(linear|radial)gradient|fe[bcdfgimopst][a-z]{3,})$/;\n\n/** The MathML element names (the HTML spec's list), matched in lowercase. None of them is an HTML element. */\nconst MATHML_TAGS =\n /^(m(ath|[ion]|s(ub(sup)?|up|qrt|pace|tyle)?|t(ext|able|[rd])|row|frac|root|error|padded|phantom|enclose|under(over)?|over|(multi|pre)scripts|labeledtr|action)|none|semantics|annotation(-xml)?)$/;\n\n/**\n * Shape of a tag name: a letter, then letters, digits or dashes. Anything else is refused, and so is `script` in\n * any letter case: it would bypass CSP nonces and Trusted Types.\n */\nconst TAG_PATTERN = /^(?!script$)[a-z][a-z0-9-]*$/i;\n\n/**\n * Warns (development only) about an SVG element name written in a case SVG does not spell it in: the namespace\n * is case-sensitive, so a `clippath` element is not the `clipPath` that `clip-path=\"url(#...)\"`, CSS and\n * `querySelector` mean. Warns once per name. The table of canonical names exists only behind `__DEV__`.\n */\nfunction warnSvgCase(tag: string, lower: string): void {\n const canonical =\n \"animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject linearGradient radialGradient textPath\"\n .split(\" \")\n .find((name) => name.toLowerCase() === lower);\n if (canonical === undefined || canonical === tag) return;\n warnOnce(\n \"DYNAMIC_SVG_CASE\",\n `Dynamic created the SVG element \"${tag}\" with the name as written, but SVG spells it \"${canonical}\": the name is case-sensitive, so \"${tag}\" is not the element SVG defines. Write \"${canonical}\".`,\n lower,\n );\n}\n\n/**\n * Creates the element of a validated tag name in its namespace. MathML names are exact (none of them is an\n * HTML element). For the rest the platform answers first: a name HTML knows (`div`, `a`, `style`, `title`, a\n * custom element) is an HTML element, which is all the common tags cost; only a name HTML does not know is\n * matched against the SVG names, and it keeps the spelling the caller wrote.\n */\nfunction createTagged(tag: string): Element {\n const lower = tag.toLowerCase();\n if (MATHML_TAGS.test(lower)) return document.createElementNS(MATHML_NS, lower);\n const el = document.createElement(tag);\n // Firefox makes `image` a plain HTMLElement, where Chromium and WebKit call it unknown: it is no HTML element\n // (the parser turns it into `img`), and SVG defines it, so it takes the SVG route in every engine.\n if ((el.constructor !== HTMLUnknownElement && lower !== \"image\") || !SVG_PATTERN.test(lower)) {\n return el;\n }\n if (__DEV__) warnSvgCase(tag, lower);\n return document.createElementNS(SVG_NS, tag);\n}\n\n/**\n * Creates an element for a validated tag name and applies the props to it, children included.\n * The namespace comes from the tag: SVG-only names get the SVG namespace (named as written), MathML names the\n * MathML namespace, the rest are HTML.\n * On the server it renders the element as markup (with the hydration key and the children region\n * the client adopts); while hydrating it claims that element instead of creating one.\n */\nfunction buildElement(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag)) {\n throw new TypeError(__DEV__ ? \"ShadowJS Dynamic: invalid tag\" : \"SHADOW_DYNAMIC_TAG\");\n }\n if (__SERVER__) {\n // The children are read lazily, after `ssrElement` took the element's hydration key: the client\n // claims the element first and builds its children second, so the keys must be drawn in that\n // order here too, or a component inside the element and every sibling after it would miss.\n return ssrElement(\n tag,\n props,\n () => {\n const { children } = props as { children?: unknown };\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const el = claims.current.claimElement(nextKey()) ?? createTagged(tag);\n // Attributes through spread; children through insert, which adopts the server's children region.\n spreadProps(el, props, el.namespaceURI === SVG_NS);\n const region = createRegion(el, null, claims.current.takeRegion(el, null));\n bindRegion(region, () => (props as { children?: unknown }).children);\n return el;\n}\n\n/**\n * Renders one value of `component`: nothing for a falsy value, an element for a tag name, the\n * component's result for a function. Anything else is a TypeError.\n */\nfunction buildTarget(target: unknown, props: object): unknown {\n if (!target) return null;\n if (typeof target === \"string\") return buildElement(target, props);\n if (typeof target === \"function\") {\n return createComponent(target as (props: object) => unknown, props);\n }\n throw new TypeError(\n __DEV__\n ? \"ShadowJS Dynamic: component must be a string, a function, or a falsy value.\"\n : \"SHADOW_DYNAMIC_COMPONENT\",\n );\n}\n\n/**\n * Renders a component function or an element chosen by a tag name, and re-renders when\n * `component` changes. Only `component` is tracked: the rest of the props are passed through\n * reactive, so changing them updates the rendered output without rebuilding it. Swapping\n * `component` disposes the old subtree, cleanups included, and builds the new one once. A falsy\n * `component` renders nothing.\n *\n * Tag names are checked against `^[a-z][a-z0-9-]*$` (case-insensitive) and `script` is refused, so\n * data-driven tags cannot inject markup. The browser decides the namespace: a name HTML knows (`div`,\n * `a`, `style`, `title`, a custom element) is an HTML element, in any letter case. A name HTML does not\n * know and that SVG defines (`circle`, `path`, `svg`, `image`, `foreignObject`, `clipPath`, the `fe*` filter\n * primitives, the gradients and animation elements, ...) is created in the SVG namespace, matched against a\n * name pattern (no HTML is parsed, so Trusted Types is never involved); any other name stays an HTML element.\n * The element keeps the name exactly as written: `Dynamic` does not derive the canonical case, which SVG\n * needs (`clipPath`, `linearGradient`, `feGaussianBlur`, `foreignObject`, ...), so write those names as SVG\n * spells them. Development builds warn once per name with `DYNAMIC_SVG_CASE` when they are not.\n * MathML names (`math`, `mi`, `mfrac`, `semantics`, `annotation-xml`, ...) are created in the MathML\n * namespace, in lowercase. `title`, `style` and `a` stay HTML elements: `Dynamic` does not know the parent\n * the element will be inserted into.\n *\n * @param props `component` and the props of what it renders.\n * @returns An accessor of the rendered output, to be inserted by the caller.\n * @throws TypeError for an invalid tag name or a component that is neither a string nor a function\n * (at read time, which is when the caller inserts it).\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { Dynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(\n * parent,\n * Dynamic({\n * get component() {\n * return level() === 1 ? \"h1\" : \"h2\";\n * },\n * children: \"Title\",\n * }),\n * );\n * });\n * @see createDynamic\n * @since 1.0.0\n */\nexport function Dynamic<C extends DynamicTarget>(props: DynamicProps<C>): () => unknown {\n const [, rest] = splitProps(props, [\"component\"]);\n // The component is built inside this memo, so its setup (or a ref, or a directive) may write signals.\n return useMemo(\n (): unknown => {\n const target: unknown = props.component;\n return untrack(() => buildTarget(target, rest));\n },\n { allowWrites: true },\n );\n}\n\n/**\n * Function form of {@link Dynamic}, for code that is not JSX: renders what `component()` returns (a\n * component, a tag name or a falsy value) with `props`, and follows it when it changes.\n *\n * @param component Accessor of the target.\n * @param props The props of what it renders (reactive getters stay reactive).\n * @returns An accessor of the rendered output.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { createDynamic, insert } from \"@shadow-js/web\";\n *\n * const parent = document.createElement(\"div\");\n * createRoot(() => {\n * const [level] = useSignal(1);\n * insert(parent, createDynamic(() => (level() === 1 ? \"h1\" : \"h2\"), { children: \"Title\" }));\n * });\n * @see Dynamic\n * @since 1.0.0\n */\nexport function createDynamic<C extends DynamicTarget>(\n component: () => C,\n props: object = {},\n): ()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ACtB,CACF,CAqBA,SAAgBI,EACd,EACA,EAAgB,CAAC,EACF,CACf,OAAOL,EACLM,EACE,CACE,IAAI,WAAe,CACjB,OAAOC,EAAU,CACnB,CACF,EACAd,CACF,CACF,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{currentScope as e,withScope as t}from"../internal/hydration-scope.js";import{rootErrorsOf as n}from"./root-errors.js";import{catchError as r,createRoot as i,getOwner as a,onCleanup as o,untrack as s,useMemo as c,useSignal as l}from"@shadow-js/core";import{createSignalNode as u,handleError as d,readSignal as f,writeSignal as p}from"@shadow-js/core/extend";function m(m){let h=u(void 0,Object.is),g=a(),_=n(g),v=e(),y=v===null?null:{id:v.id,count:v.count,resources:v.resources},b=()=>f(h),x=e=>{p(h,e,{allowInMemo:!0})},[S,C]=l(0,{equals:!1}),w=!0,T=!1,E,D=()=>{w&&(x(void 0),C(e=>e+1))},O=e=>{w&&(_?.onCaughtError?.(e),T?E===void 0&&(E={error:e}):x({error:e}))},k=()=>{let e=E;return E=void 0,e},A=e=>{let t=m.fallback;if(typeof t!=`function`)return t;try{return s(()=>t(e,D))}catch(e){d(e,g);return}},j=()=>{T=!0;try{S();let e=b()??k();if(e!==void 0)return A(e.error);let t=i(e=>({dispose:e,value:r(()=>s(()=>m.children),O)})),n=k();return n===void 0?t.value:(t.dispose(),A(n.error))}finally{i(()=>{o(()=>{T=!0})}),T=!1}},M=c(()=>y===null?j():t({...y},j),{allowWrites:!0});return i(()=>{o(()=>{w=!1})}),M}export{m as ErrorBoundary};
1
+ import{currentScope as e,withScope as t}from"../internal/hydration-scope.js";import{rootErrorsOf as n}from"./root-errors.js";import{catchError as r,createRoot as i,getOwner as a,onCleanup as o,untrack as s,useMemo as c,useSignal as l}from"@shadow-js/core";import{SignalNode as u,handleError as d,readSignal as f,writeSignal as p}from"@shadow-js/core/extend";function m(m){let h=new u(void 0,Object.is),g=a(),_=n(g),v=e(),y=v===null?null:{id:v.id,count:v.count,resources:v.resources},b=()=>f(h),x=e=>{p(h,e,{allowInMemo:!0})},[S,C]=l(0,{equals:!1}),w=!0,T=!1,E,D=()=>{w&&(x(void 0),C(e=>e+1))},O=e=>{w&&(_?.onCaughtError?.(e),T?E===void 0&&(E={error:e}):x({error:e}))},k=()=>{let e=E;return E=void 0,e},A=e=>{let t=m.fallback;if(typeof t!=`function`)return t;try{return s(()=>t(e,D))}catch(e){d(e,g);return}},j=()=>{T=!0;try{S();let e=b()??k();if(e!==void 0)return A(e.error);let t=i(e=>({dispose:e,value:r(()=>s(()=>m.children),O)})),n=k();return n===void 0?t.value:(t.dispose(),A(n.error))}finally{i(()=>{o(()=>{T=!0})}),T=!1}},M=c(()=>y===null?j():t({...y},j),{allowWrites:!0});return i(()=>{o(()=>{w=!1})}),M}export{m as ErrorBoundary};
2
2
  //# sourceMappingURL=error-boundary.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-boundary.js","names":["ErrorBoundary","failureCell","createSignalNode","parentOwner","getOwner","roots","rootErrorsOf","live","currentScope","origin","failure","readSignal","setFailure","writeSignal","next","version","setVersion","useSignal","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","props","untrack","thrown","handleError","build","current","scope","createRoot","catchError","creation","onCleanup","body","useMemo","withScope"],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createSignalNode, handleError, readSignal, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = createSignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":"A,4WA0FA,SAAgBA,EAAc,EAAmD,CAG/E,IAAMC,EAAcC,EAAsC,IAAA,GAAW,OAAO,EAAE,EAExEC,EAAcC,EAAS,EAEvBC,EAAQC,EAAaH,CAAW,EAEhCI,EAAOC,EAAa,EACpBC,EACJF,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EG,MAAqCC,EAAWV,CAAW,EAC3DW,EAAc,GAAoC,CACtDC,EAAYZ,EAAaa,EAAM,CAAE,YAAa,EAAK,CAAC,CACtD,EAEM,CAACC,EAASC,GAAcC,EAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAExDC,EAAQ,GAERC,EAAO,GAEPC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Owner","getOwner","roots","rootErrorsOf","live","currentScope","origin","failure","readSignal","setFailure","writeSignal","next","version","setVersion","useSignal","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","props","untrack","thrown","handleError","build","current","scope","createRoot","catchError","creation","onCleanup","body","useMemo","withScope"],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { handleError, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = new SignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":"A,sWA0FA,SAAgBA,EAAc,EAAmD,CAG/E,IAAMC,EAAc,IAAIC,EAAgC,IAAA,GAAW,OAAO,EAAE,EAEtEC,EAAcC,EAAS,EAEvBC,EAAQC,EAAaH,CAAW,EAEhCI,EAAOC,EAAa,EACpBC,EACJF,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EG,MAAqCC,EAAWV,CAAW,EAC3DW,EAAc,GAAoC,CACtDC,EAAYZ,EAAaa,EAAM,CAAE,YAAa,EAAK,CAAC,CACtD,EAEM,CAACC,EAASC,GAAcC,EAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAExDC,EAAQ,GAERC,EAAO,GAEPC,EAEEC,MAAoB,CACnBH,IACLN,EAAW,IAAA,EAAS,EACpBI,EAAY,GAAUM,EAAQ,CAAC,EACjC,EAYMC,EAAU,GAAyB,CAClCL,IACLb,GAAO,gBAAgBmB,CAAK,EACxBL,EACEC,IAAY,IAAA,KAAW,EAAU,CAAE,OAAM,GAG/CR,EAAW,CAAE,OAAM,CAAC,EACtB,EAGMa,MAAyC,CAC7C,IAAMC,EAAWN,EAEjB,MADA,GAAU,IAAA,GACHM,CACT,EAEMC,EAAe,GAA4B,CAC/C,IAAMC,EAAWC,EAAM,SACvB,GAAI,OAAOD,GAAa,WAAY,OAAOA,EAC3C,GAAI,CACF,OAAOE,MACJF,EAA4DJ,EAAOH,CAAK,CAC3E,CACF,OAASU,EAAQ,CAGfC,EAAYD,EAAQ5B,CAAW,EAC/B,MACF,CACF,EAGM8B,MAAuB,CAC3B,EAAO,GACP,GAAI,CACFlB,EAAQ,EACR,IAAMmB,EAAUxB,EAAQ,GAAKe,EAAY,EACzC,GAAIS,IAAY,IAAA,GAEd,OAAOP,EAAYO,EAAQ,KAAK,EAIlC,IAAMC,EAAQC,EAAY,IAEjB,CACL,UACA,MAAOC,MAAiBP,MAAcD,EAAM,QAAQ,EAAGN,CAAM,CAC/D,EACD,EACKe,EAAWb,EAAY,EAO7B,OANIa,IAAa,IAAA,GAMVH,EAAM,OALXA,EAAM,QAAQ,EAEPR,EAAYW,EAAS,KAAK,EAIrC,QAAU,CAERF,MAAiB,CACfG,MAAgB,CACd,EAAO,EACT,CAAC,CACH,CAAC,EACD,EAAO,EACT,CAEF,EAIMC,EAAOC,MACJhC,IAAW,KAAOwB,EAAM,EAAIS,EAAU,CAAE,GAAGjC,CAAO,EAAGwB,CAAK,EACjE,CAAE,YAAa,EAAK,CACtB,EASA,OANAG,MAAiB,CACfG,MAAgB,CACd,EAAQ,EAEV,CAAC,CACH,CAAC,EACMC,CACT,C"}
@@ -1,2 +1,2 @@
1
- import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,removeRegion as o}from"../insert.js";import{PortalContext as s}from"../internal/portal-context.js";import{renderServerPortal as c}from"../server/portals.js";import{createRoot as l,isServer as u,onCleanup as d,useContext as f,useRenderEffect as p}from"@shadow-js/core";function m(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function h(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function g(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function _(_){let v=t(),y=f(s);if(u||y!==null)return _.useShadow!==!0&&c(v,()=>_.children,y),null;let b,x=r.current.claimPortal(v),S=()=>{let e=b;e!==void 0&&(b=void 0,e.stopEffects(),o(e.region))},C=(t,o,s)=>{let c=a(t,null,o);return{host:t,region:c,stopEffects:l(t=>{let a=()=>{i(c,()=>_.children)};return s===`plain`?a():s===`claimed`?n(e(v),a):r.current.withoutClaiming(()=>n(e(v),a)),t})}},w=e=>{let t=b;if(t===void 0){let t=x??[],n=`plain`;x===void 0?v!==void 0&&r.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,x=void 0;for(let n of t)n.parentNode!==e&&m(e,n);b=C(e,t,n);return}let n=t.region.nodes.filter(e=>e.parentNode===t.host);t.stopEffects();for(let t of n)m(e,t);b=C(e,n,`plain`)};return p(()=>({host:g(_.mount),shadow:_.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){S();for(let e of x??[])e.parentNode?.removeChild(e);x=void 0;return}let n=t?h(e):e;(b===void 0||b.host!==n)&&w(n)}),d(S),null}export{_ as Portal};
1
+ import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{claims as r}from"../internal/hydration-hooks.js";import{bindRegion as i,createRegion as a,moveRegion as o,removeRegion as s}from"../insert.js";import{PortalContext as c}from"../internal/portal-context.js";import{createRoot as l,getOwner as u,isServer as d,onCleanup as f,runWithOwner as p,useContext as m,useRenderEffect as h}from"@shadow-js/core";function g(e,t){typeof e.moveBefore==`function`?e.moveBefore(t,null):e.appendChild(t)}function _(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function v(e){return e===void 0?document.body:(typeof e==`function`?e():e)??null}function y(y){let b=t(),x=m(c);if(d||x!==null)return y.useShadow!==!0&&x?.render?.(b,()=>y.children),null;let S=u(),C,w=r.current.claimPortal(b),T=()=>{let e=C;e!==void 0&&(C=void 0,e.stopEffects(),s(e.region))},E=(t,o,s)=>{let c=a(t,null,o);return{host:t,region:c,stopEffects:p(S,()=>l(t=>{let a=()=>{i(c,()=>y.children)};return s===`plain`?a():s===`claimed`?n(e(b),a):r.current.withoutClaiming(()=>n(e(b),a)),t}))}},D=e=>{let t=C;if(t===void 0){let t=w??[],n=`plain`;w===void 0?b!==void 0&&r.current.isClaiming()&&(n=`unclaimed`):n=`claimed`,w=void 0;for(let n of t)n.parentNode!==e&&g(e,n);C=E(e,t,n)}else o(t.region,e,t=>g(e,t)),C={host:e,region:t.region,stopEffects:t.stopEffects}};return h(()=>({host:v(y.mount),shadow:y.useShadow===!0}),({host:e,shadow:t})=>{if(e===null){T();for(let e of w??[])e.parentNode?.removeChild(e);w=void 0;return}let n=t?_(e):e;(C===void 0||C.host!==n)&&D(n)}),f(T),null}export{y as Portal};
2
2
  //# sourceMappingURL=portal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"portal.js","names":["appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","key","nextKey","sink","useContext","PortalContext","isServer","props","renderServerPortal","mounted","adopted","claims","unmount","current","removeRegion","mountInto","region","createRegion","initial","createRoot","bind","bindRegion","mode","withScope","childScope","dispose","moveTo","previous","nodes","useRenderEffect","shadow","onCleanup"],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import { createRoot, isServer, onCleanup, useContext, useRenderEffect } from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\nimport { renderServerPortal } from \"../server/portals\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content, and static nodes keep their identity while they\n * move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) renderServerPortal(key, () => props.children, sink);\n return null;\n }\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n });\n return { host, region, stopEffects };\n };\n\n /** Moves the content to `target`. The nodes move first, then the children are bound again. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n const nodes = previous.region.nodes.filter((node) => node.parentNode === previous.host);\n previous.stopEffects();\n for (const node of nodes) appendMoved(target, node);\n mounted = mountInto(target, nodes, \"plain\");\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n // The server block was adopted at the call site but has nowhere to live: leaving it would show\n // content the client does not render (stripLeftovers removes the blocks nobody claimed).\n for (const node of adopted ?? []) node.parentNode?.removeChild(node);\n adopted = undefined;\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":"A,qcAiEA,SAASA,EAAY,EAAc,EAAkB,CAC/C,OAAQC,EAAgC,YAAe,WACzDA,EAAwB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAa,EAA2B,CAC/C,OAAOC,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,MAAO,CAAC,CAC9D,CAGA,SAASC,EAAa,EAA6C,CAGjE,OAFIC,IAAU,IAAA,GAAkB,SAAS,MAC3B,OAAOA,GAAU,WAAaA,EAAM,EAAIA,IACtC,IAClB,CAqCA,SAAgBC,EAAO,EAA0B,CAI/C,IAAMC,EAAMC,EAAQ,EAGdC,EAAOC,EAAWC,CAAa,EACrC,GAAIC,GAAYH,IAAS,KAEvB,OADII,EAAM,YAAc,IAAMC,EAAmBP,MAAWM,EAAM,SAAUJ,CAAI,EACzE,KAET,IAAIM,EAGAC,EAA8BC,EAAO,QAAQ,YAAYV,CAAG,EAG1DW,MAAsB,CAC1B,IAAMC,EAAUJ,EACZI,IAAY,IAAA,KAChB,EAAU,IAAA,GACVA,EAAQ,YAAY,EACpBC,EAAaD,EAAQ,MAAM,EAC7B,EAGME,GAAa,EAAY,EAAiB,IAA6B,CA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AA,IAAaA,EAAQ,OAASf,IAC9CgC,EAAOhC,CAAM,CACf,CACF,EACAqC,EAAUnB,CAAO,EACV,IACT,C"}
1
+ {"version":3,"file":"portal.js","names":["appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","key","nextKey","sink","useContext","PortalContext","isServer","props","owner","getOwner","mounted","adopted","claims","unmount","current","removeRegion","mountInto","region","createRegion","initial","runWithOwner","createRoot","bind","bindRegion","mode","withScope","childScope","dispose","moveTo","previous","moveRegion","useRenderEffect","shadow","onCleanup"],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n onCleanup,\n runWithOwner,\n useContext,\n useRenderEffect,\n} from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n moveRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content: the children are built once, and\n * their nodes and effects keep their identity while they move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) sink?.render?.(key, () => props.children);\n return null;\n }\n // The content is built under the portal's own owner, not under the effect that picks the mount:\n // that effect runs again for each new mount and would dispose what it owns.\n const owner = getOwner();\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = runWithOwner(owner, () =>\n createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n }),\n );\n return { host, region, stopEffects };\n };\n\n /** Mounts the content in `target` the first time, and moves it there afterward. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n // The children were built once, under an owner that stays: the nodes and their effects move, so\n // an input keeps what was typed and a component is neither disposed nor set up again.\n moveRegion(previous.region, target, (node) => appendMoved(target, node));\n mounted = { host: target, region: previous.region, stopEffects: previous.stopEffects };\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n // The server block was adopted at the call site but has nowhere to live: leaving it would show\n // content the client does not render (stripLeftovers removes the blocks nobody claimed).\n for (const node of adopted ?? []) node.parentNode?.removeChild(node);\n adopted = undefined;\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":"A,2bAyEA,SAASA,EAAY,EAAc,EAAkB,CAC/C,OAAQC,EAAgC,YAAe,WACzDA,EAAwB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAa,EAA2B,CAC/C,OAAOC,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,MAAO,CAAC,CAC9D,CAGA,SAASC,EAAa,EAA6C,CAGjE,OAFIC,IAAU,IAAA,GAAkB,SAAS,MAC3B,OAAOA,GAAU,WAAaA,EAAM,EAAIA,IACtC,IAClB,CAqCA,SAAgBC,EAAO,EAA0B,CAI/C,IAAMC,EAAMC,EAAQ,EAGdC,EAAOC,EAAWC,CAAa,EACrC,GAAIC,GAAYH,IAAS,KAEvB,OADII,EAAM,YAAc,IAAMJ,GAAM,SAASF,MAAWM,EAAM,QAAQ,EAC/D,KAIT,IAAMC,EAAQC,EAAS,EACnBC,EAGAC,EAA8BC,EAAO,QAAQ,YAAYX,CAAG,EAG1DY,MAAsB,CAC1B,IAAMC,EAAUJ,EACZI,IAAY,IAAA,KAChB,EAAU,IAAA,GACVA,EAAQ,YAAY,EACpBC,EAAaD,EAAQ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C/Ca,IAAY,IAAA,IAAaA,EAAQ,OAAShB,IAC9CkC,EAAOlC,CAAM,CACf,CACF,EACAuC,EAAUpB,CAAO,EACV,IACT,C"}
@@ -1,2 +1,2 @@
1
- import{createContext as e,onCleanup as t,useContext as n}from"@shadow-js/core";import{createSignalNode as r,readSignal as i,writeSignal as a}from"@shadow-js/core/extend";const o=/* @__PURE__ */ e(null,{name:`SuspenseList`});function s(e){let n=r(0,!1),s=[],c=()=>{a(n,0,{allowInMemo:!0})};return o({value:{register(r){let a={ready:r};s.push(a),c(),t(()=>{let e=s.indexOf(a);e!==-1&&s.splice(e,1),c()});let o=()=>(i(n),s.indexOf(a)),l=()=>{let t=o();if(t===-1)return!1;switch(e.revealOrder){case`together`:return s.every(e=>e.ready());case`forwards`:return s.slice(0,t+1).every(e=>e.ready());case`backwards`:return s.slice(t).every(e=>e.ready());default:return r()}};return{reveal:l,showFallback:()=>{if(l())return!1;let t=e.revealOrder;if(t!==`forwards`&&t!==`backwards`)return!0;if(e.tail===`hidden`)return!1;if(e.tail!==`collapsed`)return!0;let n=o(),r=t===`backwards`?[...s].reverse():s,i=t===`backwards`?s.length-1-n:n;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==void 0&&!t.ready())return e===i}return!1}}}},get children(){return e.children}})}function c(e){let t=n(o);return t===null?null:t.register(e)}export{s as SuspenseList,o as SuspenseListContext,c as registerInList};
1
+ import{createContext as e,onCleanup as t,useContext as n}from"@shadow-js/core";import{SignalNode as r,readSignal as i,writeSignal as a}from"@shadow-js/core/extend";const o=/* @__PURE__ */ e(null,{name:`SuspenseList`});function s(e){let n=new r(0,!1),s=[],c=()=>{a(n,0,{allowInMemo:!0})};return o({value:{register(r){let a={ready:r};s.push(a),c(),t(()=>{let e=s.indexOf(a);e!==-1&&s.splice(e,1),c()});let o=()=>(i(n),s.indexOf(a)),l=()=>{let t=o();if(t===-1)return!1;switch(e.revealOrder){case`together`:return s.every(e=>e.ready());case`forwards`:return s.slice(0,t+1).every(e=>e.ready());case`backwards`:return s.slice(t).every(e=>e.ready());default:return r()}};return{reveal:l,showFallback:()=>{if(l())return!1;let t=e.revealOrder;if(t!==`forwards`&&t!==`backwards`)return!0;if(e.tail===`hidden`)return!1;if(e.tail!==`collapsed`)return!0;let n=o(),r=t===`backwards`?[...s].reverse():s,i=t===`backwards`?s.length-1-n:n;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==void 0&&!t.ready())return e===i}return!1}}}},get children(){return e.children}})}function c(e){let t=n(o);return t===null?null:t.register(e)}export{s as SuspenseList,o as SuspenseListContext,c as registerInList};
2
2
  //# sourceMappingURL=suspense-list.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"suspense-list.js","names":["SuspenseListContext","SuspenseList","changes","createSignalNode","slots","touch","writeSignal","entry","onCleanup","index","position","readSignal","reveal","props","slot","ready","order","ordered","wanted","i","candidate","registerInList","list","useContext"],"sources":["../../../src/control-flow/suspense-list.ts"],"sourcesContent":["import { type Accessor, type Context, createContext, onCleanup, useContext } from \"@shadow-js/core\";\nimport { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n\n/** What a `<Suspense>` inside a list learns about its place: when to show content and a fallback. @internal */\nexport interface SuspenseListSlot {\n /** True when this boundary may show its content now (it is ready and the order allows it). */\n reveal(): boolean;\n /** True when this boundary should show its fallback while it waits. */\n showFallback(): boolean;\n}\n\n/** Provided by `<SuspenseList>` to the boundaries below it. @internal */\nexport interface SuspenseListState {\n /** Registers a boundary, in creation order; `ready` reports that its own data has loaded. */\n register(ready: () => boolean): SuspenseListSlot;\n}\n\n/** The enclosing list, or null. @internal */\nexport const SuspenseListContext: Context<SuspenseListState | null> =\n /* @__PURE__ */ createContext<SuspenseListState | null>(null, { name: \"SuspenseList\" });\n\n/**\n * Props of {@link SuspenseList}.\n * @since 1.0.0\n */\nexport interface SuspenseListProps {\n /**\n * `\"forwards\"`: boundaries reveal in order, each after the ones before it. `\"backwards\"`: the\n * same from the last one. `\"together\"`: all at once, when the last one is ready. Without it each\n * boundary reveals on its own. Read reactively.\n * @default undefined (each boundary reveals as soon as its own data is ready)\n */\n readonly revealOrder?: \"forwards\" | \"backwards\" | \"together\" | undefined;\n /**\n * What the boundaries that are still waiting show: `\"collapsed\"` only the next fallback in\n * order, `\"hidden\"` none. Applies to `forwards` and `backwards`; the default shows every fallback.\n * @default undefined (every waiting boundary shows its fallback)\n */\n readonly tail?: \"collapsed\" | \"hidden\" | undefined;\n /**\n * The content, with the `<Suspense>` boundaries to coordinate anywhere below it.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Coordinates the `<Suspense>` boundaries below it so a page of independent loads reveals in a\n * calm order instead of popping in at random.\n *\n * @param props See {@link SuspenseListProps}.\n * @returns An accessor of the children, rendered with the list's coordination in context.\n * @example\n * import { Suspense, SuspenseList } from \"@shadow-js/web\";\n *\n * function Skeleton() {\n * return <p>Loading...</p>;\n * }\n *\n * function Profile() {\n * return <p>Profile</p>;\n * }\n *\n * function Feed() {\n * return <p>Feed</p>;\n * }\n *\n * function Page() {\n * return (\n * <SuspenseList revealOrder=\"forwards\" tail=\"collapsed\">\n * <Suspense fallback={<Skeleton />}>\n * <Profile />\n * </Suspense>\n * <Suspense fallback={<Skeleton />}>\n * <Feed />\n * </Suspense>\n * </SuspenseList>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function SuspenseList(props: SuspenseListProps): Accessor<unknown> {\n // The set of boundaries changes as they are created and disposed; `changes` tells readers.\n const changes = createSignalNode<number>(0, false);\n const slots: Array<{ readonly ready: () => boolean }> = [];\n const touch = (): void => {\n writeSignal(changes, 0, { allowInMemo: true });\n };\n\n const state: SuspenseListState = {\n register(ready) {\n const entry = { ready };\n slots.push(entry);\n touch();\n onCleanup(() => {\n const index = slots.indexOf(entry);\n if (index !== -1) slots.splice(index, 1);\n touch();\n });\n const position = (): number => {\n readSignal(changes);\n return slots.indexOf(entry);\n };\n const reveal = (): boolean => {\n const index = position();\n if (index === -1) return false;\n switch (props.revealOrder) {\n case \"together\":\n return slots.every((slot) => slot.ready());\n case \"forwards\":\n return slots.slice(0, index + 1).every((slot) => slot.ready());\n case \"backwards\":\n return slots.slice(index).every((slot) => slot.ready());\n default:\n return ready();\n }\n };\n const showFallback = (): boolean => {\n if (reveal()) return false;\n const order = props.revealOrder;\n const sequential = order === \"forwards\" || order === \"backwards\";\n if (!sequential) return true;\n if (props.tail === \"hidden\") return false;\n if (props.tail !== \"collapsed\") return true;\n // Only the next boundary in order that is not revealed yet shows its fallback.\n const index = position();\n const ordered = order === \"backwards\" ? [...slots].reverse() : slots;\n const wanted = order === \"backwards\" ? slots.length - 1 - index : index;\n for (let i = 0; i < ordered.length; i += 1) {\n const candidate = ordered[i];\n if (candidate !== undefined && !candidate.ready()) return i === wanted;\n }\n return false;\n };\n return { reveal, showFallback };\n },\n };\n\n return SuspenseListContext({\n value: state,\n get children() {\n return props.children;\n },\n }) as Accessor<unknown>;\n}\n\n/** The slot of the nearest list for a boundary created now, or null outside a list. @internal */\nexport function registerInList(ready: () => boolean): SuspenseListSlot | null {\n const list = useContext(SuspenseListContext);\n return list === null ? null : list.register(ready);\n}\n"],"mappings":"A,0KAkBA,MAAaA,EACK,kBAAwC,KAAM,CAAE,KAAM,cAAe,CAAC,EA+DxF,SAAgBC,EAAa,EAA6C,CAExE,IAAMC,EAAUC,EAAyB,EAAG,EAAK,EAC3CC,EAAkD,CAAC,EACnDC,MAAoB,CACxBC,EAAYJ,EAAS,EAAG,CAAE,YAAa,EAAK,CAAC,CAC/C,EAmDA,OAAOF,EAAoB,CACzB,MAAO,CAjDP,SAAS,EAAO,CACd,IAAMO,EAAQ,CAAE,OAAM,EACtBH,EAAM,KAAKG,CAAK,EAChBF,EAAM,EACNG,MAAgB,CACd,IAAMC,EAAQL,EAAM,QAAQG,CAAK,EAC7BE,IAAU,IAAIL,EAAM,OAAOK,EAAO,CAAC,EACvCJ,EAAM,CACR,CAAC,EACD,IAAMK,OACJC,EAAWT,CA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ots","touch","writeSignal","entry","onCleanup","index","position","readSignal","reveal","props","slot","ready","order","ordered","wanted","i","candidate","registerInList","list","useContext"],"sources":["../../../src/control-flow/suspense-list.ts"],"sourcesContent":["import { type Accessor, type Context, createContext, onCleanup, useContext } from \"@shadow-js/core\";\nimport { readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n\n/** What a `<Suspense>` inside a list learns about its place: when to show content and a fallback. @internal */\nexport interface SuspenseListSlot {\n /** True when this boundary may show its content now (it is ready and the order allows it). */\n reveal(): boolean;\n /** True when this boundary should show its fallback while it waits. */\n showFallback(): boolean;\n}\n\n/** Provided by `<SuspenseList>` to the boundaries below it. @internal */\nexport interface SuspenseListState {\n /** Registers a boundary, in creation order; `ready` reports that its own data has loaded. */\n register(ready: () => boolean): SuspenseListSlot;\n}\n\n/** The enclosing list, or null. @internal */\nexport const SuspenseListContext: Context<SuspenseListState | null> =\n /* @__PURE__ */ createContext<SuspenseListState | null>(null, { name: \"SuspenseList\" });\n\n/**\n * Props of {@link SuspenseList}.\n * @since 1.0.0\n */\nexport interface SuspenseListProps {\n /**\n * `\"forwards\"`: boundaries reveal in order, each after the ones before it. `\"backwards\"`: the\n * same from the last one. `\"together\"`: all at once, when the last one is ready. Without it each\n * boundary reveals on its own. Read reactively.\n * @default undefined (each boundary reveals as soon as its own data is ready)\n */\n readonly revealOrder?: \"forwards\" | \"backwards\" | \"together\" | undefined;\n /**\n * What the boundaries that are still waiting show: `\"collapsed\"` only the next fallback in\n * order, `\"hidden\"` none. Applies to `forwards` and `backwards`; the default shows every fallback.\n * @default undefined (every waiting boundary shows its fallback)\n */\n readonly tail?: \"collapsed\" | \"hidden\" | undefined;\n /**\n * The content, with the `<Suspense>` boundaries to coordinate anywhere below it.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Coordinates the `<Suspense>` boundaries below it so a page of independent loads reveals in a\n * calm order instead of popping in at random.\n *\n * @param props See {@link SuspenseListProps}.\n * @returns An accessor of the children, rendered with the list's coordination in context.\n * @example\n * import { Suspense, SuspenseList } from \"@shadow-js/web\";\n *\n * function Skeleton() {\n * return <p>Loading...</p>;\n * }\n *\n * function Profile() {\n * return <p>Profile</p>;\n * }\n *\n * function Feed() {\n * return <p>Feed</p>;\n * }\n *\n * function Page() {\n * return (\n * <SuspenseList revealOrder=\"forwards\" tail=\"collapsed\">\n * <Suspense fallback={<Skeleton />}>\n * <Profile />\n * </Suspense>\n * <Suspense fallback={<Skeleton />}>\n * <Feed />\n * </Suspense>\n * </SuspenseList>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function SuspenseList(props: SuspenseListProps): Accessor<unknown> {\n // The set of boundaries changes as they are created and disposed; `changes` tells readers.\n const changes = new SignalNode<number>(0, false);\n const slots: Array<{ readonly ready: () => boolean }> = [];\n const touch = (): void => {\n writeSignal(changes, 0, { allowInMemo: true });\n };\n\n const state: SuspenseListState = {\n register(ready) {\n const entry = { ready };\n slots.push(entry);\n touch();\n onCleanup(() => {\n const index = slots.indexOf(entry);\n if (index !== -1) slots.splice(index, 1);\n touch();\n });\n const position = (): number => {\n readSignal(changes);\n return slots.indexOf(entry);\n };\n const reveal = (): boolean => {\n const index = position();\n if (index === -1) return false;\n switch (props.revealOrder) {\n case \"together\":\n return slots.every((slot) => slot.ready());\n case \"forwards\":\n return slots.slice(0, index + 1).every((slot) => slot.ready());\n case \"backwards\":\n return slots.slice(index).every((slot) => slot.ready());\n default:\n return ready();\n }\n };\n const showFallback = (): boolean => {\n if (reveal()) return false;\n const order = props.revealOrder;\n const sequential = order === \"forwards\" || order === \"backwards\";\n if (!sequential) return true;\n if (props.tail === \"hidden\") return false;\n if (props.tail !== \"collapsed\") return true;\n // Only the next boundary in order that is not revealed yet shows its fallback.\n const index = position();\n const ordered = order === \"backwards\" ? [...slots].reverse() : slots;\n const wanted = order === \"backwards\" ? slots.length - 1 - index : index;\n for (let i = 0; i < ordered.length; i += 1) {\n const candidate = ordered[i];\n if (candidate !== undefined && !candidate.ready()) return i === wanted;\n }\n return false;\n };\n return { reveal, showFallback };\n },\n };\n\n return SuspenseListContext({\n value: state,\n get children() {\n return props.children;\n },\n }) as Accessor<unknown>;\n}\n\n/** The slot of the nearest list for a boundary created now, or null outside a list. @internal */\nexport function registerInList(ready: () => boolean): SuspenseListSlot | null {\n const list = useContext(SuspenseListContext);\n return list === null ? null : list.register(ready);\n}\n"],"mappings":"A,oKAkBA,MAAaA,EACK,kBAAwC,KAAM,CAAE,KAAM,cAAe,CAAC,EA+DxF,SAAgBC,EAAa,EAA6C,CAExE,IAAMC,EAAU,IAAIC,EAAmB,EAAG,EAAK,EACzCC,EAAkD,CAAC,EACnDC,MAAoB,CACxBC,EAAYJ,EAAS,EAAG,CAAE,YAAa,EAAK,CAAC,CAC/C,EAmDA,OAAOF,EAAoB,CACzB,MAAO,CAjDP,SAAS,EAAO,CACd,IAAMO,EAAQ,CAAE,OAAM,EACtBH,EAAM,KAAKG,CAAK,EAChBF,EAAM,EACNG,MAAgB,CACd,IAAMC,EAAQL,EAAM,QAAQG,CAAK,EAC7BE,IAAU,IAAIL,EAAM,OAAOK,EAAO,CAAC,EACvCJ,EAAM,CACR,CAAC,EACD,IAAMK,OACJC,EAAWT,CAAO,EACXE,EAAM,QAAQG,CAAK,GAEtBK,MAAwB,CAC5B,IAAMH,EAAQC,EAAS,EACvB,GAAID,IAAU,GAAI,MAAO,GACzB,OAAQI,EAAM,YAAd,CACE,IAAK,WACH,OAAOT,EAAM,MAAO,GAASU,EAAK,MAAM,CAAC,EAC3C,IAAK,WACH,OAAOV,EAAM,MAAM,EAAGK,EAAQ,CAAC,CAAC,CAAC,MAAO,GAASK,EAAK,MAAM,CAAC,EAC/D,IAAK,YACH,OAAOV,EAAM,MAAMK,CAAK,CAAC,CAAC,MAAO,GAASK,EAAK,MAAM,CAAC,EACxD,QACE,OAAOC,EAAM,CACjB,CACF,EAkBA,MAAO,CAAE,SAAQ,iBAjBmB,CAClC,GAAIH,EAAO,EAAG,MAAO,GACrB,IAAMI,EAAQH,EAAM,YAEpB,GADmBG,IAAU,YAAcA,IAAU,YACpC,MAAO,GACxB,GAAIH,EAAM,OAAS,SAAU,MAAO,GACpC,GAAIA,EAAM,OAAS,YAAa,MAAO,GAEvC,IAAMJ,EAAQC,EAAS,EACjBO,EAAUD,IAAU,YAAc,CAAC,GAAGZ,CAAK,CAAC,CAAC,QAAQ,EAAIA,EACzDc,EAASF,IAAU,YAAcZ,EAAM,OAAS,EAAIK,EAAQA,EAClE,IAAK,IAAIU,EAAI,EAAGA,EAAIF,EAAQ,OAAQ,GAAK,EAAG,CAC1C,IAAMG,EAAYH,EAAQE,GAC1B,GAAIC,IAAc,IAAA,IAAa,CAACA,EAAU,MAAM,EAAG,OAAOD,IAAMD,CAClE,CACA,MAAO,EACT,CAC8B,CAChC,CAIW,EACX,IAAI,UAAW,CACb,OAAOL,EAAM,QACf,CACF,CAAC,CACH,CAGA,SAAgBQ,EAAe,EAA+C,CAC5E,IAAMC,EAAOC,EAAWvB,CAAmB,EAC3C,OAAOsB,IAAS,KAAO,KAAOA,EAAK,SAASP,CAAK,CACnD,C"}
@@ -1,2 +1,2 @@
1
- import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{registerInList as r}from"./suspense-list.js";import{SuspenseContext as i,runWithOwner as a,useMemo as o}from"@shadow-js/core";import{createOwner as s,createSignalNode as c,readSignal as l,transitionHooks as u,writeSignal as d}from"@shadow-js/core/extend";function f(){let e=c(0,Object.is),t,n=!1,r=t=>{d(e,e.value+t,{allowInMemo:!0})};return{tracker:{increment:()=>r(1),decrement:()=>{r(-1),e.value===0&&t?.release()},hold:()=>n?(t??=u()?.boundaryHold(),t?.engage()===!0):!1},count:()=>l(e),holding:()=>t?.holding()===!0,revealed:()=>{n=!0}}}function p(c){let l=t(),{tracker:u,count:d,holding:p,revealed:m}=f(),h=r(()=>d()===0),g=s();g.gate=()=>d()>0||h!==null&&!h.reveal();let _=a(g,()=>n(e(l),()=>i({value:u,get children(){return c.children}}))),v=e(l===void 0?void 0:`${l}f`);return o(e=>(d(),p()&&e!==void 0?e:h===null?d()>0?n(v,()=>c.fallback):(m(),_()):d()===0&&h.reveal()?(m(),_()):h.showFallback()?n(v,()=>c.fallback):null),{allowWrites:!0})}export{p as Suspense};
1
+ import{childScope as e,nextKey as t,withScope as n}from"../internal/hydration-scope.js";import{registerInList as r}from"./suspense-list.js";import{SuspenseContext as i,runWithOwner as a,useMemo as o}from"@shadow-js/core";import{SignalNode as s,createOwner as c,readSignal as l,transitionHooks as u,writeSignal as d}from"@shadow-js/core/extend";function f(){let e=new s(0,Object.is),t,n=!1,r=t=>{d(e,e.value+t,{allowInMemo:!0})};return{tracker:{increment:()=>r(1),decrement:()=>{r(-1),e.value===0&&t?.release()},hold:()=>n?(t??=u()?.boundaryHold(),t?.engage()===!0):!1},count:()=>l(e),holding:()=>t?.holding()===!0,revealed:()=>{n=!0}}}function p(s){let l=t(),{tracker:u,count:d,holding:p,revealed:m}=f(),h=r(()=>d()===0),g=c();g.gate=()=>d()>0||h!==null&&!h.reveal();let _=a(g,()=>n(e(l),()=>i({value:u,get children(){return s.children}}))),v=e(l===void 0?void 0:`${l}f`);return o(e=>(d(),p()&&e!==void 0?e:h===null?d()>0?n(v,()=>s.fallback):(m(),_()):d()===0&&h.reveal()?(m(),_()):h.showFallback()?n(v,()=>s.fallback):null),{allowWrites:!0})}export{p as Suspense};
2
2
  //# sourceMappingURL=suspense.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"suspense.js","names":["createTracker","pending","createSignalNode","hold","shown","adjust","writeSignal","by","transitionHooks","readSignal","Suspense","key","nextKey","slot","registerInList","count","boundary","createOwner","content","runWithOwner","withScope","childScope","SuspenseContext","tracker","props","fallbackScope","useMemo","holding","previous","revealed"],"sources":["../../../src/control-flow/suspense.ts"],"sourcesContent":["import {\n type Accessor,\n getOwner,\n runWithOwner,\n SuspenseContext,\n type SuspenseTracker,\n useContext,\n useMemo,\n} from \"@shadow-js/core\";\nimport {\n type BoundaryHold,\n createOwner,\n createSignalNode,\n readSignal,\n transitionHooks,\n writeSignal,\n} from \"@shadow-js/core/extend\";\nimport { childScope, nextKey, StreamContext, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"../server/escape\";\nimport { registerInList } from \"./suspense-list\";\n\n/**\n * Props of {@link Suspense}.\n * @since 1.0.0\n */\nexport interface SuspenseProps {\n /**\n * Shown while any resource read inside the boundary is loading for the first time.\n * @default undefined (a pending boundary renders nothing)\n */\n fallback?: unknown;\n /**\n * The content. Created once, under the boundary, and kept alive while the fallback is visible.\n * @default undefined (renders nothing)\n */\n children?: unknown;\n}\n\n/** What a boundary tracks: its pending reads, and whether a transition holds its content. */\ninterface Tracking {\n readonly tracker: SuspenseTracker;\n readonly count: () => number;\n /** True while a transition waits for data and the boundary keeps showing its content. */\n readonly holding: () => boolean;\n /** Called when the boundary first shows its content: only then can a transition hold it. */\n readonly revealed: () => void;\n}\n\n/**\n * A counter the resources of one boundary report to (see {@link SuspenseTracker}), and the hold a\n * transition takes on the boundary. A transition that reads pending data while the boundary shows\n * content does not bring the fallback back: its readers keep their previous values, the boundary\n * keeps its content, and the readers run again when the count returns to zero.\n */\nfunction createTracker(): Tracking {\n // Counted with an extension-API cell: a resource may be read (and so hold this boundary) while a\n // memo computes, where a plain write would be rejected.\n const pending = createSignalNode<number>(0, Object.is);\n // The hold a transition takes on this boundary. Only a transition read creates it (core keeps the\n // machinery of holds behind its transition hooks); the boundary's memo reads the count before it\n // reads the hold, so it runs again when the count reaches zero (the release).\n let hold: BoundaryHold | undefined;\n let shown = false;\n const adjust = (by: number): void => {\n writeSignal(pending, pending.value + by, { allowInMemo: true });\n };\n const tracker: SuspenseTracker = {\n increment: () => adjust(1),\n decrement: () => {\n adjust(-1);\n if (pending.value === 0) hold?.release();\n },\n hold: (): boolean => {\n if (!shown) return false;\n hold ??= transitionHooks()?.boundaryHold();\n return hold?.engage() === true;\n },\n };\n return {\n tracker,\n count: () => readSignal(pending),\n holding: () => hold?.holding() === true,\n revealed: () => {\n shown = true;\n },\n };\n}\n\n/**\n * Shows `fallback` while resources read inside it are loading for the first time. The children\n * are created once and stay alive (with their state) while the fallback is visible; the boundary\n * only switches what is displayed. Nested boundaries each track their own resources.\n *\n * On the server a boundary renders its fallback when its data is not ready (`renderToString`), or\n * streams the content later (`renderToStream`). Content and fallback get their own hydration key\n * space, so what a boundary renders never shifts the keys of its siblings.\n *\n * @param props See {@link SuspenseProps}.\n * @returns An accessor of what the boundary shows: the fallback while a resource is pending, the\n * children otherwise.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n * import { Suspense } from \"@shadow-js/web\";\n *\n * function Profile() {\n * const name = useResource(() => Promise.resolve(\"Ada\"));\n * return <p>{name()}</p>;\n * }\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <Profile />\n * </Suspense>\n * );\n * }\n * @see SuspenseList\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function Suspense(props: SuspenseProps): Accessor<unknown> {\n const key = nextKey();\n const { tracker, count, holding, revealed } = createTracker();\n // The content lives under its own owner, whose gate holds back user effects and `onMount` until\n // the boundary has resolved once. Render effects (DOM bindings) are never held.\n // Inside a <SuspenseList> the boundary also waits for its turn to be revealed.\n const slot = __SERVER__ ? null : registerInList(() => count() === 0);\n const boundary = createOwner();\n boundary.gate = () => count() > 0 || (slot !== null && !slot.reveal());\n const content = runWithOwner(boundary, () =>\n withScope(childScope(key), () =>\n SuspenseContext({\n value: tracker,\n get children() {\n return props.children;\n },\n }),\n ),\n );\n if (__SERVER__) return suspenseOnServer(props, key, count, content as () => unknown);\n const fallbackScope = childScope(key === undefined ? undefined : `${key}f`);\n return useMemo<unknown>(\n (previous) => {\n // Read first: the memo depends on the count even while held, so it runs again when the hold ends.\n count();\n // A transition holds the boundary: the content stays as it was (the same value, so no DOM change).\n if (holding() && previous !== undefined) return previous;\n if (slot === null) {\n if (count() > 0) return withScope(fallbackScope, () => props.fallback);\n revealed();\n return (content as () => unknown)();\n }\n if (count() === 0 && slot.reveal()) {\n revealed();\n return (content as () => unknown)();\n }\n return slot.showFallback() ? withScope(fallbackScope, () => props.fallback) : null;\n },\n { allowWrites: true },\n );\n}\n\n/** Server behavior: ready content, a fallback, or a fallback plus a deferred stream chunk. */\nfunction suspenseOnServer(\n props: SuspenseProps,\n key: string | undefined,\n count: () => number,\n content: () => unknown,\n): Accessor<unknown> {\n const fallbackScope = childScope(key === undefined ? undefined : `${key}f`);\n if (count() === 0) return content;\n const sink = useContext(StreamContext);\n if (sink === null || key === undefined) {\n return () => withScope(fallbackScope, () => props.fallback);\n }\n const owner = getOwner();\n const boundary = {\n id: key,\n rebuild: (): string | null => {\n const next = createTracker();\n const rebuilt = runWithOwner(owner, () =>\n withScope(childScope(key), () =>\n SuspenseContext({\n value: next.tracker,\n get children() {\n return props.children;\n },\n }),\n ),\n );\n if (next.count() > 0) {\n sink.defer(boundary);\n return null;\n }\n return escape((rebuilt as () => unknown)());\n },\n };\n sink.defer(boundary);\n // The markers delimit the region the stream later replaces; hydration strips them.\n return () => [\n ssrRaw(`<!--[b:${key}-->`),\n withScope(fallbackScope, () => props.fallback),\n ssrRaw(\"<!--]-->\"),\n ];\n}\n"],"mappings":"A,8VAwDA,SAASA,GAA0B,CAGjC,IAAMC,EAAUC,EAAyB,EAAG,OAAO,EAAE,EAIjDC,EACAC,EAAQ,GACNC,EAAU,GAAqB,CACnCC,EAAYL,EAASA,EAAQ,MAAQM,EAAI,CAAE,YAAa,EAAK,CAAC,CAChE,EAaA,MAAO,CACL,QAAA,CAZA,cAAiBF,EAAO,CAAC,EACzB,cAAiB,CACfA,EAAO,EAAE,EACLJ,EAAQ,QAAU,GAAGE,GAAM,QAAQ,CACzC,EACA,SACOC,GACL,IAASI,EAAgB,CAAC,EAAE,aAAa,EAClCL,GAAM,OAAO,IAAM,IAFP,EAMf,EACN,UAAaM,EAAWR,CAAO,EAC/B,YAAeE,GAAM,QAAQ,IAAM,GACnC,aAAgB,CACd,EAAQ,EACV,CACF,CACF,CAkCA,SAAgBO,EAAS,EAAyC,CAChE,IAAMC,EAAMC,EAAQ,EACd,CAAE,UAAS,QAAO,UAAS,YAAaZ,EAAc,EAItDa,EAA2BC,MAAqBC,EAAM,IAAM,CAAC,EAC7DC,EAAWC,EAAY,EAC7B,EAAS,SAAaF,EAAM,EAAI,GAAMF,IAAS,MAAQ,CAACA,EAAK,OAAO,EACpE,IAAMK,EAAUC,EAAaH,MAC3BI,EAAUC,EAAWV,CAAG,MACtBW,EAAgB,CACd,MAAOC,EACP,IAAI,UAAW,CACb,OAAOC,EAAM,QACf,CACF,CAAC,CACH,CACF,EAEMC,EAAgBJ,EAAWV,IAAQ,IAAA,GAAY,IAAA,GAAY,GAAGA,EAAI,EAAE,EAC1E,OAAOe,EACJ,IAECX,EAAM,EAEFY,EAAQ,GAAKC,IAAa,IAAA,GAAkBA,EAC5Cf,IAAS,KACPE,EAAM,EAAI,EAAUK,EAAUK,MAAqBD,EAAM,QAAQ,GACrEK,EAAS,EACDX,EAA0B,GAEhCH,EAAM,IAAM,GAAKF,EAAK,OAAO,GAC/BgB,EAAS,EACDX,EAA0B,GAE7BL,EAAK,aAAa,EAAIO,EAAUK,MAAqBD,EAAM,QAAQ,EAAI,MAEhF,CAAE,YAAa,EAAK,CACtB,CACF,C"}
1
+ {"version":3,"file":"suspense.js","names":["createTracker","pending","SignalNode","hold","shown","adjust","writeSignal","by","transitionHooks","readSignal","Suspense","key","nextKey","slot","registerInList","count","boundary","createOwner","content","runWithOwner","withScope","childScope","SuspenseContext","tracker","props","fallbackScope","useMemo","holding","previous","revealed"],"sources":["../../../src/control-flow/suspense.ts"],"sourcesContent":["import {\n type Accessor,\n getOwner,\n runWithOwner,\n SuspenseContext,\n type SuspenseTracker,\n useContext,\n useMemo,\n} from \"@shadow-js/core\";\nimport {\n type BoundaryHold,\n createOwner,\n readSignal,\n SignalNode,\n transitionHooks,\n writeSignal,\n} from \"@shadow-js/core/extend\";\nimport { childScope, nextKey, StreamContext, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"../server/escape\";\nimport { registerInList } from \"./suspense-list\";\n\n/**\n * Props of {@link Suspense}.\n * @since 1.0.0\n */\nexport interface SuspenseProps {\n /**\n * Shown while any resource read inside the boundary is loading for the first time.\n * @default undefined (a pending boundary renders nothing)\n */\n fallback?: unknown;\n /**\n * The content. Created once, under the boundary, and kept alive while the fallback is visible.\n * @default undefined (renders nothing)\n */\n children?: unknown;\n}\n\n/** What a boundary tracks: its pending reads, and whether a transition holds its content. */\ninterface Tracking {\n readonly tracker: SuspenseTracker;\n readonly count: () => number;\n /** True while a transition waits for data and the boundary keeps showing its content. */\n readonly holding: () => boolean;\n /** Called when the boundary first shows its content: only then can a transition hold it. */\n readonly revealed: () => void;\n}\n\n/**\n * A counter the resources of one boundary report to (see {@link SuspenseTracker}), and the hold a\n * transition takes on the boundary. A transition that reads pending data while the boundary shows\n * content does not bring the fallback back: its readers keep their previous values, the boundary\n * keeps its content, and the readers run again when the count returns to zero.\n */\nfunction createTracker(): Tracking {\n // Counted with an extension-API cell: a resource may be read (and so hold this boundary) while a\n // memo computes, where a plain write would be rejected.\n const pending = new SignalNode<number>(0, Object.is);\n // The hold a transition takes on this boundary. Only a transition read creates it (core keeps the\n // machinery of holds behind its transition hooks); the boundary's memo reads the count before it\n // reads the hold, so it runs again when the count reaches zero (the release).\n let hold: BoundaryHold | undefined;\n let shown = false;\n const adjust = (by: number): void => {\n writeSignal(pending, pending.value + by, { allowInMemo: true });\n };\n const tracker: SuspenseTracker = {\n increment: () => adjust(1),\n decrement: () => {\n adjust(-1);\n if (pending.value === 0) hold?.release();\n },\n hold: (): boolean => {\n if (!shown) return false;\n hold ??= transitionHooks()?.boundaryHold();\n return hold?.engage() === true;\n },\n };\n return {\n tracker,\n count: () => readSignal(pending),\n holding: () => hold?.holding() === true,\n revealed: () => {\n shown = true;\n },\n };\n}\n\n/**\n * Shows `fallback` while resources read inside it are loading for the first time. The children\n * are created once and stay alive (with their state) while the fallback is visible; the boundary\n * only switches what is displayed. Nested boundaries each track their own resources.\n *\n * On the server a boundary renders its fallback when its data is not ready (`renderToString`), or\n * streams the content later (`renderToStream`). Content and fallback get their own hydration key\n * space, so what a boundary renders never shifts the keys of its siblings.\n *\n * @param props See {@link SuspenseProps}.\n * @returns An accessor of what the boundary shows: the fallback while a resource is pending, the\n * children otherwise.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n * import { Suspense } from \"@shadow-js/web\";\n *\n * function Profile() {\n * const name = useResource(() => Promise.resolve(\"Ada\"));\n * return <p>{name()}</p>;\n * }\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <Profile />\n * </Suspense>\n * );\n * }\n * @see SuspenseList\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function Suspense(props: SuspenseProps): Accessor<unknown> {\n const key = nextKey();\n const { tracker, count, holding, revealed } = createTracker();\n // The content lives under its own owner, whose gate holds back user effects and `onMount` until\n // the boundary has resolved once. Render effects (DOM bindings) are never held.\n // Inside a <SuspenseList> the boundary also waits for its turn to be revealed.\n const slot = __SERVER__ ? null : registerInList(() => count() === 0);\n const boundary = createOwner();\n boundary.gate = () => count() > 0 || (slot !== null && !slot.reveal());\n const content = runWithOwner(boundary, () =>\n withScope(childScope(key), () =>\n SuspenseContext({\n value: tracker,\n get children() {\n return props.children;\n },\n }),\n ),\n );\n if (__SERVER__) return suspenseOnServer(props, key, count, content as () => unknown);\n const fallbackScope = childScope(key === undefined ? undefined : `${key}f`);\n return useMemo<unknown>(\n (previous) => {\n // Read first: the memo depends on the count even while held, so it runs again when the hold ends.\n count();\n // A transition holds the boundary: the content stays as it was (the same value, so no DOM change).\n if (holding() && previous !== undefined) return previous;\n if (slot === null) {\n if (count() > 0) return withScope(fallbackScope, () => props.fallback);\n revealed();\n return (content as () => unknown)();\n }\n if (count() === 0 && slot.reveal()) {\n revealed();\n return (content as () => unknown)();\n }\n return slot.showFallback() ? withScope(fallbackScope, () => props.fallback) : null;\n },\n { allowWrites: true },\n );\n}\n\n/** Server behavior: ready content, a fallback, or a fallback plus a deferred stream chunk. */\nfunction suspenseOnServer(\n props: SuspenseProps,\n key: string | undefined,\n count: () => number,\n content: () => unknown,\n): Accessor<unknown> {\n const fallbackScope = childScope(key === undefined ? undefined : `${key}f`);\n if (count() === 0) return content;\n const sink = useContext(StreamContext);\n if (sink === null || key === undefined) {\n return () => withScope(fallbackScope, () => props.fallback);\n }\n const owner = getOwner();\n const boundary = {\n id: key,\n rebuild: (): string | null => {\n const next = createTracker();\n const rebuilt = runWithOwner(owner, () =>\n withScope(childScope(key), () =>\n SuspenseContext({\n value: next.tracker,\n get children() {\n return props.children;\n },\n }),\n ),\n );\n if (next.count() > 0) {\n sink.defer(boundary);\n return null;\n }\n return escape((rebuilt as () => unknown)());\n },\n };\n sink.defer(boundary);\n // The markers delimit the region the stream later replaces; hydration strips them.\n return () => [\n ssrRaw(`<!--[b:${key}-->`),\n withScope(fallbackScope, () => props.fallback),\n ssrRaw(\"<!--]-->\"),\n ];\n}\n"],"mappings":"A,wVAwDA,SAASA,GAA0B,CAGjC,IAAMC,EAAU,IAAIC,EAAmB,EAAG,OAAO,EAAE,EAI/CC,EACAC,EAAQ,GACNC,EAAU,GAAqB,CACnCC,EAAYL,EAASA,EAAQ,MAAQM,EAAI,CAAE,YAAa,EAAK,CAAC,CAChE,EAaA,MAAO,CACL,QAAA,CAZA,cAAiBF,EAAO,CAAC,EACzB,cAAiB,CACfA,EAAO,EAAE,EACLJ,EAAQ,QAAU,GAAGE,GAAM,QAAQ,CACzC,EACA,SACOC,GACL,IAASI,EAAgB,CAAC,EAAE,aAAa,EAClCL,GAAM,OAAO,IAAM,IAFP,EAMf,EACN,UAAaM,EAAWR,CAAO,EAC/B,YAAeE,GAAM,QAAQ,IAAM,GACnC,aAAgB,CACd,EAAQ,EACV,CACF,CACF,CAkCA,SAAgBO,EAAS,EAAyC,CAChE,IAAMC,EAAMC,EAAQ,EACd,CAAE,UAAS,QAAO,UAAS,YAAaZ,EAAc,EAItDa,EAA2BC,MAAqBC,EAAM,IAAM,CAAC,EAC7DC,EAAWC,EAAY,EAC7B,EAAS,SAAaF,EAAM,EAAI,GAAMF,IAAS,MAAQ,CAACA,EAAK,OAAO,EACpE,IAAMK,EAAUC,EAAaH,MAC3BI,EAAUC,EAAWV,CAAG,MACtBW,EAAgB,CACd,MAAOC,EACP,IAAI,UAAW,CACb,OAAOC,EAAM,QACf,CACF,CAAC,CACH,CACF,EAEMC,EAAgBJ,EAAWV,IAAQ,IAAA,GAAY,IAAA,GAAY,GAAGA,EAAI,EAAE,EAC1E,OAAOe,EACJ,IAECX,EAAM,EAEFY,EAAQ,GAAKC,IAAa,IAAA,GAAkBA,EAC5Cf,IAAS,KACPE,EAAM,EAAI,EAAUK,EAAUK,MAAqBD,EAAM,QAAQ,GACrEK,EAAS,EACDX,EAA0B,GAEhCH,EAAM,IAAM,GAAKF,EAAK,OAAO,GAC/BgB,EAAS,EACDX,EAA0B,GAE7BL,EAAK,aAAa,EAAIO,EAAUK,MAAqBD,EAAM,QAAQ,EAAI,MAEhF,CAAE,YAAa,EAAK,CACtB,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{setAttribute as e}from"./attributes.js";import{style as t}from"./class-style.js";import{nextKey as n}from"./internal/hydration-scope.js";import{claims as r}from"./internal/hydration-hooks.js";import{insert as i}from"./insert.js";import{batch as a,untrack as o,useRenderEffect as s}from"@shadow-js/core";const c=/^[a-z][a-z0-9-]*$/i;function l(e){return e.length>2&&e.startsWith(`on`)&&/^[A-Z]/.test(e.charAt(2))?e.slice(2).toLowerCase():void 0}function u(e,t,n){let r;if(typeof n==`function`)r=t=>n.call(e,t);else if(Array.isArray(n)){let[t,i]=n;typeof t==`function`&&(r=n=>t.call(e,i,n))}if(r===void 0)return;let i=r;e.addEventListener(t,e=>{a(()=>o(()=>i(e)))})}function d(a,d){if(!c.test(a)||a.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let f=d,p=r.current.claimElement(n())??document.createElement(a);for(let n of Object.keys(d)){if(n===`children`||n===`ref`)continue;let r=l(n);if(r!==void 0)u(p,r,f[n]);else if(n===`style`){let e;s(()=>f[n],n=>{e=t(p,n,e)})}else s(()=>f[n],t=>{e(p,n,t)})}let m=f.ref;return typeof m==`function`&&o(()=>m(p)),i(p,()=>f.children),p}export{d as element};
1
+ import{setAttribute as e,setBoolAttribute as t}from"./attributes.js";import{style as n}from"./class-style.js";import{nextKey as r}from"./internal/hydration-scope.js";import{claims as i}from"./internal/hydration-hooks.js";import{insert as a}from"./insert.js";import{isFlagAttribute as o}from"./internal/react-names.js";import{batch as s,untrack as c,useRenderEffect as l}from"@shadow-js/core";const u=/^[a-z][a-z0-9-]*$/i;function d(d,f){if(!u.test(d)||d.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let p=f,m=i.current.claimElement(r())??document.createElement(d);for(let r of Object.keys(f))if(r!==`children`&&r!==`ref`){if(/^on[A-Z]/.test(r)){let e=p[r],t=Array.isArray(e),[n,i]=t?e:[e];typeof n==`function`&&m.addEventListener(r.slice(2).toLowerCase(),e=>{s(()=>c(()=>t?n.call(m,i,e):n.call(m,e)))})}else if(r===`style`){let e;l(()=>p[r],t=>{e=n(m,t,e)})}else l(()=>p[r],n=>{let i=r.toLowerCase();o(i,n)?t(m,i,n):e(m,r,n)})}let h=p.ref;return typeof h==`function`&&c(()=>h(m)),a(m,()=>p.children),m}export{d as element};
2
2
  //# sourceMappingURL=element.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","names":["TAG_PATTERN","eventNameOf","key","bindListener","call","handler","el","event","fn","data","run","name","batch","untrack","element","tag","read","props","claims","nextKey","applied","useRenderEffect","style","value","setAttribute","ref","\"ref\"","insert","\"children\""],"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,sTAqBA,MAAMA,EAAc,qBAGpB,SAASC,EAAY,EAAiC,CACpD,OAAOC,EAAI,OAAS,GAAKA,EAAI,WAAW,IAAI,GAAK,SAAS,KAAKA,EAAI,OAAO,CAAC,CAAC,EACxEA,EAAI,MAAM,CAAC,CAAC,CAAC,YAAY,EACzB,IAAA,EACN,CAOA,SAASC,EAAa,EAAa,EAAc,EAAwB,CACvE,IAAIC,EACJ,GAAI,OAAOC,GAAY,WACrB,EAAQ,GAA0BA,EAAQ,KAAKC,EAAIC,CAAK,OACnD,GAAI,MAAM,QAAQF,CAAO,EAAG,CACjC,GAAM,CAACG,EAAIC,GAAQJ,EACf,OAAOG,GAAO,aAAY,EAAQ,GAA0BA,EAAG,KAAKF,EAAIG,EAAMF,CAAK,EACzF,CACA,GAAIH,IAAS,IAAA,GAAW,OACxB,IAAMM,EAAMN,EACZE,EAAG,iBAAiBK,EAAO,GAAuB,CAChDC,MAAYC,MAAcH,EAAIH,CAAK,CAAC,CAAC,CACvC,CAAC,CACH,CAsCA,SAAgBO,EAAQ,EAAa,EAAwB,CAC3D,GAAI,CAACd,EAAY,KAAKe,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAMC,EAAOC,EAiBPX,EAFUY,EAAO,QAAQ,aAAaC,EAAQ,CAEnC,GAAK,SAAS,cAAcJ,CAAG,EAChD,IAAK,IAAMb,KAAO,OAAO,KAAKe,CAAK,EAAG,CACpC,GAAIf,IAAQ,YAAcA,IAAQ,MAAO,SACzC,IAAMK,EAAQN,EAAYC,CAAG,EAC7B,GAAIK,IAAU,IAAA,GACZJ,EAAaG,EAAIC,EAAOS,EAAKd,EAAI,OAC5B,GAAIA,IAAQ,QAAS,CAE1B,IAAIkB,EACJC,MACQL,EAAKd,GACV,GAAU,CACT,EAAUoB,EAAMhB,EAAmBiB,EAAOH,CAAO,CACnD,CACF,CACF,MACEC,MACQL,EAAKd,GACV,GAAU,CACTsB,EAAalB,EAAIJ,EAAKqB,CAAK,CAC7B,CACF,CAEJ,CACA,IAAME,EAAMT,EAAKU,IAGjB,OAFI,OAAOD,GAAQ,YAAYZ,MAAcY,EAAInB,CAAE,CAAC,EACpDqB,EAAOrB,MAAUU,EAAKY,QAAW,EAC1BtB,CACT,C"}
1
+ {"version":3,"file":"element.js","names":["TAG_PATTERN","element","tag","read","props","el","claims","nextKey","key","handler","tuple","fn","data","batch","untrack","event","applied","useRenderEffect","style","value","name","isFlagAttribute","setBoolAttribute","setAttribute","ref","\"ref\"","insert","\"children\""],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setBoolAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { isFlagAttribute } from \"./internal/react-names\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/**\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 if (/^on[A-Z]/.test(key)) {\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 const handler = read[key];\n const tuple = Array.isArray(handler);\n // The tuple's data is read once, at bind time, like the handler.\n const [fn, data]: readonly unknown[] = tuple ? handler : [handler];\n if (typeof fn === \"function\") {\n el.addEventListener(key.slice(2).toLowerCase(), (event: Event): void => {\n batch(() => untrack(() => (tuple ? fn.call(el, data, event) : fn.call(el, event))));\n });\n }\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n // The server writes a boolean attribute by truthiness; the client does the same. A name\n // that is a flag has no React spelling, so lower case is its attribute name.\n const name = key.toLowerCase();\n if (isFlagAttribute(name, value)) setBoolAttribute(el, name, value);\n else setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(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2 @@
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};
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(t){e(()=>{let e=`$$${t.type}`,n=`${e}Data`,i=[];for(let a of t.composedPath()){if(t.cancelBubble)break;let o=Reflect.get(a,e);if(typeof o!=`function`)continue;let s=Reflect.get(a,n);try{Object.defineProperty(t,"currentTarget",{configurable:!0,get:()=>a}),r(()=>o.call(a,...s===void 0?[t]:[s,t]))}catch(e){i.push(e)}finally{Reflect.deleteProperty(t,`currentTarget`)}}let[a]=i;if(i.length===1)throw a;if(i.length>1)throw AggregateError(i,`SHADOW_EVENT_ERRORS`)})}function s(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function c(t,n,i,a){let o=t=>{e(()=>r(()=>i(t)))};return t.addEventListener(n,o,a),()=>{t.removeEventListener(n,o,a)}}function l(e,t,n,r){let{once:i,passive:a,signal:o}=n;return c(e,t,e=>n.handleEvent(e),{capture:n.capture===!0||r,once:i,passive:a,signal:o})}function u(...e){return function(t){for(let n of e)n.call(this,t)}}function d(e,t){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n)),!n.has(e)&&(n.add(e),t.addEventListener(e,o))}function f(e,t=globalThis.document){for(let n of e)d(n,t)}function p(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,o);a.delete(e)}}function m(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function h(e,t,n,r,a=!1){if(n==null||n===!1)return;if(s(n))return l(e,t,n,a);let o=n,u,f=!1;if(Array.isArray(n)&&typeof n[0]==`function`)o=n[0],u=n[1],f=!0;else if(typeof n!=`function`)throw TypeError(`SHADOW_EVENT_HANDLER`);let p=`$$${t}`;if(r&&(!f||u!==void 0)&&!a&&i.test(t)&&Reflect.get(e,p)===void 0){d(t,m(e));let n=`${p}Data`;return Reflect.set(e,p,o),f?Reflect.set(e,n,u):Reflect.deleteProperty(e,n),()=>{Reflect.get(e,p)===o&&(Reflect.deleteProperty(e,p),Reflect.deleteProperty(e,n))}}return c(e,t,t=>o.call(e,...f?[u,t]:[t]),a)}function g(e,r,i,a,o){let s=h(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{g as addEventListener,h as bindEvent,u as chainEvents,p as clearDelegatedEvents,f as delegateEvents};
2
2
  //# sourceMappingURL=events.js.map
@@ -1 +1 @@
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,IAAMG,EAAK,QAAQ,IAAIF,EAAMO,CAAG,EAChC,GAAI,OAAOL,GAAO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,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
+ {"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","dispatchDelegated","batch","key","event","dataKey","errors","node","fn","data","untrack","error","first","isListenerObject","handler","listen","listener","run","el","name","options","bindListenerObject","object","capture","chainEvents","handlers","installDelegate","known","target","delegateEvents","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","tuple","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 =\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 bound handler: called with `this` = the node. */\ntype Handler = (this: EventTarget, ...args: unknown[]) => unknown;\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the\n * duration of the call. 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(() => {\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 Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n untrack(() =>\n (fn as Handler).call(node, ...(data === undefined ? [event] : [data, event])),\n );\n } catch (error) {\n errors.push(error);\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\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\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/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */\nfunction listen(\n el: Element,\n name: string,\n run: (event: Event) => unknown,\n options: AddEventListenerOptions | boolean,\n): () => void {\n const listener = (event: Event): void => {\n batch(() => untrack(() => run(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\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 return listen(el, name, (event) => object.handleEvent(event), {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions);\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/** Installs the delegated listener for one event name on `target`, unless it is there already. */\nfunction installDelegate(name: string, target: Document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n if (known.has(name)) return;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\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 for (const name of names) installDelegate(name, target);\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 let fn = handler as Handler;\n let data: unknown;\n let tuple = false;\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n fn = handler[0] as Handler;\n data = handler[1];\n tuple = true;\n } else if (typeof handler !== \"function\") {\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 // 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 if (\n delegate &&\n (!tuple || data !== undefined) &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n installDelegate(name, delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, fn);\n if (tuple) Reflect.set(el, dataKey, data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n return listen(el, name, (event) => fn.call(el, ...(tuple ? [data, event] : [event])), capture);\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,EAAkB,EAAoB,CAG7CC,MAAY,CACV,IAAMC,EAAM,KAAKC,EAAM,OACjBC,EAAU,GAAGF,EAAI,MACjBG,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB,IAAMI,EAAK,QAAQ,IAAID,EAAMJ,CAAG,EAChC,GAAI,OAAOK,GAAO,WAAY,SAC9B,IAAMC,EAAO,QAAQ,IAAIF,EAAMF,CAAO,EACtC,GAAI,CACF,OAAO,eAAeD,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWG,CAAK,CAAC,EACrFG,MACGF,EAAe,KAAKD,EAAM,GAAIE,IAAS,IAAA,GAAY,CAACL,CAAK,EAAI,CAACK,EAAML,CAAK,CAAE,CAC9E,CACF,OAASO,EAAO,CACdL,EAAO,KAAKK,CAAK,CACnB,QAAU,CACR,QAAQ,eAAeP,EAAO,eAAe,CAC/C,CACF,CACA,GAAM,CAACQ,GAASN,EAChB,GAAIA,EAAO,SAAW,EAAG,MAAMM,EAC/B,GAAIN,EAAO,OAAS,EAClB,MAAU,eACRA,EAC4C,qBAC9C,CACJ,CAAC,CACH,CAWA,SAASO,EAAiB,EAA6C,CACrE,OACE,OAAOC,GAAY,YACnBA,GACA,OAAQA,EAAsC,aAAgB,UAElE,CAGA,SAASC,EACP,EACA,EACA,EACA,EACY,CACZ,IAAMC,EAAY,GAAuB,CACvCd,MAAYQ,MAAcO,EAAIb,CAAK,CAAC,CAAC,CACvC,EAE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