@shadow-js/web 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/dev/attributes.js.map +1 -1
  3. package/dist/dev/class-style.d.ts +10 -5
  4. package/dist/dev/class-style.js +47 -47
  5. package/dist/dev/class-style.js.map +1 -1
  6. package/dist/dev/control-flow/dynamic.js +2 -2
  7. package/dist/dev/control-flow/dynamic.js.map +1 -1
  8. package/dist/dev/control-flow/error-boundary.js +2 -2
  9. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  10. package/dist/dev/control-flow/portal.d.ts +2 -2
  11. package/dist/dev/control-flow/portal.js +15 -13
  12. package/dist/dev/control-flow/portal.js.map +1 -1
  13. package/dist/dev/control-flow/suspense-list.js +2 -2
  14. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  15. package/dist/dev/control-flow/suspense.js +2 -2
  16. package/dist/dev/control-flow/suspense.js.map +1 -1
  17. package/dist/dev/element.js +5 -2
  18. package/dist/dev/element.js.map +1 -1
  19. package/dist/dev/extend.d.ts +2 -2
  20. package/dist/dev/extend.js +2 -2
  21. package/dist/dev/insert.d.ts +11 -0
  22. package/dist/dev/insert.js +50 -33
  23. package/dist/dev/insert.js.map +1 -1
  24. package/dist/dev/internal/accessor.js +56 -0
  25. package/dist/dev/internal/accessor.js.map +1 -0
  26. package/dist/dev/internal/claim.js +0 -1
  27. package/dist/dev/internal/claim.js.map +1 -1
  28. package/dist/dev/internal/css-units.js +2 -2
  29. package/dist/dev/internal/css-units.js.map +1 -1
  30. package/dist/dev/internal/portal-context.d.ts +9 -0
  31. package/dist/dev/internal/portal-context.js.map +1 -1
  32. package/dist/dev/internal/react-names.js +22 -12
  33. package/dist/dev/internal/react-names.js.map +1 -1
  34. package/dist/dev/internal/reconcile.js +4 -6
  35. package/dist/dev/internal/reconcile.js.map +1 -1
  36. package/dist/dev/server/attributes.js +1 -31
  37. package/dist/dev/server/attributes.js.map +1 -1
  38. package/dist/dev/server/element.js +5 -6
  39. package/dist/dev/server/element.js.map +1 -1
  40. package/dist/dev/server/index.js +1 -1
  41. package/dist/dev/server/portals.js +3 -0
  42. package/dist/dev/server/portals.js.map +1 -1
  43. package/dist/dev/server/render.js +1 -1
  44. package/dist/dev/server/stream.js +1 -1
  45. package/dist/dev/server.js +1 -1
  46. package/dist/dev/spread.js +49 -27
  47. package/dist/dev/spread.js.map +1 -1
  48. package/dist/dev/template.js +1 -3
  49. package/dist/dev/template.js.map +1 -1
  50. package/dist/dev/view-transition.js +12 -4
  51. package/dist/dev/view-transition.js.map +1 -1
  52. package/dist/prod/attributes.js +1 -1
  53. package/dist/prod/attributes.js.map +1 -1
  54. package/dist/prod/class-style.js +1 -1
  55. package/dist/prod/class-style.js.map +1 -1
  56. package/dist/prod/control-flow/dynamic.js +1 -1
  57. package/dist/prod/control-flow/dynamic.js.map +1 -1
  58. package/dist/prod/control-flow/error-boundary.js +1 -1
  59. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  60. package/dist/prod/control-flow/portal.js +1 -1
  61. package/dist/prod/control-flow/portal.js.map +1 -1
  62. package/dist/prod/control-flow/suspense-list.js +1 -1
  63. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  64. package/dist/prod/control-flow/suspense.js +1 -1
  65. package/dist/prod/control-flow/suspense.js.map +1 -1
  66. package/dist/prod/element.js +1 -1
  67. package/dist/prod/element.js.map +1 -1
  68. package/dist/prod/extend.js +1 -1
  69. package/dist/prod/insert.js +1 -1
  70. package/dist/prod/insert.js.map +1 -1
  71. package/dist/prod/internal/accessor.js +2 -0
  72. package/dist/prod/internal/accessor.js.map +1 -0
  73. package/dist/prod/internal/claim.js +1 -1
  74. package/dist/prod/internal/claim.js.map +1 -1
  75. package/dist/prod/internal/css-units.js +1 -1
  76. package/dist/prod/internal/css-units.js.map +1 -1
  77. package/dist/prod/internal/portal-context.js.map +1 -1
  78. package/dist/prod/internal/react-names.js +1 -1
  79. package/dist/prod/internal/react-names.js.map +1 -1
  80. package/dist/prod/internal/reconcile.js +1 -1
  81. package/dist/prod/internal/reconcile.js.map +1 -1
  82. package/dist/prod/server/attributes.js +1 -1
  83. package/dist/prod/server/attributes.js.map +1 -1
  84. package/dist/prod/server/element.js +1 -1
  85. package/dist/prod/server/element.js.map +1 -1
  86. package/dist/prod/server/index.js +1 -1
  87. package/dist/prod/server/portals.js +1 -1
  88. package/dist/prod/server/portals.js.map +1 -1
  89. package/dist/prod/server/render.js +1 -1
  90. package/dist/prod/server/stream.js +1 -1
  91. package/dist/prod/server.js +1 -1
  92. package/dist/prod/spread.js +1 -1
  93. package/dist/prod/spread.js.map +1 -1
  94. package/dist/prod/template.js +1 -1
  95. package/dist/prod/template.js.map +1 -1
  96. package/dist/prod/view-transition.js +1 -1
  97. package/dist/prod/view-transition.js.map +1 -1
  98. package/dist/server/attributes.js +1 -1
  99. package/dist/server/attributes.js.map +1 -1
  100. package/dist/server/class-style.js +1 -1
  101. package/dist/server/class-style.js.map +1 -1
  102. package/dist/server/control-flow/dynamic.js.map +1 -1
  103. package/dist/server/control-flow/error-boundary.js +1 -1
  104. package/dist/server/control-flow/error-boundary.js.map +1 -1
  105. package/dist/server/control-flow/portal.js +1 -1
  106. package/dist/server/control-flow/portal.js.map +1 -1
  107. package/dist/server/control-flow/suspense-list.js +1 -1
  108. package/dist/server/control-flow/suspense-list.js.map +1 -1
  109. package/dist/server/control-flow/suspense.js +1 -1
  110. package/dist/server/control-flow/suspense.js.map +1 -1
  111. package/dist/server/element.js.map +1 -1
  112. package/dist/server/extend.js +1 -1
  113. package/dist/server/insert.js +1 -1
  114. package/dist/server/insert.js.map +1 -1
  115. package/dist/server/internal/accessor.js +2 -0
  116. package/dist/server/internal/accessor.js.map +1 -0
  117. package/dist/server/internal/claim.js +1 -1
  118. package/dist/server/internal/claim.js.map +1 -1
  119. package/dist/server/internal/css-units.js +1 -1
  120. package/dist/server/internal/css-units.js.map +1 -1
  121. package/dist/server/internal/portal-context.js.map +1 -1
  122. package/dist/server/internal/react-names.js +1 -1
  123. package/dist/server/internal/react-names.js.map +1 -1
  124. package/dist/server/internal/reconcile.js +1 -1
  125. package/dist/server/internal/reconcile.js.map +1 -1
  126. package/dist/server/server/attributes.js +1 -1
  127. package/dist/server/server/attributes.js.map +1 -1
  128. package/dist/server/server/element.js +1 -1
  129. package/dist/server/server/element.js.map +1 -1
  130. package/dist/server/server/index.js +1 -1
  131. package/dist/server/server/portals.js +1 -1
  132. package/dist/server/server/portals.js.map +1 -1
  133. package/dist/server/server/render.js +1 -1
  134. package/dist/server/server/stream.js +1 -1
  135. package/dist/server/server.js +1 -1
  136. package/dist/server/spread.js +1 -1
  137. package/dist/server/spread.js.map +1 -1
  138. package/dist/server/template.js +1 -1
  139. package/dist/server/template.js.map +1 -1
  140. package/dist/server/view-transition.js.map +1 -1
  141. package/dist/server-dev/attributes.js.map +1 -1
  142. package/dist/server-dev/class-style.js +47 -47
  143. package/dist/server-dev/class-style.js.map +1 -1
  144. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  145. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  146. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  147. package/dist/server-dev/control-flow/portal.js +15 -13
  148. package/dist/server-dev/control-flow/portal.js.map +1 -1
  149. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  150. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  151. package/dist/server-dev/control-flow/suspense.js +2 -2
  152. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  153. package/dist/server-dev/element.js.map +1 -1
  154. package/dist/server-dev/extend.js +2 -2
  155. package/dist/server-dev/insert.js +50 -33
  156. package/dist/server-dev/insert.js.map +1 -1
  157. package/dist/server-dev/internal/accessor.js +56 -0
  158. package/dist/server-dev/internal/accessor.js.map +1 -0
  159. package/dist/server-dev/internal/claim.js +0 -1
  160. package/dist/server-dev/internal/claim.js.map +1 -1
  161. package/dist/server-dev/internal/css-units.js +2 -2
  162. package/dist/server-dev/internal/css-units.js.map +1 -1
  163. package/dist/server-dev/internal/portal-context.js.map +1 -1
  164. package/dist/server-dev/internal/react-names.js +22 -12
  165. package/dist/server-dev/internal/react-names.js.map +1 -1
  166. package/dist/server-dev/internal/reconcile.js +4 -6
  167. package/dist/server-dev/internal/reconcile.js.map +1 -1
  168. package/dist/server-dev/server/attributes.js +1 -31
  169. package/dist/server-dev/server/attributes.js.map +1 -1
  170. package/dist/server-dev/server/element.js +5 -6
  171. package/dist/server-dev/server/element.js.map +1 -1
  172. package/dist/server-dev/server/index.js +1 -1
  173. package/dist/server-dev/server/portals.js +3 -0
  174. package/dist/server-dev/server/portals.js.map +1 -1
  175. package/dist/server-dev/server/render.js +1 -1
  176. package/dist/server-dev/server/stream.js +1 -1
  177. package/dist/server-dev/server.js +1 -1
  178. package/dist/server-dev/spread.js +35 -26
  179. package/dist/server-dev/spread.js.map +1 -1
  180. package/dist/server-dev/template.js +1 -3
  181. package/dist/server-dev/template.js.map +1 -1
  182. package/dist/server-dev/view-transition.js.map +1 -1
  183. package/package.json +3 -3
