@shadow-js/web 1.0.3 → 1.0.5

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 (147) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +2 -3
  3. package/dist/dev/attributes.js +1 -5
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.js +15 -13
  6. package/dist/dev/class-style.js.map +1 -1
  7. package/dist/dev/control-flow/dynamic.js +4 -4
  8. package/dist/dev/control-flow/no-hydration.js +1 -1
  9. package/dist/dev/control-flow/portal.js +1 -1
  10. package/dist/dev/element.js +10 -27
  11. package/dist/dev/element.js.map +1 -1
  12. package/dist/dev/events.js +64 -80
  13. package/dist/dev/events.js.map +1 -1
  14. package/dist/dev/extend.js +6 -6
  15. package/dist/dev/head/use-head.js +1 -1
  16. package/dist/dev/head/validate.js +1 -1
  17. package/dist/dev/hydration.js +21 -13
  18. package/dist/dev/hydration.js.map +1 -1
  19. package/dist/dev/index.d.ts +5 -5
  20. package/dist/dev/index.js +6 -6
  21. package/dist/dev/insert.js +50 -68
  22. package/dist/dev/insert.js.map +1 -1
  23. package/dist/dev/internal/reconcile.d.ts +2 -1
  24. package/dist/dev/internal/reconcile.js +19 -2
  25. package/dist/dev/internal/reconcile.js.map +1 -1
  26. package/dist/dev/jsx/global.d.ts +2 -2
  27. package/dist/dev/jsx/html.d.ts +1 -1
  28. package/dist/dev/jsx/intrinsic.d.ts +1 -1
  29. package/dist/dev/jsx/mathml.d.ts +1 -1
  30. package/dist/dev/jsx/svg.d.ts +1 -1
  31. package/dist/dev/jsx-runtime.d.ts +3 -3
  32. package/dist/dev/render.js +22 -11
  33. package/dist/dev/render.js.map +1 -1
  34. package/dist/dev/server/class-style.js +1 -1
  35. package/dist/dev/server/element.js +3 -3
  36. package/dist/dev/server/form-controls.js +1 -1
  37. package/dist/dev/server/hydration-script.js +1 -1
  38. package/dist/dev/server/portals.js +1 -1
  39. package/dist/dev/server/raw-text.js +1 -1
  40. package/dist/dev/server/render.js +2 -2
  41. package/dist/dev/server/stream.js +3 -3
  42. package/dist/dev/spread.js +59 -84
  43. package/dist/dev/spread.js.map +1 -1
  44. package/dist/dev/template.js +3 -3
  45. package/dist/prod/attributes.js +1 -1
  46. package/dist/prod/attributes.js.map +1 -1
  47. package/dist/prod/class-style.js +1 -1
  48. package/dist/prod/class-style.js.map +1 -1
  49. package/dist/prod/control-flow/dynamic.js +1 -1
  50. package/dist/prod/control-flow/no-hydration.js +1 -1
  51. package/dist/prod/control-flow/portal.js +1 -1
  52. package/dist/prod/element.js +1 -1
  53. package/dist/prod/element.js.map +1 -1
  54. package/dist/prod/events.js +1 -1
  55. package/dist/prod/events.js.map +1 -1
  56. package/dist/prod/extend.js +1 -1
  57. package/dist/prod/head/use-head.js +1 -1
  58. package/dist/prod/head/validate.js +1 -1
  59. package/dist/prod/hydration.js +1 -1
  60. package/dist/prod/hydration.js.map +1 -1
  61. package/dist/prod/index.js +1 -1
  62. package/dist/prod/insert.js +1 -1
  63. package/dist/prod/insert.js.map +1 -1
  64. package/dist/prod/internal/reconcile.js +1 -1
  65. package/dist/prod/internal/reconcile.js.map +1 -1
  66. package/dist/prod/render.js +1 -1
  67. package/dist/prod/render.js.map +1 -1
  68. package/dist/prod/server/class-style.js +1 -1
  69. package/dist/prod/server/element.js +1 -1
  70. package/dist/prod/server/form-controls.js +2 -2
  71. package/dist/prod/server/hydration-script.js +1 -1
  72. package/dist/prod/server/portals.js +1 -1
  73. package/dist/prod/server/raw-text.js +1 -1
  74. package/dist/prod/server/render.js +1 -1
  75. package/dist/prod/server/stream.js +1 -1
  76. package/dist/prod/spread.js +1 -1
  77. package/dist/prod/spread.js.map +1 -1
  78. package/dist/prod/template.js +1 -1
  79. package/dist/server/attributes.js +1 -1
  80. package/dist/server/attributes.js.map +1 -1
  81. package/dist/server/class-style.js +1 -1
  82. package/dist/server/class-style.js.map +1 -1
  83. package/dist/server/control-flow/dynamic.js +1 -1
  84. package/dist/server/control-flow/portal.js +1 -1
  85. package/dist/server/control-flow/suspense.js +1 -1
  86. package/dist/server/element.js +1 -1
  87. package/dist/server/element.js.map +1 -1
  88. package/dist/server/events.js +1 -1
  89. package/dist/server/events.js.map +1 -1
  90. package/dist/server/extend.js +1 -1
  91. package/dist/server/head/use-head.js +1 -1
  92. package/dist/server/head/validate.js +1 -1
  93. package/dist/server/hydration.js +1 -1
  94. package/dist/server/hydration.js.map +1 -1
  95. package/dist/server/index.js +1 -1
  96. package/dist/server/insert.js +1 -1
  97. package/dist/server/insert.js.map +1 -1
  98. package/dist/server/internal/reconcile.js +1 -1
  99. package/dist/server/internal/reconcile.js.map +1 -1
  100. package/dist/server/render.js +1 -1
  101. package/dist/server/render.js.map +1 -1
  102. package/dist/server/server/class-style.js +1 -1
  103. package/dist/server/server/element.js +1 -1
  104. package/dist/server/server/form-controls.js +2 -2
  105. package/dist/server/server/hydration-script.js +1 -1
  106. package/dist/server/server/portals.js +1 -1
  107. package/dist/server/server/raw-text.js +1 -1
  108. package/dist/server/server/render.js +1 -1
  109. package/dist/server/server/stream.js +1 -1
  110. package/dist/server/spread.js +1 -1
  111. package/dist/server/spread.js.map +1 -1
  112. package/dist/server/template.js +1 -1
  113. package/dist/server-dev/attributes.js +1 -5
  114. package/dist/server-dev/attributes.js.map +1 -1
  115. package/dist/server-dev/class-style.js +15 -13
  116. package/dist/server-dev/class-style.js.map +1 -1
  117. package/dist/server-dev/control-flow/dynamic.js +1 -1
  118. package/dist/server-dev/control-flow/portal.js +1 -1
  119. package/dist/server-dev/control-flow/suspense.js +2 -2
  120. package/dist/server-dev/element.js +1 -1
  121. package/dist/server-dev/element.js.map +1 -1
  122. package/dist/server-dev/events.js +64 -80
  123. package/dist/server-dev/events.js.map +1 -1
  124. package/dist/server-dev/extend.js +6 -6
  125. package/dist/server-dev/head/use-head.js +1 -1
  126. package/dist/server-dev/head/validate.js +1 -1
  127. package/dist/server-dev/hydration.js +21 -13
  128. package/dist/server-dev/hydration.js.map +1 -1
  129. package/dist/server-dev/index.js +6 -6
  130. package/dist/server-dev/insert.js +50 -68
  131. package/dist/server-dev/insert.js.map +1 -1
  132. package/dist/server-dev/internal/reconcile.js +19 -2
  133. package/dist/server-dev/internal/reconcile.js.map +1 -1
  134. package/dist/server-dev/render.js +22 -11
  135. package/dist/server-dev/render.js.map +1 -1
  136. package/dist/server-dev/server/class-style.js +1 -1
  137. package/dist/server-dev/server/element.js +3 -3
  138. package/dist/server-dev/server/form-controls.js +1 -1
  139. package/dist/server-dev/server/hydration-script.js +1 -1
  140. package/dist/server-dev/server/portals.js +1 -1
  141. package/dist/server-dev/server/raw-text.js +1 -1
  142. package/dist/server-dev/server/render.js +2 -2
  143. package/dist/server-dev/server/stream.js +3 -3
  144. package/dist/server-dev/spread.js +59 -84
  145. package/dist/server-dev/spread.js.map +1 -1
  146. package/dist/server-dev/template.js +3 -3
  147. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":[],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(fn: Binding[\"fn\"], node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n invoke(fn as Binding[\"fn\"], node, event, data === undefined ? [event] : [data, event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n const options = {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n const plain = !binding.tuple || binding.data !== undefined;\n if (\n delegate &&\n plain &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":";;;;;;AAMA,MAAM,mBACJ;;AAGF,MAAM,4BAAY,IAAI,QAA+B;;AAUrD,SAAS,OAAO,IAAmB,MAAmB,OAAc,MAAuB;CACzF,OAAO,eAAe,OAAO,iBAAiB;EAAE,cAAc;EAAM,WAAW;CAAK,CAAC;CACrF,IAAI;EACF,cAAc,GAAG,KAAK,MAAM,GAAG,IAAI,CAAC;CACtC,UAAU;EACR,QAAQ,eAAe,OAAO,eAAe;CAC/C;AACF;;;;;AAMA,SAAS,kBAAkB,OAAoB;CAG7C,YAAY,aAAa,KAAK,CAAC;AACjC;AAEA,SAAS,aAAa,OAAoB;CACxC,MAAM,MAAM,KAAK,MAAM;CACvB,MAAM,UAAU,GAAG,IAAI;CACvB,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,MAAM,aAAa,GAAG;EACvC,IAAI,MAAM,cAAc;EACxB,MAAM,KAAK,QAAQ,IAAI,MAAM,GAAG;EAChC,IAAI,OAAO,OAAO,YAAY;EAC9B,MAAM,OAAO,QAAQ,IAAI,MAAM,OAAO;EACtC,IAAI;GACF,OAAO,IAAqB,MAAM,OAAO,SAAS,KAAA,IAAY,CAAC,KAAK,IAAI,CAAC,MAAM,KAAK,CAAC;EACvF,SAAS,OAAO;GACd,OAAO,KAAK,KAAK;EACnB;CACF;CACA,MAAM,CAAC,SAAS;CAChB,IAAI,OAAO,WAAW,GAAG,MAAM;CAC/B,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,eACR,QACU,+BACZ;AACJ;AAWA,SAAS,iBAAiB,SAA6C;CACrE,OACE,OAAO,YAAY,YACnB,YAAY,QACZ,OAAQ,QAAsC,gBAAgB;A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BAAoB,MAAM,UAAU,OAAO;CAChD;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBACd,IACA,MACA,SACA,UACA,SACM;CACN,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,aAAa,MAAM,YAAY,IAAI;CAE/E,IAAI,WAAW,KAAA,KAAa,SAAS,MAAM,MAAM,UAAU,MAAM;AACnE"}
