@shadow-js/web 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/dev/attributes.d.ts +10 -3
  3. package/dist/dev/attributes.js +27 -49
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +15 -6
  6. package/dist/dev/class-style.js +64 -47
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.d.ts +11 -2
  9. package/dist/dev/control-flow/dynamic.js +57 -40
  10. package/dist/dev/control-flow/dynamic.js.map +1 -1
  11. package/dist/dev/control-flow/error-boundary.js +2 -2
  12. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  13. package/dist/dev/control-flow/portal.d.ts +2 -2
  14. package/dist/dev/control-flow/portal.js +17 -13
  15. package/dist/dev/control-flow/portal.js.map +1 -1
  16. package/dist/dev/control-flow/suspense-list.js +2 -2
  17. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  18. package/dist/dev/control-flow/suspense.js +2 -2
  19. package/dist/dev/control-flow/suspense.js.map +1 -1
  20. package/dist/dev/element.js +6 -3
  21. package/dist/dev/element.js.map +1 -1
  22. package/dist/dev/events.js +15 -44
  23. package/dist/dev/events.js.map +1 -1
  24. package/dist/dev/extend.d.ts +2 -2
  25. package/dist/dev/extend.js +2 -2
  26. package/dist/dev/insert.d.ts +26 -5
  27. package/dist/dev/insert.js +84 -45
  28. package/dist/dev/insert.js.map +1 -1
  29. package/dist/dev/internal/accessor.js +56 -0
  30. package/dist/dev/internal/accessor.js.map +1 -0
  31. package/dist/dev/internal/claim.d.ts +2 -1
  32. package/dist/dev/internal/claim.js +18 -3
  33. package/dist/dev/internal/claim.js.map +1 -1
  34. package/dist/dev/internal/css-units.js +2 -2
  35. package/dist/dev/internal/css-units.js.map +1 -1
  36. package/dist/dev/internal/diagnostics.d.ts +7 -3
  37. package/dist/dev/internal/diagnostics.js +14 -4
  38. package/dist/dev/internal/diagnostics.js.map +1 -1
  39. package/dist/dev/internal/early-events.js +20 -2
  40. package/dist/dev/internal/early-events.js.map +1 -1
  41. package/dist/dev/internal/portal-context.d.ts +9 -0
  42. package/dist/dev/internal/portal-context.js.map +1 -1
  43. package/dist/dev/internal/react-names.js +45 -71
  44. package/dist/dev/internal/react-names.js.map +1 -1
  45. package/dist/dev/internal/reconcile.js +7 -12
  46. package/dist/dev/internal/reconcile.js.map +1 -1
  47. package/dist/dev/jsx/global.d.ts +5 -2
  48. package/dist/dev/jsx/html.d.ts +1 -0
  49. package/dist/dev/resource-hints.js +4 -2
  50. package/dist/dev/resource-hints.js.map +1 -1
  51. package/dist/dev/select-value.js +5 -15
  52. package/dist/dev/select-value.js.map +1 -1
  53. package/dist/dev/server/attributes.d.ts +3 -0
  54. package/dist/dev/server/attributes.js +6 -32
  55. package/dist/dev/server/attributes.js.map +1 -1
  56. package/dist/dev/server/element.js +10 -7
  57. package/dist/dev/server/element.js.map +1 -1
  58. package/dist/dev/server/errors.js +7 -1
  59. package/dist/dev/server/errors.js.map +1 -1
  60. package/dist/dev/server/escape.js +14 -6
  61. package/dist/dev/server/escape.js.map +1 -1
  62. package/dist/dev/server/form-controls.js +5 -2
  63. package/dist/dev/server/form-controls.js.map +1 -1
  64. package/dist/dev/server/index.d.ts +2 -1
  65. package/dist/dev/server/index.js +3 -2
  66. package/dist/dev/server/portals.js +3 -0
  67. package/dist/dev/server/portals.js.map +1 -1
  68. package/dist/dev/server/raw-text.d.ts +28 -0
  69. package/dist/dev/server/raw-text.js +66 -0
  70. package/dist/dev/server/raw-text.js.map +1 -0
  71. package/dist/dev/server/render.d.ts +2 -1
  72. package/dist/dev/server/render.js +3 -3
  73. package/dist/dev/server/render.js.map +1 -1
  74. package/dist/dev/server/stream.d.ts +1 -1
  75. package/dist/dev/server/stream.js +3 -3
  76. package/dist/dev/server/stream.js.map +1 -1
  77. package/dist/dev/server.d.ts +2 -1
  78. package/dist/dev/server.js +3 -2
  79. package/dist/dev/spread.js +56 -81
  80. package/dist/dev/spread.js.map +1 -1
  81. package/dist/dev/template.js +1 -3
  82. package/dist/dev/template.js.map +1 -1
  83. package/dist/dev/view-transition.js +12 -4
  84. package/dist/dev/view-transition.js.map +1 -1
  85. package/dist/prod/attributes.js +1 -1
  86. package/dist/prod/attributes.js.map +1 -1
  87. package/dist/prod/class-style.js +1 -1
  88. package/dist/prod/class-style.js.map +1 -1
  89. package/dist/prod/control-flow/dynamic.js +1 -1
  90. package/dist/prod/control-flow/dynamic.js.map +1 -1
  91. package/dist/prod/control-flow/error-boundary.js +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/portal.js +1 -1
  94. package/dist/prod/control-flow/portal.js.map +1 -1
  95. package/dist/prod/control-flow/suspense-list.js +1 -1
  96. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  97. package/dist/prod/control-flow/suspense.js +1 -1
  98. package/dist/prod/control-flow/suspense.js.map +1 -1
  99. package/dist/prod/element.js +1 -1
  100. package/dist/prod/element.js.map +1 -1
  101. package/dist/prod/events.js +1 -1
  102. package/dist/prod/events.js.map +1 -1
  103. package/dist/prod/extend.js +1 -1
  104. package/dist/prod/insert.js +1 -1
  105. package/dist/prod/insert.js.map +1 -1
  106. package/dist/prod/internal/accessor.js +2 -0
  107. package/dist/prod/internal/accessor.js.map +1 -0
  108. package/dist/prod/internal/claim.js +1 -1
  109. package/dist/prod/internal/claim.js.map +1 -1
  110. package/dist/prod/internal/css-units.js +1 -1
  111. package/dist/prod/internal/css-units.js.map +1 -1
  112. package/dist/prod/internal/diagnostics.js +1 -1
  113. package/dist/prod/internal/diagnostics.js.map +1 -1
  114. package/dist/prod/internal/early-events.js +1 -1
  115. package/dist/prod/internal/early-events.js.map +1 -1
  116. package/dist/prod/internal/portal-context.js.map +1 -1
  117. package/dist/prod/internal/react-names.js +1 -1
  118. package/dist/prod/internal/react-names.js.map +1 -1
  119. package/dist/prod/internal/reconcile.js +1 -1
  120. package/dist/prod/internal/reconcile.js.map +1 -1
  121. package/dist/prod/resource-hints.js +1 -1
  122. package/dist/prod/resource-hints.js.map +1 -1
  123. package/dist/prod/select-value.js +1 -1
  124. package/dist/prod/select-value.js.map +1 -1
  125. package/dist/prod/server/attributes.js +1 -1
  126. package/dist/prod/server/attributes.js.map +1 -1
  127. package/dist/prod/server/element.js +1 -1
  128. package/dist/prod/server/element.js.map +1 -1
  129. package/dist/prod/server/errors.js +1 -1
  130. package/dist/prod/server/errors.js.map +1 -1
  131. package/dist/prod/server/escape.js +1 -1
  132. package/dist/prod/server/escape.js.map +1 -1
  133. package/dist/prod/server/form-controls.js +2 -2
  134. package/dist/prod/server/form-controls.js.map +1 -1
  135. package/dist/prod/server/index.js +1 -1
  136. package/dist/prod/server/portals.js +1 -1
  137. package/dist/prod/server/portals.js.map +1 -1
  138. package/dist/prod/server/raw-text.js +2 -0
  139. package/dist/prod/server/raw-text.js.map +1 -0
  140. package/dist/prod/server/render.js +1 -1
  141. package/dist/prod/server/render.js.map +1 -1
  142. package/dist/prod/server/stream.js +1 -1
  143. package/dist/prod/server/stream.js.map +1 -1
  144. package/dist/prod/server.js +1 -1
  145. package/dist/prod/spread.js +1 -1
  146. package/dist/prod/spread.js.map +1 -1
  147. package/dist/prod/template.js +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js +1 -1
  150. package/dist/prod/view-transition.js.map +1 -1
  151. package/dist/server/attributes.js +1 -1
  152. package/dist/server/attributes.js.map +1 -1
  153. package/dist/server/class-style.js +1 -1
  154. package/dist/server/class-style.js.map +1 -1
  155. package/dist/server/control-flow/dynamic.js +1 -1
  156. package/dist/server/control-flow/dynamic.js.map +1 -1
  157. package/dist/server/control-flow/error-boundary.js +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/portal.js +1 -1
  160. package/dist/server/control-flow/portal.js.map +1 -1
  161. package/dist/server/control-flow/suspense-list.js +1 -1
  162. package/dist/server/control-flow/suspense-list.js.map +1 -1
  163. package/dist/server/control-flow/suspense.js +1 -1
  164. package/dist/server/control-flow/suspense.js.map +1 -1
  165. package/dist/server/element.js +1 -1
  166. package/dist/server/element.js.map +1 -1
  167. package/dist/server/events.js +1 -1
  168. package/dist/server/events.js.map +1 -1
  169. package/dist/server/extend.js +1 -1
  170. package/dist/server/insert.js +1 -1
  171. package/dist/server/insert.js.map +1 -1
  172. package/dist/server/internal/accessor.js +2 -0
  173. package/dist/server/internal/accessor.js.map +1 -0
  174. package/dist/server/internal/claim.js +1 -1
  175. package/dist/server/internal/claim.js.map +1 -1
  176. package/dist/server/internal/css-units.js +1 -1
  177. package/dist/server/internal/css-units.js.map +1 -1
  178. package/dist/server/internal/diagnostics.js +1 -1
  179. package/dist/server/internal/diagnostics.js.map +1 -1
  180. package/dist/server/internal/early-events.js +1 -1
  181. package/dist/server/internal/early-events.js.map +1 -1
  182. package/dist/server/internal/portal-context.js.map +1 -1
  183. package/dist/server/internal/react-names.js +1 -1
  184. package/dist/server/internal/react-names.js.map +1 -1
  185. package/dist/server/internal/reconcile.js +1 -1
  186. package/dist/server/internal/reconcile.js.map +1 -1
  187. package/dist/server/resource-hints.js +1 -1
  188. package/dist/server/resource-hints.js.map +1 -1
  189. package/dist/server/select-value.js +1 -1
  190. package/dist/server/select-value.js.map +1 -1
  191. package/dist/server/server/attributes.js +1 -1
  192. package/dist/server/server/attributes.js.map +1 -1
  193. package/dist/server/server/element.js +1 -1
  194. package/dist/server/server/element.js.map +1 -1
  195. package/dist/server/server/errors.js +1 -1
  196. package/dist/server/server/errors.js.map +1 -1
  197. package/dist/server/server/escape.js +1 -1
  198. package/dist/server/server/escape.js.map +1 -1
  199. package/dist/server/server/form-controls.js +2 -2
  200. package/dist/server/server/form-controls.js.map +1 -1
  201. package/dist/server/server/index.js +1 -1
  202. package/dist/server/server/portals.js +1 -1
  203. package/dist/server/server/portals.js.map +1 -1
  204. package/dist/server/server/raw-text.js +2 -0
  205. package/dist/server/server/raw-text.js.map +1 -0
  206. package/dist/server/server/render.js +1 -1
  207. package/dist/server/server/render.js.map +1 -1
  208. package/dist/server/server/stream.js +1 -1
  209. package/dist/server/server/stream.js.map +1 -1
  210. package/dist/server/server.js +1 -1
  211. package/dist/server/spread.js +1 -1
  212. package/dist/server/spread.js.map +1 -1
  213. package/dist/server/template.js +1 -1
  214. package/dist/server/template.js.map +1 -1
  215. package/dist/server/view-transition.js.map +1 -1
  216. package/dist/server-dev/attributes.js +27 -49
  217. package/dist/server-dev/attributes.js.map +1 -1
  218. package/dist/server-dev/class-style.js +64 -47
  219. package/dist/server-dev/class-style.js.map +1 -1
  220. package/dist/server-dev/control-flow/dynamic.js +22 -10
  221. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  222. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  223. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  224. package/dist/server-dev/control-flow/portal.js +17 -13
  225. package/dist/server-dev/control-flow/portal.js.map +1 -1
  226. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  227. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  228. package/dist/server-dev/control-flow/suspense.js +2 -2
  229. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  230. package/dist/server-dev/element.js +3 -1
  231. package/dist/server-dev/element.js.map +1 -1
  232. package/dist/server-dev/events.js +15 -44
  233. package/dist/server-dev/events.js.map +1 -1
  234. package/dist/server-dev/extend.js +2 -2
  235. package/dist/server-dev/insert.js +84 -45
  236. package/dist/server-dev/insert.js.map +1 -1
  237. package/dist/server-dev/internal/accessor.js +56 -0
  238. package/dist/server-dev/internal/accessor.js.map +1 -0
  239. package/dist/server-dev/internal/claim.js +18 -3
  240. package/dist/server-dev/internal/claim.js.map +1 -1
  241. package/dist/server-dev/internal/css-units.js +2 -2
  242. package/dist/server-dev/internal/css-units.js.map +1 -1
  243. package/dist/server-dev/internal/diagnostics.js +14 -4
  244. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  245. package/dist/server-dev/internal/early-events.js +20 -2
  246. package/dist/server-dev/internal/early-events.js.map +1 -1
  247. package/dist/server-dev/internal/portal-context.js.map +1 -1
  248. package/dist/server-dev/internal/react-names.js +45 -71
  249. package/dist/server-dev/internal/react-names.js.map +1 -1
  250. package/dist/server-dev/internal/reconcile.js +7 -12
  251. package/dist/server-dev/internal/reconcile.js.map +1 -1
  252. package/dist/server-dev/resource-hints.js +4 -2
  253. package/dist/server-dev/resource-hints.js.map +1 -1
  254. package/dist/server-dev/select-value.js +5 -15
  255. package/dist/server-dev/select-value.js.map +1 -1
  256. package/dist/server-dev/server/attributes.js +6 -32
  257. package/dist/server-dev/server/attributes.js.map +1 -1
  258. package/dist/server-dev/server/element.js +10 -7
  259. package/dist/server-dev/server/element.js.map +1 -1
  260. package/dist/server-dev/server/errors.js +7 -1
  261. package/dist/server-dev/server/errors.js.map +1 -1
  262. package/dist/server-dev/server/escape.js +14 -6
  263. package/dist/server-dev/server/escape.js.map +1 -1
  264. package/dist/server-dev/server/form-controls.js +5 -2
  265. package/dist/server-dev/server/form-controls.js.map +1 -1
  266. package/dist/server-dev/server/index.js +3 -2
  267. package/dist/server-dev/server/portals.js +3 -0
  268. package/dist/server-dev/server/portals.js.map +1 -1
  269. package/dist/server-dev/server/raw-text.js +86 -0
  270. package/dist/server-dev/server/raw-text.js.map +1 -0
  271. package/dist/server-dev/server/render.js +3 -3
  272. package/dist/server-dev/server/render.js.map +1 -1
  273. package/dist/server-dev/server/stream.js +3 -3
  274. package/dist/server-dev/server/stream.js.map +1 -1
  275. package/dist/server-dev/server.js +3 -2
  276. package/dist/server-dev/spread.js +42 -80
  277. package/dist/server-dev/spread.js.map +1 -1
  278. package/dist/server-dev/template.js +1 -3
  279. package/dist/server-dev/template.js.map +1 -1
  280. package/dist/server-dev/view-transition.js.map +1 -1
  281. package/package.json +4 -3
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number. When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n timeoutMs,\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,OAAmC;CAG/D,OAAO,UADL,UAAU,KAAA,IAAY,KAAK,WAAW,MAAM,QAAQ,sBAAsB,EAAE,EAAE,GACrD,GAAG,KAAK;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eACd,MACA,UAAyB,CAAC,GACE;CAC5B,MAAM,WAAW,QAAQ,YAAY;CACrC,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,cAAc,YAAY,EAAE,YAAY,MAAM,CAAC,OAAO,SAAS,SAAS,GACjF,MAAM,IAAI,UAAU,6DAA6D;CAEnF,MAAM,SAAS,QAAQ;CACvB,MAAM,UAAU,mBAAmB,QAAQ,OAAO;CAClD,MAAM,UAAU,IAAI,YAAY;CAEhC,MAAM,SAAsB,CAAC;CAC7B,MAAM,mBAAyB;EAC7B,MAAM,SAAoB,CAAC;EAC3B,KAAK,MAAM,QAAQ,OAAO,OAAO,CAAC,GAChC,IAAI;GACF,KAAK,QAAQ;EACf,SAAS,OAAO;GACd,OAAO,KAAK,KAAK;EACnB;EAEF,IAAI,OAAO,SAAS,GAClB,MAAM,OAAO,WAAW,IAAI,OAAO,K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G,IAAI,KAAK,eACtC,OAAO,MAAM,KAAK,UAAU,SAAS,EAAE,EAAE,IAAI,QAAQ,KAAK,CAC9D;KACF;KAEA,UAAU,QAAQ,SAAS,iBAAiB,CAAC,UAAU,UAAU,IAAI;KACrE,IAAI,OAAO,WAAW,SAAS,KAAK,WAAW,GAAG,cAAc;IAClE;IAEA,MAAM,OAAgC,CAAC;IACvC,KAAK,MAAM,OAAO,OAAO,WAAW;KAClC,IAAI,CAAC,QAAQ,IAAI,GAAG,GAAG;KACvB,OAAO,eAAe,MAAM,KAAK;MAC/B,OAAO,QAAQ,IAAI,GAAG;MACtB,YAAY;MACZ,UAAU;MACV,cAAc;KAChB,CAAC;IACH;IACA,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,GAC7B,KAAK,4CAA4C,SAAS,IAAI,UAAU,IAAI,EAAE,WAAU;IAE1F,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,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V,cAAc;KAChB,CAAC;IACH;IACA,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,GAC7B,KAAK,4CAA4C,SAAS,IAAI,UAAU,IAAI,EAAE,WAAU;IAE1F,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
@@ -9,8 +9,9 @@ import { escape } from "./server/escape.js";
9
9
  import { ssrSelectValue, ssrTextArea } from "./server/form-controls.js";