@@ -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
@@ -4,12 +4,12 @@ import { ssrClass, ssrStyle } from "./server/class-style.js";
4
4
  import { ssrSelectValue, ssrTextArea } from "./server/form-controls.js";
5
5
  import { ssrRawText } from "./server/raw-text.js";
6
6
  import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./server/element.js";
7
- import { createServerPortals } from "./server/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 "./server/component.js";
11
10
  import { derived } from "./server/derived.js";
12
11
  import { HydrationScript, generateHydrationScript } from "./server/hydration-script.js";
12
+ import { createServerPortals } from "./server/portals.js";
13
13
  import { renderToString, renderToStringAsync } from "./server/render.js";
14
14
  import { deserialize, serialize } from "./server/serialize.js";
15
15
  import { renderToStream } from "./server/stream.js";
@@ -2,8 +2,8 @@ import { setAttribute, setAttributeNS, setBoolAttribute } from "./attributes.js"
2
2
  import { autoFocus } from "./autofocus.js";
3
3
  import { applyClass, asRecord, classList, style } from "./class-style.js";
4
4
  import { claims } from "./internal/hydration-hooks.js";
5
- import { bindRegion, createRegion } from "./insert.js";
6
- import { IGNORED_KEYS, attributeName, eventPlan } from "./internal/react-names.js";
5
+ import { bindRegion, createRegion, watchCommits } from "./insert.js";
6
+ import { IGNORED_KEYS, attributeName, eventPlan, isFlagAttribute } from "./internal/react-names.js";
7
7
  import { bindEvent } from "./events.js";
