@shadow-js/web 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -3
  3. package/dist/dev/attributes.js +1 -5
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +10 -5
  6. package/dist/dev/class-style.js +44 -47
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.js +2 -2
  9. package/dist/dev/control-flow/dynamic.js.map +1 -1
  10. package/dist/dev/control-flow/error-boundary.js +2 -2
  11. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  12. package/dist/dev/control-flow/portal.d.ts +2 -2
  13. package/dist/dev/control-flow/portal.js +15 -13
  14. package/dist/dev/control-flow/portal.js.map +1 -1
  15. package/dist/dev/control-flow/suspense-list.js +2 -2
  16. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  17. package/dist/dev/control-flow/suspense.js +2 -2
  18. package/dist/dev/control-flow/suspense.js.map +1 -1
  19. package/dist/dev/element.js +13 -27
  20. package/dist/dev/element.js.map +1 -1
  21. package/dist/dev/events.js +64 -80
  22. package/dist/dev/events.js.map +1 -1
  23. package/dist/dev/extend.d.ts +2 -2
  24. package/dist/dev/extend.js +2 -2
  25. package/dist/dev/insert.d.ts +11 -0
  26. package/dist/dev/insert.js +99 -100
  27. package/dist/dev/insert.js.map +1 -1
  28. package/dist/dev/internal/accessor.js +56 -0
  29. package/dist/dev/internal/accessor.js.map +1 -0
  30. package/dist/dev/internal/claim.js +0 -1
  31. package/dist/dev/internal/claim.js.map +1 -1
  32. package/dist/dev/internal/css-units.js +2 -2
  33. package/dist/dev/internal/css-units.js.map +1 -1
  34. package/dist/dev/internal/portal-context.d.ts +9 -0
  35. package/dist/dev/internal/portal-context.js.map +1 -1
  36. package/dist/dev/internal/react-names.js +22 -12
  37. package/dist/dev/internal/react-names.js.map +1 -1
  38. package/dist/dev/internal/reconcile.d.ts +2 -1
  39. package/dist/dev/internal/reconcile.js +23 -8
  40. package/dist/dev/internal/reconcile.js.map +1 -1
  41. package/dist/dev/server/attributes.js +1 -31
  42. package/dist/dev/server/attributes.js.map +1 -1
  43. package/dist/dev/server/element.js +5 -6
  44. package/dist/dev/server/element.js.map +1 -1
  45. package/dist/dev/server/index.js +1 -1
  46. package/dist/dev/server/portals.js +3 -0
  47. package/dist/dev/server/portals.js.map +1 -1
  48. package/dist/dev/server/render.js +1 -1
  49. package/dist/dev/server/stream.js +1 -1
  50. package/dist/dev/server.js +1 -1
  51. package/dist/dev/spread.js +95 -106
  52. package/dist/dev/spread.js.map +1 -1
  53. package/dist/dev/template.js +1 -3
  54. package/dist/dev/template.js.map +1 -1
  55. package/dist/dev/view-transition.js +12 -4
  56. package/dist/dev/view-transition.js.map +1 -1
  57. package/dist/prod/attributes.js +1 -1
  58. package/dist/prod/attributes.js.map +1 -1
  59. package/dist/prod/class-style.js +1 -1
  60. package/dist/prod/class-style.js.map +1 -1
  61. package/dist/prod/control-flow/dynamic.js +1 -1
  62. package/dist/prod/control-flow/dynamic.js.map +1 -1
  63. package/dist/prod/control-flow/error-boundary.js +1 -1
  64. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  65. package/dist/prod/control-flow/portal.js +1 -1
  66. package/dist/prod/control-flow/portal.js.map +1 -1
  67. package/dist/prod/control-flow/suspense-list.js +1 -1
  68. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  69. package/dist/prod/control-flow/suspense.js +1 -1
  70. package/dist/prod/control-flow/suspense.js.map +1 -1
  71. package/dist/prod/element.js +1 -1
  72. package/dist/prod/element.js.map +1 -1
  73. package/dist/prod/events.js +1 -1
  74. package/dist/prod/events.js.map +1 -1
  75. package/dist/prod/extend.js +1 -1
  76. package/dist/prod/insert.js +1 -1
  77. package/dist/prod/insert.js.map +1 -1
  78. package/dist/prod/internal/accessor.js +2 -0
  79. package/dist/prod/internal/accessor.js.map +1 -0
  80. package/dist/prod/internal/claim.js +1 -1
  81. package/dist/prod/internal/claim.js.map +1 -1
  82. package/dist/prod/internal/css-units.js +1 -1
  83. package/dist/prod/internal/css-units.js.map +1 -1
  84. package/dist/prod/internal/portal-context.js.map +1 -1
  85. package/dist/prod/internal/react-names.js +1 -1
  86. package/dist/prod/internal/react-names.js.map +1 -1
  87. package/dist/prod/internal/reconcile.js +1 -1
  88. package/dist/prod/internal/reconcile.js.map +1 -1
  89. package/dist/prod/server/attributes.js +1 -1
  90. package/dist/prod/server/attributes.js.map +1 -1
  91. package/dist/prod/server/element.js +1 -1
  92. package/dist/prod/server/element.js.map +1 -1
  93. package/dist/prod/server/index.js +1 -1
  94. package/dist/prod/server/portals.js +1 -1
  95. package/dist/prod/server/portals.js.map +1 -1
  96. package/dist/prod/server/render.js +1 -1
  97. package/dist/prod/server/stream.js +1 -1
  98. package/dist/prod/server.js +1 -1
  99. package/dist/prod/spread.js +1 -1
  100. package/dist/prod/spread.js.map +1 -1
  101. package/dist/prod/template.js +1 -1
  102. package/dist/prod/template.js.map +1 -1
  103. package/dist/prod/view-transition.js +1 -1
  104. package/dist/prod/view-transition.js.map +1 -1
  105. package/dist/server/attributes.js +1 -1
  106. package/dist/server/attributes.js.map +1 -1
  107. package/dist/server/class-style.js +1 -1
  108. package/dist/server/class-style.js.map +1 -1
  109. package/dist/server/control-flow/dynamic.js.map +1 -1
  110. package/dist/server/control-flow/error-boundary.js +1 -1
  111. package/dist/server/control-flow/error-boundary.js.map +1 -1
  112. package/dist/server/control-flow/portal.js +1 -1
  113. package/dist/server/control-flow/portal.js.map +1 -1
  114. package/dist/server/control-flow/suspense-list.js +1 -1
  115. package/dist/server/control-flow/suspense-list.js.map +1 -1
  116. package/dist/server/control-flow/suspense.js +1 -1
  117. package/dist/server/control-flow/suspense.js.map +1 -1
  118. package/dist/server/element.js.map +1 -1
  119. package/dist/server/events.js +1 -1
  120. package/dist/server/events.js.map +1 -1
  121. package/dist/server/extend.js +1 -1
  122. package/dist/server/insert.js +1 -1
  123. package/dist/server/insert.js.map +1 -1
  124. package/dist/server/internal/accessor.js +2 -0
  125. package/dist/server/internal/accessor.js.map +1 -0
  126. package/dist/server/internal/claim.js +1 -1
  127. package/dist/server/internal/claim.js.map +1 -1
  128. package/dist/server/internal/css-units.js +1 -1
  129. package/dist/server/internal/css-units.js.map +1 -1
  130. package/dist/server/internal/portal-context.js.map +1 -1
  131. package/dist/server/internal/react-names.js +1 -1
  132. package/dist/server/internal/react-names.js.map +1 -1
  133. package/dist/server/internal/reconcile.js +1 -1
  134. package/dist/server/internal/reconcile.js.map +1 -1
  135. package/dist/server/server/attributes.js +1 -1
  136. package/dist/server/server/attributes.js.map +1 -1
  137. package/dist/server/server/element.js +1 -1
  138. package/dist/server/server/element.js.map +1 -1
  139. package/dist/server/server/index.js +1 -1
  140. package/dist/server/server/portals.js +1 -1
  141. package/dist/server/server/portals.js.map +1 -1
  142. package/dist/server/server/render.js +1 -1
  143. package/dist/server/server/stream.js +1 -1
  144. package/dist/server/server.js +1 -1
  145. package/dist/server/spread.js +1 -1
  146. package/dist/server/spread.js.map +1 -1
  147. package/dist/server/template.js +1 -1
  148. package/dist/server/template.js.map +1 -1
  149. package/dist/server/view-transition.js.map +1 -1
  150. package/dist/server-dev/attributes.js +1 -5
  151. package/dist/server-dev/attributes.js.map +1 -1
  152. package/dist/server-dev/class-style.js +44 -47
  153. package/dist/server-dev/class-style.js.map +1 -1
  154. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  155. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  156. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  157. package/dist/server-dev/control-flow/portal.js +15 -13
  158. package/dist/server-dev/control-flow/portal.js.map +1 -1
  159. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  160. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  161. package/dist/server-dev/control-flow/suspense.js +2 -2
  162. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  163. package/dist/server-dev/element.js.map +1 -1
  164. package/dist/server-dev/events.js +64 -80
  165. package/dist/server-dev/events.js.map +1 -1
  166. package/dist/server-dev/extend.js +2 -2
  167. package/dist/server-dev/insert.js +99 -100
  168. package/dist/server-dev/insert.js.map +1 -1
  169. package/dist/server-dev/internal/accessor.js +56 -0
  170. package/dist/server-dev/internal/accessor.js.map +1 -0
  171. package/dist/server-dev/internal/claim.js +0 -1
  172. package/dist/server-dev/internal/claim.js.map +1 -1
  173. package/dist/server-dev/internal/css-units.js +2 -2
  174. package/dist/server-dev/internal/css-units.js.map +1 -1
  175. package/dist/server-dev/internal/portal-context.js.map +1 -1
  176. package/dist/server-dev/internal/react-names.js +22 -12
  177. package/dist/server-dev/internal/react-names.js.map +1 -1
  178. package/dist/server-dev/internal/reconcile.js +23 -8
  179. package/dist/server-dev/internal/reconcile.js.map +1 -1
  180. package/dist/server-dev/server/attributes.js +1 -31
  181. package/dist/server-dev/server/attributes.js.map +1 -1
  182. package/dist/server-dev/server/element.js +5 -6
  183. package/dist/server-dev/server/element.js.map +1 -1
  184. package/dist/server-dev/server/index.js +1 -1
  185. package/dist/server-dev/server/portals.js +3 -0
  186. package/dist/server-dev/server/portals.js.map +1 -1
  187. package/dist/server-dev/server/render.js +1 -1
  188. package/dist/server-dev/server/stream.js +1 -1
  189. package/dist/server-dev/server.js +1 -1
  190. package/dist/server-dev/spread.js +81 -105
  191. package/dist/server-dev/spread.js.map +1 -1
  192. package/dist/server-dev/template.js +1 -3
  193. package/dist/server-dev/template.js.map +1 -1
  194. package/dist/server-dev/view-transition.js.map +1 -1
  195. package/package.json +3 -3