10
10
  import { HydrationScript, HydrationScriptOptions, generateHydrationScript } from "./server/hydration-script.js";
11
11
  import { ServerPortals, createServerPortals } from "./server/portals.js";
12
+ import { ssrRawText } from "./server/raw-text.js";
12
13
  import { AsyncRenderOptions, AsyncRenderResult, RenderOptions, renderToString, renderToStringAsync } from "./server/render.js";
13
14
  import { deserialize, serialize } from "./server/serialize.js";
14
15
  import { StreamOptions, renderToStream } from "./server/stream.js";
15
16
  import { mergeProps } from "./server/index.js";
16
- export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
17
+ export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
@@ -2,15 +2,16 @@ import { escape } from "./server/escape.js";
2
2
  import { ssrAttribute } from "./server/attributes.js";
3
3
  import { ssrClass, ssrStyle } from "./server/class-style.js";
4
4
  import { ssrSelectValue, ssrTextArea } from "./server/form-controls.js";
5
+ import { ssrRawText } from "./server/raw-text.js";
5
6
  import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./server/element.js";
6
- import { createServerPortals } from "./server/portals.js";
7
7
  import { normalizeTags } from "./head/validate.js";
8
8
  import { createServerHead } from "./head/server-head.js";
9
9
  import { createComponent, memo } from "./server/component.js";
