@shadow-js/web 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +7 -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 +9 -12
  6. package/dist/dev/class-style.js.map +1 -1
  7. package/dist/dev/element.js +8 -25
  8. package/dist/dev/element.js.map +1 -1
  9. package/dist/dev/events.js +64 -80
  10. package/dist/dev/events.js.map +1 -1
  11. package/dist/dev/insert.js +50 -68
  12. package/dist/dev/insert.js.map +1 -1
  13. package/dist/dev/internal/reconcile.d.ts +2 -1
  14. package/dist/dev/internal/reconcile.js +19 -2
  15. package/dist/dev/internal/reconcile.js.map +1 -1
  16. package/dist/dev/spread.js +47 -80
  17. package/dist/dev/spread.js.map +1 -1
  18. package/dist/prod/attributes.js +1 -1
  19. package/dist/prod/attributes.js.map +1 -1
  20. package/dist/prod/class-style.js +1 -1
  21. package/dist/prod/class-style.js.map +1 -1
  22. package/dist/prod/element.js +1 -1
  23. package/dist/prod/element.js.map +1 -1
  24. package/dist/prod/events.js +1 -1
  25. package/dist/prod/events.js.map +1 -1
  26. package/dist/prod/insert.js +1 -1
  27. package/dist/prod/insert.js.map +1 -1
  28. package/dist/prod/internal/reconcile.js +1 -1
  29. package/dist/prod/internal/reconcile.js.map +1 -1
  30. package/dist/prod/spread.js +1 -1
  31. package/dist/prod/spread.js.map +1 -1
  32. package/dist/server/attributes.js +1 -1
  33. package/dist/server/attributes.js.map +1 -1
  34. package/dist/server/class-style.js +1 -1
  35. package/dist/server/class-style.js.map +1 -1
  36. package/dist/server/element.js.map +1 -1
  37. package/dist/server/events.js +1 -1
  38. package/dist/server/events.js.map +1 -1
  39. package/dist/server/insert.js +1 -1
  40. package/dist/server/insert.js.map +1 -1
  41. package/dist/server/internal/reconcile.js +1 -1
  42. package/dist/server/internal/reconcile.js.map +1 -1
  43. package/dist/server/spread.js +1 -1
  44. package/dist/server/spread.js.map +1 -1
  45. package/dist/server-dev/attributes.js +1 -5
  46. package/dist/server-dev/attributes.js.map +1 -1
  47. package/dist/server-dev/class-style.js +9 -12
  48. package/dist/server-dev/class-style.js.map +1 -1
  49. package/dist/server-dev/element.js.map +1 -1
  50. package/dist/server-dev/events.js +64 -80
  51. package/dist/server-dev/events.js.map +1 -1
  52. package/dist/server-dev/insert.js +50 -68
  53. package/dist/server-dev/insert.js.map +1 -1
  54. package/dist/server-dev/internal/reconcile.js +19 -2
  55. package/dist/server-dev/internal/reconcile.js.map +1 -1
  56. package/dist/server-dev/spread.js +47 -80
  57. package/dist/server-dev/spread.js.map +1 -1
  58. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","invoke","event","node","untrack","fn","args","dispatchDelegated","batch","dispatchPath","key","dataKey","errors","data","error","first","isListenerObject","handler","bindListenerObject","object","options","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","binding","slot","plain","delegate","addEventListener","unbind","getOwner","onCleanup"],"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":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAO,EAAmB,EAAmB,EAAc,EAAuB,CACzF,OAAO,eAAeC,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWC,CAAK,CAAC,EACrF,GAAI,CACFC,MAAcC,EAAG,KAAKF,EAAM,GAAGG,CAAI,CAAC,CACtC,QAAU,CACR,QAAQ,eAAeJ,EAAO,eAAe,CAC/C,CACF,CAMA,SAASK,EAAkB,EAAoB,CAG7CC,MAAYC,EAAaP,CAAK,CAAC,CACjC,CAEA,SAASO,EAAa,EAAoB,CACxC,IAAMC,EAAM,KAAKR,EAAM,OACjBS,EAAU,GAAGD,EAAI,MACjBE,EAAoB,CAAC,EAC3B,IAAK,IAAMT,KAAQD,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB,IAAMG,EAAK,QAAQ,IAAIF,EAAMO,CAAG,EAChC,GAAI,OAAOL,GAAO,WAAY,SAC9B,IAAMQ,EAAO,QAAQ,IAAIV,EAAMQ,CAAO,EACtC,GAAI,CACFV,EAAOI,EAAqBF,EAAMD,EAAOW,IAAS,IAAA,GAAY,CAACX,CAAK,EAAI,CAACW,EAAMX,CAAK,CAAC,CACvF,OAASY,EAAO,CACdF,EAAO,KAAKE,CAAK,CACnB,CACF,CACA,GAAM,CAACC,GAASH,EAChB,GAAIA,EAAO,SAAW,EAAG,MAAMG,EAC/B,GAAIH,E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zD,EAEA,OADAiB,EAAG,iBAAiBC,EAAMF,EAAUD,CAAO,MAC9B,CACXE,EAAG,oBAAoBC,EAAMF,EAAUD,CAAO,CAChD,CACF,CA6BA,SAAgBmB,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASN,EAAUZ,EAAIC,EAAMP,EAASsB,IAAa,GAAMlB,IAAY,EAAI,EAE3EoB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
