@shadow-js/web 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/dev/attributes.d.ts +1 -2
  4. package/dist/dev/autofocus.d.ts +1 -2
  5. package/dist/dev/class-style.d.ts +1 -2
  6. package/dist/dev/component.d.ts +1 -2
  7. package/dist/dev/control-flow/activity.d.ts +1 -2
  8. package/dist/dev/control-flow/client-only.d.ts +1 -2
  9. package/dist/dev/control-flow/dynamic.d.ts +1 -2
  10. package/dist/dev/control-flow/error-boundary.d.ts +1 -2
  11. package/dist/dev/control-flow/for.d.ts +1 -2
  12. package/dist/dev/control-flow/fragment.d.ts +1 -2
  13. package/dist/dev/control-flow/index-list.d.ts +1 -2
  14. package/dist/dev/control-flow/lazy.d.ts +1 -2
  15. package/dist/dev/control-flow/no-hydration.d.ts +1 -2
  16. package/dist/dev/control-flow/portal.d.ts +1 -2
  17. package/dist/dev/control-flow/portal.js.map +1 -1
  18. package/dist/dev/control-flow/root-errors.d.ts +2 -3
  19. package/dist/dev/control-flow/show.d.ts +1 -2
  20. package/dist/dev/control-flow/suspense-list.d.ts +2 -3
  21. package/dist/dev/control-flow/suspense.d.ts +1 -2
  22. package/dist/dev/control-flow/switch.d.ts +1 -2
  23. package/dist/dev/derived.d.ts +1 -2
  24. package/dist/dev/element.d.ts +1 -2
  25. package/dist/dev/events.d.ts +1 -2
  26. package/dist/dev/extend.d.ts +9 -0
  27. package/dist/dev/head/components.d.ts +1 -2
  28. package/dist/dev/head/server-head.d.ts +2 -3
  29. package/dist/dev/head/use-head.d.ts +1 -2
  30. package/dist/dev/head/validate.d.ts +1 -2
  31. package/dist/dev/hmr.d.ts +1 -2
  32. package/dist/dev/hmr.js.map +1 -1
  33. package/dist/dev/hydration.d.ts +1 -2
  34. package/dist/dev/insert.d.ts +1 -2
  35. package/dist/dev/insert.js.map +1 -1
  36. package/dist/dev/internal/claim.d.ts +1 -2
  37. package/dist/dev/internal/diagnostics.d.ts +1 -2
  38. package/dist/dev/internal/hydration-hooks.d.ts +1 -2
  39. package/dist/dev/internal/hydration-scope.d.ts +1 -2
  40. package/dist/dev/internal/names.d.ts +1 -2
  41. package/dist/dev/internal/portal-context.d.ts +1 -2
  42. package/dist/dev/internal/reconcile.d.ts +1 -2
  43. package/dist/dev/internal/reconcile.js.map +1 -1
  44. package/dist/dev/internal/stream-context.d.ts +1 -2
  45. package/dist/dev/jsx/aria.d.ts +7 -2
  46. package/dist/dev/jsx/component.d.ts +7 -2
  47. package/dist/dev/jsx/events.d.ts +1 -2
  48. package/dist/dev/jsx/global.d.ts +11 -2
  49. package/dist/dev/jsx/html.d.ts +8 -2
  50. package/dist/dev/jsx/intrinsic.d.ts +10 -2
  51. package/dist/dev/jsx/mathml.d.ts +8 -2
  52. package/dist/dev/jsx/svg.d.ts +13 -2
  53. package/dist/dev/jsx/types.d.ts +1 -2
  54. package/dist/dev/jsx-dev-runtime.d.ts +6 -0
  55. package/dist/dev/jsx-runtime.d.ts +13 -2
  56. package/dist/dev/reactive.d.ts +1 -2
  57. package/dist/dev/render.d.ts +1 -2
  58. package/dist/dev/resource-hints.d.ts +1 -2
  59. package/dist/dev/select-value.d.ts +1 -2
  60. package/dist/dev/server/attributes.d.ts +1 -2
  61. package/dist/dev/server/class-style.d.ts +1 -2
  62. package/dist/dev/server/component.d.ts +1 -2
  63. package/dist/dev/server/derived.d.ts +1 -2
  64. package/dist/dev/server/element.d.ts +1 -2
  65. package/dist/dev/server/errors.js.map +1 -1
  66. package/dist/dev/server/escape.d.ts +1 -2
  67. package/dist/dev/server/form-controls.d.ts +1 -2
  68. package/dist/dev/server/hydration-script.d.ts +1 -2
  69. package/dist/dev/server/index.d.ts +7 -2
  70. package/dist/dev/server/index.js +2 -2
  71. package/dist/dev/server/node.d.ts +1 -2
  72. package/dist/dev/server/node.js.map +1 -1
  73. package/dist/dev/server/portals.d.ts +1 -2
  74. package/dist/dev/server/portals.js.map +1 -1
  75. package/dist/dev/server/raw-text.d.ts +1 -2
  76. package/dist/dev/server/render.d.ts +1 -2
  77. package/dist/dev/server/serialize.d.ts +1 -2
  78. package/dist/dev/server/stream.d.ts +1 -2
  79. package/dist/dev/server/stream.js.map +1 -1
  80. package/dist/dev/server.d.ts +1 -0
  81. package/dist/dev/spread.d.ts +1 -2
  82. package/dist/dev/template.d.ts +1 -2
  83. package/dist/dev/view-transition.d.ts +1 -2
  84. package/dist/prod/attributes.js.map +1 -1
  85. package/dist/prod/autofocus.js.map +1 -1
  86. package/dist/prod/class-style.js.map +1 -1
  87. package/dist/prod/component.js.map +1 -1
  88. package/dist/prod/control-flow/activity.js.map +1 -1
  89. package/dist/prod/control-flow/branch.js.map +1 -1
  90. package/dist/prod/control-flow/client-only.js.map +1 -1
  91. package/dist/prod/control-flow/dynamic.js.map +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/for.js.map +1 -1
  94. package/dist/prod/control-flow/fragment.js.map +1 -1
  95. package/dist/prod/control-flow/hot-link.js.map +1 -1
  96. package/dist/prod/control-flow/index-list.js.map +1 -1
  97. package/dist/prod/control-flow/lazy.js.map +1 -1
  98. package/dist/prod/control-flow/no-hydration.js.map +1 -1
  99. package/dist/prod/control-flow/portal.js.map +1 -1
  100. package/dist/prod/control-flow/root-errors.js.map +1 -1
  101. package/dist/prod/control-flow/show.js.map +1 -1
  102. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  103. package/dist/prod/control-flow/suspense.js.map +1 -1
  104. package/dist/prod/control-flow/switch.js.map +1 -1
  105. package/dist/prod/derived.js.map +1 -1
  106. package/dist/prod/element.js.map +1 -1
  107. package/dist/prod/events.js.map +1 -1
  108. package/dist/prod/head/components.js.map +1 -1
  109. package/dist/prod/head/registry.js.map +1 -1
  110. package/dist/prod/head/server-head.js.map +1 -1
  111. package/dist/prod/head/sink.js.map +1 -1
  112. package/dist/prod/head/use-head.js.map +1 -1
  113. package/dist/prod/head/validate.js.map +1 -1
  114. package/dist/prod/hmr.js.map +1 -1
  115. package/dist/prod/hydration.js.map +1 -1
  116. package/dist/prod/insert.js.map +1 -1
  117. package/dist/prod/internal/accessor.js.map +1 -1
  118. package/dist/prod/internal/claim.js.map +1 -1
  119. package/dist/prod/internal/css-units.js.map +1 -1
  120. package/dist/prod/internal/diagnostics.js.map +1 -1
  121. package/dist/prod/internal/early-events.js.map +1 -1
  122. package/dist/prod/internal/hydration-hooks.js.map +1 -1
  123. package/dist/prod/internal/hydration-scope.js.map +1 -1
  124. package/dist/prod/internal/portal-context.js.map +1 -1
  125. package/dist/prod/internal/react-names.js.map +1 -1
  126. package/dist/prod/internal/reconcile.js.map +1 -1
  127. package/dist/prod/internal/stream-context.js.map +1 -1
  128. package/dist/prod/reactive.js.map +1 -1
  129. package/dist/prod/render.js.map +1 -1
  130. package/dist/prod/resource-hints.js.map +1 -1
  131. package/dist/prod/select-value.js.map +1 -1
  132. package/dist/prod/server/attributes.js.map +1 -1
  133. package/dist/prod/server/class-style.js.map +1 -1
  134. package/dist/prod/server/component.js.map +1 -1
  135. package/dist/prod/server/derived.js.map +1 -1
  136. package/dist/prod/server/element.js.map +1 -1
  137. package/dist/prod/server/errors.js.map +1 -1
  138. package/dist/prod/server/escape.js.map +1 -1
  139. package/dist/prod/server/form-controls.js.map +1 -1
  140. package/dist/prod/server/hydration-script.js.map +1 -1
  141. package/dist/prod/server/node.js.map +1 -1
  142. package/dist/prod/server/portals.js.map +1 -1
  143. package/dist/prod/server/raw-text.js.map +1 -1
  144. package/dist/prod/server/render.js.map +1 -1
  145. package/dist/prod/server/serialize.js.map +1 -1
  146. package/dist/prod/server/stream.js.map +1 -1
  147. package/dist/prod/spread.js.map +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js.map +1 -1
  150. package/dist/server/attributes.js.map +1 -1
  151. package/dist/server/autofocus.js.map +1 -1
  152. package/dist/server/class-style.js.map +1 -1
  153. package/dist/server/component.js.map +1 -1
  154. package/dist/server/control-flow/activity.js.map +1 -1
  155. package/dist/server/control-flow/branch.js.map +1 -1
  156. package/dist/server/control-flow/client-only.js.map +1 -1
  157. package/dist/server/control-flow/dynamic.js.map +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/for.js.map +1 -1
  160. package/dist/server/control-flow/fragment.js.map +1 -1
  161. package/dist/server/control-flow/index-list.js.map +1 -1
  162. package/dist/server/control-flow/lazy.js.map +1 -1
  163. package/dist/server/control-flow/no-hydration.js.map +1 -1
  164. package/dist/server/control-flow/portal.js.map +1 -1
  165. package/dist/server/control-flow/root-errors.js.map +1 -1
  166. package/dist/server/control-flow/show.js.map +1 -1
  167. package/dist/server/control-flow/suspense-list.js.map +1 -1
  168. package/dist/server/control-flow/suspense.js.map +1 -1
  169. package/dist/server/control-flow/switch.js.map +1 -1
  170. package/dist/server/derived.js.map +1 -1
  171. package/dist/server/element.js.map +1 -1
  172. package/dist/server/events.js.map +1 -1
  173. package/dist/server/head/components.js.map +1 -1
  174. package/dist/server/head/registry.js.map +1 -1
  175. package/dist/server/head/server-head.js.map +1 -1
  176. package/dist/server/head/sink.js.map +1 -1
  177. package/dist/server/head/use-head.js.map +1 -1
  178. package/dist/server/head/validate.js.map +1 -1
  179. package/dist/server/hydration.js.map +1 -1
  180. package/dist/server/insert.js.map +1 -1
  181. package/dist/server/internal/accessor.js.map +1 -1
  182. package/dist/server/internal/claim.js.map +1 -1
  183. package/dist/server/internal/css-units.js.map +1 -1
  184. package/dist/server/internal/diagnostics.js.map +1 -1
  185. package/dist/server/internal/early-events.js.map +1 -1
  186. package/dist/server/internal/hydration-hooks.js.map +1 -1
  187. package/dist/server/internal/hydration-scope.js.map +1 -1
  188. package/dist/server/internal/portal-context.js.map +1 -1
  189. package/dist/server/internal/react-names.js.map +1 -1
  190. package/dist/server/internal/reconcile.js.map +1 -1
  191. package/dist/server/internal/stream-context.js.map +1 -1
  192. package/dist/server/reactive.js.map +1 -1
  193. package/dist/server/render.js.map +1 -1
  194. package/dist/server/resource-hints.js.map +1 -1
  195. package/dist/server/select-value.js.map +1 -1
  196. package/dist/server/server/attributes.js.map +1 -1
  197. package/dist/server/server/class-style.js.map +1 -1
  198. package/dist/server/server/component.js.map +1 -1
  199. package/dist/server/server/derived.js.map +1 -1
  200. package/dist/server/server/element.js.map +1 -1
  201. package/dist/server/server/errors.js.map +1 -1
  202. package/dist/server/server/escape.js.map +1 -1
  203. package/dist/server/server/form-controls.js.map +1 -1
  204. package/dist/server/server/hydration-script.js.map +1 -1
  205. package/dist/server/server/node.js.map +1 -1
  206. package/dist/server/server/portals.js.map +1 -1
  207. package/dist/server/server/raw-text.js.map +1 -1
  208. package/dist/server/server/render.js.map +1 -1
  209. package/dist/server/server/serialize.js.map +1 -1
  210. package/dist/server/server/stream.js.map +1 -1
  211. package/dist/server/spread.js.map +1 -1
  212. package/dist/server/template.js.map +1 -1
  213. package/dist/server/view-transition.js.map +1 -1
  214. package/dist/server-dev/control-flow/portal.js.map +1 -1
  215. package/dist/server-dev/insert.js.map +1 -1
  216. package/dist/server-dev/internal/reconcile.js.map +1 -1
  217. package/dist/server-dev/server/errors.js.map +1 -1
  218. package/dist/server-dev/server/index.js +2 -2
  219. package/dist/server-dev/server/node.js.map +1 -1
  220. package/dist/server-dev/server/portals.js.map +1 -1
  221. package/dist/server-dev/server/stream.js.map +1 -1
  222. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"error-boundary.js","names":["ErrorBoundary","failureCell","SignalNode","parentOwner","getOwner","roots","rootErrorsOf","live","currentScope","origin","failure","readSignal","setFailure","writeSignal","next","version","setVersion","useSignal","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","props","untrack","thrown","handleError","build","current","scope","createRoot","catchError","creation","onCleanup","body","useMemo","withScope"],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { handleError, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = new SignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":"A,sWA0FA,SAAgBA,EAAc,EAAmD,CAG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ANIa,IAAa,IAAA,GAMVH,EAAM,OALXA,EAAM,QAAQ,EAEPR,EAAYW,EAAS,KAAK,EAIrC,QAAU,CAERF,MAAiB,CACfG,MAAgB,CACd,EAAO,EACT,CAAC,CACH,CAAC,EACD,EAAO,EACT,CAEF,EAIMC,EAAOC,MACJhC,IAAW,KAAOwB,EAAM,EAAIS,EAAU,CAAE,GAAGjC,CAAO,EAAGwB,CAAK,EACjE,CAAE,YAAa,EAAK,CACtB,EASA,OANAG,MAAiB,CACfG,MAAgB,CACd,EAAQ,EAEV,CAAC,CACH,CAAC,EACMC,CACT,C"}
1
+ {"version":3,"file":"error-boundary.js","names":["currentScope","withScope","rootErrorsOf","catchError","createRoot","getOwner","onCleanup","untrack","useMemo","useSignal","SignalNode","handleError","readSignal","writeSignal","ErrorBoundary","props","failureCell","parentOwner","roots","live","origin","failure","setFailure","next","version","setVersion","alive","busy","pending","reset","count","report","error","takePending","captured","fallbackFor","fallback","thrown","build","current","scope","dispose","creation","body"],"sources":["../../../src/control-flow/error-boundary.ts"],"sourcesContent":["import {\n type Accessor,\n catchError,\n createRoot,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useSignal,\n} from \"@shadow-js/core\";\nimport { handleError, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\nimport { currentScope, type HydrationScope, withScope } from \"../extend\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { attachHotModules, createHotLink, type HotLink } from \"./hot-link\";\nimport { rootErrorsOf } from \"./root-errors\";\n\n/**\n * Props of {@link ErrorBoundary}.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryProps {\n /**\n * Shown after an error. A function is called untracked as `(error, reset)`; any other value is\n * shown as is.\n */\n readonly fallback: JsxChild | ((error: unknown, reset: () => void) => unknown);\n /**\n * The protected content, read untracked when the children are built.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: JsxChild | (() => unknown);\n}\n\n/**\n * {@link ErrorBoundaryProps} with untyped members, for code that forwards a fallback or children it\n * does not know the shape of.\n * @since 1.0.0\n */\nexport interface ErrorBoundaryLooseProps {\n /** Shown after an error; the same contract as {@link ErrorBoundaryProps.fallback}. */\n readonly fallback: unknown;\n /**\n * The protected content; the same contract as {@link ErrorBoundaryProps.children}.\n * @default undefined (nothing is protected; the boundary renders nothing)\n */\n readonly children?: unknown;\n}\n\n/** A caught error, wrapped so that any thrown value (including `undefined`) is representable. */\ninterface Failure {\n readonly error: unknown;\n}\n\n/**\n * Renders `children`. If they throw while being created, or any effect, memo or cleanup inside\n * them throws later, the children are disposed and `fallback` is rendered instead. A function\n * fallback receives the error and a `reset` that rebuilds the children from scratch.\n *\n * Errors raised while the boundary is building or tearing down its children are captured and\n * never write a signal, because writing inside a memo is an error. Late errors write the failure\n * signal, which re-runs the boundary. After the boundary is disposed, late errors are dropped.\n * Errors thrown by the fallback are not caught by this boundary; they reach the parent.\n *\n * @param props See {@link ErrorBoundaryProps}.\n * @returns An accessor of the current content (children or fallback).\n * @throws Nothing itself. An error from the children is shown through `fallback`, and an error\n * thrown by a function `fallback` goes to the enclosing boundary or the root's error handler.\n * @example\n * import { ErrorBoundary } from \"@shadow-js/web\";\n *\n * function Dashboard() {\n * return <p>Dashboard</p>;\n * }\n *\n * function Page() {\n * return (\n * <ErrorBoundary\n * fallback={(error, reset) => (\n * <button onClick={reset}>Retry after: {String(error)}</button>\n * )}\n * >\n * <Dashboard />\n * </ErrorBoundary>\n * );\n * }\n * @see Suspense\n * @since 1.0.0\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown>;\nexport function ErrorBoundary(props: ErrorBoundaryLooseProps): Accessor<unknown> {\n // An extension-API cell: a failure is boundary state, written from places a plain write refuses\n // (a sibling boundary's fallback throwing while its memo computes).\n const failureCell = new SignalNode<Failure | undefined>(undefined, Object.is);\n /** Where an error of this boundary's own fallback goes: the boundary that encloses it. */\n const parentOwner = getOwner();\n // The root's reporters (render/hydrate options): an error this boundary takes is reported to them.\n const roots = rootErrorsOf(parentOwner);\n /** The hydration scope at creation (a copy of its counts), or null outside a hydration or server render. */\n const live = currentScope();\n const origin: HydrationScope | null =\n live === null ? null : { id: live.id, count: live.count, resources: live.resources };\n const failure = (): Failure | undefined => readSignal(failureCell);\n const setFailure = (next: Failure | undefined): void => {\n writeSignal(failureCell, next, { allowInMemo: true });\n };\n /** Bumped by reset(): forces a rebuild even when no failure was recorded. */\n const [version, setVersion] = useSignal(0, { equals: false });\n /** False once the boundary's owner is disposed. */\n let alive = true;\n /** True while the body memo is building or tearing down children; errors are captured then. */\n let busy = false;\n /** An error captured while busy, consumed by the next body computation. */\n let pending: Failure | undefined;\n\n const reset = (): void => {\n if (!alive) return;\n setFailure(undefined);\n setVersion((count) => count + 1);\n };\n\n /**\n * Dev only: the modules the children were built from. While the fallback is shown, a hot update of one of\n * them resets the boundary, so the edit that fixes the error shows the children without a retry.\n */\n const hot: HotLink | undefined = __DEV__\n ? createHotLink(() => {\n reset();\n })\n : undefined;\n\n const report = (error: unknown): void => {\n if (!alive) return;\n roots?.onCaughtError?.(error);\n if (busy) {\n if (pending === undefined) pending = { error };\n return;\n }\n setFailure({ error });\n };\n\n /** Returns the captured error and clears it. A function, so TypeScript does not narrow the variable. */\n const takePending = (): Failure | undefined => {\n const captured = pending;\n pending = undefined;\n return captured;\n };\n\n const fallbackFor = (error: unknown): unknown => {\n const fallback = props.fallback;\n if (typeof fallback !== \"function\") return fallback;\n try {\n return untrack(() =>\n (fallback as (error: unknown, reset: () => void) => unknown)(error, reset),\n );\n } catch (thrown) {\n // A failing fallback is not this boundary's business: hand it to the enclosing boundary now.\n // Left to the memo it would only surface when a consumer outside that boundary reads it.\n handleError(thrown, parentOwner);\n return undefined;\n }\n };\n\n /** Builds the children or the fallback, as the current failure state says. */\n const build = (): unknown => {\n busy = true;\n try {\n version();\n const current = failure() ?? takePending();\n if (current !== undefined) {\n hot?.arm();\n return fallbackFor(current.error);\n }\n\n hot?.modules.clear();\n const scope = createRoot((dispose) => {\n if (hot !== undefined) attachHotModules(hot.modules);\n return {\n dispose,\n value: catchError(() => untrack(() => props.children), report),\n };\n });\n const creation = takePending();\n if (creation !== undefined) {\n scope.dispose();\n hot?.arm();\n return fallbackFor(creation.error);\n }\n hot?.disarm();\n return scope.value;\n } finally {\n // Newest child of the body memo: its cleanup marks the teardown before any child cleanup runs.\n createRoot(() => {\n onCleanup(() => {\n busy = true;\n });\n });\n busy = false;\n }\n // Children and the fallback are built here; their setup may write signals.\n };\n // Every build starts from the hydration scope the boundary was created in (a copy, so the count\n // is the same each time). A rebuild during a hydration pass then numbers its templates as the\n // first build did, so it claims the server's elements instead of missing keys.\n const body = useMemo<unknown>(\n () => (origin === null ? build() : withScope({ ...origin }, build)),\n { allowWrites: true },\n );\n\n // Created after the body memo, so it is the newest child of the owner and is disposed first.\n createRoot(() => {\n onCleanup(() => {\n alive = false;\n hot?.disarm();\n });\n });\n return body;\n}\n"],"mappings":"A,sWA0FA,SAAgBc,EAAcC,EAAmD,CAG/E,IAAMC,EAAc,IAAIN,EAAgC,IAAA,GAAW,OAAO,EAAE,EAEtEO,EAAcZ,EAAS,EAEvBa,EAAQhB,EAAae,CAAW,EAEhCE,EAAOnB,EAAa,EACpBoB,EACJD,IAAS,KAAO,KAAO,CAAE,GAAIA,EAAK,GAAI,MAAOA,EAAK,MAAO,UAAWA,EAAK,SAAU,EAC/EE,MAAqCT,EAAWI,CAAW,EAC3DM,EAAcC,GAAoC,CACtDV,EAAYG,EAAaO,EAAM,CAAE,YAAa,EAAK,CAAC,CACtD,EAEM,CAACC,EAASC,GAAchB,EAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAExDiB,EAAQ,GAERC,EAAO,GAEPC,EAEEC,MAAoB,CACnBH,IACLJ,EAAW,IAAA,EAAS,EACpBG,EAAYK,GAAUA,EAAQ,CAAC,EACjC,EAYMC,EAAUC,GAAyB,CAClCN,IACLR,GAAO,gBAAgBc,CAAK,EACxBL,EACEC,IAAY,IAAA,KAAWA,EAAU,CAAEI,OAAM,GAG/CV,EAAW,CAAEU,OAAM,CAAC,EACtB,EAGMC,MAAyC,CAC7C,IAAMC,EAAWN,EAEjB,MADAA,GAAU,IAAA,GACHM,CACT,EAEMC,EAAeH,GAA4B,CAC/C,IAAMI,EAAWrB,EAAM,SACvB,GAAI,OAAOqB,GAAa,WAAY,OAAOA,EAC3C,GAAI,CACF,OAAO7B,MACJ6B,EAA4DJ,EAAOH,CAAK,CAC3E,CACF,OAASQ,EAAQ,CAGf1B,EAAY0B,EAAQpB,CAAW,EAC/B,MACF,CACF,EAGMqB,MAAuB,CAC3BX,EAAO,GACP,GAAI,CACFH,EAAQ,EACR,IAAMe,EAAUlB,EAAQ,GAAKY,EAAY,EACzC,GAAIM,IAAY,IAAA,GAEd,OAAOJ,EAAYI,EAAQ,KAAK,EAIlC,IAAMC,EAAQpC,EAAYqC,IAEjB,CACLA,UACA,MAAOtC,MAAiBI,MAAcQ,EAAM,QAAQ,EAAGgB,CAAM,CAC/D,EACD,EACKW,EAAWT,EAAY,EAO7B,OANIS,IAAa,IAAA,GAMVF,EAAM,OALXA,EAAM,QAAQ,EAEPL,EAAYO,EAAS,KAAK,EAIrC,QAAU,CAERtC,MAAiB,CACfE,MAAgB,CACdqB,EAAO,EACT,CAAC,CACH,CAAC,EACDA,EAAO,EACT,CAEF,EAIMgB,EAAOnC,MACJY,IAAW,KAAOkB,EAAM,EAAIrC,EAAU,CAAE,GAAGmB,CAAO,EAAGkB,CAAK,EACjE,CAAE,YAAa,EAAK,CACtB,EASA,OANAlC,MAAiB,CACfE,MAAgB,CACdoB,EAAQ,EAEV,CAAC,CACH,CAAC,EACMiB,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"for.js","names":["renderRow","untrack","props","item","index","For","list","fallback","keyOf","mapArray"],"sources":["../../../src/control-flow/for.ts"],"sourcesContent":["import { type Accessor, mapArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link For} without `key`: rows are matched by item reference.\n * @since 1.0.0\n */\nexport interface ForUnkeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Absent in this form: rows are matched by item reference. Pass `key` to match by key.\n * No default: omit it for reference matching.\n */\n readonly key?: undefined;\n /** Called once per row, untracked. The callback receives the item value. */\n readonly children: (item: T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For} with `key`: rows are matched by `key(item)`.\n * @since 1.0.0\n */\nexport interface ForKeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /** Identifies each item. A new object under the same key updates the row's `item()`. */\n readonly key: (item: T) => unknown;\n /** Called once per row, untracked. The callback receives an accessor of the item. */\n readonly children: (item: () => T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For}.\n * @since 1.0.0\n */\nexport type ForProps<T> = ForUnkeyedProps<T> | ForKeyedProps<T>;\n\n/**\n * Calls the row callback. `props.children` is read untracked, once per row.\n * @internal\n */\nfunction renderRow(props: { readonly children: unknown }, item: unknown, index: () => number) {\n const render = untrack(() => props.children) as (item: unknown, index: () => number) => unknown;\n return render(item, index);\n}\n\n/**\n * Renders one row per item. Rows whose key survives an update keep their DOM and state; only\n * changed items create or dispose rows. The list is read lazily, inside the list memo.\n *\n * Whether rows are keyed is decided when `For` is created: it reads `key` once. When the list\n * is empty and `fallback` is not given, the result is `[undefined]`, which renders nothing.\n *\n * @param props See {@link ForUnkeyedProps} and {@link ForKeyedProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { For } from \"@shadow-js/web\";\n *\n * function TodoList() {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * return (\n * <ul>\n * <For each={todos()} key={(todo) => todo.id} fallback={<li>Nothing to do</li>}>\n * {(todo) => <li>{todo().title}</li>}\n * </For>\n * </ul>\n * );\n * }\n * @see Index\n * @since 1.0.0\n */\nexport function For<T>(props: ForKeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForUnkeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForProps<T>): Accessor<unknown[]> {\n const list = (): readonly T[] | null | undefined | false => props.each;\n const fallback = (): unknown => props.fallback;\n const keyOf = props.key;\n if (keyOf === undefined) {\n return mapArray(list, (item: T, index: () => number) => renderRow(props, item, index), {\n fallback,\n });\n }\n return mapArray(list, (item: () => T, index: () => number) => renderRow(props, item, index), {\n key: keyOf,\n fallback,\n });\n}\n"],"mappings":"A,wDAyDA,SAASA,EAAU,EAAuC,EAAe,EAAqB,CAE5F,OADeC,MAAcC,EAAM,QACvB,CAAC,CAACC,EAAMC,CAAK,CAC3B,CA8BA,SAAgBC,EAAO,EAAyC,CAC9D,IAAMC,MAAsDJ,EAAM,KAC5DK,MAA0BL,EAAM,SAChCM,EAAQN,EAAM,IAMpB,OALIM,IAAU,IAAA,GACLC,EAASH,GAAO,EAAS,IAAwBN,EAAUE,EAAOC,EAAMC,CAAK,EAAG,CACrF,UACF,CAAC,EAEIK,EAASH,GAAO,EAAe,IAAwBN,EAAUE,EAAOC,EAAMC,CAAK,EAAG,CAC3F,IAAKI,EACL,UACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"for.js","names":["mapArray","untrack","renderRow","props","item","index","For","list","fallback","keyOf"],"sources":["../../../src/control-flow/for.ts"],"sourcesContent":["import { type Accessor, mapArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link For} without `key`: rows are matched by item reference.\n * @since 1.0.0\n */\nexport interface ForUnkeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Absent in this form: rows are matched by item reference. Pass `key` to match by key.\n * No default: omit it for reference matching.\n */\n readonly key?: undefined;\n /** Called once per row, untracked. The callback receives the item value. */\n readonly children: (item: T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For} with `key`: rows are matched by `key(item)`.\n * @since 1.0.0\n */\nexport interface ForKeyedProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, inside\n * the list memo, so it is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /** Identifies each item. A new object under the same key updates the row's `item()`. */\n readonly key: (item: T) => unknown;\n /** Called once per row, untracked. The callback receives an accessor of the item. */\n readonly children: (item: () => T, index: () => number) => unknown;\n}\n\n/**\n * Props of {@link For}.\n * @since 1.0.0\n */\nexport type ForProps<T> = ForUnkeyedProps<T> | ForKeyedProps<T>;\n\n/**\n * Calls the row callback. `props.children` is read untracked, once per row.\n * @internal\n */\nfunction renderRow(props: { readonly children: unknown }, item: unknown, index: () => number) {\n const render = untrack(() => props.children) as (item: unknown, index: () => number) => unknown;\n return render(item, index);\n}\n\n/**\n * Renders one row per item. Rows whose key survives an update keep their DOM and state; only\n * changed items create or dispose rows. The list is read lazily, inside the list memo.\n *\n * Whether rows are keyed is decided when `For` is created: it reads `key` once. When the list\n * is empty and `fallback` is not given, the result is `[undefined]`, which renders nothing.\n *\n * @param props See {@link ForUnkeyedProps} and {@link ForKeyedProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { For } from \"@shadow-js/web\";\n *\n * function TodoList() {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * return (\n * <ul>\n * <For each={todos()} key={(todo) => todo.id} fallback={<li>Nothing to do</li>}>\n * {(todo) => <li>{todo().title}</li>}\n * </For>\n * </ul>\n * );\n * }\n * @see Index\n * @since 1.0.0\n */\nexport function For<T>(props: ForKeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForUnkeyedProps<T>): Accessor<unknown[]>;\nexport function For<T>(props: ForProps<T>): Accessor<unknown[]> {\n const list = (): readonly T[] | null | undefined | false => props.each;\n const fallback = (): unknown => props.fallback;\n const keyOf = props.key;\n if (keyOf === undefined) {\n return mapArray(list, (item: T, index: () => number) => renderRow(props, item, index), {\n fallback,\n });\n }\n return mapArray(list, (item: () => T, index: () => number) => renderRow(props, item, index), {\n key: keyOf,\n fallback,\n });\n}\n"],"mappings":"A,wDAyDA,SAASE,EAAUC,EAAuCC,EAAeC,EAAqB,CAE5F,OADeJ,MAAcE,EAAM,QACvB,CAAC,CAACC,EAAMC,CAAK,CAC3B,CA8BA,SAAgBC,EAAOH,EAAyC,CAC9D,IAAMI,MAAsDJ,EAAM,KAC5DK,MAA0BL,EAAM,SAChCM,EAAQN,EAAM,IAMpB,OALIM,IAAU,IAAA,GACLT,EAASO,GAAOH,EAASC,IAAwBH,EAAUC,EAAOC,EAAMC,CAAK,EAAG,CACrFG,UACF,CAAC,EAEIR,EAASO,GAAOH,EAAeC,IAAwBH,EAAUC,EAAOC,EAAMC,CAAK,EAAG,CAC3F,IAAKI,EACLD,UACF,CAAC,CACH,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"fragment.js","names":["Fragment","props"],"sources":["../../../src/control-flow/fragment.ts"],"sourcesContent":["/**\n * Props of {@link Fragment}.\n * @since 1.0.0\n */\nexport interface FragmentProps {\n /**\n * The children to group.\n * @default undefined (the Fragment renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * A no-op wrapper: returns `props.children` untouched, so the children are created by the caller's\n * getter exactly as if no wrapper existed. Use it to group several children under one element.\n *\n * @param props The children to group.\n * @returns `props.children`, unchanged.\n * @example\n * import { Fragment } from \"@shadow-js/web\";\n *\n * function Header() {\n * return <h1>Title</h1>;\n * }\n *\n * function Page() {\n * return (\n * <Fragment>\n * <Header />\n * <p>Body</p>\n * </Fragment>\n * );\n * }\n * @since 1.0.0\n */\nexport function Fragment(props: FragmentProps): unknown {\n return props.children;\n}\n"],"mappings":"AAmCA,SAAgBA,EAAS,EAA+B,CACtD,OAAOC,EAAM,QACf,C"}
1
+ {"version":3,"file":"fragment.js","names":["Fragment","props"],"sources":["../../../src/control-flow/fragment.ts"],"sourcesContent":["/**\n * Props of {@link Fragment}.\n * @since 1.0.0\n */\nexport interface FragmentProps {\n /**\n * The children to group.\n * @default undefined (the Fragment renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * A no-op wrapper: returns `props.children` untouched, so the children are created by the caller's\n * getter exactly as if no wrapper existed. Use it to group several children under one element.\n *\n * @param props The children to group.\n * @returns `props.children`, unchanged.\n * @example\n * import { Fragment } from \"@shadow-js/web\";\n *\n * function Header() {\n * return <h1>Title</h1>;\n * }\n *\n * function Page() {\n * return (\n * <Fragment>\n * <Header />\n * <p>Body</p>\n * </Fragment>\n * );\n * }\n * @since 1.0.0\n */\nexport function Fragment(props: FragmentProps): unknown {\n return props.children;\n}\n"],"mappings":"AAmCA,SAAgBA,EAASC,EAA+B,CACtD,OAAOA,EAAM,QACf,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"index-list.js","names":["Index","indexArray","props","untrack","item","index"],"sources":["../../../src/control-flow/index-list.ts"],"sourcesContent":["import { type Accessor, indexArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link Index}.\n * @since 1.0.0\n */\nexport interface IndexProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, so it\n * is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Called once per position, untracked. The item is an accessor that follows the value at this\n * position; the index is a plain number, because a position never changes.\n */\n readonly children: (item: () => T, index: number) => unknown;\n}\n\n/**\n * Renders one row per position. Rows are created and removed only when the length changes; the\n * row at position `i` stays, and its item accessor follows the value at `i`. Use it for\n * primitive lists where identity does not matter.\n *\n * @param props See {@link IndexProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Index } from \"@shadow-js/web\";\n *\n * function Cells() {\n * const [values] = useSignal([10, 20, 30]);\n * return (\n * <ul>\n * <Index each={values()}>{(value, index) => <li>{`${index}: ${value()}`}</li>}</Index>\n * </ul>\n * );\n * }\n * @see For\n * @since 1.0.0\n */\nexport function Index<T>(props: IndexProps<T>): Accessor<unknown[]> {\n return indexArray(\n () => props.each,\n (item: () => T, index: number) => untrack(() => props.children)(item, index),\n { fallback: () => props.fallback },\n );\n}\n"],"mappings":"A,0DA8CA,SAAgBA,EAAS,EAA2C,CAClE,OAAOC,MACCC,EAAM,MACX,EAAe,IAAkBC,MAAcD,EAAM,QAAQ,CAAC,CAACE,EAAMC,CAAK,EAC3E,CAAE,aAAgBH,EAAM,QAAS,CACnC,CACF,C"}
1
+ {"version":3,"file":"index-list.js","names":["indexArray","untrack","Index","props","item","index"],"sources":["../../../src/control-flow/index-list.ts"],"sourcesContent":["import { type Accessor, indexArray, untrack } from \"@shadow-js/core\";\n\n/**\n * Props of {@link Index}.\n * @since 1.0.0\n */\nexport interface IndexProps<T> {\n /**\n * The list to render. `null`, `undefined` and `false` count as an empty list. Read lazily, so it\n * is tracked.\n */\n readonly each: readonly T[] | null | undefined | false;\n /**\n * Shown while the list is empty. Read lazily.\n * @default undefined (an empty list renders nothing)\n */\n readonly fallback?: unknown;\n /**\n * Called once per position, untracked. The item is an accessor that follows the value at this\n * position; the index is a plain number, because a position never changes.\n */\n readonly children: (item: () => T, index: number) => unknown;\n}\n\n/**\n * Renders one row per position. Rows are created and removed only when the length changes; the\n * row at position `i` stays, and its item accessor follows the value at `i`. Use it for\n * primitive lists where identity does not matter.\n *\n * @param props See {@link IndexProps}.\n * @returns An accessor of the row values, in input order.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Index } from \"@shadow-js/web\";\n *\n * function Cells() {\n * const [values] = useSignal([10, 20, 30]);\n * return (\n * <ul>\n * <Index each={values()}>{(value, index) => <li>{`${index}: ${value()}`}</li>}</Index>\n * </ul>\n * );\n * }\n * @see For\n * @since 1.0.0\n */\nexport function Index<T>(props: IndexProps<T>): Accessor<unknown[]> {\n return indexArray(\n () => props.each,\n (item: () => T, index: number) => untrack(() => props.children)(item, index),\n { fallback: () => props.fallback },\n );\n}\n"],"mappings":"A,0DA8CA,SAAgBE,EAASC,EAA2C,CAClE,OAAOH,MACCG,EAAM,MACXC,EAAeC,IAAkBJ,MAAcE,EAAM,QAAQ,CAAC,CAACC,EAAMC,CAAK,EAC3E,CAAE,aAAgBF,EAAM,QAAS,CACnC,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"lazy.js","names":["lazy","pending","loaded","load","loader","module","error","Lazy","component","useMemo","untrack","props","resource","useResource"],"sources":["../../../src/control-flow/lazy.ts"],"sourcesContent":["import { type Accessor, untrack, useMemo, useResource } from \"@shadow-js/core\";\n\ntype ComponentFunction<P> = (props: P) => unknown;\n\n/**\n * A component made by {@link lazy}: call it (or write it in JSX) like any component, and use\n * `preload` to start the load early.\n * @since 1.0.0\n */\nexport interface LazyComponent<P> {\n /**\n * Renders the loaded component with `props`. While the code is loading the result is empty and the\n * nearest `<Suspense>` shows its fallback; without a boundary nothing is rendered until the load\n * resolves.\n */\n (props: P): Accessor<unknown>;\n /**\n * Starts loading without rendering and resolves to the component. Calls share one load, so the\n * loader runs once. A failed load is not cached: the next call or render loads again.\n */\n preload(): Promise<ComponentFunction<P>>;\n}\n\n/**\n * Defines a component whose code is loaded on first render. While loading, the nearest\n * `<Suspense>` shows its fallback; a failed load throws to the nearest `<ErrorBoundary>` and the\n * next render retries.\n *\n * @param loader Returns a promise of a module whose `default` export is the component, such as\n * `() => import(\"./chart\")`. Called at most once while its load succeeds.\n * @returns A {@link LazyComponent}.\n * @throws Nothing synchronously. A rejected load surfaces as an error when the component's output\n * is read, so the nearest `<ErrorBoundary>` takes it; `preload()` rejects with the same error.\n * @example\n * import { lazy, Suspense } from \"@shadow-js/web\";\n *\n * function Chart(props: { title: string }) {\n * return <h2>{props.title}</h2>;\n * }\n *\n * // In an app the loader is `() => import(\"./chart\")`.\n * const LazyChart = lazy(() => Promise.resolve({ default: Chart }));\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <LazyChart title=\"Sales\" />\n * </Suspense>\n * );\n * }\n * @see Suspense\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function lazy<P>(\n loader: () => Promise<{ default: ComponentFunction<P> }>,\n): LazyComponent<P> {\n let pending: Promise<ComponentFunction<P>> | undefined;\n let loaded: ComponentFunction<P> | undefined;\n\n const load = (): Promise<ComponentFunction<P>> => {\n if (pending === undefined) {\n pending = loader().then(\n (module) => {\n loaded = module.default;\n return module.default;\n },\n (error: unknown) => {\n pending = undefined;\n throw error;\n },\n );\n }\n return pending;\n };\n\n const Lazy = ((props: P): Accessor<unknown> => {\n if (loaded !== undefined) {\n const component = loaded;\n return useMemo(() => untrack(() => component(props)), { allowWrites: true });\n }\n const resource = useResource(() => load());\n return useMemo(\n () => {\n const component = resource();\n return component === undefined ? undefined : untrack(() => component(props));\n },\n { allowWrites: true },\n );\n }) as LazyComponent<P>;\n Lazy.preload = load;\n return Lazy;\n}\n"],"mappings":"A,wEAsDA,SAAgBA,EACd,EACkB,CAClB,IAAIC,EACAC,EAEEC,OACAF,IAAY,IAAA,KACd,EAAUG,EAAO,CAAC,CAAC,KAChB,IACC,EAASC,EAAO,QACTA,EAAO,SAEf,GAAmB,CAElB,KADA,GAAU,IAAA,GACJC,CACR,CACF,GAEKL,GAGHM,GAAS,GAAgC,CAC7C,GAAIL,IAAW,IAAA,GAAW,CACxB,IAAMM,EAAYN,EAClB,OAAOO,MAAcC,MAAcF,EAAUG,CAAK,CAAC,EAAG,CAAE,YAAa,EAAK,CAAC,CAC7E,CACA,IAAMC,EAAWC,MAAkBV,EAAK,CAAC,EACzC,OAAOM,MACC,CACJ,IAAMD,EAAYI,EAAS,EAC3B,OAAOJ,IAAc,IAAA,GAAY,IAAA,GAAYE,MAAcF,EAAUG,CAAK,CAAC,CAC7E,EACA,CAAE,YAAa,EAAK,CACtB,CACF,GAEA,MADA,GAAK,QAAUR,EACRI,CACT,C"}
1
+ {"version":3,"file":"lazy.js","names":["untrack","useMemo","useResource","lazy","loader","pending","loaded","load","module","error","Lazy","props","component","resource"],"sources":["../../../src/control-flow/lazy.ts"],"sourcesContent":["import { type Accessor, untrack, useMemo, useResource } from \"@shadow-js/core\";\n\ntype ComponentFunction<P> = (props: P) => unknown;\n\n/**\n * A component made by {@link lazy}: call it (or write it in JSX) like any component, and use\n * `preload` to start the load early.\n * @since 1.0.0\n */\nexport interface LazyComponent<P> {\n /**\n * Renders the loaded component with `props`. While the code is loading the result is empty and the\n * nearest `<Suspense>` shows its fallback; without a boundary nothing is rendered until the load\n * resolves.\n */\n (props: P): Accessor<unknown>;\n /**\n * Starts loading without rendering and resolves to the component. Calls share one load, so the\n * loader runs once. A failed load is not cached: the next call or render loads again.\n */\n preload(): Promise<ComponentFunction<P>>;\n}\n\n/**\n * Defines a component whose code is loaded on first render. While loading, the nearest\n * `<Suspense>` shows its fallback; a failed load throws to the nearest `<ErrorBoundary>` and the\n * next render retries.\n *\n * @param loader Returns a promise of a module whose `default` export is the component, such as\n * `() => import(\"./chart\")`. Called at most once while its load succeeds.\n * @returns A {@link LazyComponent}.\n * @throws Nothing synchronously. A rejected load surfaces as an error when the component's output\n * is read, so the nearest `<ErrorBoundary>` takes it; `preload()` rejects with the same error.\n * @example\n * import { lazy, Suspense } from \"@shadow-js/web\";\n *\n * function Chart(props: { title: string }) {\n * return <h2>{props.title}</h2>;\n * }\n *\n * // In an app the loader is `() => import(\"./chart\")`.\n * const LazyChart = lazy(() => Promise.resolve({ default: Chart }));\n *\n * function Page() {\n * return (\n * <Suspense fallback={<p>Loading...</p>}>\n * <LazyChart title=\"Sales\" />\n * </Suspense>\n * );\n * }\n * @see Suspense\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function lazy<P>(\n loader: () => Promise<{ default: ComponentFunction<P> }>,\n): LazyComponent<P> {\n let pending: Promise<ComponentFunction<P>> | undefined;\n let loaded: ComponentFunction<P> | undefined;\n\n const load = (): Promise<ComponentFunction<P>> => {\n if (pending === undefined) {\n pending = loader().then(\n (module) => {\n loaded = module.default;\n return module.default;\n },\n (error: unknown) => {\n pending = undefined;\n throw error;\n },\n );\n }\n return pending;\n };\n\n const Lazy = ((props: P): Accessor<unknown> => {\n if (loaded !== undefined) {\n const component = loaded;\n return useMemo(() => untrack(() => component(props)), { allowWrites: true });\n }\n const resource = useResource(() => load());\n return useMemo(\n () => {\n const component = resource();\n return component === undefined ? undefined : untrack(() => component(props));\n },\n { allowWrites: true },\n );\n }) as LazyComponent<P>;\n Lazy.preload = load;\n return Lazy;\n}\n"],"mappings":"A,wEAsDA,SAAgBG,EACdC,EACkB,CAClB,IAAIC,EACAC,EAEEC,OACAF,IAAY,IAAA,KACdA,EAAUD,EAAO,CAAC,CAAC,KAChBI,IACCF,EAASE,EAAO,QACTA,EAAO,SAEfC,GAAmB,CAElB,KADAJ,GAAU,IAAA,GACJI,CACR,CACF,GAEKJ,GAGHK,GAASC,GAAgC,CAC7C,GAAIL,IAAW,IAAA,GAAW,CACxB,IAAMM,EAAYN,EAClB,OAAOL,MAAcD,MAAcY,EAAUD,CAAK,CAAC,EAAG,CAAE,YAAa,EAAK,CAAC,CAC7E,CACA,IAAME,EAAWX,MAAkBK,EAAK,CAAC,EACzC,OAAON,MACC,CACJ,IAAMW,EAAYC,EAAS,EAC3B,OAAOD,IAAc,IAAA,GAAY,IAAA,GAAYZ,MAAcY,EAAUD,CAAK,CAAC,CAC7E,EACA,CAAE,YAAa,EAAK,CACtB,CACF,GAEA,MADAD,GAAK,QAAUH,EACRG,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-hydration.js","names":["NoHydration","key","nextKey","built","withScope","props","ssrRaw"],"sources":["../../../src/control-flow/no-hydration.ts"],"sourcesContent":["import type { Accessor } from \"@shadow-js/core\";\nimport { claims, nextKey, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n\n/** The nodes between `<!--nh:KEY-->` and its `<!--/nh-->` in the lifted regions, or undefined when the server sent none. */\nfunction findStatic(\n key: string | undefined,\n regions: readonly (readonly Node[])[] | undefined,\n): Node[] | undefined {\n if (key === undefined || regions === undefined) return undefined;\n for (const region of regions) {\n const open = region.findIndex(\n (node) => node.nodeType === 8 && (node as Comment).data === `nh:${key}`,\n );\n if (open === -1) continue;\n const nodes: Node[] = [];\n let depth = 1;\n for (let i = open + 1; i < region.length; i += 1) {\n const node = region[i] as Node;\n if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data.startsWith(\"nh:\")) depth += 1;\n else if (data === \"/nh\" && --depth === 0) break;\n }\n nodes.push(node);\n }\n return nodes;\n }\n return undefined;\n}\n\n/**\n * Props of {@link NoHydration}.\n * @since 1.0.0\n */\nexport interface NoHydrationProps {\n /**\n * The static content. Rendered by the server without hydration keys and left untouched by the\n * browser's hydration pass.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Content the browser never hydrates: the server renders it without hydration keys, and while the\n * page hydrates the browser leaves that markup exactly as it is (no code runs for it, no event\n * handlers or reactivity are attached). Use it for static, heavy markup such as rendered\n * documentation or a long article. Rendered by the browser alone (a client-side navigation), its\n * children render normally.\n *\n * @param props See {@link NoHydrationProps}.\n * @returns An accessor of the content: the children, or the server's own nodes while the browser hydrates.\n * @example\n * import { NoHydration } from \"@shadow-js/web\";\n *\n * function Docs(props: { html: string }) {\n * return (\n * <NoHydration>\n * <article innerHTML={props.html} />\n * </NoHydration>\n * );\n * }\n * @see ClientOnly\n * @since 1.0.0\n */\nexport function NoHydration(props: NoHydrationProps): Accessor<unknown> {\n // The component has its own scope, so this key does not move the keys of its siblings.\n const key = nextKey();\n if (__SERVER__) {\n // No scope for the content: the keys of what is rendered inside are not handed out.\n const built = withScope(null, () => props.children);\n return () => [ssrRaw(`<!--nh:${key ?? \"\"}-->`), built, ssrRaw(\"<!--/nh-->\")];\n }\n if (claims.current.isClaiming()) {\n // Hydrating: the server's nodes between the markers are handed to the region as they are.\n const kept = findStatic(key, claims.current.liftedRegions());\n if (kept !== undefined) return () => kept;\n // No markers from the server (the root of the container): render on the client, claiming nothing.\n return () => claims.current.withoutClaiming(() => props.children);\n }\n return () => props.children;\n}\n"],"mappings":"A,sHAkEA,SAAgBA,EAAY,EAA4C,CAEtE,IAAMC,EAAMC,EAAQ,EACJ,CAEd,IAAMC,EAAQC,EAAU,SAAYC,EAAM,QAAQ,EAClD,UAAa,CAACC,EAAO,UAAUL,GAAO,GAAG,IAAI,EAAGE,EAAOG,EAAO,YAAY,CAAC,CAC7E,CASF,C"}
1
+ {"version":3,"file":"no-hydration.js","names":["nextKey","withScope","ssrRaw","NoHydration","props","key","built"],"sources":["../../../src/control-flow/no-hydration.ts"],"sourcesContent":["import type { Accessor } from \"@shadow-js/core\";\nimport { claims, nextKey, withScope } from \"../extend\";\nimport { ssrRaw } from \"../server/element\";\n\n/** The nodes between `<!--nh:KEY-->` and its `<!--/nh-->` in the lifted regions, or undefined when the server sent none. */\nfunction findStatic(\n key: string | undefined,\n regions: readonly (readonly Node[])[] | undefined,\n): Node[] | undefined {\n if (key === undefined || regions === undefined) return undefined;\n for (const region of regions) {\n const open = region.findIndex(\n (node) => node.nodeType === 8 && (node as Comment).data === `nh:${key}`,\n );\n if (open === -1) continue;\n const nodes: Node[] = [];\n let depth = 1;\n for (let i = open + 1; i < region.length; i += 1) {\n const node = region[i] as Node;\n if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data.startsWith(\"nh:\")) depth += 1;\n else if (data === \"/nh\" && --depth === 0) break;\n }\n nodes.push(node);\n }\n return nodes;\n }\n return undefined;\n}\n\n/**\n * Props of {@link NoHydration}.\n * @since 1.0.0\n */\nexport interface NoHydrationProps {\n /**\n * The static content. Rendered by the server without hydration keys and left untouched by the\n * browser's hydration pass.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Content the browser never hydrates: the server renders it without hydration keys, and while the\n * page hydrates the browser leaves that markup exactly as it is (no code runs for it, no event\n * handlers or reactivity are attached). Use it for static, heavy markup such as rendered\n * documentation or a long article. Rendered by the browser alone (a client-side navigation), its\n * children render normally.\n *\n * @param props See {@link NoHydrationProps}.\n * @returns An accessor of the content: the children, or the server's own nodes while the browser hydrates.\n * @example\n * import { NoHydration } from \"@shadow-js/web\";\n *\n * function Docs(props: { html: string }) {\n * return (\n * <NoHydration>\n * <article innerHTML={props.html} />\n * </NoHydration>\n * );\n * }\n * @see ClientOnly\n * @since 1.0.0\n */\nexport function NoHydration(props: NoHydrationProps): Accessor<unknown> {\n // The component has its own scope, so this key does not move the keys of its siblings.\n const key = nextKey();\n if (__SERVER__) {\n // No scope for the content: the keys of what is rendered inside are not handed out.\n const built = withScope(null, () => props.children);\n return () => [ssrRaw(`<!--nh:${key ?? \"\"}-->`), built, ssrRaw(\"<!--/nh-->\")];\n }\n if (claims.current.isClaiming()) {\n // Hydrating: the server's nodes between the markers are handed to the region as they are.\n const kept = findStatic(key, claims.current.liftedRegions());\n if (kept !== undefined) return () => kept;\n // No markers from the server (the root of the container): render on the client, claiming nothing.\n return () => claims.current.withoutClaiming(() => props.children);\n }\n return () => props.children;\n}\n"],"mappings":"A,sHAkEA,SAAgBG,EAAYC,EAA4C,CAEtE,IAAMC,EAAML,EAAQ,EACJ,CAEd,IAAMM,EAAQL,EAAU,SAAYG,EAAM,QAAQ,EAClD,UAAa,CAACF,EAAO,UAAUG,GAAO,GAAG,IAAI,EAAGC,EAAOJ,EAAO,YAAY,CAAC,CAC7E,CASF,C"}
@@ -1 +1 @@
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,MAAM,EAC7B,EAGME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IAAaA,EAAQ,OAAShB,IAC9CkC,EAAOlC,CAAM,CACf,CACF,EACAuC,EAAUpB,CAAO,EACV,IACT,C"}
1
+ {"version":3,"file":"portal.js","names":["bindRegion","createRegion","moveRegion","removeRegion","childScope","nextKey","withScope","claims","PortalContext","createRoot","getOwner","isServer","onCleanup","runWithOwner","useContext","useRenderEffect","appendMoved","target","node","shadowRootOf","host","resolveMount","mount","Portal","props","key","sink","owner","mounted","adopted","unmount","current","mountInto","initial","mode","region","dispose","bind","moveTo","previous","shadow"],"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,SAASgB,EAAYC,EAAcC,EAAkB,CAC/C,OAAQD,EAAgC,YAAe,WACxDA,EAAuB,WAAWC,EAAM,IAAI,EAE7CD,EAAO,YAAYC,CAAI,CAE3B,CAGA,SAASC,EAAaC,EAA2B,CAC/C,OAAOA,EAAK,YAAcA,EAAK,aAAa,CAAE,KAAM,MAAO,CAAC,CAC9D,CAGA,SAASC,EAAaC,EAA6C,CAGjE,OAFIA,IAAU,IAAA,GAAkB,SAAS,MAC3B,OAAOA,GAAU,WAAaA,EAAM,EAAIA,IACtC,IAClB,CAqCA,SAAgBC,EAAOC,EAA0B,CAI/C,IAAMC,EAAMpB,EAAQ,EAGdqB,EAAOZ,EAAWN,CAAa,EACrC,GAAIG,GAAYe,IAAS,KAEvB,OADIF,EAAM,YAAc,IAAME,GAAM,SAASD,MAAWD,EAAM,QAAQ,EAC/D,KAIT,IAAMG,EAAQjB,EAAS,EACnBkB,EAGAC,EAA8BtB,EAAO,QAAQ,YAAYkB,CAAG,EAG1DK,MAAsB,CAC1B,IAAMC,EAAUH,EACZG,IAAY,IAAA,KAChBH,EAAU,IAAA,GACVG,EAAQ,YAAY,EACpB5B,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AAeuB,EAASrB,EAAaC,CAAI,EAAIA,GAC/CQ,IAAY,IAAA,IAAaA,EAAQ,OAASX,IAC9CqB,EAAOrB,CAAM,CACf,CACF,EACAL,EAAUkB,CAAO,EACV,IACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"root-errors.js","names":["ROOT_ERRORS","attachRootErrors","root","getOwner","map","options","rootErrorsOf","owner"],"sources":["../../../src/control-flow/root-errors.ts"],"sourcesContent":["import { getOwner, type Owner } from \"@shadow-js/core\";\n\n/**\n * The error reporters a root was rendered or hydrated with (see `RenderOptions` and `HydrateOptions`).\n * @since 1.0.0\n */\nexport interface RootErrorOptions {\n /**\n * Receives an error that no error boundary took. The root then does not rethrow it.\n * @default undefined (no reporter; an error no boundary takes follows the default handling)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n /**\n * Receives an error an `ErrorBoundary` caught (its fallback is shown).\n * @default undefined (no reporter)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives a hydration mismatch that was repaired on the client. Only `hydrate` reports these.\n * @default undefined (no reporter)\n */\n readonly onRecoverableError?: (error: unknown) => void;\n}\n\n/**\n * The key the reporters are stored under in an owner's context map. A symbol the context map inherits\n * (as a Provider's value is inherited), so every node below the root sees it, detached roots included.\n * A plain value rather than a context: a context would bring its Provider into every bundle.\n */\nconst ROOT_ERRORS: symbol = /* @__PURE__ */ Symbol(\"RootErrors\");\n\n/**\n * Attaches the options to the root that is being created (called inside its `createRoot`). The reporters\n * go into the root's context map, and an `onUncaughtError` becomes the root's error handler (a fresh root\n * has none, so it is the only one).\n * @internal\n */\nexport function attachRootErrors(options: RootErrorOptions): void {\n const root = getOwner();\n if (root === null) return;\n const map = Object.create(root.context) as Record<symbol, unknown>;\n map[ROOT_ERRORS] = options;\n root.context = map;\n if (options.onUncaughtError !== undefined) root.errorHandlers = [options.onUncaughtError];\n}\n\n/**\n * The reporters of the nearest root above `owner`, or undefined when no root was given options.\n * @internal\n */\nexport function rootErrorsOf(owner: Owner | null): RootErrorOptions | undefined {\n return owner?.context?.[ROOT_ERRORS] as RootErrorOptions | undefined;\n}\n"],"mappings":"A,2CA6BA,MAAMA,EAAsC,uBAAO,YAAY,EAQ/D,SAAgBC,EAAiB,EAAiC,CAChE,IAAMC,EAAOC,EAAS,EACtB,GAAID,IAAS,KAAM,OACnB,IAAME,EAAM,OAAO,OAAOF,EAAK,OAAO,EACtC,EAAIF,GAAeK,EACnB,EAAK,QAAUD,EACXC,EAAQ,kBAAoB,IAAA,KAAW,EAAK,cAAgB,CAACA,EAAQ,eAAe,EAC1F,CAMA,SAAgBC,EAAa,EAAmD,CAC9E,OAAOC,GAAO,UAAUP,EAC1B,C"}
1
+ {"version":3,"file":"root-errors.js","names":["getOwner","ROOT_ERRORS","attachRootErrors","options","root","map","rootErrorsOf","owner"],"sources":["../../../src/control-flow/root-errors.ts"],"sourcesContent":["import { getOwner, type Owner } from \"@shadow-js/core\";\n\n/**\n * The error reporters a root was rendered or hydrated with (see `RenderOptions` and `HydrateOptions`).\n * @since 1.0.0\n */\nexport interface RootErrorOptions {\n /**\n * Receives an error that no error boundary took. The root then does not rethrow it.\n * @default undefined (no reporter; an error no boundary takes follows the default handling)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n /**\n * Receives an error an `ErrorBoundary` caught (its fallback is shown).\n * @default undefined (no reporter)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives a hydration mismatch that was repaired on the client. Only `hydrate` reports these.\n * @default undefined (no reporter)\n */\n readonly onRecoverableError?: (error: unknown) => void;\n}\n\n/**\n * The key the reporters are stored under in an owner's context map. A symbol the context map inherits\n * (as a Provider's value is inherited), so every node below the root sees it, detached roots included.\n * A plain value rather than a context: a context would bring its Provider into every bundle.\n */\nconst ROOT_ERRORS: symbol = /* @__PURE__ */ Symbol(\"RootErrors\");\n\n/**\n * Attaches the options to the root that is being created (called inside its `createRoot`). The reporters\n * go into the root's context map, and an `onUncaughtError` becomes the root's error handler (a fresh root\n * has none, so it is the only one).\n * @internal\n */\nexport function attachRootErrors(options: RootErrorOptions): void {\n const root = getOwner();\n if (root === null) return;\n const map = Object.create(root.context) as Record<symbol, unknown>;\n map[ROOT_ERRORS] = options;\n root.context = map;\n if (options.onUncaughtError !== undefined) root.errorHandlers = [options.onUncaughtError];\n}\n\n/**\n * The reporters of the nearest root above `owner`, or undefined when no root was given options.\n * @internal\n */\nexport function rootErrorsOf(owner: Owner | null): RootErrorOptions | undefined {\n return owner?.context?.[ROOT_ERRORS] as RootErrorOptions | undefined;\n}\n"],"mappings":"A,2CA6BA,MAAMC,EAAsC,uBAAO,YAAY,EAQ/D,SAAgBC,EAAiBC,EAAiC,CAChE,IAAMC,EAAOJ,EAAS,EACtB,GAAII,IAAS,KAAM,OACnB,IAAMC,EAAM,OAAO,OAAOD,EAAK,OAAO,EACtCC,EAAIJ,GAAeE,EACnBC,EAAK,QAAUC,EACXF,EAAQ,kBAAoB,IAAA,KAAWC,EAAK,cAAgB,CAACD,EAAQ,eAAe,EAC1F,CAMA,SAAgBG,EAAaC,EAAmD,CAC9E,OAAOA,GAAO,UAAUN,EAC1B,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"show.js","names":["Show","createBranches","when","props"],"sources":["../../../src/control-flow/show.ts"],"sourcesContent":["import type { Accessor } from \"@shadow-js/core\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { createBranches, FALLBACK } from \"./branch\";\n\n/** What `when` accepts: the value, or any falsy stand-in (`0` and `\"\"` count as falsy). */\ntype ShowCondition<T> = T | undefined | null | false | 0 | \"\";\n\n/** Props shared by both forms of {@link Show}. */\ninterface ShowBaseProps<T> {\n /** The condition. The children are shown while it is truthy. */\n readonly when: ShowCondition<T>;\n /**\n * Shown while `when` is falsy. Read lazily, only when it is needed.\n * @default undefined (a falsy `when` renders nothing)\n */\n readonly fallback?: unknown;\n}\n\n/**\n * Keyed form: the children are rebuilt whenever the identity of `when` changes and a callback\n * child receives the value itself.\n * @since 1.0.0\n */\nexport interface ShowKeyedProps<T> extends ShowBaseProps<T> {\n /** Must be `true` in this form: a change of the identity of `when` rebuilds the children. */\n readonly keyed: true;\n /**\n * Plain content, an accessor, or a callback `(item) => content` called untracked in the branch.\n * @default undefined (a truthy `when` renders nothing)\n */\n readonly children?: JsxChild | (() => unknown) | ((item: NonNullable<T>) => unknown);\n}\n\n/**\n * Default form: the branch is rebuilt only when the truthiness of `when` changes. A callback child\n * receives an accessor of the latest truthy value; reading it after `when` became falsy throws a\n * TypeError, except while the branch is being torn down.\n * @since 1.0.0\n */\nexport interface ShowAccessorProps<T> extends ShowBaseProps<T> {\n /**\n * Absent or `false` in this form: the children are rebuilt only when the truthiness of `when`\n * changes.\n * @default false\n */\n readonly keyed?: false;\n /**\n * Plain content, an accessor, or a callback `(item) => content` called untracked in the branch.\n * @default undefined (a truthy `when` renders nothing)\n */\n readonly children?: JsxChild | (() => unknown) | ((item: Accessor<NonNullable<T>>) => unknown);\n}\n\n/**\n * Props of {@link Show}.\n * @since 1.0.0\n */\nexport type ShowProps<T> = ShowKeyedProps<T> | ShowAccessorProps<T>;\n\n/**\n * The same props with untyped `children`, for code that forwards children it does not know the\n * shape of (a wrapper component's own `props.children`).\n * @since 1.0.0\n */\nexport interface ShowLooseProps<T> extends ShowBaseProps<T> {\n /**\n * Same meaning as in {@link ShowKeyedProps}: `true` rebuilds the children when the identity of\n * `when` changes.\n * @default false\n */\n readonly keyed?: boolean;\n /**\n * Plain content, an accessor, or a callback, as in {@link ShowProps}.\n * @default undefined (a truthy `when` renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Shows `children` while `when` is truthy, and `fallback` otherwise. The branch is rebuilt only\n * when the truthiness of `when` changes (or, with `keyed`, when its identity changes).\n *\n * `when` follows JavaScript truthiness: `0`, `\"\"`, `null`, `undefined` and `false` show the\n * fallback. While `fallback` is not given, a falsy `when` renders nothing.\n *\n * @param props See {@link ShowProps}.\n * @returns An accessor of the current branch's content. The DOM runtime's `insert` consumes it.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Show } from \"@shadow-js/web\";\n *\n * function Greeting() {\n * const [user] = useSignal<{ name: string } | null>(null);\n * return (\n * <Show when={user()} fallback={<p>Sign in</p>}>\n * {(u) => <p>Hello {u().name}</p>}\n * </Show>\n * );\n * }\n * @see Switch\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function Show<T>(props: ShowProps<T>): Accessor<unknown>;\nexport function Show<T>(props: ShowLooseProps<T>): Accessor<unknown>;\nexport function Show<T>(props: ShowLooseProps<T>): Accessor<unknown> {\n return createBranches(\n \"Show\",\n () => {\n const when = props.when;\n return {\n index: when ? 0 : FALLBACK,\n keyed: props.keyed === true,\n when,\n read: () => props.when,\n body: () => props.children,\n };\n },\n () => props.fallback,\n );\n}\n"],"mappings":"A,6CAyGA,SAAgBA,EAAQ,EAA6C,CACnE,OAAOC,EACL,WACM,CACJ,IAAMC,EAAOC,EAAM,KACnB,MAAO,CACL,MAAOD,EAAO,EAAA,GACd,MAAOC,EAAM,QAAU,GACvB,OACA,SAAYA,EAAM,KAClB,SAAYA,EAAM,QACpB,CACF,MACMA,EAAM,QACd,CACF,C"}
1
+ {"version":3,"file":"show.js","names":["createBranches","Show","props","when"],"sources":["../../../src/control-flow/show.ts"],"sourcesContent":["import type { Accessor } from \"@shadow-js/core\";\nimport type { JsxChild } from \"../jsx/types\";\nimport { createBranches, FALLBACK } from \"./branch\";\n\n/** What `when` accepts: the value, or any falsy stand-in (`0` and `\"\"` count as falsy). */\ntype ShowCondition<T> = T | undefined | null | false | 0 | \"\";\n\n/** Props shared by both forms of {@link Show}. */\ninterface ShowBaseProps<T> {\n /** The condition. The children are shown while it is truthy. */\n readonly when: ShowCondition<T>;\n /**\n * Shown while `when` is falsy. Read lazily, only when it is needed.\n * @default undefined (a falsy `when` renders nothing)\n */\n readonly fallback?: unknown;\n}\n\n/**\n * Keyed form: the children are rebuilt whenever the identity of `when` changes and a callback\n * child receives the value itself.\n * @since 1.0.0\n */\nexport interface ShowKeyedProps<T> extends ShowBaseProps<T> {\n /** Must be `true` in this form: a change of the identity of `when` rebuilds the children. */\n readonly keyed: true;\n /**\n * Plain content, an accessor, or a callback `(item) => content` called untracked in the branch.\n * @default undefined (a truthy `when` renders nothing)\n */\n readonly children?: JsxChild | (() => unknown) | ((item: NonNullable<T>) => unknown);\n}\n\n/**\n * Default form: the branch is rebuilt only when the truthiness of `when` changes. A callback child\n * receives an accessor of the latest truthy value; reading it after `when` became falsy throws a\n * TypeError, except while the branch is being torn down.\n * @since 1.0.0\n */\nexport interface ShowAccessorProps<T> extends ShowBaseProps<T> {\n /**\n * Absent or `false` in this form: the children are rebuilt only when the truthiness of `when`\n * changes.\n * @default false\n */\n readonly keyed?: false;\n /**\n * Plain content, an accessor, or a callback `(item) => content` called untracked in the branch.\n * @default undefined (a truthy `when` renders nothing)\n */\n readonly children?: JsxChild | (() => unknown) | ((item: Accessor<NonNullable<T>>) => unknown);\n}\n\n/**\n * Props of {@link Show}.\n * @since 1.0.0\n */\nexport type ShowProps<T> = ShowKeyedProps<T> | ShowAccessorProps<T>;\n\n/**\n * The same props with untyped `children`, for code that forwards children it does not know the\n * shape of (a wrapper component's own `props.children`).\n * @since 1.0.0\n */\nexport interface ShowLooseProps<T> extends ShowBaseProps<T> {\n /**\n * Same meaning as in {@link ShowKeyedProps}: `true` rebuilds the children when the identity of\n * `when` changes.\n * @default false\n */\n readonly keyed?: boolean;\n /**\n * Plain content, an accessor, or a callback, as in {@link ShowProps}.\n * @default undefined (a truthy `when` renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Shows `children` while `when` is truthy, and `fallback` otherwise. The branch is rebuilt only\n * when the truthiness of `when` changes (or, with `keyed`, when its identity changes).\n *\n * `when` follows JavaScript truthiness: `0`, `\"\"`, `null`, `undefined` and `false` show the\n * fallback. While `fallback` is not given, a falsy `when` renders nothing.\n *\n * @param props See {@link ShowProps}.\n * @returns An accessor of the current branch's content. The DOM runtime's `insert` consumes it.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Show } from \"@shadow-js/web\";\n *\n * function Greeting() {\n * const [user] = useSignal<{ name: string } | null>(null);\n * return (\n * <Show when={user()} fallback={<p>Sign in</p>}>\n * {(u) => <p>Hello {u().name}</p>}\n * </Show>\n * );\n * }\n * @see Switch\n * @see ErrorBoundary\n * @since 1.0.0\n */\nexport function Show<T>(props: ShowProps<T>): Accessor<unknown>;\nexport function Show<T>(props: ShowLooseProps<T>): Accessor<unknown>;\nexport function Show<T>(props: ShowLooseProps<T>): Accessor<unknown> {\n return createBranches(\n \"Show\",\n () => {\n const when = props.when;\n return {\n index: when ? 0 : FALLBACK,\n keyed: props.keyed === true,\n when,\n read: () => props.when,\n body: () => props.children,\n };\n },\n () => props.fallback,\n );\n}\n"],"mappings":"A,6CAyGA,SAAgBC,EAAQC,EAA6C,CACnE,OAAOF,EACL,WACM,CACJ,IAAMG,EAAOD,EAAM,KACnB,MAAO,CACL,MAAOC,EAAO,EAAA,GACd,MAAOD,EAAM,QAAU,GACvBC,OACA,SAAYD,EAAM,KAClB,SAAYA,EAAM,QACpB,CACF,MACMA,EAAM,QACd,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"suspense-list.js","names":["SuspenseListContext","SuspenseList","changes","SignalNode","slots","touch","writeSignal","entry","onCleanup","index","position","readSignal","reveal","props","slot","ready","order","ordered","wanted","i","candidate"],"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,oJAkBA,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,C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AG,OAAOD,IAAMD,CAClE,CACA,MAAO,EACT,CAC8B,CAChC,CAIW,EACX,IAAI,UAAW,CACb,OAAOL,EAAM,QACf,CACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"suspense-list.js","names":["createContext","onCleanup","SignalNode","readSignal","writeSignal","SuspenseListContext","SuspenseList","props","changes","slots","touch","ready","entry","index","position","reveal","slot","order","ordered","wanted","i","candidate"],"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,oJAkBA,MAAaK,EACKL,kBAAwC,KAAM,CAAE,KAAM,cAAe,CAAC,EA+DxF,SAAgBM,EAAaC,EAA6C,CAExE,IAAMC,EAAU,IAAIN,EAAmB,EAAG,EAAK,EACzCO,EAAkD,CAAC,EACnDC,MAAoB,CACxBN,EAAYI,EAAS,EAAG,CAAE,YAAa,EAAK,CAAC,CAC/C,EAmDA,OAAOH,EAAoB,CACzB,MAAO,CAjDP,SAASM,EAAO,CACd,IAAMC,EAAQ,CAAED,OAAM,EACtBF,EAAM,KAAKG,CAAK,EAChBF,EAAM,EACNT,MAAgB,CACd,IAAMY,EAAQJ,EAAM,QAAQG,CAAK,EAC7BC,IAAU,IAAIJ,EAAM,OAAOI,EAAO,CAAC,EACvCH,EAAM,CACR,CAAC,EACD,IAAMI,OACJX,EAAWK,CAAO,EACXC,EAAM,QAAQG,CAAK,GAEtBG,MAAwB,CAC5B,IAAMF,EAAQC,EAAS,EACvB,GAAID,IAAU,GAAI,MAAO,GACzB,OAAQN,EAAM,YAAd,CACE,IAAK,WACH,OAAOE,EAAM,MAAOO,GAASA,EAAK,MAAM,CAAC,EAC3C,IAAK,WACH,OAAOP,EAAM,MAAM,EAAGI,EAAQ,CAAC,CAAC,CAAC,MAAOG,GAASA,EAAK,MAAM,CAAC,EAC/D,IAAK,YACH,OAAOP,EAAM,MAAMI,CAAK,CAAC,CAAC,MAAOG,GAASA,EAAK,MAAM,CAAC,EACxD,QACE,OAAOL,EAAM,CACjB,CACF,EAkBA,MAAO,CAAEI,SAAQ,iBAjBmB,CAClC,GAAIA,EAAO,EAAG,MAAO,GACrB,IAAME,EAAQV,EAAM,YAEpB,GADmBU,IAAU,YAAcA,IAAU,YACpC,MAAO,GACxB,GAAIV,EAAM,OAAS,SAAU,MAAO,GACpC,GAAIA,EAAM,OAAS,YAAa,MAAO,GAEvC,IAAMM,EAAQC,EAAS,EACjBI,EAAUD,IAAU,YAAc,CAAC,GAAGR,CAAK,CAAC,CAAC,QAAQ,EAAIA,EACzDU,EAASF,IAAU,YAAcR,EAAM,OAAS,EAAII,EAAQA,EAClE,IAAK,IAAIO,EAAI,EAAGA,EAAIF,EAAQ,OAAQE,GAAK,EAAG,CAC1C,IAAMC,EAAYH,EAAQE,GAC1B,GAAIC,IAAc,IAAA,IAAa,CAACA,EAAU,MAAM,EAAG,OAAOD,IAAMD,CAClE,CACA,MAAO,EACT,CAC8B,CAChC,CAIW,EACX,IAAI,UAAW,CACb,OAAOZ,EAAM,QACf,CACF,CAAC,CACH,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"suspense.js","names":["createTracker","pending","SignalNode","hold","shown","adjust","writeSignal","by","transitionHooks","readSignal","Suspense","key","nextKey","boundary","createOwner","count","suspenseOnServer","props","runWithOwner","withScope","childScope","SuspenseContext","tracker","fallbackScope","content","sink","useContext","StreamContext","owner","getOwner","next","rebuilt","escape","ssrRaw"],"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,8cAwDA,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,EAKtDa,EAAWC,EAAY,EAYb,MAXhB,GAAS,SAAaC,EAAM,EAAI,GAAM,GAWfC,EAAiBC,EAAON,EAAKI,EAVpCG,EAAaL,MAC3BM,EAAUC,EAAWT,CAAG,MACtBU,EAAgB,CACd,MAAOC,EACP,IAAI,UAAW,CACb,OAAOL,EAAM,QACf,CACF,CAAC,CACH,CAE+D,CAAkB,CAqBrF,CAGA,SAASD,EACP,EACA,EACA,EACA,EACmB,CACnB,IAAMO,EAAgBH,EAAWT,IAAQ,IAAA,GAAY,IAAA,GAAY,GAAGA,EAAI,EAAE,EAC1E,GAAII,EAAM,IAAM,EAAG,OAAOS,EAC1B,IAAMC,EAAOC,EAAWC,CAAa,EACrC,GAAIF,IAAS,MAAQd,IAAQ,IAAA,GAC3B,UAAaQ,EAAUI,MAAqBN,EAAM,QAAQ,EAE5D,IAAMW,EAAQC,EAAS,EACjBhB,EAAW,CACf,GAAIF,EACJ,YAA8B,CAC5B,IAAMmB,EAAO9B,EAAc,EACrB+B,EAAUb,EAAaU,MAC3BT,EAAUC,EAAWT,CAAG,MACtBU,EAAgB,CACd,MAAOS,EAAK,QACZ,IAAI,UAAW,CACb,OAAOb,EAAM,QACf,CACF,CAAC,CACH,CACF,EAKA,OAJIa,EAAK,MAAM,EAAI,GACjBL,EAAK,MAAMZ,CAAQ,EACZ,MAEFmB,EAAQD,EAA0B,CAAC,CAC5C,CACF,EAGA,OAFAN,EAAK,MAAMZ,CAAQ,MAEN,CACXoB,EAAO,UAAUtB,EAAI,IAAI,EACzBQ,EAAUI,MAAqBN,EAAM,QAAQ,EAC7CgB,EAAO,UAAU,CACnB,CACF,C"}
1
+ {"version":3,"file":"suspense.js","names":["childScope","nextKey","withScope","StreamContext","ssrRaw","escape","SuspenseContext","getOwner","runWithOwner","useContext","SignalNode","createOwner","readSignal","transitionHooks","writeSignal","createTracker","pending","hold","shown","adjust","by","Suspense","props","key","tracker","count","holding","revealed","boundary","suspenseOnServer","content","fallbackScope","sink","owner","next","rebuilt"],"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,8cAwDA,SAASe,GAA0B,CAGjC,IAAMC,EAAU,IAAIN,EAAmB,EAAG,OAAO,EAAE,EAI/CO,EACAC,EAAQ,GACNC,EAAUC,GAAqB,CACnCN,EAAYE,EAASA,EAAQ,MAAQI,EAAI,CAAE,Y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EAKA,OAJIY,EAAK,MAAM,EAAI,GACjBF,EAAK,MAAMJ,CAAQ,EACZ,MAEFvB,EAAQ8B,EAA0B,CAAC,CAC5C,CACF,EAGA,OAFAH,EAAK,MAAMJ,CAAQ,MAEN,CACXxB,EAAO,UAAUmB,EAAI,IAAI,EACzBrB,EAAU6B,MAAqBT,EAAM,QAAQ,EAC7ClB,EAAO,UAAU,CACnB,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"switch.js","names":["resolveChildren","Match","props","isMatch","item","matchesOf","matches","resolved","Switch","children","createBranches","list","index","match","when"],"sources":["../../../src/control-flow/switch.ts"],"sourcesContent":["import { type Accessor, type ResolvedChildren, children as resolveChildren } from \"@shadow-js/core\";\nimport { createBranches, FALLBACK } from \"./branch\";\n\n/**\n * Props of {@link Match}. A Match descriptor is the props object itself.\n * @since 1.0.0\n */\nexport interface MatchProps<T> {\n /** The condition. The first Match whose `when` is truthy is shown. */\n readonly when: T | undefined | null | false | 0 | \"\";\n /**\n * Same meaning as in {@link ShowLooseProps}: `true` rebuilds the branch when the identity of\n * `when` changes.\n * @default false\n */\n readonly keyed?: boolean;\n /**\n * The branch content: plain content, an accessor, or a callback, as the children of\n * {@link ShowProps}.\n * @default undefined (the selected Match renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Describes one branch of a {@link Switch}. It returns its props unchanged.\n *\n * @param props The condition and the branch content.\n * @returns The same props object, which `Switch` reads.\n * @example\n * import { Match } from \"@shadow-js/web\";\n *\n * const branch = Match({ when: \"ready\", children: \"Loaded\" });\n * console.log(branch.when); // \"ready\"\n * @see Switch\n * @since 1.0.0\n */\nexport function Match<T>(props: MatchProps<T>): MatchProps<T> {\n return props;\n}\n\n/**\n * Props of {@link Switch}.\n * @since 1.0.0\n */\nexport interface SwitchProps {\n /**\n * Shown when no Match is truthy. Read lazily.\n * @default undefined (nothing is rendered when no Match is truthy)\n */\n readonly fallback?: unknown;\n /**\n * One or more {@link Match} descriptors. `null`, `undefined` and booleans are ignored.\n * @default undefined (no branches; the fallback is shown)\n */\n readonly children?: unknown;\n}\n\n/** A Match descriptor is any object with a `when` key. Anything else is not a Match. */\nfunction isMatch(item: unknown): item is MatchProps<unknown> {\n return typeof item === \"object\" && item !== null && \"when\" in item;\n}\n\n/** Resolves the children into Match descriptors. Throws for any other kind of child. */\nfunction matchesOf(resolved: ResolvedChildren): MatchProps<unknown>[] {\n const matches: MatchProps<unknown>[] = [];\n for (const item of resolved.toArray()) {\n if (!isMatch(item))\n throw new TypeError(\n __DEV__ ? \"ShadowJS Switch: children must be <Match>\" : \"SHADOW_SWITCH_CHILDREN\",\n );\n matches.push(item);\n }\n return matches;\n}\n\n/**\n * Shows the first {@link Match} whose `when` is truthy, or the fallback when none is.\n * Re-selecting the same branch with the same truthiness (or, when keyed, the same value) does not\n * rebuild it.\n *\n * @param props See {@link SwitchProps}.\n * @returns An accessor of the selected branch's content.\n * @throws TypeError (production message `SHADOW_SWITCH_CHILDREN`) when a child is neither a Match\n * nor `null`, `undefined` or a boolean.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Match, Switch } from \"@shadow-js/web\";\n *\n * function Status() {\n * const [error] = useSignal<string | null>(null);\n * const [data] = useSignal<string | null>(\"ready\");\n * return (\n * <Switch fallback={<p>Loading...</p>}>\n * <Match when={error()}>\n * <p>Failed</p>\n * </Match>\n * <Match when={data()}>\n * <p>Ready</p>\n * </Match>\n * </Switch>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Switch(props: SwitchProps): Accessor<unknown> {\n const matches = resolveChildren(() => props.children);\n // Validate now, so that a wrong child is reported where the Switch is written.\n matchesOf(matches);\n return createBranches(\n \"Switch\",\n () => {\n const list = matchesOf(matches);\n for (const [index, match] of list.entries()) {\n const when = match.when;\n if (when) {\n return {\n index,\n keyed: match.keyed === true,\n when,\n read: () => match.when,\n body: () => match.children,\n };\n }\n }\n return {\n index: FALLBACK,\n keyed: false,\n when: undefined,\n read: () => undefined,\n body: () => undefined,\n };\n },\n () => props.fallback,\n );\n}\n"],"mappings":"A,wFAqCA,SAAgBC,EAAS,EAAqC,CAC5D,OAAOC,CACT,CAoBA,SAASC,EAAQ,EAA4C,CAC3D,OAAO,OAAOC,GAAS,YAAYA,GAAiB,SAAUA,CAChE,CAGA,SAASC,EAAU,EAAmD,CACpE,IAAMC,EAAiC,CAAC,EACxC,IAAK,IAAMF,KAAQG,EAAS,QAAQ,EAAG,CACrC,GAAI,CAACJ,EAAQC,CAAI,EACf,MAAU,UACgD,wBAC1D,EACFE,EAAQ,KAAKF,CAAI,CACnB,CACA,OAAOE,CACT,CAgCA,SAAgBE,EAAO,EAAuC,CAC5D,IAAMF,EAAUN,MAAsBE,EAAM,QAAQ,EAGpD,OADAG,EAAUC,CAAO,EACVI,EACL,aACM,CACJ,IAAMC,EAAON,EAAUC,CAAO,EAC9B,IAAK,GAAM,CAACM,EAAOC,KAAUF,EAAK,QAAQ,EAAG,CAC3C,IAAMG,EAAOD,EAAM,KACnB,GAAIC,EACF,MAAO,CACL,QACA,MAAOD,EAAM,QAAU,GACvB,OACA,SAAYA,EAAM,KAClB,SAAYA,EAAM,QACpB,CAEJ,CACA,MAAO,CACL,MAAA,GACA,MAAO,GACP,KAAM,IAAA,GACN,SAAY,IAAA,GACZ,SAAY,IAAA,EACd,CACF,MACMX,EAAM,QACd,CACF,C"}
1
+ {"version":3,"file":"switch.js","names":["resolveChildren","createBranches","children","Match","props","isMatch","item","matchesOf","resolved","matches","Switch","list","index","match","when"],"sources":["../../../src/control-flow/switch.ts"],"sourcesContent":["import { type Accessor, type ResolvedChildren, children as resolveChildren } from \"@shadow-js/core\";\nimport { createBranches, FALLBACK } from \"./branch\";\n\n/**\n * Props of {@link Match}. A Match descriptor is the props object itself.\n * @since 1.0.0\n */\nexport interface MatchProps<T> {\n /** The condition. The first Match whose `when` is truthy is shown. */\n readonly when: T | undefined | null | false | 0 | \"\";\n /**\n * Same meaning as in {@link ShowLooseProps}: `true` rebuilds the branch when the identity of\n * `when` changes.\n * @default false\n */\n readonly keyed?: boolean;\n /**\n * The branch content: plain content, an accessor, or a callback, as the children of\n * {@link ShowProps}.\n * @default undefined (the selected Match renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Describes one branch of a {@link Switch}. It returns its props unchanged.\n *\n * @param props The condition and the branch content.\n * @returns The same props object, which `Switch` reads.\n * @example\n * import { Match } from \"@shadow-js/web\";\n *\n * const branch = Match({ when: \"ready\", children: \"Loaded\" });\n * console.log(branch.when); // \"ready\"\n * @see Switch\n * @since 1.0.0\n */\nexport function Match<T>(props: MatchProps<T>): MatchProps<T> {\n return props;\n}\n\n/**\n * Props of {@link Switch}.\n * @since 1.0.0\n */\nexport interface SwitchProps {\n /**\n * Shown when no Match is truthy. Read lazily.\n * @default undefined (nothing is rendered when no Match is truthy)\n */\n readonly fallback?: unknown;\n /**\n * One or more {@link Match} descriptors. `null`, `undefined` and booleans are ignored.\n * @default undefined (no branches; the fallback is shown)\n */\n readonly children?: unknown;\n}\n\n/** A Match descriptor is any object with a `when` key. Anything else is not a Match. */\nfunction isMatch(item: unknown): item is MatchProps<unknown> {\n return typeof item === \"object\" && item !== null && \"when\" in item;\n}\n\n/** Resolves the children into Match descriptors. Throws for any other kind of child. */\nfunction matchesOf(resolved: ResolvedChildren): MatchProps<unknown>[] {\n const matches: MatchProps<unknown>[] = [];\n for (const item of resolved.toArray()) {\n if (!isMatch(item))\n throw new TypeError(\n __DEV__ ? \"ShadowJS Switch: children must be <Match>\" : \"SHADOW_SWITCH_CHILDREN\",\n );\n matches.push(item);\n }\n return matches;\n}\n\n/**\n * Shows the first {@link Match} whose `when` is truthy, or the fallback when none is.\n * Re-selecting the same branch with the same truthiness (or, when keyed, the same value) does not\n * rebuild it.\n *\n * @param props See {@link SwitchProps}.\n * @returns An accessor of the selected branch's content.\n * @throws TypeError (production message `SHADOW_SWITCH_CHILDREN`) when a child is neither a Match\n * nor `null`, `undefined` or a boolean.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Match, Switch } from \"@shadow-js/web\";\n *\n * function Status() {\n * const [error] = useSignal<string | null>(null);\n * const [data] = useSignal<string | null>(\"ready\");\n * return (\n * <Switch fallback={<p>Loading...</p>}>\n * <Match when={error()}>\n * <p>Failed</p>\n * </Match>\n * <Match when={data()}>\n * <p>Ready</p>\n * </Match>\n * </Switch>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Switch(props: SwitchProps): Accessor<unknown> {\n const matches = resolveChildren(() => props.children);\n // Validate now, so that a wrong child is reported where the Switch is written.\n matchesOf(matches);\n return createBranches(\n \"Switch\",\n () => {\n const list = matchesOf(matches);\n for (const [index, match] of list.entries()) {\n const when = match.when;\n if (when) {\n return {\n index,\n keyed: match.keyed === true,\n when,\n read: () => match.when,\n body: () => match.children,\n };\n }\n }\n return {\n index: FALLBACK,\n keyed: false,\n when: undefined,\n read: () => undefined,\n body: () => undefined,\n };\n },\n () => props.fallback,\n );\n}\n"],"mappings":"A,wFAqCA,SAAgBG,EAASC,EAAqC,CAC5D,OAAOA,CACT,CAoBA,SAASC,EAAQC,EAA4C,CAC3D,OAAO,OAAOA,GAAS,YAAYA,GAAiB,SAAUA,CAChE,CAGA,SAASC,EAAUC,EAAmD,CACpE,IAAMC,EAAiC,CAAC,EACxC,IAAK,IAAMH,KAAQE,EAAS,QAAQ,EAAG,CACrC,GAAI,CAACH,EAAQC,CAAI,EACf,MAAU,UACgD,wBAC1D,EACFG,EAAQ,KAAKH,CAAI,CACnB,CACA,OAAOG,CACT,CAgCA,SAAgBC,EAAON,EAAuC,CAC5D,IAAMK,EAAUT,MAAsBI,EAAM,QAAQ,EAGpD,OADAG,EAAUE,CAAO,EACVR,EACL,aACM,CACJ,IAAMU,EAAOJ,EAAUE,CAAO,EAC9B,IAAK,GAAM,CAACG,EAAOC,KAAUF,EAAK,QAAQ,EAAG,CAC3C,IAAMG,EAAOD,EAAM,KACnB,GAAIC,EACF,MAAO,CACLF,QACA,MAAOC,EAAM,QAAU,GACvBC,OACA,SAAYD,EAAM,KAClB,SAAYA,EAAM,QACpB,CAEJ,CACA,MAAO,CACL,MAAA,GACA,MAAO,GACP,KAAM,IAAA,GACN,SAAY,IAAA,GACZ,SAAY,IAAA,EACd,CACF,MACMT,EAAM,QACd,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"derived.js","names":["derived","memo","useMemo","compute","read","args","current"],"sources":["../../src/derived.ts"],"sourcesContent":["import { useMemo } from \"@shadow-js/core\";\n\n/**\n * A value the compiler keeps live: the result of `const x = <expression reading signals>` inside a\n * component. Read it as `x.value` or call it as `x()`, so `{double}` and `{double()}` both work in\n * JSX. When the value is itself a function, calling the derived calls that function with the\n * arguments, so a derived function stays callable.\n *\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { derived } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [count, setCount] = useSignal(2);\n * const double = derived(() => count() * 2);\n * console.log(double.value); // 4\n * setCount(5);\n * console.log(double()); // 10\n * }\n * @see derived\n * @since 1.0.0\n */\nexport interface Derived<T> {\n /**\n * Returns the current value, tracked. When the value is a function, calls it with `args` and\n * returns its result instead.\n */\n (...args: unknown[]): unknown;\n /** The current value, tracked: reading it inside an effect or binding subscribes that reader. */\n readonly value: T;\n}\n\n/**\n * Wraps a computation as a {@link Derived} value that recomputes only when the signals it reads\n * change. The compiler emits it for `const x = <expression reading signals>` inside components; it\n * is not meant to be written by hand.\n *\n * @param compute The computation. Runs in a memo, so it is tracked and cached between reads.\n * @returns A {@link Derived} whose `value` (and call result) follows `compute`.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { derived } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [price] = useSignal(20);\n * const total = derived(() => price() * 3);\n * console.log(total.value); // 60\n * }\n * @see Derived\n * @since 1.0.0\n */\nexport function derived<T>(compute: () => T): Derived<T> {\n const memo = useMemo(compute);\n const read = ((...args: unknown[]): unknown => {\n const current = memo();\n return typeof current === \"function\"\n ? (current as (...a: unknown[]) => unknown)(...args)\n : current;\n }) as { (...args: unknown[]): unknown; value: T };\n Object.defineProperty(read, \"value\", { get: memo });\n return read as Derived<T>;\n}\n"],"mappings":"A,0CAmDA,SAAgBA,EAAW,EAA8B,CACvD,IAAMC,EAAOC,EAAQC,CAAO,EACtBC,IAAS,GAAGC,IAA6B,CAC7C,IAAMC,EAAUL,EAAK,EACrB,OAAO,OAAOK,GAAY,WACrBA,EAAyC,GAAGD,CAAI,EACjDC,CACN,GAEA,OADA,OAAO,eAAeF,EAAM,QAAS,CAAE,IAAKH,CAAK,CAAC,EAC3CG,CACT,C"}
1
+ {"version":3,"file":"derived.js","names":["useMemo","derived","compute","memo","read","args","current"],"sources":["../../src/derived.ts"],"sourcesContent":["import { useMemo } from \"@shadow-js/core\";\n\n/**\n * A value the compiler keeps live: the result of `const x = <expression reading signals>` inside a\n * component. Read it as `x.value` or call it as `x()`, so `{double}` and `{double()}` both work in\n * JSX. When the value is itself a function, calling the derived calls that function with the\n * arguments, so a derived function stays callable.\n *\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { derived } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [count, setCount] = useSignal(2);\n * const double = derived(() => count() * 2);\n * console.log(double.value); // 4\n * setCount(5);\n * console.log(double()); // 10\n * }\n * @see derived\n * @since 1.0.0\n */\nexport interface Derived<T> {\n /**\n * Returns the current value, tracked. When the value is a function, calls it with `args` and\n * returns its result instead.\n */\n (...args: unknown[]): unknown;\n /** The current value, tracked: reading it inside an effect or binding subscribes that reader. */\n readonly value: T;\n}\n\n/**\n * Wraps a computation as a {@link Derived} value that recomputes only when the signals it reads\n * change. The compiler emits it for `const x = <expression reading signals>` inside components; it\n * is not meant to be written by hand.\n *\n * @param compute The computation. Runs in a memo, so it is tracked and cached between reads.\n * @returns A {@link Derived} whose `value` (and call result) follows `compute`.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { derived } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [price] = useSignal(20);\n * const total = derived(() => price() * 3);\n * console.log(total.value); // 60\n * }\n * @see Derived\n * @since 1.0.0\n */\nexport function derived<T>(compute: () => T): Derived<T> {\n const memo = useMemo(compute);\n const read = ((...args: unknown[]): unknown => {\n const current = memo();\n return typeof current === \"function\"\n ? (current as (...a: unknown[]) => unknown)(...args)\n : current;\n }) as { (...args: unknown[]): unknown; value: T };\n Object.defineProperty(read, \"value\", { get: memo });\n return read as Derived<T>;\n}\n"],"mappings":"A,0CAmDA,SAAgBC,EAAWC,EAA8B,CACvD,IAAMC,EAAOH,EAAQE,CAAO,EACtBE,IAAS,GAAGC,IAA6B,CAC7C,IAAMC,EAAUH,EAAK,EACrB,OAAO,OAAOG,GAAY,WACrBA,EAAyC,GAAGD,CAAI,EACjDC,CACN,GAEA,OADA,OAAO,eAAeF,EAAM,QAAS,CAAE,IAAKD,CAAK,CAAC,EAC3CC,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","names":["TAG_PATTERN","element","tag","read","props","ssrElement","children","\"children\"","isTextOnlyElement","ssrRaw"],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, 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(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":"A,8IAsBA,MAAMA,EAAc,qBAsCpB,SAAgBC,EAAQ,EAAa,EAAwB,CAC3D,GAAI,CAACD,EAAY,KAAKE,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAMC,EAAOC,EAGX,OAAOC,EACLH,EACAE,MACM,CACJ,IAAME,EAAWH,EAAKI,SAGtB,OADID,IAAa,IAAA,IAAaE,EAAkBN,CAAG,EAAUI,EACtD,CAACG,EAAO,UAAU,EAAGH,EAAUG,EAAO,UAAU,CAAC,CAC1D,EACA,EACF,CA8CJ,C"}
1
+ {"version":3,"file":"element.js","names":["ssrElement","ssrRaw","isTextOnlyElement","TAG_PATTERN","element","tag","props","read","children","\"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(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":"A,8IAsBA,MAAMG,EAAc,qBAsCpB,SAAgBC,EAAQC,EAAaC,EAAwB,CAC3D,GAAI,CAACH,EAAY,KAAKE,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAME,EAAOD,EAGX,OAAON,EACLK,EACAC,MACM,CACJ,IAAME,EAAWD,EAAKE,SAGtB,OADID,IAAa,IAAA,IAAaN,EAAkBG,CAAG,EAAUG,EACtD,CAACP,EAAO,UAAU,EAAGO,EAAUP,EAAO,UAAU,CAAC,CAC1D,EACA,EACF,CA8CJ,C"}
@@ -1 +1 @@
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,EA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B,CAAI,EAC/B,QAAQ,eAAelB,EAAIb,CAAO,EAEtC,CACF,CACA,OAAOU,EAAOG,EAAIC,EAAO,GAAUX,EAAG,KAAKU,EAAI,GAAIiB,EAAQ,CAAC1B,EAAML,CAAK,EAAI,CAACA,CAAK,CAAE,EAAGmB,CAAO,CAC/F,CA6BA,SAAgBe,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASL,EAAUhB,EAAIC,EAAML,EAASuB,IAAa,GAAMd,IAAY,EAAI,EAE3EgB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
1
+ {"version":3,"file":"events.js","names":["batch","getOwner","onCleanup","untrack","DELEGATED_EVENTS","installed","dispatchDelegated","event","key","dataKey","errors","node","fn","data","error","first","isListenerObject","handler","listen","el","name","run","options","listener","bindListenerObject","object","capture","once","passive","signal","chainEvents","handlers","installDelegate","target","known","delegateEvents","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","delegate","tuple","slot","addEventListener","unbind"],"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) onCle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