10
10
  import { derived } from "./server/derived.js";
11
11
  import { HydrationScript, generateHydrationScript } from "./server/hydration-script.js";
12
+ import { createServerPortals } from "./server/portals.js";
12
13
  import { renderToString, renderToStringAsync } from "./server/render.js";
13
14
  import { deserialize, serialize } from "./server/serialize.js";
14
15
  import { renderToStream } from "./server/stream.js";
15
16
  import { mergeProps } from "./server/index.js";
16
- export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
17
+ export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
@@ -1,11 +1,11 @@
1
1
  import { setAttribute, setAttributeNS, setBoolAttribute } from "./attributes.js";
2
2
  import { autoFocus } from "./autofocus.js";
3
- import { applyClass, classList, style } from "./class-style.js";
3
+ import { applyClass, asRecord, classList, style } from "./class-style.js";
4
4
  import { claims } from "./internal/hydration-hooks.js";
5
- import { bindRegion, createRegion } from "./insert.js";
6
- import { IGNORED_KEYS, attributeName, eventPlan } from "./internal/react-names.js";
5
+ import { bindRegion, createRegion, watchCommits } from "./insert.js";
6
+ import { IGNORED_KEYS, attributeName, eventPlan, isFlagAttribute } from "./internal/react-names.js";
7
7
  import { bindEvent } from "./events.js";