@@ -7,7 +7,7 @@
7
7
  * stylesheet writer are the only importers, so it is linked only where a style is written.
8
8
  * @internal
9
9
  */
10
- const UNITLESS = new Set("animation-iteration-count aspect-ratio border-image-outset border-image-slice border-image-width box-flex box-flex-group box-ordinal-group column-count columns flex flex-grow flex-positive flex-shrink flex-negative flex-order grid-area grid-row grid-row-end grid-row-span grid-row-start grid-column grid-column-end grid-column-span grid-column-start font-weight line-clamp line-height opacity order orphans scale tab-size widows z-index zoom fill-opacity flood-opacity stop-opacity stroke-dasharray stroke-dashoffset stroke-miterlimit stroke-opacity stroke-width".split(" "));
10
+ const UNITLESS = /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;
11
11
  /**
12
12
  * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a
13
13
  * custom property (`--x`) or unitless; every other value is `String(value)`.
@@ -18,7 +18,7 @@ const UNITLESS = new Set("animation-iteration-count aspect-ratio border-image-ou
18
18
  function cssValueText(property, value) {
19
19
  if (typeof value !== "number" || value === 0 || property.startsWith("--")) return String(value);
20
20
  const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
21
- return UNITLESS.has(bare) ? String(value) : `${value}px`;
21
+ return UNITLESS.test(bare) ? String(value) : `${value}px`;
22
22
  }
23
23
  export { cssValueText };
24
24
 
@@ -1 +1 @@
1
- {"version":3,"file":"css-units.js","names":[],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS: ReadonlySet<string> = new Set(\n (\n \"animation-iteration-count aspect-ratio border-image-outset border-image-slice \" +\n \"border-image-width box-flex box-flex-group box-ordinal-group column-count columns flex \" +\n \"flex-grow flex-positive flex-shrink flex-negative flex-order grid-area grid-row grid-row-end \" +\n \"grid-row-span grid-row-start grid-column grid-column-end grid-column-span grid-column-start \" +\n \"font-weight line-clamp line-height opacity order orphans scale tab-size widows z-index zoom \" +\n \"fill-opacity flood-opacity stop-opacity stroke-dasharray stroke-dashoffset stroke-miterlimit \" +\n \"stroke-opacity stroke-width\"\n ).split(\" \"),\n);\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.has(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,WAAgC,IAAI,IAEtC,qjBAOA,MAAM,GAAG,CACb;;;;;;;;AASA,SAAgB,aAAa,UAAkB,OAAwB;CACrE,IAAI,OAAO,UAAU,YAAY,UAAU,KAAK,SAAS,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK;CAC9F,MAAM,OAAO,SAAS,QAAQ,0BAA0B,EAAE;CAC1D,OAAO,SAAS,IAAI,IAAI,IAAI,OAAO,KAAK,IAAI,GAAG,MAAM;AACvD"}
1
+ {"version":3,"file":"css-units.js","names":[],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS =\n /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.test(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,WACJ;;;;;;;;AASF,SAAgB,aAAa,UAAkB,OAAwB;CACrE,IAAI,OAAO,UAAU,YAAY,UAAU,KAAK,SAAS,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK;CAC9F,MAAM,OAAO,SAAS,QAAQ,0BAA0B,EAAE;CAC1D,OAAO,SAAS,KAAK,IAAI,IAAI,OAAO,KAAK,IAAI,GAAG,MAAM;AACxD"}
@@ -11,6 +11,15 @@ export interface PortalSink {
11
11
  * render.
12
12
  */
13
13
  add(key: string, html: string): void;
14
+ /**
15
+ * Renders a `Portal`'s content into this sink under hydration key `key`. The collectors the
16
+ * renderers provide have it; `Portal` calls it instead of importing the markup writer, so the
17
+ * browser bundle of an app that uses `Portal` does not carry server rendering code. A sink without
18
+ * it receives nothing from `Portal`.
19
+ * @param key The portal's key, `undefined` when the render has no scope (nothing is written).
20
+ * @param children Reads the content: a thunk, because it must be built inside the portal's scope.
21
+ */
22
+ render?(key: string | undefined, children: () => unknown): void;
14
23
  }
