@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
@@ -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,39 @@ 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
+ function applyProps(el, read, isSVG, state) {
245
+ const textarea = el.localName === "textarea";
237
246
  onCleanup(() => {
238
247
  for (const unbind of state.unbinders.values()) unbind();
239
248
  state.unbinders.clear();
@@ -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(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/C;;AAGA,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAezE,SAAS,WAAW,KAAsB;CACxC,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI;AAC9C;;AAGA,SAAS,OAAO,KAAqB;CACnC,MAAM,QAAQ,IAAI,QAAQ,GAAG;CA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C,IAAI,QAAQ,IAAI,GAAG,GAAG;EACtB,MAAM,OAAO,OAAO,GAAG;EAGvB,SAAS,IAAI,KAAK,KAAA,GAAW,OAAO,GAAG;CACzC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,OAAO,IAAa,OAAgB,QAAQ,OAAO,eAAe,OAAa;CAC7F,IAAI,UAAU,QAAS,OAAO,UAAU,YAAY,OAAO,UAAU,YAAa;CAGlF,MAAM,aAAuB,OAAO,UAAU,aAAc,MAAwB,IAAI;CACxF,MAAM,WAAW,GAAG,cAAc;CAClC,IAAI,CAAC,gBAAgB,CAAC,UAAU;EAE9B,MAAM,UAAU,OAAO,QAAQ,WAAW,IACrC,OAAO,QAAQ,WAAW,IAAI,IAAI,KAAK,MAAM,KAAK,GAAG,UAAU,IAChE,KAAA;EACJ,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO;EAC7C,WAAW,cAAe,KAAK,CAAC,EAA6C,QAAQ;CACvF;CACA,MAAM,QAAqB;EACzB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;CAEA,gBAAgB;EACd,KAAK,MAAM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
1
+ {"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/C;;AAGA,MAAM,kBAAkB;;AAexB,SAAS,WAAW,KAAsB;CACxC,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI;AAC9C;;AAGA,SAAS,OAAO,KAAqB;CACnC,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAC7B,OAAO,UAAU,KAAK,MAAM,IAAI,MAAM,QAAQ,CAAC;AACjD;;AAGA,SAAS,YAAY,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,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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O;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,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C;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,MAAc,QAAQ,GAAe;CAC5D,MAAM,cAAc,QAAA,OAAkC;CAKtD,IAAI;CACJ,MAAM,iBAAyB;EAC7B,MAAM,OAAO,WAAW,MAAM;EAC9B,IAAI,SAAS,KAAA,GAAW,OAAO;EAC/B,MAAM,QAAQ,MAAM,MAAM,KAAK;EAC/B,YAAY,IAAI,QAAQ,KAAK;EAC7B,OAAO;CACT;CACA,MAAM,QAAQ,SACZ,aAAa,SAAS,WAAW,MAAM,IAAI,IAAI,KAAK,UAAU,IAAI;CACpE,aAAa;EAEX,MAAM,UAAU,OAAO,QAAQ,aAAa,QAAQ,CAAC;EACrD,IAAI,YAAY,MAAM;GACP;IAEX,MAAM,SAAS,SAAS;IACxB,MAAM,CAAC,QAAQ;IACf,IAAI,OAAO,WAAW,KAAK,gBAAgB,SACzC,gBAAgB,SAAS,KAAK,SAAS;GAC3C;GACA,OAAO;EACT;EAEA,MAAM,SAAmB,SAAS;EAClC,IAAI,OAAO,WAAW,GAAG;GACvB,MAAM,CAAC,QAAQ;GACf,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK,IAAI;EAC1C;EACA,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,MAAM,QAAQ,QAAQ,SAAS,YAAY,KAAK,IAAI,CAAC;EAC1D,OAAO;CACT;AACF"}
@@ -1 +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;CAC5D,aAAa,MAAM;AAuBrC"}
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;CAC5D,aAAa,MAAM;AA+BrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shadow-js/web",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "A DOM renderer with no virtual DOM, plus control flow, server rendering and hydration",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -106,10 +106,10 @@
106
106
  },
107
107
  "scripts": {
108
108
  "build": "tsdown --config-loader native",
109
- "typecheck": "tsc -p tsconfig.json"
109
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test-types.json"
110
110
  },
111
111
  "peerDependencies": {
112
- "@shadow-js/core": "^1.0.2"
112
+ "@shadow-js/core": "^1.0.3"
113
113
  },
114
114
  "devDependencies": {
115
115
  "@biomejs/biome": "2.5.15",