1
+ {"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","dispatchDelegated","batch","key","event","dataKey","errors","node","fn","data","untrack","error","first","isListenerObject","handler","listen","listener","run","el","name","options","bindListenerObject","object","capture","chainEvents","handlers","installDelegate","known","target","delegateEvents","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","tuple","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"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":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAkB,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AMsB,EAAO,KAAKjB,IAGlB,GACEkB,IACC,CAACF,GAAS1B,IAAS,IAAA,KACpB,CAACc,GACDxB,EAAiB,KAAKoB,CAAI,GAC1B,QAAQ,IAAID,EAAIkB,CAAI,IAAM,IAAA,GAC1B,CACAV,EAAgBP,EAAMa,EAAmBd,CAAE,CAAC,EAC5C,IAAMb,EAAU,GAAG+B,EAAK,MAIxB,OAHA,QAAQ,IAAIlB,EAAIkB,EAAM5B,CAAE,EACpB2B,EAAO,QAAQ,IAAIjB,EAAIb,EAASI,CAAI,EACnC,QAAQ,eAAeS,EAAIb,CAAO,MAC1B,CACP,QAAQ,IAAIa,EAAIkB,CAAI,IAAM5B,IAC5B,QAAQ,eAAeU,EAAIkB,CAAI,EAC/B,QAAQ,eAAelB,EAAIb,CAAO,EAEtC,CACF,CACA,OAAOU,EAAOG,EAAIC,EAAO,GAAUX,EAAG,KAAKU,EAAI,GAAIiB,EAAQ,CAAC1B,EAAML,CAAK,EAAI,CAACA,CAAK,CAAE,EAAGmB,CAAO,CAC/F,CA6BA,SAAgBe,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASL,EAAUhB,EAAIC,EAAML,EAASuB,IAAa,GAAMd,IAAY,EAAI,EAE3EgB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
@@ -1,2 +1,2 @@
1
- import{leaves as e}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{reconcileNodes as n}from"./internal/reconcile.js";import{onCleanup as r,useRenderEffect as i}from"@shadow-js/core";import{addCleanup as a,createComputation as o,currentOwner as s,disposeOwner as c,readComputation as l}from"@shadow-js/core/extend";const u=/* @__PURE__ */ new WeakMap;function d(e){return e instanceof Document?e:e.ownerDocument??document}function f(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function p(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function m(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}const h=/* @__PURE__ */ new WeakMap;function g(t,n){let r=[];for(let i of e(t,`SHADOW_INSERT_CYCLE`,n))if(i!=null&&typeof i!=`boolean`){if(i instanceof DocumentFragment){let e=h.get(i)??[...i.childNodes];h.set(i,e);for(let t of e)r.push(t)}else r.push(i instanceof Node?i:String(i))}return r}function _(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!f(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function v(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&f(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=_(e);let t=o.get(n)?.pop();t===void 0&&(t=d(e.parent).createTextNode(n),p(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function y(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}const b=/* @__PURE__ */ new WeakMap;function x(e,t){let n=b.get(e)??/* @__PURE__ */ new Set;b.set(e,n.add(t)),r(()=>{n.delete(t)})}function S(e,t){let r=e.parent,i=e.nodes.filter(e=>e.parentNode===r),a=y(e,i.at(-1)),o=i[0];t.length===0&&o!==void 0&&(e.marker=o.previousSibling),n(r,i,t,a),e.nodes=t,m(e,t),b.get(r)?.forEach(e=>{e()})}function C(e,t){S(e,v(e,t))}function w(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=typeof t==`string`?t:String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&f(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=d(e.parent).createTextNode(r);p(e,t),e.parent.insertBefore(t,y(e,void 0)),e.nodes=[t];return}}C(e,g(t))}function T(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i of g(t))typeof i==`string`||r.has(i)||i.parentNode!==e||(r.add(i),n.push(i));return n}function E(e,t,n){let r=n===void 0?[]:T(e,n),i={parent:e,anchor:t,marker:r.length>0?r[0]?.previousSibling??null:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&p(i,e);return i}function D(e){let t=e.parent,n=u.get(t);e.owner=s(),u.set(t,e);let r=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||y(n,n.nodes.at(-1))!==r)return;let i=N(t,r);n.anchor=e.marker=i,n.owner&&a(n.owner,()=>i.remove())}function O(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop();for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function k(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;return{begin(){n=/* @__PURE__ */ new Set},call(r){n.add(r);let i=t.get(r);return i===void 0&&(i=o({kind:`memo`,fn:()=>r(),allowWrites:!0,owner:e}),t.set(r,i)),l(i)},prune(){for(let[e,r]of t)n.has(e)||(t.delete(e),c(r))}}}function A(e,t,n){if(!O(t))return w(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n===!0&&D(e),i(typeof t==`function`?t:()=>t,t=>{if(r=t,O(t)){let n=k(s());i(()=>{n.begin();let e=g(t,n.call);return n.prune(),e},t=>{C(e,t)})}else w(e,t)}),r}function j(e,t,n){let r=e.nodes.filter(t=>t.parentNode===e.parent);for(let e of r)n(e);e.parent=t,e.marker=r[0]?.previousSibling??t.lastChild}function M(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function N(e,t){let n=d(e).createTextNode(``);return e.insertBefore(n,t),n}function P(e,n,r,i){let a=r??null;return A(E(e,a,i===void 0?t.current.takeRegion(e,a):i),n,a===null)}export{N as anchor,A as bindRegion,E as createRegion,P as insert,j as moveRegion,M as removeRegion,x as watchCommits};
1
+ import{leaves as e}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{keepFocus as n,reconcileNodes as r}from"./internal/reconcile.js";import{onCleanup as i,useRenderEffect as a}from"@shadow-js/core";import{addCleanup as o,createComputation as s,currentOwner as c,disposeOwner as l,readComputation as u}from"@shadow-js/core/extend";const d=/* @__PURE__ */ new WeakMap;function f(e){return e instanceof Document?e:e.ownerDocument??document}function p(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function m(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function h(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}const g=/* @__PURE__ */ new WeakMap;function _(t,n){let r=[];for(let i of e(t,`SHADOW_INSERT_CYCLE`,n))if(i!=null&&typeof i!=`boolean`){if(i instanceof DocumentFragment){let e=g.get(i)??[...i.childNodes];g.set(i,e);for(let t of e)r.push(t)}else r.push(i instanceof Node?i:String(i))}return r}function v(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!p(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function y(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&p(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=v(e);let t=o.get(n)?.pop();t===void 0&&(t=f(e.parent).createTextNode(n),m(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function b(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}const x=/* @__PURE__ */ new WeakMap;function S(e,t){let n=x.get(e)??/* @__PURE__ */ new Set;x.set(e,n.add(t)),i(()=>{n.delete(t)})}function C(e,t){let n=y(e,t),i=e.parent,a=e.nodes.filter(e=>e.parentNode===i),o=a[0],s=b(e,a.at(-1));n.length===0&&o!==void 0&&(e.marker=o.previousSibling),r(i,a,n,s),e.nodes=n,h(e,n),x.get(i)?.forEach(e=>{e()})}function w(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&p(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=f(e.parent).createTextNode(r);m(e,t),e.parent.insertBefore(t,b(e,void 0)),e.nodes=[t];return}}C(e,_(t))}function T(e,t,n){let r=[];if(n!==void 0){let t=/* @__PURE__ */ new Set;for(let i of _(n))typeof i==`string`||t.has(i)||i.parentNode!==e||(t.add(i),r.push(i))}let i={parent:e,anchor:t,marker:r.length>0?r[0].previousSibling:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&m(i,e);return i}function E(e){let t=e.parent,n=d.get(t);e.owner=c(),d.set(t,e);let r=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||b(n,n.nodes.at(-1))!==r)return;let i=j(t,r);n.anchor=e.marker=i,n.owner&&o(n.owner,()=>i.remove())}function D(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop();for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function O(e,t,n){if(!D(t))return w(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n===!0&&E(e),a(typeof t==`function`?t:()=>t,t=>{if(r=t,D(t)){let n=c(),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,o=e=>{i.add(e);let t=r.get(e);return t===void 0&&(t=s({kind:`memo`,fn:()=>e(),allowWrites:!0,owner:n}),r.set(e,t)),u(t)};a(()=>{i=/* @__PURE__ */ new Set;let e=_(t,o);for(let[e,t]of r)i.has(e)||(r.delete(e),l(t));return e},t=>{C(e,t)})}else w(e,t)}),r}function k(e,t,r){let i=e.nodes.filter(t=>t.parentNode===e.parent);n(e.parent,()=>{for(let e of i)r(e)}),e.parent=t,e.marker=i[0]?.previousSibling??t.lastChild}function A(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function j(e,t){let n=f(e).createTextNode(``);return e.insertBefore(n,t),n}function M(e,n,r,i){let a=r??null;return O(T(e,a,i===void 0?t.current.takeRegion(e,a):i),n,a===null)}export{j as anchor,O as bindRegion,T as createRegion,M as insert,k as moveRegion,A as removeRegion,S as watchCommits};
2
2
  //# sourceMappingURL=insert.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","reconcileRegion","attached","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","createCallCache","memos","touched","fn","createComputation","readComputation","disposeOwner","bindRegion","value","latest","ordered","useRenderEffect","cache","moveRegion","move","removeRegion","before","insert","resolvedAnchor","claims"],"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":"A,qWA+CA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IAAKA,EAAM,IAAIG,CAAI,EACpCH,IAAUG,IAAM,EAAO,sBAAQ,IAAI,IAAI,CAACH,EAAOG,CAAI,CAAC,EAC/D,CAGA,SAASC,EAAW,EAAgB,EAA6B,CAC/D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tB,CACF,CACF,MACEiC,EAAYzC,EAAQ0C,CAAG,CAE3B,CAAC,EACMyB,CACT,CAYA,SAAgBI,EAAW,EAAgB,EAAc,EAAkC,CACzF,IAAMpC,EAAWnC,EAAO,MAAM,OAAQ,GAASH,EAAK,aAAeG,EAAO,MAAM,EAChF,IAAK,IAAMH,KAAQsC,EAAUqC,EAAK3E,CAAI,EAEtC,EAA6B,OAASkC,EACtC,EAAO,OAASI,EAAS,EAAE,EAAE,iBAAmBJ,EAAO,SACzD,CAOA,SAAgB0C,EAAa,EAAsB,CACjD,IAAK,IAAM5E,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgBwD,EAAO,EAAc,EAA2B,CAC9D,IAAMnD,EAAON,EAAWmC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAa7B,EAAMwE,CAAM,EACzBxE,CACT,CAwCA,SAAgByE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOiB,EADQlB,EAAahB,EAAQ6C,EADlC9B,IAAY,IAAA,GAAY+B,EAAO,QAAQ,WAAW9C,EAAQ6C,CAAc,EAAI9B,CAEvD,EAAGoB,EAAOU,IAAmB,IAAI,CAC1D,C"}
1
+ {"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","commit","next","attached","first","end","reconcileNodes","commitValue","raw","created","createRegion","initial","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","bindRegion","value","latest","ordered","useRenderEffect","owner","memos","touched","fn","createComputation","readComputation","disposeOwner","moveRegion","keepFocus","move","removeRegion","before","insert","resolvedAnchor","claims"],"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":"A,oXA+CA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IAAKA,EAAM,IAAIG,CAAI,EACpCH,IAAUG,IAAM,EAAO,sBAAQ,IAAI,IAAI,CAACH,EAAOG,CAAI,CAAC,EAC/D,CAGA,SAASC,EAAW,EAAgB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ASkC,EACtC,EAAO,OAASK,EAAS,EAAE,EAAE,iBAAmBL,EAAO,SACzD,CAOA,SAAgBuC,EAAa,EAAsB,CACjD,IAAK,IAAMzE,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgBqD,EAAO,EAAc,EAA2B,CAC9D,IAAMhD,EAAON,EAAWmC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAa7B,EAAMqE,CAAM,EACzBrE,CACT,CAwCA,SAAgBsE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOU,EADQZ,EAAaZ,EAAQ0C,EADlC7B,IAAY,IAAA,GAAY8B,EAAO,QAAQ,WAAW3C,EAAQ0C,CAAc,EAAI7B,CAEvD,EAAGY,EAAOiB,IAAmB,IAAI,CAC1D,C"}
@@ -1,2 +1,2 @@
1
- function e(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function t(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t],a=0,o=r.length;for(;a<o;){let t=a+o>>1;e[r[t]]<n?a=t+1:o=t}i[t]=r[a-1]??-1,r[a]=t}let a=r.at(-1)??-1;for(;a!==-1;)n[e[a]-t]=1,a=i[a]}function n(n,r,i,a){let o=r.length,s=i.length,c=0;for(;c<o&&c<s&&r[c]===i[c];)c+=1;let l=o,u=s;for(;l>c&&u>c&&r[l-1]===i[u-1];)--l,--u;if(l===c&&u===c)return;let d=u<s?i[u]??null:a;if(u===c){for(let t=c;t<l;t+=1)e(n,r[t]);return}let f=/* @__PURE__ */ new Map;for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&f.set(t,e)}let p=[];for(let t=c;t<l;t+=1){let i=r[t],a=f.get(i);a===void 0?e(n,i):p.push(a)}if(p.length===0){for(let e of i.slice(c,u))n.insertBefore(e,d);return}let m=new Uint8Array(u-c);t(p,c,m);let h=typeof n.moveBefore==`function`,g=d;for(let e=u-1;e>=c;--e){let t=i[e];m[e-c]!==1&&(h&&t.parentNode===n?n.moveBefore(t,g):n.insertBefore(t,g)),g=t}}export{n as reconcileNodes};
1
+ function e(e,t){let n=e.getRootNode(),r=n.activeElement;t(),r!=null&&n.activeElement!==r&&r.focus({preventScroll:!0})}function t(e,t){t!==void 0&&t.parentNode===e&&e.removeChild(t)}function n(e,t,n){let r=[],i=e.map(()=>-1);for(let t=0;t<e.length;t+=1){let n=e[t],a=0,o=r.length;for(;a<o;){let t=a+o>>1;e[r[t]]<n?a=t+1:o=t}i[t]=r[a-1]??-1,r[a]=t}let a=r.at(-1)??-1;for(;a!==-1;)n[e[a]-t]=1,a=i[a]}function r(e,r,i,a){let o=r.length,s=i.length,c=0;for(;c<o&&c<s&&r[c]===i[c];)c+=1;let l=o,u=s;for(;l>c&&u>c&&r[l-1]===i[u-1];)--l,--u;if(l===c&&u===c)return;let d=u<s?i[u]??null:a;if(u===c){for(let n=c;n<l;n+=1)t(e,r[n]);return}let f=/* @__PURE__ */ new Map;for(let e=c;e<u;e+=1){let t=i[e];t!==void 0&&f.set(t,e)}let p=[];for(let n=c;n<l;n+=1){let i=r[n],a=f.get(i);a===void 0?t(e,i):p.push(a)}if(p.length===0){for(let t of i.slice(c,u))e.insertBefore(t,d);return}let m=new Uint8Array(u-c);n(p,c,m);let h=typeof e.moveBefore==`function`,g=e.getRootNode(),_=h?null:g.activeElement,v=d;for(let t=u-1;t>=c;--t){let n=i[t];m[t-c]!==1&&(h&&n.parentNode===e?e.moveBefore(n,v):e.insertBefore(n,v)),v=n}_!=null&&g.activeElement!==_&&_.focus({preventScroll:!0})}export{e as keepFocus,r as reconcileNodes};
2
2
  //# sourceMappingURL=reconcile.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconcile.js","names":["removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise. Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n}\n"],"mappings":"AAMA,SAASA,EAAW,EAAc,EAA8B,CAC1DC,IAAS,IAAA,IAAaA,EAAK,aAAeC,GAAQA,EAAO,YAAYD,CAAI,CAC/E,CAOA,SAASE,EAAsB,EAA2B,EAAgB,EAAyB,CAEjG,IAAMC,EAAkB,CAAC,EACnBC,EAAqBC,EAAO,QAAU,EAAE,EAC9C,IAAK,IAAIC,EAAQ,EAAGA,EAAQD,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAME,EAAQF,EAAOC,GACjBE,EAAM,EACNC,EAAON,EAAM,OACjB,KAAOK,EAAMC,GAAM,CACjB,IAAMC,EAAUF,EAAMC,GAAS,EACjBJ,EAAOF,EAAMO,IACfH,EAAO,EAAMG,EAAS,EAC7B,EAAOA,CACd,CAEA,EAASJ,GAASH,EAAMK,EAAM,IAAM,GACpC,EAAMA,GAAOF,CACf,CACA,IAAIK,EAASR,EAAM,GAAG,EAAE,GAAK,GAC7B,KAAOQ,IAAW,IAChB,EAAON,EAAOM,GAAqBC,GAAU,EAC7C,EAASR,EAASO,EAEtB,CAsCA,SAAgBE,EACd,EACA,EACA,EACA,EACM,CACN,IAAMC,EAAaC,EAAK,OAClBC,EAAaC,EAAK,OAEpBC,EAAO,EACX,KAAOA,EAAOJ,GAAcI,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K,aAAeC,EACjCA,EAA0B,WAAWD,EAAM4B,CAAU,EAClD3B,EAAO,aAAaD,EAAM4B,CAAU,GAE3C,EAAa5B,CACf,CACF,C"}
1
+ {"version":3,"file":"reconcile.js","names":["keepFocus","root","at","active","run","removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":"AAYA,SAAgBA,EAAU,EAAU,EAAuB,CACzD,IAAM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}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{IGNORED_KEYS as f,attributeName as p,eventPlan as m,isFlagAttribute as h}from"./internal/react-names.js";import{bindEvent as g}from"./events.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";function S(e){return typeof e!=`object`||!e?``:_(Reflect.get(e,`__html`))}const C=/^(?:__proto__|constructor|prototype)$/;function w(e){return e.length>2&&e.startsWith(`on`)}function T(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function E(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))C.test(T(a))||f.test(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function D(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,b(t))}function O(e,t,n,c,l){if(t===`ref`){if(D(c),typeof n==`function`){let t=n,r=b(()=>t(e));typeof r==`function`&&(c.refCleanup=r)}}else if(t===`autoFocus`)c.autoFocused||(c.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,l);else if(t===`style`)c.styleValue=s(e,n,c.styleValue);else if(t===`classList`)c.classListValue=o(e,a(n),c.classListValue);else if(w(t)){c.unbinders.get(t)?.(),c.unbinders.delete(t);let r=m(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=g(e,r.type,i,!0,r.capture);a!==void 0&&c.unbinders.set(t,a)}else t===`innerHTML`||t===`dangerouslySetInnerHTML`?e.innerHTML=t===`innerHTML`?_(n):S(n):t===`textContent`?e.textContent=_(n):!l&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?v(e,n):!l&&A.test(t)&&t in e?(M(e,t,n,l)&&Reflect.set(e,t,j.test(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=_(n))):k(e,t,n,l)}function k(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let s=p(i,o);h(s,a)?n(r,s,a):s.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,s,a):e(r,s,a)}}const A=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,j=/^(?:value|defaultValue)$/;function M(e,t,n,r){if(r||!A.test(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return j.test(t)?i!==_(n):i!==!!n}function N(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!M(e,a,o,r))&&(n.values.set(a,o),O(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),O(e,t,void 0,n,r))}function P(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=I();if(!r&&e.localName!==`textarea`){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),F(e,n,a)}L(e,i,n,a)}function F(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function I(){return{values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0}}function L(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbinders.values())e();r.unbinders.clear(),D(r)}),x(()=>E(t(),i),t=>{N(e,t,r,n)})}export{P as spread};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{IGNORED_KEYS as f,attributeName as p,eventPlan as m,isFlagAttribute as h}from"./internal/react-names.js";import{bindEvent as g}from"./events.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";const S=/^(?:__proto__|constructor|prototype)$/;function C(e){let t=e.unref;t!==void 0&&(e.unref=void 0,b(t))}function w(c,l,u,d,f){if(l===`ref`){if(C(d),typeof u==`function`){let e=u,t=b(()=>e(c));typeof t==`function`&&(d.unref=t)}}else if(l===`autoFocus`)d.focused||(d.focused=!0,r(c,u));else if(l===`class`||l===`className`)i(c,u,f);else if(l===`style`)d.styled=s(c,u,d.styled);else if(l===`classList`)d.listed=o(c,a(u),d.listed);else if(l.length>2&&l.startsWith(`on`)){d.unbind.get(l)?.(),d.unbind.delete(l);let e=m(l,c.localName,c.getAttribute(`type`)?.toLowerCase()??null),t=e.passive&&typeof u==`function`?{handleEvent:u,passive:!0}:u,n=g(c,e.type,t,!0,e.capture);n!==void 0&&d.unbind.set(l,n)}else if(l===`innerHTML`||l===`dangerouslySetInnerHTML`)c.innerHTML=_(l===`innerHTML`?u:typeof u==`object`&&u?Reflect.get(u,`__html`):void 0);else if(l===`textContent`)c.textContent=_(u);else if(!f&&(l===`value`||l===`defaultValue`)&&c instanceof HTMLSelectElement)v(c,u);else if(!f&&T.test(l)&&l in c)D(c,l,u,f)&&Reflect.set(c,l,E.test(l)?u??``:!!u),l===`value`&&c instanceof HTMLInputElement&&(c.defaultValue=_(u));else if(l.startsWith(`prop:`))Reflect.set(c,l.slice(5),u);else if(l.startsWith(`attr:`))e(c,l.slice(5),u);else if(l.startsWith(`bool:`))n(c,l.slice(5),u);else{let r=p(l,f);h(r,u)?n(c,r,u):r.startsWith(`xlink:`)?t(c,`http://www.w3.org/1999/xlink`,r,u):e(c,r,u)}}const T=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,E=/^(?:value|defaultValue)$/;function D(e,t,n,r){if(r||!T.test(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return E.test(t)?i!==_(n):i!==!!n}function O(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=A();if(!r&&e.localName!==`textarea`){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),k(e,n,a)}j(e,i,n,a)}function k(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function A(){return{values:/* @__PURE__ */ new Map,unbind:/* @__PURE__ */ new Map}}function j(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbind.values())e();r.unbind.clear(),C(r)}),x(()=>{let e=t(),n=[];if(typeof e!=`object`||!e)return n;let r,a=!1;for(let t of Object.keys(e))S.test(t.slice(t.indexOf(`:`)+1))||f.test(t)||(t===`children`?i&&(r=Reflect.get(e,t),a=!0):n.push([t,Reflect.get(e,t)]));return a&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n},t=>{let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(r.values.has(a)&&Object.is(r.values.get(a),o)&&!D(e,a,o,n))&&(r.values.set(a,o),w(e,a,o,r,n));for(let t of[...r.values.keys()])i.has(t)||(r.values.delete(t),w(e,t,void 0,r,n))})}export{O as spread};
2
2
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","applyEntries","current","spread","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","onCleanup","useRenderEffect"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":"A,soBAcA,SAASA,EAAe,EAAwB,CAE9C,OADsB,OAAOC,GAAU,WAAnCA,EAAoD,GACjDC,EAAU,QAAQ,IAAID,EAAO,QAAQ,CAAC,CAC/C,CAGA,MAAME,EAAkB,wCAexB,SAASC,EAAW,EAAsB,CACxC,OAAOC,EAAI,OAAS,GAAKA,EAAI,WAAW,IAAI,CAC9C,CAGA,SAASC,EAAO,EAAqB,CACnC,IAAMC,EAAQF,EAAI,QAAQ,GAAG,EAC7B,OAAOE,IAAU,GAAKF,EAAMA,EAAI,MAAME,EAAQ,CAAC,CACjD,CAGA,SAASC,EAAY,EAAgB,EAA6C,CAChF,IAAMC,EAAoC,CAAC,EAC3C,GAAsB,OAAOC,GAAU,WAAnCA,EAA6C,OAAOD,EACxD,IAAIR,EACAU,EAAW,GACf,IAAK,IAAMN,KAAO,OAAO,KAAKK,CAAK,EAC7BP,EAAgB,KAAKG,EAAOD,CAAG,CAAC,GAAKO,EAAa,KAAKP,CAAG,IAC1DA,IAAQ,WAGNQ,IACF,EAAQ,QAAQ,IAAIH,EAAOL,CAAG,EAC9B,EAAW,IAIfI,EAAQ,KAAK,CAACJ,EAAK,QAAQ,IAAIK,EAAOL,CAAG,CAAC,CAAC,GAG7C,OADIM,GAAY,CAACF,EAAQ,MAAM,CAACJ,KAASA,IAAQ,OAAO,GAAGI,EAAQ,KAAK,CAAC,QAASR,CAAK,CAAC,EACjFQ,CACT,CAGA,SAASK,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,WAClBD,IAAY,IAAA,KAChB,EAAM,WAAa,IAAA,GACnBE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIb,IAAQ,MAGV,IADAS,EAAcE,CA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AAG,CAAC,CACrE,CAAC,CACH,CAGA,SAAS2C,GAAwB,CAC/B,MAAO,CACL,uBAAQ,IAAI,IACZ,0BAAW,IAAI,IACf,WAAY,IAAA,GACZ,eAAgB,IAAA,GAChB,WAAY,IAAA,EACd,CACF,CAqBA,SAASS,EAAW,EAAa,EAAqB,EAAgB,EAA0B,CAC9F,IAAM5C,EAAWO,EAAG,YAAc,WAElCuC,MAAgB,CACd,IAAK,IAAM7B,KAAUd,EAAM,UAAU,OAAO,EAAGc,EAAO,EACtDd,EAAM,UAAU,MAAM,EACtBF,EAAcE,CAAK,CACrB,CAAC,EACD4C,MACQpD,EAAYuC,EAAK,EAAGlC,CAAQ,EACjC,GAAY,CACX+B,EAAaxB,EAAIX,EAASO,EAAOwC,CAAK,CACxC,CACF,CACF,C"}
1
+ {"version":3,"file":"spread.js","names":["FORBIDDEN_NAMES","runRefCleanup","cleanup","state","untrack","applyKey","key","value","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","plainText","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","spread","props","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","textarea","onCleanup","useRenderEffect","entries","hasValue","IGNORED_KEYS","current"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":"A,soBAWA,MAGMA,EAAkB,wCAexB,SAASC,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,MAClBD,IAAY,IAAA,KAChB,EAAM,MAAQ,IAAA,GACdE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIC,IAAQ,MAGV,IADAL,EAAcE,CAAK,EACf,OAAOI,GAAU,WAAY,CAC/B,IAAMC,EAAUD,EACVL,EAAUE,MAAcI,EAAQC,CAAE,CAAC,EACrC,OAAOP,GAAY,aAAY,EAAM,MAAQA,EACnD,OAGF,GAAII,IAAQ,YACLH,EAAM,UACT,EAAM,QAAU,GAChBO,EAAUD,EAAIF,CAAK,QAIvB,GAAID,IAAQ,SAAWA,IAAQ,YAC7BK,EAAWF,EAAIF,EAAOK,CAAG,OAG3B,GAAIN,IAAQ,QACV,EAAM,OAASO,EAAMJ,EAAgCF,EAAOJ,EAAM,MAAM,OAG1E,GAAIG,IAAQ,YACV,EAAM,OAASQ,EAAUL,EAAIM,EAASR,CAAK,EAAGJ,EAAM,MAAM,OAG5D,GAAIG,EAAI,OAAS,GAAKA,EAAI,WAAW,IAAI,EAAG,CAC1CH,EAAM,OAAO,IAAIG,CAAG,CAAC,GAAG,EACxBH,EAAM,OAAO,OAAOG,CAAG,EAEvB,IAAMU,EAAOC,EAAUX,EAAKG,EAAG,UAAWA,EAAG,aAAa,MAAM,CAAC,EAAE,YAAY,GAAK,IAAI,EAClFS,EACJF,EAAK,SAAW,OAAOT,GAAU,WAAa,CAAE,YAAaA,EAAO,QAAS,EAAK,EAAIA,EAClFY,EAASC,EAAUX,EAAIO,EAAK,KAAME,EAAS,GAAMF,EAAK,OAAO,EAC/DG,IAAW,IAAA,IAAWhB,EAAM,OAAO,IAAIG,EAAKa,CAAM,CAExD,MACA,GAAIb,IA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html|vbscript:)/;
22
22
  function assertAttributeName(name) {
23
23
  if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);
24
24
  }
25
- /** Removes C0 and C1 control characters (`\p{Cc}`), which browsers ignore inside a URL scheme. */
26
- function stripControls(text) {
27
- return text.replace(/\p{Cc}/gu, "");
28
- }
29
25
  /** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */
30
26
  function isUnsafeUrl(value) {
31
- return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());
27
+ return UNSAFE_URL_PREFIXES.test(value.replace(/\p{Cc}/gu, "").trim().toLowerCase());
32
28
  }
33
29
  /**
34
30
  * Reports whether writing `value` to the attribute `name` would run script: the URL check that
@@ -1 +1 @@
1
- {"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iBAAiB;;;;;AAMvB,MAAM,gBAAgB;;AAGtB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;AAGA,SAAS,YAAY,OAAwB;CAC3C,OAAO,oBAAoB,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;AAC3E;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,qBAAqB,MAAc,OAAwB;CACzE,MAAM,YAAY,KAAK,YAAY;CACnC,IAAI,CAAC,eAAe,KAAK,SAAS,GAAG,OAAO;CAE5C,OAAO,cAAc,WAAW,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,WAAW,IAAI,YAAY,KAAK;AACxF;;AAGA,SAAS,cAAc,WAAmB,OAA+B;CACvE,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,OAAO,OAAO,cAAc,KAAK,SAAS,IAAI,UAAU;CACtE,IAAI,UAAU,MAAM,OA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{"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,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IAAI,GAAG;EAEvC,SAAS,sBAAsB,gCAAgC,UAAU,aAAa;EACxF;CACF;CACA,IAAI,cAAc,MACZ;MAAA,GAAG,aAAa,SAAS,MAAM,MAAM,GAAG,aAAa,WAAW,IAAI;CAAA,OACnE,IAAI,GAAG,eAAe,WAAW,UAAU,SAAS,CAAC,MAAM,MAChE,GAAG,eAAe,WAAW,WAAW,IAAI;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,aAAa,IAAa,MAAc,OAAsB;CAC5E,oBAAoB,IAAI;CACxB,OAAO,IAAI,MAAM,MAAM,KAAK;AAC9B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,IAAa,WAAmB,MAAc,OAAsB;CACjG,oBAAoB,IAAI;CACxB,OAAO,IAAI,cAAc,KAAK,OAAO,WAAW,MAAM,KAAK;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,IAAa,MAAc,OAAsB;CAChF,oBAAoB,IAAI;CACxB,GAAG,gBAAgB,MAAM,QAAQ,KAAK,CAAC;AACzC"}
@@ -2,16 +2,6 @@ import { leaves, unwrap } from "./internal/accessor.js";
2
2
  import { cssValueText } from "./internal/css-units.js";
3
3
  import { HTML_NS } from "./internal/names.js";
4
4
  // src/class-style.ts
5
- /** `map` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied. */
6
- function resolveMap(map) {
7
- let out = map;
8
- for (const key of Object.keys(map)) {
9
- if (typeof map[key] !== "function") continue;
10
- if (out === map) out = { ...map };
11
- out[key] = unwrap(map[key]);
12
- }
13
- return out;
14
- }
15
5
  /** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */
16
6
  function collectClasses(root, parts) {
17
7
  for (const item of leaves(root, "className(): a class array contains itself.")) if (typeof item === "string") {
@@ -105,7 +95,13 @@ function enabled(map, key) {
105
95
  * @since 1.0.0
106
96
  */
107
97
  function classList(el, value, prev) {
108
- const next = resolveMap(value ?? {});
98
+ const source = value ?? {};
99
+ let next = source;
100
+ for (const key of Object.keys(source)) {
101
+ if (typeof source[key] !== "function") continue;
102
+ if (next === source) next = { ...source };
103
+ next[key] = unwrap(source[key]);
104
+ }
109
105
  const before = prev ?? {};
110
106
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
111
107
  for (const key of keys) {
@@ -198,7 +194,8 @@ function style(el, value, prev) {
198
194
  }
199
195
  return resolved;
200
196
  }
201
- const next = resolveMap({ ...resolved });
197
+ const next = { ...resolved };
198
+ for (const key of Object.keys(next)) next[key] = unwrap(next[key]);
202
199
  const before = asRecord(prev) ?? {};
203
200
  if (typeof prev === "string" || Array.isArray(prev)) el.style.cssText = "";
204
201
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);