15
24
  /**
16
25
  * The context through which a server render hands portals their collector: the renderers provide it
@@ -1 +1 @@
1
- {"version":3,"file":"portal-context.js","names":[],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,gBACK,8BAAiC,MAAM,EACrD,MAAM,SACR,CAAC"}
1
+ {"version":3,"file":"portal-context.js","names":[],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n /**\n * Renders a `Portal`'s content into this sink under hydration key `key`. The collectors the\n * renderers provide have it; `Portal` calls it instead of importing the markup writer, so the\n * browser bundle of an app that uses `Portal` does not carry server rendering code. A sink without\n * it receives nothing from `Portal`.\n * @param key The portal's key, `undefined` when the render has no scope (nothing is written).\n * @param children Reads the content: a thunk, because it must be built inside the portal's scope.\n */\n render?(key: string | undefined, children: () => unknown): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,gBACK,8BAAiC,MAAM,EACrD,MAAM,SACR,CAAC"}
@@ -39,22 +39,14 @@ function attributeName(name, svg) {
39
39
  return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
40
40
  }
41
41
  /** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */
42
- const IGNORED_KEYS = /* @__PURE__ */ new Set([
43
- "key",
44
- "suppressHydrationWarning",
45
- "suppressContentEditableWarning"
46
- ]);
42
+ const IGNORED_KEYS = /^(?:key|suppress(?:Hydration|ContentEditable)Warning)$/;
47
43
  /** React events that bubble under another name. */
48
44
  const REACT_EVENTS = /* @__PURE__ */ new Map([
49
45
  ["focus", "focusin"],
50
46
  ["blur", "focusout"],
51
47
  ["doubleclick", "dblclick"]
52
48
  ]);
53
- const CHANGE_ON_TYPES = /* @__PURE__ */ new Set([
54
- "checkbox",
55
- "radio",
56
- "file"
57
- ]);
49
+ const CHANGE_ON_TYPES = /^(?:checkbox|radio|file)$/;
58
50
  /**
59
51
  * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit
60
52
  * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and
@@ -67,13 +59,31 @@ function eventPlan(attribute, tag, type) {
67
59
  const capture = reactSpelling && attribute.endsWith("Capture");
68
60
  const lower = attribute.slice(2, capture ? -7 : void 0).toLowerCase();
69
61
  let planned = lower;
70
- if (reactSpelling) planned = lower === "change" ? tag === "textarea" || tag === "input" && (type === null || !CHANGE_ON_TYPES.has(type)) ? "input" : "change" : REACT_EVENTS.get(lower) ?? lower;
62
+ if (reactSpelling) planned = lower === "change" ? tag === "textarea" || tag === "input" && (type === null || !CHANGE_ON_TYPES.test(type)) ? "input" : "change" : REACT_EVENTS.get(lower) ?? lower;
71
63
  return {
72
64
  type: planned,
73
65
  capture,
74
66
  passive: reactSpelling && lower === "wheel" && !capture
75
67
  };
76
68
  }
77
- export { IGNORED_KEYS, attributeName, eventPlan };
69
+ /**
70
+ * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare
71
+ * `disabled`). Lower-case names only. The server and the client share this test, so a value that
72
+ * renders a flag on one side renders it on the other. One space-separated string, not a set of
73
+ * strings, because every bundle that spreads props carries it. A name with a space in it can match
74
+ * two neighbors, but such a name is not a valid attribute name and both renderers refuse it before
75
+ * they write anything.
76
+ */
77
+ const BOOLEAN_ATTRIBUTES = " async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert ismap loop multiple muted nomodule novalidate open playsinline readonly required reversed selected ";
78
+ /**
79
+ * True when a prop written under attribute name `name` is a presence flag for `value`: one of the
80
+ * boolean attributes, except `hidden="until-found"`, a keyword that only collapses the element
81
+ * (a bare `hidden` would hide it). The client writes the flag with truthiness, as the server does.
82
+ * @internal
83
+ */
84
+ function isFlagAttribute(name, value) {
85
+ return BOOLEAN_ATTRIBUTES.includes(` ${name} `) && !(name === "hidden" && value === "until-found");
86
+ }
87
+ export { IGNORED_KEYS, attributeName, eventPlan, isFlagAttribute };
78
88
 
79
89
  //# sourceMappingURL=react-names.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"react-names.js","names":[],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: ReadonlySet<string> = new Set([\n \"key\",\n \"suppressHydrationWarning\",\n \"suppressContentEditableWarning\",\n]);\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES: ReadonlySet<string> = new Set([\"checkbox\", \"radio\", \"file\"]);\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.has(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAM,sBACJ;;A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S;EAAS,SAAS,iBAAiB,UAAU,WAAW,CAAC;CAAQ;AAC3F"}
1
+ {"version":3,"file":"react-names.js","names":[],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: RegExp = /^(?:key|suppress(?:Hydration|ContentEditable)Warning)$/;\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES = /^(?:checkbox|radio|file)$/;\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.test(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only. The server and the client share this test, so a value that\n * renders a flag on one side renders it on the other. One space-separated string, not a set of\n * strings, because every bundle that spreads props carries it. A name with a space in it can match\n * two neighbors, but such a name is not a valid attribute name and both renderers refuse it before\n * they write anything.\n */\nconst BOOLEAN_ATTRIBUTES =\n \" async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert \" +\n \"ismap loop multiple muted nomodule novalidate open playsinline readonly required reversed selected \";\n\n/**\n * True when a prop written under attribute name `name` is a presence flag for `value`: one of the\n * boolean attributes, except `hidden=\"until-found\"`, a keyword that only collapses the element\n * (a bare `hidden` would hide it). The client writes the flag with truthiness, as the server does.\n * @internal\n */\nexport function isFlagAttribute(name: string, value: unknown): boolean {\n return (\n BOOLEAN_ATTRIBUTES.includes(` ${name} `) && !(name === \"hidden\" && value === \"until-found\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAM,sBACJ;;AAGF,MAAM,0BAAuC,IAAI,IAAI;CACnD,CAAC,aAAa,OAAO;CACrB,CAAC,WAAW,KAAK;CACjB,CAAC,aAAa,YAAY;CAC1B,CAAC,iBAAiB,gBAAgB;AACpC,CAAC;;;;;;;AAQD,SAAgB,cAAc,MAAc,KAAsB;CAChE,MAAM,UAAU,QAAQ,IAAI,IAAI;CAChC,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,IAAI,CAAC,KAAK,OAAO,KAAK,YAAY;CAClC,IAAI,KAAK,SAAS,GAAG,GAAG,OAAO;CAC/B,MAAM,WAAW,2BAA2B,KAAK,IAAI;CACrD,IAAI,aAAa,MAAM,OAAO,GAAG,SAAS,GAAG,GAAG,SAAS,EAAE,EAAE,YAAY,IAAI,SAAS;CACtF,IAAI,CAAC,oBAAoB,KAAK,IAAI,GAAG,OAAO;CAC5C,OAAO,KAAK,QAAQ,WAAW,WAAW,IAAI,OAAO,YAAY,GAAG;AACtE;;AAGA,MAAa,eAAuB;;AAUpC,MAAM,+BAA4C,IAAI,IAAI;CACxD,CAAC,SAAS,SAAS;CACnB,CAAC,QAAQ,UAAU;CACnB,CAAC,eAAe,UAAU;AAC5B,CAAC;AAED,MAAM,kBAAkB;;;;;;;;AASxB,SAAgB,UAAU,WAAmB,KAAa,MAAgC;CACxF,MAAM,gBAAgB,WAAW,KAAK,SAAS;CAC/C,MAAM,UAAU,iBAAiB,UAAU,SAAS,SAAS;CAC7D,MAAM,QAAQ,UAAU,MAAM,GAAG,UAAU,KAAoB,KAAA,CAAS,CAAC,CAAC,YAAY;CACtF,IAAI,UAAU;CACd,IAAI,eACF,UACE,UAAU,WACN,QAAQ,cAAe,QAAQ,YAAY,SAAS,QAAQ,CAAC,gBAAgB,KAAK,IAAI,KACpF,UACA,WACD,aAAa,IAAI,KAAK,KAAK;CAEpC,OAAO;EAAE,MAAM;EAAS;EAAS,SAAS,iBAAiB,UAAU,WAAW,CAAC;CAAQ;AAC3F;;;;;;;;;AAUA,MAAM,qBACJ;;;;;;;AASF,SAAgB,gBAAgB,MAAc,OAAyB;CACrE,OACE,mBAAmB,SAAS,IAAI,KAAK,EAAE,KAAK,EAAE,SAAS,YAAY,UAAU;AAEjF"}
@@ -13,7 +13,8 @@
13
13
  * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of
14
14
  * surviving positions stay where they are; every other node is moved (or inserted) directly
15
15
  * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,
16
- * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,
16
+ * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move
17
+ * blurred gets the focus back). Each node moves at most once,
17
18
  * and the number of moves is minimal for the surviving order.