1
+ {"version":3,"file":"events.js","names":[],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A bound handler: called with `this` = the node. */\ntype Handler = (this: EventTarget, ...args: unknown[]) => unknown;\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the\n * duration of the call. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n untrack(() =>\n (fn as Handler).call(node, ...(data === undefined ? [event] : [data, event])),\n );\n } catch (error) {\n errors.push(error);\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n });\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */\nfunction listen(\n el: Element,\n name: string,\n run: (event: Event) => unknown,\n options: AddEventListenerOptions | boolean,\n): () => void {\n const listener = (event: Event): void => {\n batch(() => untrack(() => run(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n return listen(el, name, (event) => object.handleEvent(event), {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions);\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/** Installs the delegated listener for one event name on `target`, unless it is there already. */\nfunction installDelegate(name: string, target: Document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n if (known.has(name)) return;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n for (const name of names) installDelegate(name, target);\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n let fn = handler as Handler;\n let data: unknown;\n let tuple = false;\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n fn = handler[0] as Handler;\n data = handler[1];\n tuple = true;\n } else if (typeof handler !== \"function\") {\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n }\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n if (\n delegate &&\n (!tuple || data !== undefined) &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n installDelegate(name, delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, fn);\n if (tuple) Reflect.set(el, dataKey, data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n return listen(el, name, (event) => fn.call(el, ...(tuple ? [data, event] : [event])), capture);\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":";;;;;;AAMA,MAAM,mBACJ;;AAGF,MAAM,4BAAY,IAAI,QAA+B;;;;;;AAUrD,SAAS,kBAAkB,OAAoB;CAG7C,YAAY;EACV,MAAM,MAAM,KAAK,MAAM;EACvB,MAAM,UAAU,GAAG,IAAI;EACvB,MAAM,SAAoB,CAAC;EAC3B,KAAK,MAAM,QAAQ,MAAM,aAAa,GAAG;GACvC,IAAI,MAAM,cAAc;GACxB,MAAM,KAAK,QAAQ,IAAI,MAAM,GAAG;GAChC,IAAI,OAAO,OAAO,YAAY;GAC9B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E,CAAC;EAC5C,MAAM,UAAU,GAAG,KAAK;EACxB,QAAQ,IAAI,IAAI,MAAM,EAAE;EACxB,IAAI,OAAO,QAAQ,IAAI,IAAI,SAAS,IAAI;OACnC,QAAQ,eAAe,IAAI,OAAO;EACvC,aAAa;GACX,IAAI,QAAQ,IAAI,IAAI,IAAI,MAAM,IAAI;IAChC,QAAQ,eAAe,IAAI,IAAI;IAC/B,QAAQ,eAAe,IAAI,OAAO;GACpC;EACF;CACF;CACA,OAAO,OAAO,IAAI,OAAO,UAAU,GAAG,KAAK,IAAI,GAAI,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,KAAK,CAAE,GAAG,OAAO;AAC/F;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBACd,IACA,MACA,SACA,UACA,SACM;CACN,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,aAAa,MAAM,YAAY,IAAI;CAE/E,IAAI,WAAW,KAAA,KAAa,SAAS,MAAM,MAAM,UAAU,MAAM;AACnE"}
@@ -1,12 +1,12 @@
1
- import { warnOnce } from "./internal/diagnostics.js";
2
1
  import { isUnsafeUrlAttribute } from "./attributes.js";
3
- import { HTML_NS, MATHML_NS, SVG_NS } from "./internal/names.js";
4
- import { childScope, createRootScope, currentScope, enterComponent, nextKey, resourceKey, withScope } from "./internal/hydration-scope.js";
2
+ import { element } from "./element.js";
3
+ import { bindRegion, createRegion, moveRegion, removeRegion } from "./insert.js";
5
4
  import { claimElement, claimPortal, isClaiming, takeRegion, withoutClaiming } from "./internal/claim.js";
5
+ import { warnOnce } from "./internal/diagnostics.js";
6
6
  import { claims } from "./internal/hydration-hooks.js";
7
- import { reconcileNodes } from "./internal/reconcile.js";
8
- import { bindRegion, createRegion, moveRegion, removeRegion } from "./insert.js";
9
- import { element } from "./element.js";
7
+ import { childScope, createRootScope, currentScope, enterComponent, nextKey, resourceKey, withScope } from "./internal/hydration-scope.js";
8
+ import { HTML_NS, MATHML_NS, SVG_NS } from "./internal/names.js";
10
9
  import { PortalContext } from "./internal/portal-context.js";
10
+ import { reconcileNodes } from "./internal/reconcile.js";
11
11
  import { StreamContext } from "./internal/stream-context.js";
12
12
  export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, moveRegion, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
@@ -1,7 +1,7 @@
1
1
  import { createHeadRegistry } from "./registry.js";
2
- import { normalizeTags } from "./validate.js";
3
2
  import { ServerHeadContext } from "./server-head.js";
4
3
  import { createDomHeadSink } from "./sink.js";
4
+ import { normalizeTags } from "./validate.js";
5
5
  import { createRoot, getOwner, isServer, untrack, useContext, useEffect, useRenderEffect, useSignal } from "@shadow-js/core";
6
6
  // src/head/use-head.ts
7
7
  /** One registry per document, shared by every `useHead` call on it. */
@@ -1,5 +1,5 @@
1
- import { warnOnce } from "../internal/diagnostics.js";
2
1
  import { isUnsafeUrlAttribute } from "../attributes.js";
2
+ import { warnOnce } from "../internal/diagnostics.js";
3
3
  // src/head/validate.ts
4
4
  /** Marks every element the sink created or adopted. Callers may not supply it. @internal */
5
5
  const HEAD_MARKER = "data-shadow-head";
@@ -1,9 +1,9 @@
1
- import { createRootScope, resourceKey, withScope } from "./internal/hydration-scope.js";
2
- import { beginClaiming, claimElement, claimPortal, endClaiming, isClaiming, liftedRegions, releaseUnclaimedPortals, takeRegion, withoutClaiming } from "./internal/claim.js";
3
- import { claims } from "./internal/hydration-hooks.js";
4
- import { bindRegion, createRegion, removeRegion } from "./insert.js";
5
1
  import { attachRootErrors } from "./control-flow/root-errors.js";
2
+ import { bindRegion, createRegion, removeRegion } from "./insert.js";
3
+ import { beginClaiming, claimElement, claimPortal, endClaiming, isClaiming, liftedRegions, releaseUnclaimedPortals, takeRegion, withoutClaiming } from "./internal/claim.js";
6
4
  import { replayEarlyEvents } from "./internal/early-events.js";
5
+ import { claims } from "./internal/hydration-hooks.js";
6
+ import { createRootScope, resourceKey, withScope } from "./internal/hydration-scope.js";
7
7
  import { ResourceCacheContext, batch, createRoot, flushSync, runWithOwner, untrack } from "@shadow-js/core";
8
8
  import { withHydration } from "@shadow-js/core/extend";
9
9
  // src/hydration.ts
@@ -87,8 +87,16 @@ function hydrate(code, container, options = {}) {
87
87
  const cache = dataCache(options.data ?? {});
88
88
  const region = createRegion(container, null, Array.from(container.childNodes));
89
89
  let stop;
90
+ let disposed = false;
91
+ const teardown = () => {
92
+ if (disposed) return;
93
+ disposed = true;
94
+ stop?.();
95
+ removeRegion(region);
96
+ };
90
97
  try {
91
- stop = withHydration(() => batch(() => withScope(createRootScope(options.renderId), () => runWithOwner(options.owner ?? null, () => createRoot((dispose) => {
98
+ withHydration(() => batch(() => withScope(createRootScope(options.renderId), () => runWithOwner(options.owner ?? null, () => createRoot((dispose) => {
99
+ stop = dispose;
92
100
  attachRootErrors(options);
93
101
  ResourceCacheContext({
94
102
  value: cache,
@@ -97,22 +105,22 @@ function hydrate(code, container, options = {}) {
97
105
  return null;
98
106
  }
99
107
  });
100
- return dispose;
101
108
  })))));
102
109
  flushSync();
110
+ } catch (error) {
111
+ try {
112
+ stop?.();
113
+ } catch (cleanupError) {
114
+ throw new AggregateError([error, cleanupError], "hydrate() failed and so did its teardown.");
115
+ }
116
+ throw error;
103
117
  } finally {
104
118
  endClaiming();
105
119
  claims.current = previousClaims;
106
120
  }
107
121
  replayEarlyEvents();
108
122
  stripLeftovers(container);
109
- let disposed = false;
110
- return () => {
111
- if (disposed) return;
112
- disposed = true;
113
- stop();
114
- removeRegion(region);
115
- };
123
+ return teardown;
116
124
  }
117
125
  export { hydrate };
118
126
 
@@ -1 +1 @@
1
- {"version":3,"file":"hydration.js","names":[],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: () => void;\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n stop = withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n return dispose;\n }),\n ),\n ),\n ),\n );\n flushSync();\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n stop();\n removeRegion(region);\n };\n}\n"],"mappings":";;;;;;;;;AAsDA,SAAS,UAAU,MAA8C;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO;EACL,KAAK;EACL,KAAK,KAAK;GACR,IAAI,KAAK,IAAI,GAAG,KAAK,CAAC,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAA;GACvD,KAAK,IAAI,GAAG;GACZ,OAAO,EAAE,OAAO,KAAK,KAAK;EAC5B;EACA,QAAQ,CAER;CACF;AACF;;;;;AAMA,SAAS,eAAe,WAAuB;CAC7C,MAAM,MAAM,qBAAqB,WAAW,YAAY,UAAU;CAClE,IAAI,QAAQ,MAAM;CAClB,IAAI,IAAI,SAAS,MAAM,wBAAwB,IAAI,IAAI;CACvD,MAAM,SAAS,IAAI,iBAAiB,WAAW,WAAW,YAAY;CACtE,MAAM,QAAmB,CAAC;CAC1B,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,UAAU,OAAO;EACvB,IAAI,QAAQ,SAAS,OAAO,QAAQ,SAAS,KAAK,MAAM,KA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":[],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n stop = dispose;\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n }),\n ),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a hydration that throws, so the root must not stay alive. Its\n // effects and listeners go; the server's markup stays, so the page keeps what the server rendered.\n try {\n stop?.();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"hydrate() failed and so did its teardown.\" : \"SHADOW_HYDRATE_ERRORS\",\n );\n }\n throw error;\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n return teardown;\n}\n"],"mappings":";;;;;;;;;AAsDA,SAAS,UAAU,MAA8C;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO;EACL,KAAK;EACL,KAAK,KAAK;GACR,IAAI,KAAK,IAAI,GAAG,KAAK,CAAC,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,KAAA;GACvD,KAAK,IAAI,GAAG;GACZ,OAAO,EAAE,OAAO,KAAK,KAAK;EAC5B;EACA,QAAQ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U,gBAAgB,QAAQ,QAAQ,SACxC,aAAa,QAAQ,SAAS,YAC5B,YAAY,YAAY;GACtB,OAAO;GACP,iBAAiB,OAAO;GACxB,qBAAqB;IACnB,OAAO;IACP,IAAI,WAAW;KACb,WAAW,QAAQ,QAAQ,IAAI,CAAC;KAChC,OAAO;IACT;GACF,CAAC;EACH,CAAC,CACH,CACF,CACF,CACF;EACA,UAAU;CACZ,SAAS,OAAO;EAGd,IAAI;GACF,OAAO;EACT,SAAS,cAAc;GACrB,MAAM,IAAI,eACR,CAAC,OAAO,YAAY,GACV,2CACZ;EACF;EACA,MAAM;CACR,UAAU;EACR,YAAY;EACZ,OAAO,UAAU;CACnB;CACA,kBAAkB;CAClB,eAAe,SAAS;CACxB,OAAO;AACT"}
@@ -5,11 +5,11 @@ import { createComponent } from "./component.js";
5
5
  import { Activity } from "./control-flow/activity.js";
6
6
  import { Show } from "./control-flow/show.js";
7
7
  import { ClientOnly } from "./control-flow/client-only.js";
8
- import { anchor, insert } from "./insert.js";
8
+ import { derived } from "./derived.js";
9
9
  import { element } from "./element.js";
10
10
  import { addEventListener, chainEvents, clearDelegatedEvents, delegateEvents } from "./events.js";
11
- import { setSelectValue } from "./select-value.js";
12
- import { spread } from "./spread.js";
11
+ import { hydrate } from "./hydration.js";
12
+ import { anchor, insert } from "./insert.js";
13
13
  import { Dynamic, createDynamic } from "./control-flow/dynamic.js";
14
14
  import { ErrorBoundary } from "./control-flow/error-boundary.js";
15
15
  import { For } from "./control-flow/for.js";
@@ -21,13 +21,13 @@ import { Portal } from "./control-flow/portal.js";
21
21
  import { SuspenseList } from "./control-flow/suspense-list.js";
22
22
  import { Suspense } from "./control-flow/suspense.js";
23
23
  import { Match, Switch } from "./control-flow/switch.js";
24
- import { derived } from "./derived.js";
24
+ import { effect, memo, refTo, use } from "./reactive.js";
25
25
  import { useHead } from "./head/use-head.js";
26
26
  import { Base, Link, Meta, Style, Title } from "./head/components.js";
27
- import { hydrate } from "./hydration.js";
28
- import { effect, memo, refTo, use } from "./reactive.js";
29
27
  import { render } from "./render.js";
30
28
  import { preconnect, prefetchDNS, preinit, preinitModule, preload, preloadModule } from "./resource-hints.js";
29
+ import { setSelectValue } from "./select-value.js";
30
+ import { spread } from "./spread.js";
31
31
  import { template } from "./template.js";
32
32
  import { ViewTransition, startViewTransition } from "./view-transition.js";
33
33
  import { isDev, isServer, mergeProps } from "@shadow-js/core";
@@ -1,7 +1,7 @@
1
1
  import { leaves } from "./internal/accessor.js";
2
2
  import { checkClaimedText } from "./internal/claim.js";
3
3
  import { claims } from "./internal/hydration-hooks.js";
4
- import { reconcileNodes } from "./internal/reconcile.js";
4
+ import { keepFocus, reconcileNodes } from "./internal/reconcile.js";
5
5
  import { onCleanup, useRenderEffect } from "@shadow-js/core";
6
6
  import { addCleanup, createComputation, currentOwner, disposeOwner, readComputation } from "@shadow-js/core/extend";
7
7
  // src/insert.ts
@@ -120,12 +120,17 @@ function watchCommits(parent, run) {
120
120
  set.delete(run);
121
121
  });
122
122
  }
123
- /** Makes the DOM show `next` for this region. */
124
- function reconcileRegion(region, next) {
123
+ /** Applies a flattened value to a region. */
124
+ function commit(region, parts) {
125
+ if (region.claimed !== void 0) {
126
+ checkClaimedText(region.claimed, parts);
127
+ region.claimed = void 0;
128
+ }
129
+ const next = materialize(region, parts);
125
130
  const parent = region.parent;
126
131
  const attached = region.nodes.filter((node) => node.parentNode === parent);
127
- const end = endOf(region, attached.at(-1));
128
132
  const first = attached[0];
133
+ const end = endOf(region, attached.at(-1));
129
134
  if (next.length === 0 && first !== void 0) region.marker = first.previousSibling;
130
135
  reconcileNodes(parent, attached, next, end);
131
136
  region.nodes = next;
@@ -134,14 +139,6 @@ function reconcileRegion(region, next) {
134
139
  run();
135
140
  });
136
141
  }
137
- /** Applies a flattened value to a region. */
138
- function commit(region, parts) {
139
- if (region.claimed !== void 0) {
140
- checkClaimedText(region.claimed, parts);
141
- region.claimed = void 0;
142
- }
143
- reconcileRegion(region, materialize(region, parts));
144
- }
145
142
  /**
146
143
  * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region
147
144
  * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of
@@ -150,7 +147,7 @@ function commit(region, parts) {
150
147
  function commitValue(region, raw) {
151
148
  if ((typeof raw === "string" || typeof raw === "number") && !region.claimed) {
152
149
  const nodes = region.nodes;
153
- const text = typeof raw === "string" ? raw : String(raw);
150
+ const text = String(raw);
154
151
  if (nodes.length === 1) {
155
152
  const current = nodes[0];
156
153
  if (current instanceof Text && current.parentNode === region.parent && ownsText(region, current)) {
@@ -167,28 +164,25 @@ function commitValue(region, raw) {
167
164
  }
168
165
  commit(region, flatten(raw));
169
166
  }
170
- /** Nodes of `initial` (already in the parent) that the region adopts as its current content. */
171
- function adoptInitial(parent, initial) {
172
- const adopted = [];
173
- const seen = /* @__PURE__ */ new Set();
174
- for (const part of flatten(initial)) {
175
- if (typeof part === "string" || seen.has(part) || part.parentNode !== parent) continue;
176
- seen.add(part);
177
- adopted.push(part);
178
- }
179
- return adopted;
180
- }
181
167
  /**
182
168
  * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes
183
169
  * already in the DOM, from hydration or splitText) are both optional.
184
170
  * @internal
185
171
  */
186
172
  function createRegion(parent, anchorNode, initial) {
187
- const nodes = initial === void 0 ? [] : adoptInitial(parent, initial);
173
+ const nodes = [];
174
+ if (initial !== void 0) {
175
+ const seen = /* @__PURE__ */ new Set();
176
+ for (const part of flatten(initial)) {
177
+ if (typeof part === "string" || seen.has(part) || part.parentNode !== parent) continue;
178
+ seen.add(part);
179
+ nodes.push(part);
180
+ }
181
+ }
188
182
  const region = {
189
183
  parent,
190
184
  anchor: anchorNode,
191
- marker: nodes.length > 0 ? nodes[0]?.previousSibling ?? null : parent.lastChild,
185
+ marker: nodes.length > 0 ? nodes[0].previousSibling : parent.lastChild,
192
186
  nodes,
193
187
  texts: null
194
188
  };
@@ -201,7 +195,9 @@ function createRegion(parent, anchorNode, initial) {
201
195
  * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then
202
196
  * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling
203
197
  * region can replace: the order of the calls holds however the regions change. A region with static content
204
- * between it and this one needs nothing, because its marker and its end are the static nodes.
198
+ * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its
199
+ * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep
200
+ * the regions of that call alive as long as the parent's owner.)
205
201
  */
206
202
  function linkRegion(region) {
207
203
  const parent = region.parent;
@@ -236,42 +232,6 @@ function containsFunction(root) {
236
232
  return false;
237
233
  }
238
234
  /**
239
- * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,
240
- * so a new result drops them all; the effect that resolves the result runs many times and must not
241
- * own them). `prune` disposes the memos of accessors the last
242
- * run did not meet, which bounds the cache by what the region currently shows.
243
- */
244
- function createCallCache(owner) {
245
- const memos = /* @__PURE__ */ new Map();
246
- let touched = /* @__PURE__ */ new Set();
247
- return {
248
- begin() {
249
- touched = /* @__PURE__ */ new Set();
250
- },
251
- call(fn) {
252
- touched.add(fn);
253
- let node = memos.get(fn);
254
- if (node === void 0) {
255
- node = createComputation({
256
- kind: "memo",
257
- fn: () => fn(),
258
- allowWrites: true,
259
- owner
260
- });
261
- memos.set(fn, node);
262
- }
263
- return readComputation(node);
264
- },
265
- prune() {
266
- for (const [fn, node] of memos) {
267
- if (touched.has(fn)) continue;
268
- memos.delete(fn);
269
- disposeOwner(node);
270
- }
271
- }
272
- };
273
- }
274
- /**
275
235
  * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an
276
236
  * array with accessor members) runs inside a render effect, so its reads are tracked. Anything
277
237
  * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps
@@ -288,11 +248,31 @@ function bindRegion(region, value, ordered) {
288
248
  useRenderEffect(typeof value === "function" ? value : () => value, (raw) => {
289
249
  latest = raw;
290
250
  if (containsFunction(raw)) {
291
- const cache = createCallCache(currentOwner());
251
+ const owner = currentOwner();
252
+ const memos = /* @__PURE__ */ new Map();
253
+ let touched = /* @__PURE__ */ new Set();
254
+ const call = (fn) => {
255
+ touched.add(fn);
256
+ let node = memos.get(fn);
257
+ if (node === void 0) {
258
+ node = createComputation({
259
+ kind: "memo",
260
+ fn: () => fn(),
261
+ allowWrites: true,
262
+ owner
263
+ });
264
+ memos.set(fn, node);
265
+ }
266
+ return readComputation(node);
267
+ };
292
268
  useRenderEffect(() => {
293
- cache.begin();
294
- const parts = flatten(raw, cache.call);
295
- cache.prune();
269
+ touched = /* @__PURE__ */ new Set();
270
+ const parts = flatten(raw, call);
271
+ for (const [fn, node] of memos) {
272
+ if (touched.has(fn)) continue;
273
+ memos.delete(fn);
274
+ disposeOwner(node);
275
+ }
296
276
  return parts;
297
277
  }, (parts) => {
298
278
  commit(region, parts);
@@ -313,7 +293,9 @@ function bindRegion(region, value, ordered) {
313
293
  */
314
294
  function moveRegion(region, parent, move) {
315
295
  const attached = region.nodes.filter((node) => node.parentNode === region.parent);
316
- for (const node of attached) move(node);
296
+ keepFocus(region.parent, () => {
297
+ for (const node of attached) move(node);
298
+ });
317
299
  region.parent = parent;
318
300
  region.marker = attached[0]?.previousSibling ?? parent.lastChild;
319
301
  }
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n for (const node of attached) move(node);\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;MAC9B,IAAI,iBAAiB,KAAK,MAAM,IAAI,IAAI;MACxC,IAAI,UAAU,MAAM,OAAO,wBAAQ,IAAI,IAAI,CAAC,OAAO,IAAI,CAAC;AAC/D;;AAGA,SAAS,WAAW,QAAgB,MAA6B;CAC/D,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM;CACpB,IAAI,iBAAiB,KAAK;EACxB,MAAM,OAAO,IAAI,IAAU,IAAI;EAC/B,KAAK,MAAM,QAAQ,OACjB,IAAI,CAAC,KAAK,IAAI,IAAI,GAAG,MAAM,OAAO,IAAI;CAE1C,OAAO,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ;A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CACD,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,WAAW,QAAgB,QAAc,MAAkC;CACzF,MAAM,WAAW,OAAO,MAAM,QAAQ,SAAS,KAAK,eAAe,OAAO,MAAM;CAChF,KAAK,MAAM,QAAQ,UAAU,KAAK,IAAI;CAEtC,OAA6B,SAAS;CACtC,OAAO,SAAS,SAAS,EAAE,EAAE,mBAAmB,OAAO;AACzD;;;;;;AAOA,SAAgB,aAAa,QAAsB;CACjD,KAAK,MAAM,QAAQ,OAAO,OACxB,IAAI,KAAK,eAAe,OAAO,QAAQ,OAAO,OAAO,YAAY,IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
1
+ {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;MAC9B,IAAI,iBAAiB,KAAK,MAAM,IAAI,IAAI;MACxC,IAAI,UAAU,MAAM,OAAO,wBAAQ,IAAI,IAAI,CAAC,OAAO,IAAI,CAAC;AAC/D;;AAGA,SAAS,WAAW,QAAgB,MAA6B;CAC/D,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM;CACpB,IAAI,iBAAiB,KAAK;EACxB,MAAM,OAAO,IAAI,IAAU,IAAI;EAC/B,KAAK,MAAM,QAAQ,OACjB,IAAI,CAAC,KAAK,IAAI,IAAI,GAAG,MAAM,OAAO,IAAI;CAE1C,OAAO,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ;AACnD;;;;;AAMA,MAAM,mCAAmB,IAAI,QAAkC;;;;;AAM/D,SAAS,QAAQ,MAAe,MAA+C;CAC7E,MAAM,QAAgB,CAAC;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IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
@@ -1,4 +1,17 @@
1
1
  // src/internal/reconcile.ts
2
+ /**
3
+ * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused
4
+ * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it
5
+ * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps
6
+ * it. The focused element is read once, before `run`.
7
+ * @internal
8
+ */
9
+ function keepFocus(at, run) {
10
+ const root = at.getRootNode();
11
+ const active = root.activeElement;
12
+ run();
13
+ if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });
14
+ }
2
15
  /** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */
3
16
  function removeNode(parent, node) {
4
17
  if (node !== void 0 && node.parentNode === parent) parent.removeChild(node);
@@ -44,7 +57,8 @@ function markLongestIncreasing(values, offset, marks) {
44
57
  * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of
45
58
  * surviving positions stay where they are; every other node is moved (or inserted) directly
46
59
  * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,
47
- * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,
60
+ * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move
61
+ * blurred gets the focus back). Each node moves at most once,
48
62
  * and the number of moves is minimal for the surviving order.
49
63
  *
50
64
  * @param parent The parent of the region.
@@ -101,6 +115,8 @@ function reconcileNodes(parent, prev, next, end) {
101
115
  const stable = new Uint8Array(nextTail - head);
102
116
  markLongestIncreasing(survivors, head, stable);
103
117
  const movable = typeof parent.moveBefore === "function";
118
+ const root = parent.getRootNode();
119
+ const active = movable ? null : root.activeElement;
104
120
  let anchorNode = before;
105
121
  for (let index = nextTail - 1; index >= head; index -= 1) {
106
122
  const node = next[index];
@@ -110,7 +126,8 @@ function reconcileNodes(parent, prev, next, end) {
110
126
  }
111
127
  anchorNode = node;
112
128
  }
129
+ if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });
113
130
  }
114
- export { reconcileNodes };
131
+ export { keepFocus, reconcileNodes };
115
132
 
116
133
  //# sourceMappingURL=reconcile.js.map