8
8
  import { plainText, setSelectValue } from "./select-value.js";
9
9
  import { onCleanup, untrack, useRenderEffect } from "@shadow-js/core";
@@ -16,11 +16,7 @@ function innerHtmlValue(value) {
16
16
  return plainText(Reflect.get(value, "__html"));
17
17
  }
18
18
  /** Keys that would reach a prototype if written as properties. Ignored everywhere. */
19
- const FORBIDDEN_NAMES = /* @__PURE__ */ new Set([
20
- "__proto__",
21
- "constructor",
22
- "prototype"
23
- ]);
19
+ const FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;
24
20
  /** True for `on*` keys, which bind event handlers. */
25
21
  function isEventKey(key) {
26
22
  return key.length > 2 && key.startsWith("on");
@@ -37,7 +33,7 @@ function readEntries(props, textarea) {
37
33
  let value;
38
34
  let hasValue = false;
39
35
  for (const key of Object.keys(props)) {
40
- if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;
36
+ if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;
41
37
  if (key === "children") {
42
38
  if (textarea) {
43
39
  value = Reflect.get(props, key);
@@ -111,8 +107,8 @@ function applyKey(el, key, value, state, svg) {
111
107
  setSelectValue(el, value);
112
108
  return;
113
109
  }
114
- if (!svg && LIVE_PROPERTIES.has(key) && key in el) {
115
- liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.has(key) ? value ?? "" : Boolean(value));
110
+ if (!svg && LIVE_PROPERTIES.test(key) && key in el) {
111
+ liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.test(key) ? value ?? "" : Boolean(value));
116
112
  if (key === "value" && el instanceof HTMLInputElement) el.defaultValue = plainText(value);
117
113
  return;
118
114
  }
@@ -129,31 +125,24 @@ function writeKey(el, key, value, svg) {
129
125
  else if (key.startsWith("bool:")) setBoolAttribute(el, key.slice(5), value);
130
126
  else {
131
127
  const wire = attributeName(key, svg);
132
- if (wire.startsWith("xlink:")) setAttributeNS(el, XLINK_NS, wire, value);
128
+ if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);
129
+ else if (wire.startsWith("xlink:")) setAttributeNS(el, XLINK_NS, wire, value);
133
130
  else setAttribute(el, wire, value);
134
131
  }
135
132
  }
136
133
  /** Props written as element properties, like the compiler does for the same names in JSX. */
137
- const LIVE_PROPERTIES = /* @__PURE__ */ new Set([
138
- "value",
139
- "checked",
140
- "selected",
141
- "muted",
142
- "indeterminate",
143
- "defaultValue",
144
- "defaultChecked"
145
- ]);
134
+ const LIVE_PROPERTIES = /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;
146
135
  /** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */
147
- const STRING_PROPERTIES = /* @__PURE__ */ new Set(["value", "defaultValue"]);
136
+ const STRING_PROPERTIES = /^(?:value|defaultValue)$/;
148
137
  /**
149
138
  * True when a live property (typed value, toggled box) no longer matches the value last applied, so
150
139
  * an unchanged prop is written again and the element follows the data.
151
140
  */
152
141
  function liveDiffers(el, key, value, svg) {
153
- if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;
142
+ if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;
154
143
  if (key === "value" && el instanceof HTMLSelectElement) return true;
155
144
  const live = Reflect.get(el, key);
156
- return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);
145
+ return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);
157
146
  }
158
147
  /**
159
148
  * Applies the entries that changed since the last run and undoes the ones that disappeared.
@@ -221,19 +210,52 @@ function applyEntries(el, entries, state, svg) {
221
210
  function spread(el, props, isSVG = false, skipChildren = false) {
222
211
  if (props === null || typeof props !== "object" && typeof props !== "function") return;
223
212
  const read = () => typeof props === "function" ? props() : props;
224
- const textarea = el.localName === "textarea";
225
- if (!skipChildren && !textarea) {
213
+ const state = newState();
214
+ if (!skipChildren && el.localName !== "textarea") {
226
215
  const initial = claims.current.isClaiming() ? claims.current.takeRegion(el, null) ?? Array.from(el.childNodes) : void 0;
227
216
  const region = createRegion(el, null, initial);
228
217
  bindRegion(region, () => read()?.children);
218
+ followOptions(el, isSVG, state);
229
219
  }
230
- const state = {
220
+ applyProps(el, read, isSVG, state);
221
+ }
222
+ /**
223
+ * New options replace the ones that held the selection, and the value effect does not read
224
+ * `children`: a select spread selects its value again after every commit to its children, as the
225
+ * compiled path does.
226
+ */
227
+ function followOptions(el, isSVG, state) {
228
+ if (isSVG || !(el instanceof HTMLSelectElement)) return;
229
+ watchCommits(el, () => {
230
+ const key = state.values.has("value") ? "value" : "defaultValue";
231
+ if (state.values.has(key)) setSelectValue(el, state.values.get(key));
232
+ });
233
+ }
234
+ /** The bookkeeping of a spread that has applied nothing yet. */
235
+ function newState() {
236
+ return {
231
237
  values: /* @__PURE__ */ new Map(),
232
238
  unbinders: /* @__PURE__ */ new Map(),
233
239
  styleValue: void 0,
234
240
  classListValue: void 0,
235
241
  refCleanup: void 0
236
242
  };
243
+ }
244
+ /**
245
+ * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what
246
+ * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds
247
+ * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's
248
+ * children. A select still selects its value again when `Dynamic` commits new options.
249
+ * @internal
250
+ */
251
+ function spreadProps(el, props, isSVG) {
252
+ if (props === null || typeof props !== "object" && typeof props !== "function") return;
253
+ const state = newState();
254
+ followOptions(el, isSVG, state);
255
+ applyProps(el, () => typeof props === "function" ? props() : props, isSVG, state);
256
+ }
257
+ function applyProps(el, read, isSVG, state) {
258
+ const textarea = el.localName === "textarea";
237
259
  onCleanup(() => {
238
260
  for (const unbind of state.unbinders.values()) unbind();
239
261
  state.unbinders.clear();
@@ -243,6 +265,6 @@ function spread(el, props, isSVG = false, skipChildren = false) {
243
265
  applyEntries(el, entries, state, isSVG);
244
266
  });
245
267
  }
246
- export { spread };
268
+ export { spread, spreadProps };
247
269
 
248
270
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read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AM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
1
+ {"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isS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AAG,eAAe,IAAI,MAAM,OAAO,IAAI,GAAG,CAAC;CACrE,CAAC;AACH;;AAGA,SAAS,WAAwB;CAC/B,OAAO;EACL,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;AACF;;;;;;;;AASA,SAAgB,YAAY,IAAa,OAAgB,OAAsB;CAC7E,IAAI,UAAU,QAAS,OAAO,UAAU,YAAY,OAAO,UAAU,YAAa;CAClF,MAAM,QAAQ,SAAS;CACvB,cAAc,IAAI,OAAO,KAAK;CAC9B,WACE,UACO,OAAO,UAAU,aAAc,MAAwB,IAAI,OAClE,OACA,KACF;AACF;AAEA,SAAS,WAAW,IAAa,MAAqB,OAAgB,OAA0B;CAC9F,MAAM,WAAW,GAAG,cAAc;CAElC,gBAAgB;EACd,KAAK,MAAM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
@@ -35,9 +35,7 @@ function inNamespace(source, namespace) {
35
35
  const root = copyOf(source);
36
36
  const stack = [[source, root]];
37
37
  while (stack.length > 0) {
38
- const pair = stack.pop();
39
- if (pair === void 0) break;
40
- const [from, to] = pair;
38
+ const [from, to] = stack.pop();
41
39
  for (const child of Array.from(from.childNodes)) if (child instanceof Element) {
42
40
  const copy = copyOf(child);
43
41
  to.appendChild(copy);
@@ -1 +1 @@
1
- {"version":3,"file":"template.js","names":[],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const pair = stack.pop();\n if (pair === undefined) break;\n const [from, to] = pair;\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,YACJ;;AAEF,MAAM,YAAY;;;;;;AAOlB,SAAS,mBAAmB,MAAoB;CAC9C,KAAK,MAAM,OAAO,KAAK,SAAS,SAAS,GAAG;EAG1C,IADgB,CADI,IAAI,IAAI,MAAM,GAAA,CAAI,SAAS,SAAS,CAC/B,CAAC,CAAC,QAAQ,UAAU,MAAM,EAAE,EAAE,YAAY,MAAM,OAC/D,CAAC,CAAC,SAAS,GAAG;EACxB,MAAM,OAAO,eAAe,KAAK,IAAI,EAAE,CAAC,GAAG,MAAM;EACjD,SACE,6BACA,IAAI,KAAK,0GACX;EACA;CACF;AACF;;;;;AAMA,SAAS,YAAY,QAAiB,WAA4B;CAChE,MAAM,MAAM;CACZ,MAAM,UAAU,YAA8B;EAC5C,MAAM,OAAO,IAAI,gBAAgB,WAAW,QAAQ,SAAS;EAC7D,KAAK,MAAM,aAAa,MAAM,KAAK,QAAQ,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9B,IAAI,SAAS,KAAA,GAAW,OAAO;EAC/B,MAAM,QAAQ,MAAM,MAAM,KAAK;EAC/B,YAAY,IAAI,QAAQ,KAAK;EAC7B,OAAO;CACT;CACA,MAAM,QAAQ,SACZ,aAAa,SAAS,WAAW,MAAM,IAAI,IAAI,KAAK,UAAU,IAAI;CACpE,aAAa;EAEX,MAAM,UAAU,OAAO,QAAQ,aAAa,QAAQ,CAAC;EACrD,IAAI,YAAY,MAAM;GACP;IAEX,MAAM,SAAS,SAAS;IACxB,MAAM,CAAC,QAAQ;IACf,IAAI,OAAO,WAAW,KAAK,gBAAgB,SACzC,gBAAgB,SAAS,KAAK,SAAS;GAC3C;GACA,OAAO;EACT;EAEA,MAAM,SAAmB,SAAS;EAClC,IAAI,OAAO,WAAW,GAAG;GACvB,MAAM,CAAC,QAAQ;GACf,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK,IAAI;EAC1C;EACA,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,MAAM,QAAQ,QAAQ,SAAS,YAAY,KAAK,IAAI,CAAC;EAC1D,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"template.js","names":[],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const [from, to] = stack.pop() as [Element, Element];\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,YACJ;;AAEF,MAAM,YAAY;;;;;;AAOlB,SAAS,mBAAmB,MAAoB;CAC9C,KAAK,MAAM,OAAO,KAAK,SAAS,SAAS,GAAG;EAG1C,IADgB,CADI,IAAI,IAAI,MAAM,GAAA,CAAI,SAAS,SAAS,CAC/B,CAAC,CAAC,QAAQ,UAAU,MAAM,EAAE,EAAE,YAAY,MAAM,OAC/D,CAAC,CAAC,SAAS,GAAG;EACxB,MAAM,OAAO,eAAe,KAAK,IAAI,EAAE,CAAC,GAAG,MAAM;EACjD,SACE,6BACA,IAAI,KAAK,0GACX;EACA;CACF;AACF;;;;;AAMA,SAAS,YAAY,QAAiB,WAA4B;CAChE,MAAM,MAAM;CACZ,MAAM,UAAU,YAA8B;EAC5C,MAAM,OAAO,IAAI,gBAAgB,WAAW,QAAQ,SAAS;EAC7D,KAAK,MAAM,aAAa,MAAM,KAAK,QAAQ,UAAU,GACnD,KAAK,aAAa,UAAU,MAAM,UAAU,KAAK;EAEnD,OAAO;CACT;CACA,MAAM,OAAO,OAAO,MAAM;CAC1B,MAAM,QAAmC,CAAC,CAAC,QAAQ,IAAI,CAAC;CACxD,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,CAAC,MAAM,MAAM,MAAM,IAAI;EAC7B,KAAK,MAAM,SAAS,MAAM,KAAK,KAAK,UAAU,GAC5C,IAAI,iBAAiB,SAAS;GAC5B,MAAM,OAAO,OAAO,KAAK;GACzB,GAAG,YA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AgB,SAAS,KAAK,SAAS;GAC3C;GACA,OAAO;EACT;EAEA,MAAM,SAAmB,SAAS;EAClC,IAAI,OAAO,WAAW,GAAG;GACvB,MAAM,CAAC,QAAQ;GACf,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK,IAAI;EAC1C;EACA,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,MAAM,QAAQ,QAAQ,SAAS,YAAY,KAAK,IAAI,CAAC;EAC1D,OAAO;CACT;AACF"}
@@ -1,3 +1,4 @@
1
+ import { watchCommits } from "./insert.js";
1
2
  import { flushSync, untrack, useEffect, useId } from "@shadow-js/core";
2
3
  // src/view-transition.ts
3
4
  /**
@@ -95,10 +96,17 @@ function ViewTransition(props) {
95
96
  const end = document.createTextNode("");
96
97
  const generated = props.name === true ? `vt-${useId()}` : void 0;
97
98
  useEffect(() => {
98
- const element = firstElementBetween(start, end);
99
- if (element === null) return;
100
- setOrClear(element, "view-transition-name", generated ?? (typeof props.name === "string" ? props.name : void 0));
101
- setOrClear(element, "view-transition-class", props.class);
99
+ const name = generated ?? (typeof props.name === "string" ? props.name : void 0);
100
+ const transitionClass = props.class;
101
+ const apply = () => {
102
+ const element = firstElementBetween(start, end);
103
+ if (element === null) return;
104
+ setOrClear(element, "view-transition-name", name);
105
+ setOrClear(element, "view-transition-class", transitionClass);
106
+ };
107
+ apply();
108
+ const parent = start.parentNode;
109
+ if (parent !== null) watchCommits(parent, apply);
102
110
  });
103
111
  return () => [
104
112
  start,
@@ -1 +1 @@
1
- {"version":3,"file":"view-transition.js","names":[],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists.\n useEffect(() => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", props.class);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,oBACd,QACA,SACe;CACf,MAAM,MAAM,OAAO,aAAa,cAAc,KAAA,IAAa;CAC3D,IAAI,QAAQ,KAAA,KAAa,OAAO,IAAI,wBAAwB,YAAY;EACtE,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,OAAO,QAAQ,OAAO,KAAK;EAC7B;EACA,OAAO,QAAQ,QAAQ;CACzB;CACA,IAAI;CACJ,MAAM,iBAAuB;EAC3B,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,UAAU,EAAE,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,SAAS;CAIvB,OAHmB,IAAI,oBACrB,UAAU,KAAA,KAAa,MAAM,WAAW,IAAI,WAAW;EAAE,QAAQ;EAAU,OAAO,CAAC,GAAG,KAAK;CAAE,CAE/E,CAAC,CAAC,SAAS,WAAW;EACpC,IAAI,YAAY,KAAA,GAAW,MAAM,QAAQ;CAC3C,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,eAAe,OAA+C;CAG5E,IAAI;CACJ,IAAI,QAAQ;CACZ,MAAM,qBAA8B;EAClC,IAAI,CAAC,OAAO;GACV,QAAQ;GACR,QAAQ,cAAc,MAAM,QAAQ;EACtC;EACA,OAAO;CACT;CACA,MAAM,QAAQ,SAAS,eAAe,EAAE;CACxC,MAAM,MAAM,SAAS,eAAe,EAAE;CACtC,MAAM,YAAY,MAAM,SAAS,OAAO,MAAM,MAAM,MAAM,KAAA;CAE1D,gBAAgB;EACd,MAAM,UAAU,oBAAoB,OAAO,GAAG;EAC9C,IAAI,YAAY,MAAM;EAEtB,WAAW,SAAS,wBADP,cAAc,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,KAAA,EACzB;EAChD,WAAW,SAAS,yBAAyB,MAAM,KAAK;CAC1D,CAAC;CACD,aAAa;EAAC;EAAO,aAAa;EAAG;CAAG;AAC1C;;AAGA,SAAS,oBAAoB,OAAa,KAA+B;CACvE,KAAK,IAAI,OAAO,MAAM,aAAa,SAAS,QAAQ,SAAS,KAAK,OAAO,KAAK,aAC5E,IAAI,KAAK,aAAa,GAAG,OAAO;CAElC,OAAO;AACT;AAEA,SAAS,WAAW,SAAsB,UAAkB,OAAiC;CAC3F,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,QAAQ,MAAM,eAAe,QAAQ;MACzE,QAAQ,MAAM,YAAY,UAAU,KAAK;AAChD"}
1
+ {"version":3,"file":"view-transition.js","names":[],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\nimport { watchCommits } from \"./insert\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists. The content can change later\n // (a Show that opens, a fallback replaced by content) and the first element is then another one:\n // the name is applied again after each commit to the parent's regions, where that change lands.\n useEffect(() => {\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n const transitionClass = props.class;\n const apply = (): void => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", transitionClass);\n };\n apply();\n const parent = start.parentNode;\n if (parent !== null) watchCommits(parent, apply);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,oBACd,QACA,SACe;CACf,MAAM,MAAM,OAAO,aAAa,cAAc,KAAA,IAAa;CAC3D,IAAI,QAAQ,KAAA,KAAa,OAAO,IAAI,wBAAwB,YAAY;EACtE,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,OAAO,QAAQ,OAAO,KAAK;EAC7B;EACA,OAAO,QAAQ,QAAQ;CACzB;CACA,IAAI;CACJ,MAAM,iBAAuB;EAC3B,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,UAAU,EAAE,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,SAAS;CAIvB,OAHmB,IAAI,oBACrB,UAAU,KAAA,KAAa,MAAM,WAAW,IAAI,WAAW;EAAE,QAAQ;EAAU,OAAO,CAAC,GAAG,KAAK;CAAE,CAE/E,CAAC,CAAC,SAAS,WAAW;EACpC,IAAI,YAAY,KAAA,GAAW,MAAM,QAAQ;CAC3C,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,eAAe,OAA+C;CAG5E,IAAI;CACJ,IAAI,QAAQ;CACZ,MAAM,qBAA8B;EAClC,IAAI,CAAC,OAAO;GACV,QAAQ;GACR,QAAQ,cAAc,MAAM,QAAQ;EACtC;EACA,OAAO;CACT;CACA,MAAM,QAAQ,SAAS,eAAe,EAAE;CACxC,MAAM,MAAM,SAAS,eAAe,EAAE;CACtC,MAAM,YAAY,MAAM,SAAS,OAAO,MAAM,MAAM,MAAM,KAAA;CAI1D,gBAAgB;EACd,MAAM,OAAO,cAAc,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,KAAA;EACzE,MAAM,kBAAkB,MAAM;EAC9B,MAAM,cAAoB;GACxB,MAAM,UAAU,oBAAoB,OAAO,GAAG;GAC9C,IAAI,YAAY,MAAM;GACtB,WAAW,SAAS,wBAAwB,IAAI;GAChD,WAAW,SAAS,yBAAyB,eAAe;EAC9D;EACA,MAAM;EACN,MAAM,SAAS,MAAM;EACrB,IAAI,WAAW,MAAM,aAAa,QAAQ,KAAK;CACjD,CAAC;CACD,aAAa;EAAC;EAAO,aAAa;EAAG;CAAG;AAC1C;;AAGA,SAAS,oBAAoB,OAAa,KAA+B;CACvE,KAAK,IAAI,OAAO,MAAM,aAAa,SAAS,QAAQ,SAAS,KAAK,OAAO,KAAK,aAC5E,IAAI,KAAK,aAAa,GAAG,OAAO;CAElC,OAAO;AACT;AAEA,SAAS,WAAW,SAAsB,UAAkB,OAAiC;CAC3F,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,QAAQ,MAAM,eAAe,QAAQ;MACzE,QAAQ,MAAM,YAAY,UAAU,KAAK;AAChD"}
@@ -1,2 +1,2 @@
1
- import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n=/^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/,r=/^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/,i=/^(?:javascript:|data:text\/html|vbscript:)/;function a(n){if(!t.test(n))throw e(n)}function o(e){return e.replace(/\p{Cc}/gu,``)}function s(e){return i.test(o(e).trim().toLowerCase())}function c(e,t){let r=e.toLowerCase();return n.test(r)?r===`values`?t.split(`;`).some(s):s(t):!1}function l(e,t){return t==null?null:t===!1?r.test(e)?`false`:null:t===!0?r.test(e)?`true`:``:String(t)}function u(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function d(e,t,n,r){let i=n.toLowerCase(),a=l(i,r);a===null?t===null?e.removeAttribute(n):e.removeAttributeNS(t,u(n)):/^on./.test(i)||(c(i,a)?`${n}`:t===null?e.getAttribute(n)!==a&&e.setAttribute(n,a):e.getAttributeNS(t,u(n))!==a&&e.setAttributeNS(t,n,a))}function f(e,t,n){a(t),d(e,null,t,n)}function p(e,t,n,r){a(n),d(e,t===``?null:t,n,r)}function m(e,t,n){a(t),e.toggleAttribute(t,!!n)}export{a as assertAttributeName,c as isUnsafeUrlAttribute,f as setAttribute,p as setAttributeNS,m as setBoolAttribute};
1
+ import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n=/^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/,r=/^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/,i=/^(?:javascript:|data:text\/html|vbscript:)/;function a(n){if(!t.test(n))throw e(n)}function o(e){return e.replace(/\p{Cc}/gu,``)}function s(e){return i.test(o(e).trim().toLowerCase())}function c(e,t){let r=e.toLowerCase();return n.test(r)?r===`values`?t.split(`;`).some(s):s(t):!1}function l(e,t){return t==null?null:t===!1?r.test(e)?`false`:null:t===!0?r.test(e)?`true`:``:String(t)}function u(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function d(e,t,n,r){let i=n.toLowerCase(),a=l(i,r);a===null?t===null?e.removeAttribute(n):e.removeAttributeNS(t,u(n)):/^on./.test(i)||c(i,a)||(t===null?e.getAttribute(n)!==a&&e.setAttribute(n,a):e.getAttributeNS(t,u(n))!==a&&e.setAttributeNS(t,n,a))}function f(e,t,n){a(t),d(e,null,t,n)}function p(e,t,n,r){a(n),d(e,t===``?null:t,n,r)}function m(e,t,n){a(t),e.toggleAttribute(t,!!n)}export{a as assertAttributeName,c as isUnsafeUrlAttribute,f as setAttribute,p as setAttributeNS,m as setBoolAttribute};
2
2
  //# sourceMappingURL=attributes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","stripControls","text","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAc,EAAsB,CAC3C,OAAOC,EAAK,QAAQ,WAAY,EAAE,CACpC,CAGA,SAASC,EAAY,EAAwB,CAC3C,OAAON,EAAoB,KAAKI,EAAcG,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,CAC3E,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYP,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKW,CAAS,EAE3BA,IAAc,SAAWF,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKD,CAAW,EAAIA,EAAYC,CAAK,EAF1C,EAG9C,CAGA,SAASG,EAAc,EAAmB,EAA+B,CAIvE,OAHIH,GAAU,KAAoC,KAC9CA,IAAU,GAAcR,EAAc,KAAKU,CAAS,EAAI,QAAU,KAClEF,IAAU,GAAaR,EAAc,KAAKU,CAAS,EAAI,OAAS,GAC7D,OAAOF,CAAK,CACrB,CAGA,SAASI,EAAU,EAA2B,CAC5C,IAAMC,EAAQC,EAAU,QAAQ,GAAG,EACnC,OAAOD,IAAU,GAAKC,EAAYA,EAAU,MAAMD,EAAQ,CAAC,CAC7D,CAGA,SAASE,EAAO,EAAa,EAA0B,EAAmB,EAAsB,CAC9F,IAAML,EAAYI,EAAU,YAAY,EAClCR,EAAOK,EAAcD,EAAWF,CAAK,EACvCF,IAAS,KACPU,IAAc,KAAMC,EAAG,gBAAgBH,CAAS,EAC/CG,EAAG,kBAAkBD,EAAWJ,EAAUE,CAAS,CAAC,EAKvD,OAAO,KAAKJ,CAAS,IAErBD,EAAqBC,EAAWJ,CAAI,EACP,GAAgCQ,EAAhC,EAG7BE,IAAc,KACZC,EAAG,aAAaH,CAAS,IAAMR,GAAMW,EAAG,aAAaH,EAAWR,CAAI,EAC/DW,EAAG,eAAeD,EAAWJ,EAAUE,CAAS,CAAC,IAAMR,GAChEW,EAAG,eAAeD,EAAWF,EAAWR,CAAI,EAEhD,CA+BA,SAAgBY,EAAa,EAAa,EAAc,EAAsB,CAC5EhB,EAAoBC,CAAI,EACxBY,EAAOE,EAAI,KAAMd,EAAMK,CAAK,CAC9B,CAuBA,SAAgBW,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGjB,EAAoBC,CAAI,EACxBY,EAAOE,EAAID,IAAc,GAAK,KAAOA,EAAWb,EAAMK,CAAK,CAC7D,CAoBA,SAAgBY,EAAiB,EAAa,EAAc,EAAsB,CAChFlB,EAAoBC,CAAI,EACxBc,EAAG,gBAAgBd,EAAM,EAAQK,CAAM,CACzC,C"}
1
+ {"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","stripControls","text","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAc,EAAsB,CAC3C,OAAOC,EAAK,QAAQ,WAAY,EAAE,CACpC,CAGA,SAASC,EAAY,EAAwB,CAC3C,OAAON,EAAoB,KAAKI,EAAcG,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,CAC3E,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYP,EAAK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AAoBC,CAAI,EACxBc,EAAG,gBAAgBd,EAAM,EAAQK,CAAM,CACzC,C"}
@@ -1,2 +1,2 @@
1
- import{cssValueText as e}from"./internal/css-units.js";import{HTML_NS as t}from"./internal/names.js";function n(e,t){let n=[[e]],r=[0],i=/* @__PURE__ */ new Set;for(;n.length>0;){let e=n.length-1,a=n[e],o=r[e]??0;if(a===void 0||o>=a.length){let e=n.pop();e!==void 0&&i.delete(e),r.pop();continue}r[e]=o+1;let s=a[o];if(Array.isArray(s)){if(i.has(s))throw TypeError(`SHADOW_CLASS_CYCLE`);i.add(s),n.push(s),r.push(0)}else if(typeof s==`string`)s!==``&&t.push(s);else if(typeof s==`number`)s!==0&&!Number.isNaN(s)&&t.push(String(s));else if(typeof s==`object`&&s){let e=s;for(let n of Object.keys(e))e[n]&&n!==``&&t.push(n)}}}function r(e){if(typeof e==`string`)return e;if(e==null||e===!1)return null;let t=[];return n(e,t),t.join(` `)}function i(e,t,n){let i=r(t);i===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==i&&e.setAttribute(`class`,i):e.className!==i&&(e.className=i)}function a(e,n){i(e,n,e.namespaceURI!==t)}function o(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function s(e,t){return Object.hasOwn(e,t)&&!!e[t]}function c(e,t,n){let r=t??{},i=n??{},a=/* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(r)]);for(let t of a){let n=s(r,t);if(n!==s(i,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return r}function l(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function u(t,n,r){let i=l(n);r==null||r===!1?t.style.removeProperty(i):t.style.setProperty(i,e(i,r))}function d(e,t,n){if(t==null||t===!1)return e.removeAttribute(`style`),t;if(typeof t!=`object`)return e.style.cssText=String(t),t;if(Array.isArray(t)){e.style.cssText=``;for(let n of t)if(typeof n==`string`)e.style.cssText+=`;${n}`;else if(n!=null&&n!==!1){if(typeof n!=`object`||Array.isArray(n))throw TypeError(`SHADOW_STYLE_ITEM`);d(e,n,{})}return t}let r={...t},i=o(n)??{};(typeof n==`string`||Array.isArray(n))&&(e.style.cssText=``);let a=/* @__PURE__ */ new Set([...Object.keys(i),...Object.keys(r)]);for(let t of a)Object.is(i[t],r[t])||u(e,t,r[t]);return r}export{i as applyClass,o as asRecord,c as classList,a as className,u as setStyleProperty,d as style,l as toCssProperty};
1
+ import{leaves as e,unwrap as t}from"./internal/accessor.js";import{cssValueText as n}from"./internal/css-units.js";import{HTML_NS as r}from"./internal/names.js";function i(e){let n=e;for(let r of Object.keys(e))typeof e[r]==`function`&&(n===e&&(n={...e}),n[r]=t(e[r]));return n}function a(n,r){for(let i of e(n,`SHADOW_CLASS_CYCLE`))if(typeof i==`string`)i!==``&&r.push(i);else if(typeof i==`number`)i!==0&&!Number.isNaN(i)&&r.push(String(i));else if(typeof i==`object`&&i){let e=i;for(let n of Object.keys(e))t(e[n])&&n!==``&&r.push(n)}}function o(e){let n=t(e);if(typeof n==`string`)return n;if(n==null||n===!1)return null;let r=[];return a(n,r),r.join(` `)}function s(e,t,n){let r=o(t);r===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==r&&e.setAttribute(`class`,r):e.className!==r&&(e.className=r)}function c(e,t){s(e,t,e.namespaceURI!==r)}function l(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function u(e,t){return Object.hasOwn(e,t)&&!!e[t]}function d(e,t,n){let r=i(t??{}),a=n??{},o=/* @__PURE__ */ new Set([...Object.keys(a),...Object.keys(r)]);for(let t of o){let n=u(r,t);if(n!==u(a,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return r}function f(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function p(e,t,r){let i=f(t);r==null||r===!1?e.style.removeProperty(i):e.style.setProperty(i,n(i,r))}function m(e,n,r){let a=t(n);if(a==null||a===!1)return e.removeAttribute(`style`),a;if(typeof a!=`object`)return e.style.cssText=String(a),a;if(Array.isArray(a)){e.style.cssText=``;for(let n of a){let r=t(n);if(typeof r==`string`)e.style.cssText+=`;${r}`;else if(r!=null&&r!==!1){if(typeof r!=`object`||Array.isArray(r))throw TypeError(`SHADOW_STYLE_ITEM`);m(e,r,{})}}return a}let o=i({...a}),s=l(r)??{};(typeof r==`string`||Array.isArray(r))&&(e.style.cssText=``);let c=/* @__PURE__ */ new Set([...Object.keys(s),...Object.keys(o)]);for(let t of c)Object.is(s[t],o[t])||p(e,t,o[t]);return o}export{s as applyClass,l as asRecord,d as classList,c as className,p as setStyleProperty,m as style,f as toCssProperty};
2
2
  //# sourceMappingURL=class-style.js.map