18
19
  *
19
20
  * @param parent The parent of the region.
@@ -1,4 +1,17 @@
1
1
  // src/internal/reconcile.ts
2
+ /**
3
+ * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused
4
+ * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it
5
+ * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps
6
+ * it. The focused element is read once, before `run`.
7
+ * @internal
8
+ */
9
+ function keepFocus(at, run) {
10
+ const root = at.getRootNode();
11
+ const active = root.activeElement;
12
+ run();
13
+ if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });
14
+ }
2
15
  /** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */
3
16
  function removeNode(parent, node) {
4
17
  if (node !== void 0 && node.parentNode === parent) parent.removeChild(node);
@@ -12,12 +25,12 @@ function markLongestIncreasing(values, offset, marks) {
12
25
  const tails = [];
13
26
  const previous = values.map(() => -1);
14
27
  for (let index = 0; index < values.length; index += 1) {
15
- const value = values[index] ?? 0;
28
+ const value = values[index];
16
29
  let low = 0;
17
30
  let high = tails.length;
18
31
  while (low < high) {
19
32
  const middle = low + high >> 1;
20
- if ((values[tails[middle] ?? 0] ?? 0) < value) low = middle + 1;
33
+ if (values[tails[middle]] < value) low = middle + 1;
21
34
  else high = middle;
22
35
  }
23
36
  previous[index] = tails[low - 1] ?? -1;
@@ -25,8 +38,8 @@ function markLongestIncreasing(values, offset, marks) {
25
38
  }
26
39
  let cursor = tails.at(-1) ?? -1;
27
40
  while (cursor !== -1) {
28
- marks[(values[cursor] ?? 0) - offset] = 1;
29
- cursor = previous[cursor] ?? -1;
41
+ marks[values[cursor] - offset] = 1;
42
+ cursor = previous[cursor];
30
43
  }
31
44
  }
32
45
  /**
@@ -44,7 +57,8 @@ function markLongestIncreasing(values, offset, marks) {
44
57
  * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of
45
58
  * surviving positions stay where they are; every other node is moved (or inserted) directly
46
59
  * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,
47
- * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,
60
+ * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move
61
+ * blurred gets the focus back). Each node moves at most once,
48
62
  * and the number of moves is minimal for the surviving order.
49
63
  *
50
64
  * @param parent The parent of the region.
@@ -90,7 +104,6 @@ function reconcileNodes(parent, prev, next, end) {
90
104
  const survivors = [];
91
105
  for (let index = head; index < prevTail; index += 1) {
92
106
  const node = prev[index];
93
- if (node === void 0) continue;
94
107
  const position = target.get(node);
95
108
  if (position === void 0) removeNode(parent, node);
96
109
  else survivors.push(position);
@@ -102,17 +115,19 @@ function reconcileNodes(parent, prev, next, end) {
102
115
  const stable = new Uint8Array(nextTail - head);
103
116
  markLongestIncreasing(survivors, head, stable);
104
117
  const movable = typeof parent.moveBefore === "function";
118
+ const root = parent.getRootNode();
119
+ const active = movable ? null : root.activeElement;
105
120
  let anchorNode = before;
106
121
  for (let index = nextTail - 1; index >= head; index -= 1) {
107
122
  const node = next[index];
108
- if (node === void 0) continue;
109
123
  if (stable[index - head] !== 1) {
110
124
  if (movable && node.parentNode === parent) parent.moveBefore(node, anchorNode);
111
125
  else parent.insertBefore(node, anchorNode);
112
126
  }
113
127
  anchorNode = node;
114
128
  }
129
+ if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });
115
130
  }
116
- export { reconcileNodes };
131
+ export { keepFocus, reconcileNodes };
117
132
 
118
133
  //# sourceMappingURL=reconcile.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] ?? 0;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] ?? 0] ?? 0;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] ?? 0) - offset] = 1;\n cursor = previous[cursor] ?? -1;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index];\n if (node === undefined) continue;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index];\n if (node === undefined) continue;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n}\n"],"mappings":";;AAMA,SAAS,WAAW,QAAc,MAA8B;CAC9D,IAAI,SAAS,KAAA,KAAa,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI;AAC/E;;;;;;AAOA,SAAS,sBAAsB,QAA2B,QAAgB,OAAyB;CAEjG,MAAM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M,KAAK;CAChD;CAEA,MAAM,YAAsB,CAAC;CAC7B,KAAK,IAAI,QAAQ,MAAM,QAAQ,UAAU,SAAS,GAAG;EACnD,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,WAAW,OAAO,IAAI,IAAI;EAChC,IAAI,aAAa,KAAA,GAAW,WAAW,QAAQ,IAAI;OAC9C,UAAU,KAAK,QAAQ;CAC9B;CAKA,IAAI,UAAU,WAAW,GAAG;EAC1B,KAAK,MAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,GAAG,OAAO,aAAa,MAAM,MAAM;EAC/E;CACF;CAEA,MAAM,SAAS,IAAI,WAAW,WAAW,IAAI;CAC7C,sBAAsB,WAAW,MAAM,MAAM;CAC7C,MAAM,UAAU,OAAQ,OAAkC,eAAe;CAEzE,IAAI,aAAa;CACjB,KAAK,IAAI,QAAQ,WAAW,GAAG,SAAS,MAAM,SAAS,GAAG;EACxD,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,QAAQ,UAAU,GAAG;GAC9B,IAAI,WAAW,KAAK,eAAe,QACjC,OAA0B,WAAW,MAAM,UAAU;QAClD,OAAO,aAAa,MAAM,UAAU;EAC3C;EACA,aAAa;CACf;AACF"}
1
+ {"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":";;;;;;;;AAYA,SAAgB,UAAU,IAAU,KAAuB;CACzD,MAAM,OAAO,GAAG,YAAY;CAC5B,MAAM,SAAS,KAAK;CACpB,IAAI;CACJ,IAAI,UAAU,QAAQ,KAAK,kBAAkB,QAAQ,OAAO,MAAM,EAAE,eAAe,KAAK,CAAC;AAC3F;;AAGA,SAAS,WAAW,QAAc,MAA8B;CAC9D,IAAI,SAAS,KAAA,KAAa,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI;AAC/E;;;;;;AAOA,SAAS,sBAAsB,QAA2B,QAAgB,OAAyB;CAEjG,MAAM,QAAkB,CAAC;CACzB,MAAM,WAAqB,OAAO,UAAU,EAAE;CAC9C,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,QAAQ,OAAO;EACrB,IAAI,MAAM;EACV,IAAI,OAAO,MAAM;EACjB,OAAO,MAAM,MAAM;GACjB,MAAM,SAAU,MAAM,QAAS;GAE/B,IADc,OAAO,MAAM,WACf,OAAO,MAAM,SAAS;QAC7B,OAAO;EACd;EAEA,SAAS,SAAS,MAAM,MAAM,MAAM;EACpC,MAAM,OAAO;CACf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AAW,WAAW,IAAI;CAC7C,sBAAsB,WAAW,MAAM,MAAM;CAC7C,MAAM,UAAU,OAAQ,OAAkC,eAAe;CAIzE,MAAM,OAAO,OAAO,YAAY;CAChC,MAAM,SAAS,UAAU,OAAQ,KAAK;CACtC,IAAI,aAAa;CACjB,KAAK,IAAI,QAAQ,WAAW,GAAG,SAAS,MAAM,SAAS,GAAG;EACxD,MAAM,OAAO,KAAK;EAClB,IAAI,OAAO,QAAQ,UAAU,GAAG;GAC9B,IAAI,WAAW,KAAK,eAAe,QACjC,OAA0B,WAAW,MAAM,UAAU;QAClD,OAAO,aAAa,MAAM,UAAU;EAC3C;EACA,aAAa;CACf;CACA,IAAI,UAAU,QAAQ,KAAK,kBAAkB,QAAQ,OAAO,MAAM,EAAE,eAAe,KAAK,CAAC;AAC3F"}
@@ -30,36 +30,6 @@ const ENUMERATED_ATTRIBUTES = /* @__PURE__ */ new Set([
30
30
  "spellcheck",
31
31
  "contenteditable"
32
32
  ]);
33
- /**
34
- * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare
35
- * `disabled`). Lower-case names only.
36
- * @internal
37
- */
38
- const BOOLEAN_ATTRIBUTES = /* @__PURE__ */ new Set([
39
- "async",
40
- "autofocus",
41
- "autoplay",
42
- "checked",
43
- "controls",
44
- "default",
45
- "defer",
46
- "disabled",
47
- "formnovalidate",
48
- "hidden",
49
- "inert",
50
- "ismap",
51
- "loop",
52
- "multiple",
53
- "muted",
54
- "nomodule",
55
- "novalidate",
56
- "open",
57
- "playsinline",
58
- "readonly",
59
- "required",
60
- "reversed",
61
- "selected"
62
- ]);
63
33
  /** URL prefixes (after normalization) that are never written. Same as the client. */
64
34
  const UNSAFE_URL_PREFIXES = [
65
35
  "javascript:",
@@ -153,6 +123,6 @@ function ssrAttribute(name, value, isBoolean = false) {
153
123
  if (isUnsafeAttributeValue(lowerName, text)) return "";
154
124
  return ` ${name}="${escapeHtml(text)}"`;
155
125
  }
156
- export { BOOLEAN_ATTRIBUTES, assertAttributeName, attributeText, isEventName, isUnsafeUrl, ssrAttribute };
126
+ export { assertAttributeName, attributeText, isEventName, isUnsafeUrl, ssrAttribute };
157
127
 
158
128
  //# sourceMappingURL=attributes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"attributes.js","names":[],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"../internal/diagnostics\";\nimport { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"poster\",\n \"data\",\n]);\n\n/**\n * SVG animation attributes (`animate`, `set`): with `attributeName=\"href\"` they write an `href` by animation, so their value\n * is checked like one. `values` is a `;` list and every entry is checked. Same as the client.\n */\nconst ANIMATION_VALUE_ATTRIBUTES: ReadonlySet<string> = new Set([\"values\", \"from\", \"to\", \"by\"]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"draggable\",\n \"spellcheck\",\n \"contenteditable\",\n]);\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only.\n * @internal\n */\nexport const BOOLEAN_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"async\",\n \"autofocus\",\n \"autoplay\",\n \"checked\",\n \"controls\",\n \"default\",\n \"defer\",\n \"disabled\",\n \"formnovalidate\",\n \"hidden\",\n \"inert\",\n \"ismap\",\n \"loop\",\n \"multiple\",\n \"muted\",\n \"nomodule\",\n \"novalidate\",\n \"open\",\n \"playsinline\",\n \"readonly\",\n \"required\",\n \"reversed\",\n \"selected\",\n]);\n\n/** URL prefixes (after normalization) that are never written. Same as the client. */\nconst UNSAFE_URL_PREFIXES: readonly string[] = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/** Throws a TypeError unless `name` can be written as an attribute name. @internal */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) {\n throw invalid(\"INVALID_ATTRIBUTE_NAME\", `\"${name}\" is not a valid attribute name.`);\n }\n}\n\n/** True for `on*` names, which never reach markup. Length matches the client's event test. @internal */\nexport function isEventName(lowerName: string): boolean {\n return lowerName.length > 2 && lowerName.startsWith(\"on\");\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their booleans are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters, which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script, after the normalization browsers apply. @internal */\nexport function isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** True when `lowerName` carries a URL (or an animated one) and `value` would run script. */\nfunction isUnsafeAttributeValue(lowerName: string, value: string): boolean {\n if (URL_ATTRIBUTES.has(lowerName)) return isUnsafeUrl(value);\n return ANIMATION_VALUE_ATTRIBUTES.has(lowerName) && value.split(\";\").some(isUnsafeUrl);\n}\n\n/** Text to write for `value`, or null when the attribute is removed. Same rules as the client. @internal */\nexport function attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** Refuses symbols, which have no markup form and would otherwise be coerced silently. */\nfunction assertNotSymbol(value: unknown): void {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be an attribute value.\");\n }\n}\n\n/**\n * Renders one attribute as markup with a leading space, or `\"\"` when the attribute is absent: the\n * helper the compiler's server output calls for a dynamic attribute. It applies the client's value\n * rules and URL check, so server and client agree on what is written.\n *\n * - `null`, `undefined` and `false` give `\"\"` (except `false` on `aria-*`, `data-*`, `draggable`,\n * `spellcheck` and `contenteditable`, which is written as `\"false\"`); `true` writes `=\"\"` (or\n * `\"true\"` for those same names). Other values are written as `String(value)`, HTML-escaped.\n * - URL attributes whose value would run script are dropped, with the check of\n * `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).\n * - `srcdoc` is an HTML sink, not a URL: its value is a document the frame runs, escaped for the attribute\n * and otherwise written as it is, with the trust of `innerHTML`. Sanitize it and give the frame a `sandbox`\n * attribute. Development builds warn once with `SRCDOC_DYNAMIC`.\n * - `on*` names are dropped: event handlers never reach markup.\n * - Accessors are called (untracked) until a plain value remains.\n *\n * @param name Attribute name, matching `[A-Za-z_:][A-Za-z0-9_:.-]*`. It is validated before\n * anything else, so an invalid name always throws.\n * @param value The value, or an accessor of it.\n * @param isBoolean `true` for a presence attribute such as `disabled`: a truthy value writes the bare\n * name, a falsy one writes nothing. Default: `false`.\n * @returns Markup such as `' title=\"a&amp;b\"'`, or `\"\"`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an invalid name, and `UNRECOGNIZED_INSERT_VALUE`\n * when the value is a symbol.\n * @example\n * import { ssrAttribute } from \"@shadow-js/web/server\";\n *\n * ssrAttribute(\"title\", \"Tom & Jerry\"); // ' title=\"Tom &amp; Jerry\"'\n * ssrAttribute(\"disabled\", true, true); // \" disabled\"\n * ssrAttribute(\"href\", \"javascript:alert(1)\"); // \"\"\n * @since 1.0.0\n */\nexport function ssrAttribute(name: string, value: unknown, isBoolean = false): string {\n assertAttributeName(name);\n const lowerName = name.toLowerCase();\n if (isEventName(lowerName)) return \"\";\n const resolved = resolveValue(value);\n assertNotSymbol(resolved);\n if (isBoolean) return resolved ? ` ${name}` : \"\";\n const text = attributeText(lowerName, resolved);\n if (text === null) return \"\";\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeAttributeValue(lowerName, text)) return \"\";\n return ` ${name}=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":";;;;;AAKA,MAAM,iBAAiB;;AAGvB,MAAM,iCAAsC,IAAI,IAAI;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,MAAM,6CAAkD,IAAI,IAAI;CAAC;CAAU;CAAQ;CAAM;AAAI,CAAC;;AAG9F,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,sBAAyC;CAAC;CAAe;CAAkB;AAAW;;AAG5F,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAC3B,MAAM,QAAQ,0BAA0B,IAAI,KAAK,iCAAiC;AAEtF;;AAGA,SAAgB,YAAY,WAA4B;CACtD,OAAO,UAAU,SAAS,KAAK,UAAU,WAAW,IAAI;AAC1D;;AAGA,SAAS,eAAe,WAA4B;CAClD,OACE,UAAU,WAAW,OAAO,KAC5B,UAAU,WAAW,OAAO,KAC5B,sBAAsB,IAAI,SAAS;AAEvC;;AAGA,SAAS,cAAc,MAAsB;CAC3C,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;EACvB,MA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AI,EAAE;AACvC"}
1
+ {"version":3,"file":"attributes.js","names":[],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"../internal/diagnostics\";\nimport { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"poster\",\n \"data\",\n]);\n\n/**\n * SVG animation attributes (`animate`, `set`): with `attributeName=\"href\"` they write an `href` by animation, so their value\n * is checked like one. `values` is a `;` list and every entry is checked. Same as the client.\n */\nconst ANIMATION_VALUE_ATTRIBUTES: ReadonlySet<string> = new Set([\"values\", \"from\", \"to\", \"by\"]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"draggable\",\n \"spellcheck\",\n \"contenteditable\",\n]);\n\n/** URL prefixes (after normalization) that are never written. Same as the client. */\nconst UNSAFE_URL_PREFIXES: readonly string[] = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/** Throws a TypeError unless `name` can be written as an attribute name. @internal */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) {\n throw invalid(\"INVALID_ATTRIBUTE_NAME\", `\"${name}\" is not a valid attribute name.`);\n }\n}\n\n/** True for `on*` names, which never reach markup. Length matches the client's event test. @internal */\nexport function isEventName(lowerName: string): boolean {\n return lowerName.length > 2 && lowerName.startsWith(\"on\");\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their booleans are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters, which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script, after the normalization browsers apply. @internal */\nexport function isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** True when `lowerName` carries a URL (or an animated one) and `value` would run script. */\nfunction isUnsafeAttributeValue(lowerName: string, value: string): boolean {\n if (URL_ATTRIBUTES.has(lowerName)) return isUnsafeUrl(value);\n return ANIMATION_VALUE_ATTRIBUTES.has(lowerName) && value.split(\";\").some(isUnsafeUrl);\n}\n\n/** Text to write for `value`, or null when the attribute is removed. Same rules as the client. @internal */\nexport function attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** Refuses symbols, which have no markup form and would otherwise be coerced silently. */\nfunction assertNotSymbol(value: unknown): void {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be an attribute value.\");\n }\n}\n\n/**\n * Renders one attribute as markup with a leading space, or `\"\"` when the attribute is absent: the\n * helper the compiler's server output calls for a dynamic attribute. It applies the client's value\n * rules and URL check, so server and client agree on what is written.\n *\n * - `null`, `undefined` and `false` give `\"\"` (except `false` on `aria-*`, `data-*`, `draggable`,\n * `spellcheck` and `contenteditable`, which is written as `\"false\"`); `true` writes `=\"\"` (or\n * `\"true\"` for those same names). Other values are written as `String(value)`, HTML-escaped.\n * - URL attributes whose value would run script are dropped, with the check of\n * `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).\n * - `srcdoc` is an HTML sink, not a URL: its value is a document the frame runs, escaped for the attribute\n * and otherwise written as it is, with the trust of `innerHTML`. Sanitize it and give the frame a `sandbox`\n * attribute. Development builds warn once with `SRCDOC_DYNAMIC`.\n * - `on*` names are dropped: event handlers never reach markup.\n * - Accessors are called (untracked) until a plain value remains.\n *\n * @param name Attribute name, matching `[A-Za-z_:][A-Za-z0-9_:.-]*`. It is validated before\n * anything else, so an invalid name always throws.\n * @param value The value, or an accessor of it.\n * @param isBoolean `true` for a presence attribute such as `disabled`: a truthy value writes the bare\n * name, a falsy one writes nothing. Default: `false`.\n * @returns Markup such as `' title=\"a&amp;b\"'`, or `\"\"`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an invalid name, and `UNRECOGNIZED_INSERT_VALUE`\n * when the value is a symbol.\n * @example\n * import { ssrAttribute } from \"@shadow-js/web/server\";\n *\n * ssrAttribute(\"title\", \"Tom & Jerry\"); // ' title=\"Tom &amp; Jerry\"'\n * ssrAttribute(\"disabled\", true, true); // \" disabled\"\n * ssrAttribute(\"href\", \"javascript:alert(1)\"); // \"\"\n * @since 1.0.0\n */\nexport function ssrAttribute(name: string, value: unknown, isBoolean = false): string {\n assertAttributeName(name);\n const lowerName = name.toLowerCase();\n if (isEventName(lowerName)) return \"\";\n const resolved = resolveValue(value);\n assertNotSymbol(resolved);\n if (isBoolean) return resolved ? ` ${name}` : \"\";\n const text = attributeText(lowerName, resolved);\n if (text === null) return \"\";\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeAttributeValue(lowerName, text)) return \"\";\n return ` ${name}=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":";;;;;AAKA,MAAM,iBAAiB;;AAGvB,MAAM,iCAAsC,IAAI,IAAI;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,MAAM,6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K;AACrB;;AAGA,SAAS,gBAAgB,OAAsB;CAC7C,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,wCAAwC;AAEvF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,aAAa,MAAc,OAAgB,YAAY,OAAe;CACpF,oBAAoB,IAAI;CACxB,MAAM,YAAY,KAAK,YAAY;CACnC,IAAI,YAAY,SAAS,GAAG,OAAO;CACnC,MAAM,WAAW,aAAa,KAAK;CACnC,gBAAgB,QAAQ;CACxB,IAAI,WAAW,OAAO,WAAW,IAAI,SAAS;CAC9C,MAAM,OAAO,cAAc,WAAW,QAAQ;CAC9C,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAe,cAAc,UAAU,SAAS,kBAAkB,qBAAqB;CACvF,IAAI,uBAAuB,WAAW,IAAI,GAAG,OAAO;CACpD,OAAO,IAAI,KAAK,IAAI,WAAW,IAAI,EAAE;AACvC"}
@@ -1,9 +1,9 @@
1
1
  import { nextKey } from "../internal/hydration-scope.js";
2
- import { IGNORED_KEYS, attributeName } from "../internal/react-names.js";
2
+ import { IGNORED_KEYS, attributeName, isFlagAttribute } from "../internal/react-names.js";
3
3
  import { invalid } from "./errors.js";
4
4
  import { SsrNode, isSsrNode } from "./node.js";
5
5
  import { escape, escapeHtml, resolveValue } from "./escape.js";
6
- import { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from "./attributes.js";
6
+ import { isEventName, ssrAttribute } from "./attributes.js";
7
7
  import { classText, ssrStyle, styleText } from "./class-style.js";
8
8
  import { keepLeadingNewline, markSelectedOptions, textareaContent } from "./form-controls.js";
9
9
  import { rawElementContent } from "./raw-text.js";
@@ -156,7 +156,7 @@ function ssrElement(tag, props, children = void 0, needsKey = false, svg = false
156
156
  let style = "";
157
157
  let innerHtml;
158
158
  if (props !== null && typeof props === "object") for (const key of Object.keys(props)) {
159
- if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;
159
+ if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.test(key)) continue;
160
160
  if (key === "ref" || key.startsWith("on:") || key.startsWith("use:") || key.startsWith("prop:")) continue;
161
161
  if (isEventName(key)) continue;
162
162
  if (needsKey && key === "data-hk") continue;
@@ -181,8 +181,7 @@ function ssrElement(tag, props, children = void 0, needsKey = false, svg = false
181
181
  if (!Object.hasOwn(props, name)) attributes += ssrAttribute(name, value, name === "checked");
182
182
  } else {
183
183
  const name = attributeName(key, svg);
184
- const flag = BOOLEAN_ATTRIBUTES.has(name) && !(name === "hidden" && value === "until-found");
185
- attributes += ssrAttribute(name, value, flag);
184
+ attributes += ssrAttribute(name, value, isFlagAttribute(name, value));
186
185
  }
187
186
  }
188
187
  if (classes.length > 0) attributes += ` class="${escapeHtml(classes.join(" "))}"`;
@@ -194,7 +193,7 @@ function ssrElement(tag, props, children = void 0, needsKey = false, svg = false
194
193
  if (innerHtml === void 0 && (hasValue || hasFallback)) {
195
194
  const value = hasValue ? control.value : control.fallback;
196
195
  content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);
197
- } else if (isTextarea && innerHtml === void 0) content = keepLeadingNewline(content);
196
+ } else if ((isTextarea || lowerTag === "pre" || lowerTag === "listing") && innerHtml === void 0) content = keepLeadingNewline(content);
198
197
  return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);
199
198
  }
200
199
  /** The `children` of a spread props object (read once, so a getter runs once), or undefined. */
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","names":[],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { keepLeadingNewline, markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\nimport { rawElementContent } from \"./raw-text\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, &lt;Ada&gt;</p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"&lt;b&gt;escaped&lt;/b&gt;<!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n // `hidden=\"until-found\"` is a keyword, not a flag: a bare `hidden` would hide what it should only collapse.\n const flag =\n BOOLEAN_ATTRIBUTES.has(name) && !(name === \"hidden\" && value === \"until-found\");\n attributes += ssrAttribute(name, value, flag);\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n // The text of a script or a style is raw (no entities), so it is written as it is and checked instead.\n const raw = !svg && (lowerTag === \"script\" || lowerTag === \"style\");\n const given = children === undefined ? propsChildren(props) : children;\n let content =\n innerHtml !== undefined ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n } else if (isTextarea && innerHtml === undefined) {\n // The children of a textarea are its value (as on the client): keep a first line break the parser drops.\n content = keepLeadingNewline(content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,WAAW;;AAGjB,MAAM,gCAAqC,IAAI,IAAI;CACjD;CACA;CACA;CACA;CACA;C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,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;CACzE,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,QAAQ,MAAM,aAAa,QAAQ,IAAI,OAAO,GAAG,CAAC,GAAG,IAAI,KAAK,GAAG;AAEzE;;AAGA,SAAS,UAAU,OAAwB;CACzC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,KAAK,GAAG,OAAO,MAAM;CACnC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,+BAA+B;CAC5E,OAAO,OAAO,KAAK;AACrB"}
1
+ {"version":3,"file":"element.js","names":[],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS, isFlagAttribute } from \"../internal/react-names\";\nimport { isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { keepLeadingNewline, markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\nimport { rawElementContent } from \"./raw-text\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, &lt;Ada&gt;</p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"&lt;b&gt;escaped&lt;/b&gt;<!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.test(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n attributes += ssrAttribute(name, value, isFlagAttribute(name, value));\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n // The text of a script or a style is raw (no entities), so it is written as it is and checked instead.\n const raw = !svg && (lowerTag === \"script\" || lowerTag === \"style\");\n const given = children === undefined ? propsChildren(props) : children;\n let content =\n innerHtml !== undefined ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n } else if (\n (isTextarea || lowerTag === \"pre\" || lowerTag === \"listing\") &&\n innerHtml === undefined\n ) {\n // The parser drops one line break right after these start tags (a textarea's children are its\n // value, as on the client): write one more so the content is read as it was given.\n content = keepLeadingNewline(content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,WAAW;;AAGjB,MAAM,gCAAqC,IAAI,IAAI;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,+BAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAS,iBAAiB,OAAyB;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,OAAO,QAAQ,IAAI,OAAO,QAAQ;AACpC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,IAAI,OAA0B,GAAG,OAA2B;CAC1E,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,MAAM,SAAS,GAC3D,MAAM,IAAI,UAAU,6DAA6D;CAEnF,IAAI,OAAO,MAAM,MAAM;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,OAAO,MAAM;EACnB,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a;CAC3D,MAAM,QAAQ,aAAa,KAAA,IAAY,cAAc,KAAK,IAAI;CAC9D,IAAI,UACF,cAAc,KAAA,IAAY,YAAY,MAAM,kBAAkB,UAAU,KAAK,IAAI,OAAO,KAAK;CAC/F,IAAI,cAAc,KAAA,MAAc,YAAY,cAAc;EACxD,MAAM,QAAQ,WAAW,QAAQ,QAAQ,QAAQ;EACjD,UAAU,aAAa,gBAAgB,KAAK,IAAI,oBAAoB,OAAO,OAAO;CACpF,OAAO,KACJ,cAAc,aAAa,SAAS,aAAa,cAClD,cAAc,KAAA,GAId,UAAU,mBAAmB,OAAO;CAEtC,OAAO,IAAI,QAAQ,IAAI,MAAM,WAAW,GAAG,QAAQ,IAAI,IAAI,EAAE;AAC/D;;AAGA,SAAS,cAAc,OAAyB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,OAAO,QAAQ,IAAI,OAAO,UAAU;AACtC;;AAGA,SAAS,kBAAkB,OAAgB,KAAqB;CAC9D,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;CACzE,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,QAAQ,MAAM,aAAa,QAAQ,IAAI,OAAO,GAAG,CAAC,GAAG,IAAI,KAAK,GAAG;AAEzE;;AAGA,SAAS,UAAU,OAAwB;CACzC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,KAAK,GAAG,OAAO,MAAM;CACnC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,+BAA+B;CAC5E,OAAO,OAAO,KAAK;AACrB"}
@@ -4,12 +4,12 @@ import { ssrClass, ssrStyle } from "./class-style.js";
4
4
  import { ssrSelectValue, ssrTextArea } from "./form-controls.js";
5
5
  import { ssrRawText } from "./raw-text.js";
6
6
  import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./element.js";
7
- import { createServerPortals } from "./portals.js";
8
7
  import { normalizeTags } from "../head/validate.js";
9
8
  import { createServerHead } from "../head/server-head.js";
10
9
  import { createComponent, memo } from "./component.js";
11
10
  import { derived } from "./derived.js";
12
11
  import { HydrationScript, generateHydrationScript } from "./hydration-script.js";
12
+ import { createServerPortals } from "./portals.js";
13
13
  import { renderToString, renderToStringAsync } from "./render.js";
14
14
  import { deserialize, serialize } from "./serialize.js";
15
15
  import { renderToStream } from "./stream.js";
@@ -13,6 +13,9 @@ var PortalCollector = class {
13
13
  clear() {
14
14
  this.entries.clear();
15
15
  }
16
+ render(key, children) {
17
+ renderServerPortal(key, children, this);
18
+ }
16
19
  html() {
17
20
  let out = "";
18
21
  for (const [key, html] of this.entries) out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;
@@ -1 +1 @@
1
- {"version":3,"file":"portals.js","names":[],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":";;;;;AAuCA,IAAa,kBAAb,MAAmD;CACjD,0BAA2B,IAAI,IAAoB;CAEnD,IAAI,KAAa,MAAoB;EACnC,IAAI,CAAC,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,QAAQ,QAAA,KACzC,MAAM,IAAI,SACR,oBACA,kFACF;EAEF,KAAK,QAAQ,IAAI,KAAK,IAAI;CAC5B;;CAGA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;CAEA,OAAe;EACb,IAAI,MAAM;EACV,KAAK,MAAM,CAAC,KAAK,SAAS,KAAK,SAC7B,OAAO,cAAc,IAAI,KAAK,KAAK,cAAc,IAAI;EAEvD,OAAO;CACT;AACF;AAEA,MAAM,6BAAa,IAAI,QAAwC;;;;;;;;;;;;;;;;;;AAmB/D,SAAgB,sBAAqC;CACnD,MAAM,YAAY,IAAI,gBAAgB;CACtC,MAAM,UAAyB,EAAE,YAAY,UAAU,KAAK,EAAE;CAC9D,WAAW,IAAI,SAAS,SAAS;CACjC,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,SAAyC;CACnE,MAAM,YAAY,WAAW,IAAI,OAAO;CACxC,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,UAAU,qDAAqD;CAE3E,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,mBACd,KACA,UACA,MACM;CACN,IAAI,SAAS,QAAQ,QAAQ,KAAA,GAAW;CACxC,MAAM,OAAO,UAAU,WAAW,GAAG,SAAS,OAAO,SAAS,CAAC,CAAC;CAChE,KAAK,IAAI,KAAK,IAAI;AACpB;;;;;;AAOA,SAAgB,eAAkB,MAAyB,OAAmB;CAO5E,OANa,cAAc;EACzB,OAAO;EACP,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CACW,CAAC,CAAa;AAC3B;;;;;;AAOA,SAAgB,mBAAmB,SAA4D;CAC7F,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,MAAM,YAAY,YAAY,OAAO;CACrC,UAAU,MAAM;CAChB,OAAO;AACT"}
1
+ {"version":3,"file":"portals.js","names":[],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n render(key: string | undefined, children: () => unknown): void {\n renderServerPortal(key, children, this);\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":";;;;;AAuCA,IAAa,kBAAb,MAAmD;CACjD,0BAA2B,IAAI,IAAoB;CAEnD,IAAI,KAAa,MAAoB;EACnC,IAAI,CAAC,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,QAAQ,QAAA,KACzC,MAAM,IAAI,SACR,oBACA,kFACF;EAEF,KAAK,QAAQ,IAAI,KAAK,IAAI;CAC5B;;CAGA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;CAEA,OAAO,KAAyB,UAA+B;EAC7D,mBAAmB,KAAK,UAAU,IAAI;CACxC;CAEA,OAAe;EACb,IAAI,MAAM;EACV,KAAK,MAAM,CAAC,KAAK,SAAS,KAAK,SAC7B,OAAO,cAAc,IAAI,KAAK,KAAK,cAAc,IAAI;EAEvD,OAAO;CACT;AACF;AAEA,MAAM,6BAAa,IAAI,QAAwC;;;;;;;;;;;;;;;;;;AAmB/D,SAAgB,sBAAqC;CACnD,MAAM,YAAY,IAAI,gBAAgB;CACtC,MAAM,UAAyB,EAAE,YAAY,UAAU,KAAK,EAAE;CAC9D,WAAW,IAAI,SAAS,SAAS;CACjC,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,SAAyC;CACnE,MAAM,YAAY,WAAW,IAAI,OAAO;CACxC,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,UAAU,qDAAqD;CAE3E,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,mBACd,KACA,UACA,MACM;CACN,IAAI,SAAS,QAAQ,QAAQ,KAAA,GAAW;CACxC,MAAM,OAAO,UAAU,WAAW,GAAG,SAAS,OAAO,SAAS,CAAC,CAAC;CAChE,KAAK,IAAI,KAAK,IAAI;AACpB;;;;;;AAOA,SAAgB,eAAkB,MAAyB,OAAmB;CAO5E,OANa,cAAc;EACzB,OAAO;EACP,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CACW,CAAC,CAAa;AAC3B;;;;;;AAOA,SAAgB,mBAAmB,SAA4D;CAC7F,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,MAAM,YAAY,YAAY,OAAO;CACrC,UAAU,MAAM;CAChB,OAAO;AACT"}
@@ -2,8 +2,8 @@ import { createRootScope, resourceKey, withScope } from "../internal/hydration-s
2
2
  import { MAX_TIMER_MS, SsrError } from "./errors.js";
3
3
  import { escape } from "./escape.js";
4
4
  import { attachRootErrors } from "../control-flow/root-errors.js";
5
- import { portalCollectorFor, withPortalSink } from "./portals.js";
6
5
  import { runWithServerHead } from "../head/server-head.js";
6
+ import { portalCollectorFor, withPortalSink } from "./portals.js";
7
7
  import { ResourceCacheContext, createRoot } from "@shadow-js/core";
8
8
  // src/server/render.ts
9
9
  const DEFAULT_TIMEOUT_MS = 1e4;
@@ -3,8 +3,8 @@ import { MAX_TIMER_MS, SsrError } from "./errors.js";
3
3
  import { escape } from "./escape.js";
4
4
  import { StreamContext } from "../internal/stream-context.js";
5
5
  import { attachRootErrors } from "../control-flow/root-errors.js";
6
- import { portalCollectorFor, withPortalSink } from "./portals.js";
7
6
  import { runWithServerHead } from "../head/server-head.js";
7
+ import { portalCollectorFor, withPortalSink } from "./portals.js";
8
8
  import { serialize } from "./serialize.js";
9
9
  import { ResourceCacheContext, createRoot, untrack } from "@shadow-js/core";
10
10
  // src/server/stream.ts