8
- import { selectShows, setSelectValue } from "./select-value.js";
8
+ import { plainText, setSelectValue } from "./select-value.js";
9
9
  import { onCleanup, untrack, useRenderEffect } from "@shadow-js/core";
10
10
  // src/spread.ts
11
11
  /** The namespace of `xlink:` attributes (SVG's legacy links). */
@@ -16,11 +16,7 @@ function innerHtmlValue(value) {
16
16
  return plainText(Reflect.get(value, "__html"));
17
17
  }
18
18
  /** Keys that would reach a prototype if written as properties. Ignored everywhere. */
19
- const FORBIDDEN_NAMES = /* @__PURE__ */ new Set([
20
- "__proto__",
21
- "constructor",
22
- "prototype"
23
- ]);
19
+ const FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;
24
20
  /** True for `on*` keys, which bind event handlers. */
25
21
  function isEventKey(key) {
26
22
  return key.length > 2 && key.startsWith("on");
@@ -30,15 +26,6 @@ function nameOf(key) {
30
26
  const colon = key.indexOf(":");
31
27
  return colon === -1 ? key : key.slice(colon + 1);
32
28
  }
33
- /** Narrows an object value to a record of keys; arrays and primitives are not class maps. */
34
- function asRecord(value) {
35
- if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
36
- return value;
37
- }
38
- /** Text for innerHTML and textContent: null and undefined become the empty string. */
39
- function plainText(value) {
40
- return value === null || value === void 0 ? "" : String(value);
41
- }
42
29
  /** Reads every prop except children, inside the render effect so each read is tracked. */
43
30
  function readEntries(props, textarea) {
44
31
  const entries = [];
@@ -46,7 +33,7 @@ function readEntries(props, textarea) {
46
33
  let value;
47
34
  let hasValue = false;
48
35
  for (const key of Object.keys(props)) {
49
- if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;
36
+ if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;
50
37
  if (key === "children") {
51
38
  if (textarea) {
52
39
  value = Reflect.get(props, key);
@@ -108,12 +95,8 @@ function applyKey(el, key, value, state, svg) {
108
95
  if (unbind !== void 0) state.unbinders.set(key, unbind);
109
96
  return;
110
97
  }
111
- if (key === "innerHTML") {
112
- el.innerHTML = plainText(value);
113
- return;
114
- }
115
- if (key === "dangerouslySetInnerHTML") {
116
- el.innerHTML = innerHtmlValue(value);
98
+ if (key === "innerHTML" || key === "dangerouslySetInnerHTML") {
99
+ el.innerHTML = key === "innerHTML" ? plainText(value) : innerHtmlValue(value);
117
100
  return;
118
101
  }
119
102
  if (key === "textContent") {
@@ -124,8 +107,8 @@ function applyKey(el, key, value, state, svg) {
124
107
  setSelectValue(el, value);
125
108
  return;
126
109
  }
127
- if (!svg && LIVE_PROPERTIES.has(key) && key in el) {
128
- liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.has(key) ? value ?? "" : Boolean(value));
110
+ if (!svg && LIVE_PROPERTIES.test(key) && key in el) {
111
+ liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.test(key) ? value ?? "" : Boolean(value));
129
112
  if (key === "value" && el instanceof HTMLInputElement) el.defaultValue = plainText(value);
130
113
  return;
131
114
  }
@@ -134,7 +117,7 @@ function applyKey(el, key, value, state, svg) {
134
117
  /**
135
118
  * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute
136
119
  * under its React name. An `undefined` value removes the attribute or resets the property, which is how
137
- * {@link clearKey} undoes a prop.
120
+ * a prop that disappeared is undone.
138
121
  */
139
122
  function writeKey(el, key, value, svg) {
140
123
  if (key.startsWith("prop:")) Reflect.set(el, key.slice(5), value);
@@ -142,65 +125,24 @@ function writeKey(el, key, value, svg) {
142
125
  else if (key.startsWith("bool:")) setBoolAttribute(el, key.slice(5), value);
143
126
  else {
144
127
  const wire = attributeName(key, svg);
145
- if (wire.startsWith("xlink:")) setAttributeNS(el, XLINK_NS, wire, value);
128
+ if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);
129
+ else if (wire.startsWith("xlink:")) setAttributeNS(el, XLINK_NS, wire, value);
146
130
  else setAttribute(el, wire, value);
147
131
  }
148
132
  }
149
133
  /** Props written as element properties, like the compiler does for the same names in JSX. */
150
- const LIVE_PROPERTIES = /* @__PURE__ */ new Set([
151
- "value",
152
- "checked",
153
- "selected",
154
- "muted",
155
- "indeterminate",
156
- "defaultValue",
157
- "defaultChecked"
158
- ]);
134
+ const LIVE_PROPERTIES = /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;
159
135
  /** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */
160
- const STRING_PROPERTIES = /* @__PURE__ */ new Set(["value", "defaultValue"]);
136
+ const STRING_PROPERTIES = /^(?:value|defaultValue)$/;
161
137
  /**
162
138
  * True when a live property (typed value, toggled box) no longer matches the value last applied, so
163
139
  * an unchanged prop is written again and the element follows the data.
164
140
  */
165
141
  function liveDiffers(el, key, value, svg) {
166
- if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;
167
- if (key === "value" && el instanceof HTMLSelectElement) return !selectShows(el, value);
142
+ if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;
143
+ if (key === "value" && el instanceof HTMLSelectElement) return true;
168
144
  const live = Reflect.get(el, key);
169
- return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);
170
- }
171
- /** Undoes a prop that disappeared from the props object. */
172
- function clearKey(el, key, state, svg) {
173
- if (key === "ref") {
174
- runRefCleanup(state);
175
- return;
176
- }
177
- if (key === "autoFocus") return;
178
- if (key === "class" || key === "className") {
179
- applyClass(el, void 0, svg);
180
- return;
181
- }
182
- if (key === "style") {
183
- state.styleValue = style(el, void 0, state.styleValue);
184
- return;
185
- }
186
- if (key === "classList") {
187
- state.classListValue = classList(el, void 0, state.classListValue);
188
- return;
189
- }
190
- if (isEventKey(key)) {
191
- state.unbinders.get(key)?.();
192
- state.unbinders.delete(key);
193
- return;
194
- }
195
- if (key === "innerHTML" || key === "dangerouslySetInnerHTML" || key === "textContent") {
196
- el.textContent = "";
197
- return;
198
- }
199
- if (!svg && LIVE_PROPERTIES.has(key) && key in el) {
200
- Reflect.set(el, key, STRING_PROPERTIES.has(key) ? "" : false);
201
- return;
202
- }
203
- writeKey(el, key, void 0, svg);
145
+ return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);
204
146
  }
205
147
  /**
206
148
  * Applies the entries that changed since the last run and undoes the ones that disappeared.
@@ -217,7 +159,7 @@ function applyEntries(el, entries, state, svg) {
217
159
  for (const key of [...state.values.keys()]) {
218
160
  if (current.has(key)) continue;
219
161
  state.values.delete(key);
220
- clearKey(el, key, state, svg);
162
+ applyKey(el, key, void 0, state, svg);
221
163
  }
222
164
  }
223
165
  /**
@@ -268,19 +210,52 @@ function applyEntries(el, entries, state, svg) {
268
210
  function spread(el, props, isSVG = false, skipChildren = false) {
269
211
  if (props === null || typeof props !== "object" && typeof props !== "function") return;
270
212
  const read = () => typeof props === "function" ? props() : props;
271
- const textarea = el.localName === "textarea";
272
- if (!skipChildren && !textarea) {
213
+ const state = newState();
214
+ if (!skipChildren && el.localName !== "textarea") {
273
215
  const initial = claims.current.isClaiming() ? claims.current.takeRegion(el, null) ?? Array.from(el.childNodes) : void 0;
274
216
  const region = createRegion(el, null, initial);
275
217
  bindRegion(region, () => read()?.children);
218
+ followOptions(el, isSVG, state);
276
219
  }
277
- const state = {
220
+ applyProps(el, read, isSVG, state);
221
+ }
222
+ /**
223
+ * New options replace the ones that held the selection, and the value effect does not read
224
+ * `children`: a select spread selects its value again after every commit to its children, as the
225
+ * compiled path does.
226
+ */
227
+ function followOptions(el, isSVG, state) {
228
+ if (isSVG || !(el instanceof HTMLSelectElement)) return;
229
+ watchCommits(el, () => {
230
+ const key = state.values.has("value") ? "value" : "defaultValue";
231
+ if (state.values.has(key)) setSelectValue(el, state.values.get(key));
232
+ });
233
+ }
234
+ /** The bookkeeping of a spread that has applied nothing yet. */
235
+ function newState() {
236
+ return {
278
237
  values: /* @__PURE__ */ new Map(),
279
238
  unbinders: /* @__PURE__ */ new Map(),
280
239
  styleValue: void 0,
281
240
  classListValue: void 0,
282
241
  refCleanup: void 0
283
242
  };
243
+ }
244
+ /**
245
+ * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what
246
+ * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds
247
+ * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's
248
+ * children. A select still selects its value again when `Dynamic` commits new options.
249
+ * @internal
250
+ */
251
+ function spreadProps(el, props, isSVG) {
252
+ if (props === null || typeof props !== "object" && typeof props !== "function") return;
253
+ const state = newState();
254
+ followOptions(el, isSVG, state);
255
+ applyProps(el, () => typeof props === "function" ? props() : props, isSVG, state);
256
+ }
257
+ function applyProps(el, read, isSVG, state) {
258
+ const textarea = el.localName === "textarea";
284
259
  onCleanup(() => {
285
260
  for (const unbind of state.unbinders.values()) unbind();
286
261
  state.unbinders.clear();
@@ -290,6 +265,6 @@ function spread(el, props, isSVG = false, skipChildren = false) {
290
265
  applyEntries(el, entries, state, isSVG);
291
266
  });
292
267
  }
293
- export { spread };
268
+ export { spread, spreadProps };
294
269
 
295
270
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { selectShows, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Text for innerHTML and textContent: null and undefined become the empty string. */\nfunction plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\") {\n el.innerHTML = plainText(value);\n return;\n }\n if (key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * {@link clearKey} undoes a prop.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n if (key === \"value\" && el instanceof HTMLSelectElement) return !selectShows(el, value);\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/** Undoes a prop that disappeared from the props object. */\nfunction clearKey(el: Element, key: string, state: SpreadState, svg: boolean): void {\n if (key === \"ref\") {\n runRefCleanup(state);\n return;\n }\n // A focus request is not a state: removing the prop does not unfocus the element.\n if (key === \"autoFocus\") return;\n if (key === \"class\" || key === \"className\") {\n applyClass(el, undefined, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, undefined, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, undefined, state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\" || key === \"textContent\") {\n el.textContent = \"\";\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? \"\" : false);\n return;\n }\n writeKey(el, key, undefined, svg);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n clearKey(el, key, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/C;;AAGA,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAezE,SAAS,WAAW,KAAsB;CACxC,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI;AAC9C;;AAGA,SAAS,OAAO,KAAqB;CACnC,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAC7B,OAAO,UAAU,KAAK,MAAM,IAAI,MAAM,QAAQ,CAAC;AACjD;;AAGA,SAAS,SAAS,OAAqD;CACrE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO,KAAA;CAChF,OAAO;AACT;;AAGA,SAAS,UAAU,OAAwB;CACzC,OAAO,UAAU,QAAQ,UAAU,KAAA,IAA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W,IACrC,OAAO,QAAQ,WAAW,IAAI,IAAI,KAAK,MAAM,KAAK,GAAG,UAAU,IAChE,KAAA;EACJ,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO;EAC7C,WAAW,cAAe,KAAK,CAAC,EAA6C,QAAQ;CACvF;CACA,MAAM,QAAqB;EACzB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;CAEA,gBAAgB;EACd,KAAK,MAAM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
1
+ {"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/C;;AAGA,MAAM,kBAAkB;;AAexB,SAAS,WAAW,KAAsB;CACxC,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI;AAC9C;;AAGA,SAAS,OAAO,KAAqB;CACnC,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAC7B,OAAO,UAAU,KAAK,MAAM,IAAI,MAAM,QAAQ,CAAC;AACjD;;AAGA,SAAS,YAAY,OAAgB,UAA6C;CAChF,MAAM,UAAoC,CAAC;CAC3C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI;CACJ,IAAI,WAAW;CACf,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG;EACpC,IAAI,gBAAgB,KAAK,OAAO,GAAG,CAAC,KAAK,aAAa,KAAK,GAAG,GAAG;EACjE,IAAI,QAAQ,YAAY;GAGtB,IAAI,UAAU;IACZ,QAAQ,QAAQ,IAAI,OAAO,GAAG;IAC9B,WAAW;GACb;GACA;EACF;EACA,QAAQ,KAAK,CAAC,KAAK,QAAQ,IAAI,OAAO,GAAG,CAAC,CAAC;CAC7C;CACA,IAAI,YAAY,CAAC,QAAQ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IAAI,MAAM,OAAO;EAC7C,WAAW,cAAe,KAAK,CAAC,EAA6C,QAAQ;EACrF,cAAc,IAAI,OAAO,KAAK;CAChC;CACA,WAAW,IAAI,MAAM,OAAO,KAAK;AACnC;;;;;;AAOA,SAAS,cAAc,IAAa,OAAgB,OAA0B;CAC5E,IAAI,SAAS,EAAE,cAAc,oBAAoB;CACjD,aAAa,UAAU;EACrB,MAAM,MAAM,MAAM,OAAO,IAAI,OAAO,IAAI,UAAU;EAClD,IAAI,MAAM,OAAO,IAAI,GAAG,GAAG,eAAe,IAAI,MAAM,OAAO,IAAI,GAAG,CAAC;CACrE,CAAC;AACH;;AAGA,SAAS,WAAwB;CAC/B,OAAO;EACL,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;AACF;;;;;;;;AASA,SAAgB,YAAY,IAAa,OAAgB,OAAsB;CAC7E,IAAI,UAAU,QAAS,OAAO,UAAU,YAAY,OAAO,UAAU,YAAa;CAClF,MAAM,QAAQ,SAAS;CACvB,cAAc,IAAI,OAAO,KAAK;CAC9B,WACE,UACO,OAAO,UAAU,aAAc,MAAwB,IAAI,OAClE,OACA,KACF;AACF;AAEA,SAAS,WAAW,IAAa,MAAqB,OAAgB,OAA0B;CAC9F,MAAM,WAAW,GAAG,cAAc;CAElC,gBAAgB;EACd,KAAK,MAAM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
@@ -35,9 +35,7 @@ function inNamespace(source, namespace) {
35
35
  const root = copyOf(source);
36
36
  const stack = [[source, root]];
37
37
  while (stack.length > 0) {
38
- const pair = stack.pop();
39
- if (pair === void 0) break;
40
- const [from, to] = pair;
38
+ const [from, to] = stack.pop();
41
39
  for (const child of Array.from(from.childNodes)) if (child instanceof Element) {
42
40
  const copy = copyOf(child);
43
41
  to.appendChild(copy);
@@ -1 +1 @@
1
- {"version":3,"file":"template.js","names":[],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const pair = stack.pop();\n if (pair === undefined) break;\n const [from, to] = pair;\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,YACJ;;AAEF,MAAM,YAAY;;;;;;AAOlB,SAAS,mBAAmB,MAAoB;CAC9C,KAAK,MAAM,OAAO,KAAK,SAAS,SAAS,GAAG;EAG1C,IADgB,CADI,IAAI,IAAI,MAAM,GAAA,CAAI,SAAS,SAAS,CAC/B,CAAC,CAAC,QAAQ,UAAU,MAAM,EAAE,EA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AAgB,UAAU,OAAO,CAAC;CACxC,IAAI,YAAY,UAAU,KAAK,iBAAA,sCAC7B,OAAO,MAAM,KAAK,YAAY,MAAM,SAAS,CAAC,CAAC,UAAU;CAE3D,OAAO,MAAM,KAAK,KAAK,UAAU;AACnC;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,MAAc,QAAQ,GAAe;CAC5D,MAAM,cAAc,QAAA,OAAkC;CAKtD,IAAI;CACJ,MAAM,iBAAyB;EAC7B,MAAM,OAAO,WAAW,MAAM;EAC9B,IAAI,SAAS,KAAA,GAAW,OAAO;EAC/B,MAAM,QAAQ,MAAM,MAAM,KAAK;EAC/B,YAAY,IAAI,QAAQ,KAAK;EAC7B,OAAO;CACT;CACA,MAAM,QAAQ,SACZ,aAAa,SAAS,WAAW,MAAM,IAAI,IAAI,KAAK,UAAU,IAAI;CACpE,aAAa;EAEX,MAAM,UAAU,OAAO,QAAQ,aAAa,QAAQ,CAAC;EACrD,IAAI,YAAY,MAAM;GACP;IAEX,MAAM,SAAS,SAAS;IACxB,MAAM,CAAC,QAAQ;IACf,IAAI,OAAO,WAAW,KAAK,gBAAgB,SACzC,gBAAgB,SAAS,KAAK,SAAS;GAC3C;GACA,OAAO;EACT;EAEA,MAAM,SAAmB,SAAS;EAClC,IAAI,OAAO,WAAW,GAAG;GACvB,MAAM,CAAC,QAAQ;GACf,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK,IAAI;EAC1C;EACA,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,MAAM,QAAQ,QAAQ,SAAS,YAAY,KAAK,IAAI,CAAC;EAC1D,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"template.js","names":[],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const [from, to] = stack.pop() as [Element, Element];\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,YACJ;;AAEF,MAAM,YAAY;;;;;;AAOlB,SAAS,mBAAmB,MAAoB;CAC9C,KAAK,MAAM,OAAO,KAAK,SAAS,SAAS,GAAG;EAG1C,IADgB,CADI,IAAI,IAAI,MAAM,GAAA,CAAI,SAAS,SAAS,CAC/B,CAAC,CAAC,QAAQ,UAAU,MAAM,EAAE,EAAE,YAAY,MAAM,OAC/D,CAAC,CAAC,SAAS,GAAG;EACxB,MAAM,OAAO,eAAe,KAAK,IAAI,EAAE,CAAC,GAAG,MAAM;EACjD,SACE,6BACA,IAAI,KAAK,0GACX;EACA;CACF;AACF;;;;;AAMA,SAAS,YAAY,QAAiB,WAA4B;CAChE,MAAM,MAAM;CACZ,MAAM,UAAU,YAA8B;EAC5C,MAAM,OAAO,IAAI,gBAAgB,WAAW,QAAQ,SAAS;EAC7D,KAAK,MAAM,aAAa,MAAM,KAAK,QAAQ,UAAU,G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MAAM,MAAM,KAAK;EAC/B,YAAY,IAAI,QAAQ,KAAK;EAC7B,OAAO;CACT;CACA,MAAM,QAAQ,SACZ,aAAa,SAAS,WAAW,MAAM,IAAI,IAAI,KAAK,UAAU,IAAI;CACpE,aAAa;EAEX,MAAM,UAAU,OAAO,QAAQ,aAAa,QAAQ,CAAC;EACrD,IAAI,YAAY,MAAM;GACP;IAEX,MAAM,SAAS,SAAS;IACxB,MAAM,CAAC,QAAQ;IACf,IAAI,OAAO,WAAW,KAAK,gBAAgB,SACzC,gBAAgB,SAAS,KAAK,SAAS;GAC3C;GACA,OAAO;EACT;EAEA,MAAM,SAAmB,SAAS;EAClC,IAAI,OAAO,WAAW,GAAG;GACvB,MAAM,CAAC,QAAQ;GACf,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK,IAAI;EAC1C;EACA,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,MAAM,QAAQ,QAAQ,SAAS,YAAY,KAAK,IAAI,CAAC;EAC1D,OAAO;CACT;AACF"}
@@ -1,3 +1,4 @@
1
+ import { watchCommits } from "./insert.js";
1
2
  import { flushSync, untrack, useEffect, useId } from "@shadow-js/core";
2
3
  // src/view-transition.ts
3
4
  /**
@@ -95,10 +96,17 @@ function ViewTransition(props) {
95
96
  const end = document.createTextNode("");
96
97
  const generated = props.name === true ? `vt-${useId()}` : void 0;
97
98
  useEffect(() => {
98
- const element = firstElementBetween(start, end);
99
- if (element === null) return;
100
- setOrClear(element, "view-transition-name", generated ?? (typeof props.name === "string" ? props.name : void 0));
101
- setOrClear(element, "view-transition-class", props.class);
99
+ const name = generated ?? (typeof props.name === "string" ? props.name : void 0);
100
+ const transitionClass = props.class;
101
+ const apply = () => {
102
+ const element = firstElementBetween(start, end);
103
+ if (element === null) return;
104
+ setOrClear(element, "view-transition-name", name);
105
+ setOrClear(element, "view-transition-class", transitionClass);
106
+ };
107
+ apply();
108
+ const parent = start.parentNode;
109
+ if (parent !== null) watchCommits(parent, apply);
102
110
  });
103
111
  return () => [
104
112
  start,
@@ -1 +1 @@
1
- {"version":3,"file":"view-transition.js","names":[],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists.\n useEffect(() => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", props.class);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,oBACd,QACA,SACe;CACf,MAAM,MAAM,OAAO,aAAa,cAAc,KAAA,IAAa;CAC3D,IAAI,QAAQ,KAAA,KAAa,OAAO,IAAI,wBAAwB,YAAY;EACtE,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,OAAO,QAAQ,OAAO,KAAK;EAC7B;EACA,OAAO,QAAQ,QAAQ;CACzB;CACA,IAAI;CACJ,MAAM,iBAAuB;EAC3B,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,UAAU,EAAE,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,SAAS;CAIvB,OAHmB,IAAI,oBACrB,UAAU,KAAA,KAAa,MAAM,WAAW,IAAI,WAAW;EAAE,QAAQ;EAAU,OAAO,CAAC,GAAG,KAAK;CAAE,CAE/E,CAAC,CAAC,SAAS,WAAW;EACpC,IAAI,YAAY,KAAA,GAAW,MAAM,QAAQ;CAC3C,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,eAAe,OAA+C;CAG5E,IAAI;CACJ,IAAI,QAAQ;CACZ,MAAM,qBAA8B;EAClC,IAAI,CAAC,OAAO;GACV,QAAQ;GACR,QAAQ,cAAc,MAAM,QAAQ;EACtC;EACA,OAAO;CACT;CACA,MAAM,QAAQ,SAAS,eAAe,EAAE;CACxC,MAAM,MAAM,SAAS,eAAe,EAAE;CACtC,MAAM,YAAY,MAAM,SAAS,OAAO,MAAM,MAAM,MAAM,KAAA;CAE1D,gBAAgB;EACd,MAAM,UAAU,oBAAoB,OAAO,GAAG;EAC9C,IAAI,YAAY,MAAM;EAEtB,WAAW,SAAS,wBADP,cAAc,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,KAAA,EACzB;EAChD,WAAW,SAAS,yBAAyB,MAAM,KAAK;CAC1D,CAAC;CACD,aAAa;EAAC;EAAO,aAAa;EAAG;CAAG;AAC1C;;AAGA,SAAS,oBAAoB,OAAa,KAA+B;CACvE,KAAK,IAAI,OAAO,MAAM,aAAa,SAAS,QAAQ,SAAS,KAAK,OAAO,KAAK,aAC5E,IAAI,KAAK,aAAa,GAAG,OAAO;CAElC,OAAO;AACT;AAEA,SAAS,WAAW,SAAsB,UAAkB,OAAiC;CAC3F,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,QAAQ,MAAM,eAAe,QAAQ;MACzE,QAAQ,MAAM,YAAY,UAAU,KAAK;AAChD"}
1
+ {"version":3,"file":"view-transition.js","names":[],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\nimport { watchCommits } from \"./insert\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists. The content can change later\n // (a Show that opens, a fallback replaced by content) and the first element is then another one:\n // the name is applied again after each commit to the parent's regions, where that change lands.\n useEffect(() => {\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n const transitionClass = props.class;\n const apply = (): void => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", transitionClass);\n };\n apply();\n const parent = start.parentNode;\n if (parent !== null) watchCommits(parent, apply);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,oBACd,QACA,SACe;CACf,MAAM,MAAM,OAAO,aAAa,cAAc,KAAA,IAAa;CAC3D,IAAI,QAAQ,KAAA,KAAa,OAAO,IAAI,wBAAwB,YAAY;EACtE,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,OAAO,QAAQ,OAAO,KAAK;EAC7B;EACA,OAAO,QAAQ,QAAQ;CACzB;CACA,IAAI;CACJ,MAAM,iBAAuB;EAC3B,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,UAAU,EAAE,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,SAAS;CAIvB,OAHmB,IAAI,oBACrB,UAAU,KAAA,KAAa,MAAM,WAAW,IAAI,WAAW;EAAE,QAAQ;EAAU,OAAO,CAAC,GAAG,KAAK;CAAE,CAE/E,CAAC,CAAC,SAAS,WAAW;EACpC,IAAI,YAAY,KAAA,GAAW,MAAM,QAAQ;CAC3C,CAAC;AACH;;;;;;;;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