@shadow-js/web 1.0.4 → 1.0.6
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.
- package/CHANGELOG.md +14 -0
- package/README.md +1 -1
- package/dist/dev/class-style.js +6 -1
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +4 -4
- package/dist/dev/control-flow/no-hydration.js +1 -1
- package/dist/dev/control-flow/portal.js +1 -1
- package/dist/dev/element.js +2 -2
- package/dist/dev/extend.js +6 -6
- package/dist/dev/head/use-head.js +1 -1
- package/dist/dev/head/validate.js +1 -1
- package/dist/dev/hydration.js +21 -13
- package/dist/dev/hydration.js.map +1 -1
- package/dist/dev/index.d.ts +5 -5
- package/dist/dev/index.js +6 -6
- package/dist/dev/insert.js +12 -1
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/jsx/global.d.ts +2 -2
- package/dist/dev/jsx/html.d.ts +1 -1
- package/dist/dev/jsx/intrinsic.d.ts +1 -1
- package/dist/dev/jsx/mathml.d.ts +1 -1
- package/dist/dev/jsx/svg.d.ts +1 -1
- package/dist/dev/jsx-runtime.d.ts +3 -3
- package/dist/dev/render.js +22 -11
- package/dist/dev/render.js.map +1 -1
- package/dist/dev/select-value.d.ts +3 -1
- package/dist/dev/select-value.js +11 -1
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/class-style.js +1 -1
- package/dist/dev/server/element.js +3 -3
- package/dist/dev/server/form-controls.js +1 -1
- package/dist/dev/server/hydration-script.js +1 -1
- package/dist/dev/server/portals.js +1 -1
- package/dist/dev/server/raw-text.js +1 -1
- package/dist/dev/server/render.js +2 -2
- package/dist/dev/server/stream.js +3 -3
- package/dist/dev/spread.js +12 -4
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +3 -3
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/no-hydration.js +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/extend.js +1 -1
- package/dist/prod/head/use-head.js +1 -1
- package/dist/prod/head/validate.js +1 -1
- package/dist/prod/hydration.js +1 -1
- package/dist/prod/hydration.js.map +1 -1
- package/dist/prod/index.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/render.js +1 -1
- package/dist/prod/render.js.map +1 -1
- package/dist/prod/select-value.js +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/class-style.js +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/hydration-script.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/raw-text.js +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/element.js +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/extend.js +1 -1
- package/dist/server/head/use-head.js +1 -1
- package/dist/server/head/validate.js +1 -1
- package/dist/server/hydration.js +1 -1
- package/dist/server/hydration.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/render.js +1 -1
- package/dist/server/render.js.map +1 -1
- package/dist/server/select-value.js +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/class-style.js +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/hydration-script.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/raw-text.js +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js +1 -1
- package/dist/server-dev/class-style.js +6 -1
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +1 -1
- package/dist/server-dev/control-flow/portal.js +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/element.js +1 -1
- package/dist/server-dev/extend.js +6 -6
- package/dist/server-dev/head/use-head.js +1 -1
- package/dist/server-dev/head/validate.js +1 -1
- package/dist/server-dev/hydration.js +21 -13
- package/dist/server-dev/hydration.js.map +1 -1
- package/dist/server-dev/index.js +6 -6
- package/dist/server-dev/insert.js +12 -1
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/render.js +22 -11
- package/dist/server-dev/render.js.map +1 -1
- package/dist/server-dev/select-value.js +11 -1
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/class-style.js +1 -1
- package/dist/server-dev/server/element.js +3 -3
- package/dist/server-dev/server/form-controls.js +1 -1
- package/dist/server-dev/server/hydration-script.js +1 -1
- package/dist/server-dev/server/portals.js +1 -1
- package/dist/server-dev/server/raw-text.js +1 -1
- package/dist/server-dev/server/render.js +2 -2
- package/dist/server-dev/server/stream.js +3 -3
- package/dist/server-dev/spread.js +12 -4
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +3 -3
- package/package.json +3 -3
package/dist/prod/events.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,EAAoB,CAG7CC,MAAY,CACV,IAAMC,EAAM,KAAKC,EAAM,OACjBC,EAAU,GAAGF,EAAI,MACjBG,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB,IAAMI,EAAK,QAAQ,IAAID,EAAMJ,CAAG,EAChC,GAAI,OAAOK,GAAO,WAAY,SAC9B,IAAMC,EAAO,QAAQ,IAAIF,EAAMF,CAAO,EACtC,GAAI,CACF,OAAO,eAAeD,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWG,CAAK,CAAC,EACrFG,MACGF,EAAe,KAAKD,EAAM,GAAIE,IAAS,IAAA,GAAY,CAACL,CAAK,EAAI,CAACK,EAAML,CAAK,CAAE,CAC9E,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,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
|
+
{"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,MAAM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AI,OAAOA,GAAY,WAC5B,MAAU,UAGJ,sBACN,EAIF,IAAMsB,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"}
|
package/dist/prod/extend.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isUnsafeUrlAttribute as e}from"./attributes.js";import{element as t}from"./element.js";import{bindRegion as n,createRegion as r,moveRegion as i,removeRegion as a}from"./insert.js";import{claimElement as o,claimPortal as s,isClaiming as c,takeRegion as l,withoutClaiming as u}from"./internal/claim.js";import{warnOnce as d}from"./internal/diagnostics.js";import{claims as f}from"./internal/hydration-hooks.js";import{childScope as p,createRootScope as m,currentScope as h,enterComponent as g,nextKey as _,resourceKey as v,withScope as y}from"./internal/hydration-scope.js";import{HTML_NS as b,MATHML_NS as x,SVG_NS as S}from"./internal/names.js";import{PortalContext as C}from"./internal/portal-context.js";import{reconcileNodes as w}from"./internal/reconcile.js";import{StreamContext as T}from"./internal/stream-context.js";export{b as HTML_NS,x as MATHML_NS,C as PortalContext,S as SVG_NS,T as StreamContext,n as bindRegion,p as childScope,o as claimElement,s as claimPortal,f as claims,r as createRegion,m as createRootScope,h as currentScope,t as element,g as enterComponent,c as isClaiming,e as isUnsafeUrlAttribute,i as moveRegion,_ as nextKey,w as reconcileNodes,a as removeRegion,v as resourceKey,l as takeRegion,d as warnOnce,y as withScope,u as withoutClaiming};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHeadRegistry as e}from"./registry.js";import{
|
|
1
|
+
import{createHeadRegistry as e}from"./registry.js";import{ServerHeadContext as t}from"./server-head.js";import{createDomHeadSink as n}from"./sink.js";import{normalizeTags as r}from"./validate.js";import{createRoot as i,getOwner as a,isServer as o,untrack as s,useContext as c,useEffect as l,useRenderEffect as u,useSignal as d}from"@shadow-js/core";const f=/* @__PURE__ */ new WeakMap;function p(t){return i(()=>{let[r,i]=d(0),a=e(()=>{i(e=>e+1)}),o=n(t);return l(()=>(r(),a.winners()),e=>{o(e)}),a},{detached:!0})}function m(e){let t=f.get(e);if(t!==void 0)return t;let n=p(e);return f.set(e,n),n}function h(e){if(o){let n=a()===null?null:c(t);n!==null&&n.add(r(s(()=>typeof e==`function`?e():e)));return}if(a()===null)return;let n=m(document);u(()=>r(typeof e==`function`?e():e),e=>n.add(e))}export{h as useHead};
|
|
2
2
|
//# sourceMappingURL=use-head.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{isUnsafeUrlAttribute as e}from"../attributes.js";import"../internal/diagnostics.js";const t=`data-shadow-head`,n=`data-shadow-key`,r=/* @__PURE__ */ new Set([`title`,`meta`,`link`,`style`,`base`]),i=/^[a-zA-Z_][a-zA-Z0-9_:.-]*$/,a=/* @__PURE__ */ new Set([t,n]),o=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),s=[`name`,`property`,`http-equiv`,`charset`],c=/* @__PURE__ */ new Set([`og:image`,`og:video`,`og:audio`,`og:locale:alternate`,`og:email`,`og:phone_number`,`og:fax_number`,`article:tag`,`article:author`,`book:author`,`book:tag`,`music:album`,`music:song`,`music:musician`,`music:creator`,`video:actor`,`video:director`,`video:writer`,`video:tag`,`fb:admins`,`twitter:image`]),l=/* @__PURE__ */ new Set([`alternate`,`author`,`archives`,`assets`,`bookmarks`,`me`,`apple-touch-startup-image`]),u=/* @__PURE__ */ new Set([`preload`,`modulepreload`,`prefetch`,`preconnect`,`dns-prefetch`,`stylesheet`]);function d(e){return r.has(e)}function f(e){return e.map(e=>`${e.length}:${e}`).join(``)}function p(e){if(e!=null&&e!==!1){if(e===!0)return``;if(typeof e==`string`)return e;if(typeof e==`number`)return String(e);throw TypeError(`SHADOW_HEAD_ATTRIBUTE_VALUE`)}}function m(t,n){if(n==null)return/* @__PURE__ */ new Map;if(typeof n!=`object`||Array.isArray(n))throw TypeError(`SHADOW_HEAD_PROPS`);let r=/* @__PURE__ */ new Map;for(let s of Object.keys(n)){if(!i.test(s))throw TypeError(`SHADOW_HEAD_ATTRIBUTE_NAME`);let c=s.toLowerCase();if(c.startsWith(`on`))throw TypeError(`SHADOW_HEAD_EVENT_ATTRIBUTE`);if(a.has(c))throw TypeError(`SHADOW_HEAD_RESERVED`);if(o.has(c))continue;let l=p(Reflect.get(n,s));l!==void 0&&(e(c,l)?`${c}${t}`:r.set(c,l))}return r}function h(e,t){if(t!=null){if(e!==`title`&&e!==`style`)throw TypeError(`SHADOW_HEAD_NO_CHILDREN`);if(typeof t!=`string`)throw TypeError(`SHADOW_HEAD_TEXT`);return t}}function g(e,t){if(t!=null){if(e!==`style`)throw TypeError(`SHADOW_HEAD_STYLE_KEY`);if(typeof t!=`string`||t===``)throw TypeError(`SHADOW_HEAD_KEY`);return t}}function _(e){if(e===void 0)return;let t=e.toLowerCase().split(/\s+/).filter(e=>e!==``);if(t.length!==0)return t.sort().join(` `)}function v(e){let t=e.get(`media`)??``;for(let n of s){let r=e.get(n);if(r!==void 0)return n===`charset`?f([`meta`,n]):c.has(r)?f([`meta`,n,r,t,e.get(`content`)??``]):f([`meta`,n,r,t])}}function y(e){let t=_(e.get(`rel`));if(t!==void 0){if(t.split(` `).some(e=>e===`icon`||e.endsWith(`-icon`)))return f([`link`,`icon`,t,e.get(`sizes`)??``,e.get(`type`)??``]);if(t===`canonical`)return f([`link`,`canonical`]);if(u.has(t))return f([`link`,`resource`,t,e.get(`href`)??``,e.get(`as`)??``]);if(l.has(t))return f([`link`,`multi`,t,e.get(`href`)??``,e.get(`hreflang`)??``,e.get(`media`)??``,e.get(`type`)??``])}}function b(e,t,n){return e===`title`?f([`title`]):e===`base`?f([`base`]):e===`style`?n===void 0?void 0:f([`style`,n]):e===`meta`?v(t):y(t)}function x(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`SHADOW_HEAD_TAG`);let t=Reflect.get(e,`tag`);if(typeof t!=`string`||!d(t))throw TypeError(`SHADOW_HEAD_TAG_NAME`);let n=m(t,Reflect.get(e,`props`)),r=h(t,Reflect.get(e,`children`)),i=g(t,Reflect.get(e,`key`));return{tag:t,attributes:[...n],text:r,key:i,identity:b(t,n,i)}}function S(e){return e==null||e===!1?[]:Array.isArray(e)?e.map(e=>x(e)):[x(e)]}function C(e){let t=e.localName;if(!d(t))return;let n=/* @__PURE__ */ new Map;for(let t of Array.from(e.attributes))t.name!==`data-shadow-head`&&t.name!==`data-shadow-key`&&n.set(t.name.toLowerCase(),t.value);return b(t,n,e.getAttribute(`data-shadow-key`)??void 0)}export{n as HEAD_KEY,t as HEAD_MARKER,b as identityOf,C as identityOfElement,d as isHeadTagName,x as normalizeTag,S as normalizeTags};
|
|
2
2
|
//# sourceMappingURL=validate.js.map
|
package/dist/prod/hydration.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{attachRootErrors as e}from"./control-flow/root-errors.js";import{bindRegion as t,createRegion as n,removeRegion as r}from"./insert.js";import{beginClaiming as i,claimElement as a,claimPortal as o,endClaiming as s,isClaiming as c,liftedRegions as l,releaseUnclaimedPortals as u,takeRegion as d,withoutClaiming as f}from"./internal/claim.js";import{replayEarlyEvents as p}from"./internal/early-events.js";import{claims as m}from"./internal/hydration-hooks.js";import{createRootScope as h,resourceKey as g,withScope as _}from"./internal/hydration-scope.js";import{ResourceCacheContext as v,batch as y,createRoot as b,flushSync as x,runWithOwner as S,untrack as C}from"@shadow-js/core";import{withHydration as w}from"@shadow-js/core/extend";function T(e){let t=/* @__PURE__ */ new Set;return{key:g,read(n){if(!t.has(n)&&Object.hasOwn(e,n))return t.add(n),{value:e[n]}},track(){}}}function E(e){let t=e instanceof Document?e:e.ownerDocument;if(t===null)return;t.body!==null&&u(t.body);let n=t.createTreeWalker(e,NodeFilter.SHOW_COMMENT),r=[];for(;n.nextNode();){let e=n.currentNode;(e.data===`[`||e.data===`]`)&&r.push(e)}for(let e of r)e.remove()}function D(u,g,D={}){if(c())throw Error(`SHADOW_HYDRATE_RUNNING`);let O=/* @__PURE__ */ new Map,k=g instanceof Element?[g]:[];for(let e of[...k,...Array.from(g.querySelectorAll(`[data-hk]`))]){let t=e.getAttribute(`data-hk`);t!==null&&O.set(t,e)}i(O,D.onRecoverableError);let A={claimElement:a,takeRegion:d,liftedRegions:l,claimPortal:o,isClaiming:c,withoutClaiming:f},j=m.current;m.current=A;let M=T(D.data??{}),N=n(g,null,Array.from(g.childNodes)),P,F=!1,I=()=>{F||(F=!0,P?.(),r(N))};try{w(()=>y(()=>_(h(D.renderId),()=>S(D.owner??null,()=>b(n=>{P=n,e(D),v({value:M,get children(){return t(N,C(u)),null}})}))))),x()}catch(e){try{P?.()}catch(t){throw AggregateError([e,t],`SHADOW_HYDRATE_ERRORS`)}throw e}finally{s(),m.current=j}return p(),E(g),I}export{D as hydrate};
|
|
2
2
|
//# sourceMappingURL=hydration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration.js","names":["dataCache","used","resourceKey","key","data","stripLeftovers","doc","container","releaseUnclaimedPortals","walker","stale","comment","hydrate","isClaiming","registry","roots","element","beginClaiming","options","passClaims","previousClaims","claims","cache","region","createRegion","stop","withHydration","batch","withScope","createRootScope","runWithOwner","createRoot","attachRootErrors","ResourceCacheContext","bindRegion","untrack","code","
|
|
1
|
+
{"version":3,"file":"hydration.js","names":["dataCache","used","resourceKey","key","data","stripLeftovers","doc","container","releaseUnclaimedPortals","walker","stale","comment","hydrate","isClaiming","registry","roots","element","beginClaiming","options","passClaims","previousClaims","claims","cache","region","createRegion","stop","disposed","teardown","removeRegion","withHydration","batch","withScope","createRootScope","runWithOwner","createRoot","dispose","attachRootErrors","ResourceCacheContext","bindRegion","untrack","code","flushSync","error","cleanupError","endClaiming","replayEarlyEvents"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n stop = dispose;\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n }),\n ),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a hydration that throws, so the root must not stay alive. Its\n // effects and listeners go; the server's markup stays, so the page keeps what the server rendered.\n try {\n stop?.();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"hydrate() failed and so did its teardown.\" : \"SHADOW_HYDRATE_ERRORS\",\n );\n }\n throw error;\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n return teardown;\n}\n"],"mappings":"A,wuBAsDA,SAASA,EAAU,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB,MAAO,CACL,IAAKC,EACL,KAAK,EAAK,CACR,GAAI,GAAK,IAAIC,CAAG,GAAM,OAAO,OAAOC,EAAMD,CAAG,EAE7C,OADAF,EAAK,IAAIE,CAAG,EACL,CAAE,MAAOC,EAAKD,EAAK,CAC5B,EACA,OAAQ,CAER,CACF,CACF,CAMA,SAASE,EAAe,EAAuB,CAC7C,IAAMC,EAAMC,aAAqB,SAAWA,EAAYA,EAAU,cAClE,GAAID,IAAQ,KAAM,OACdA,EAAI,OAAS,MAAME,EAAwBF,EAAI,IAAI,EACvD,IAAMG,EAASH,EAAI,iBAAiBC,EAAW,WAAW,YAAY,EAChEG,EAAmB,CAAC,EAC1B,KAAOD,EAAO,SAAS,GAAG,CACxB,IAAME,EAAUF,EAAO,aACnBE,EAAQ,OAAS,KAAOA,EAAQ,OAAS,MAAKD,EAAM,KAAKC,CAAO,CACtE,CACA,IAAK,IAAMA,KAAWD,EAAOC,EAAQ,OAAO,CAC9C,CAgCA,SAAgBC,EACd,EACA,EACA,EAA0B,CAAC,EACf,CACZ,GAAIC,EAAW,EACb,MAAU,MACsD,wBAChE,EACF,IAAMC,kBAAW,IAAI,IACfC,EAAmBR,aAAqB,QAAU,CAACA,CAAS,EAAI,CAAC,EACvE,IAAK,IAAMS,IAAW,CAAC,GAAGD,EAAO,GAAG,MAAM,KAAKR,EAAU,iBAAiB,WAAW,CAAC,CAAC,EAAG,CACxF,IAAMJ,EAAMa,EAAQ,aAAa,SAAS,EACtCb,IAAQ,MAAMW,EAAS,IAAIX,EAAKa,CAAO,CAC7C,CACAC,EAAcH,EAAUI,EAAQ,kBAAkB,EAElD,IAAMC,EAAqB,CACzB,eACA,aACA,gBACA,cACA,aACA,iBACF,EACMC,EAAiBC,EAAO,QAC9B,EAAO,QAAUF,EACjB,IAAMG,EAAQtB,EAAUkB,EAAQ,MAAQ,CAAC,CAAC,EACpCK,EAASC,EAAajB,EAAW,KAAM,MAAM,KAAKA,EAAU,UAAU,CAAC,EACzEkB,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaL,CAAM,EACrB,EACA,GAAI,CAMFM,MACEC,MACEC,EAAUC,EAAgBd,EAAQ,QAAQ,MACxCe,EAAaf,EAAQ,OAAS,SAC5BgB,EAAY,GAAY,CACtB,EAAOC,EACPC,EAAiBlB,CAAO,EACxBmB,EAAqB,CACnB,MAAOf,EACP,IAAI,UAAW,CAEb,OADAgB,EAAWf,EAAQgB,EAAQC,CAAI,CAAC,EACzB,IACT,CACF,CAAC,CACH,CAAC,CACH,CACF,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFjB,IAAO,CACT,OAASkB,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACoC,uBAC1D,CACF,CACA,MAAMD,CACR,QAAU,CACRE,EAAY,EACZ,EAAO,QAAUxB,CACnB,CAGA,OAFAyB,EAAkB,EAClBxC,EAAeE,CAAS,EACjBoB,CACT,C"}
|
package/dist/prod/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{classList as i,className as a,setStyleProperty as o,style as s}from"./class-style.js";import{createComponent as c}from"./component.js";import{Activity as l}from"./control-flow/activity.js";import{Show as u}from"./control-flow/show.js";import{ClientOnly as d}from"./control-flow/client-only.js";import{
|
|
1
|
+
import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{classList as i,className as a,setStyleProperty as o,style as s}from"./class-style.js";import{createComponent as c}from"./component.js";import{Activity as l}from"./control-flow/activity.js";import{Show as u}from"./control-flow/show.js";import{ClientOnly as d}from"./control-flow/client-only.js";import{derived as f}from"./derived.js";import{element as p}from"./element.js";import{addEventListener as m,chainEvents as h,clearDelegatedEvents as g,delegateEvents as _}from"./events.js";import{hydrate as v}from"./hydration.js";import{anchor as y,insert as b}from"./insert.js";import{Dynamic as x,createDynamic as S}from"./control-flow/dynamic.js";import{ErrorBoundary as C}from"./control-flow/error-boundary.js";import{For as w}from"./control-flow/for.js";import{Fragment as T}from"./control-flow/fragment.js";import{Index as E}from"./control-flow/index-list.js";import{lazy as D}from"./control-flow/lazy.js";import{NoHydration as O}from"./control-flow/no-hydration.js";import{Portal as k}from"./control-flow/portal.js";import{SuspenseList as A}from"./control-flow/suspense-list.js";import{Suspense as j}from"./control-flow/suspense.js";import{Match as M,Switch as N}from"./control-flow/switch.js";import{effect as P,memo as F,refTo as I,use as L}from"./reactive.js";import{useHead as R}from"./head/use-head.js";import{Base as z,Link as B,Meta as V,Style as H,Title as U}from"./head/components.js";import{render as W}from"./render.js";import{preconnect as G,prefetchDNS as K,preinit as q,preinitModule as J,preload as Y,preloadModule as X}from"./resource-hints.js";import{setSelectValue as Z}from"./select-value.js";import{spread as Q}from"./spread.js";import{template as $}from"./template.js";import{ViewTransition as ee,startViewTransition as te}from"./view-transition.js";import{isDev as ne,isServer as re,mergeProps as ie}from"@shadow-js/core";export{l as Activity,z as Base,d as ClientOnly,x as Dynamic,C as ErrorBoundary,w as For,T as Fragment,E as Index,B as Link,M as Match,V as Meta,O as NoHydration,k as Portal,u as Show,H as Style,j as Suspense,A as SuspenseList,N as Switch,U as Title,ee as ViewTransition,m as addEventListener,y as anchor,r as autoFocus,h as chainEvents,i as classList,a as className,g as clearDelegatedEvents,c as createComponent,S as createDynamic,_ as delegateEvents,f as derived,P as effect,p as element,v as hydrate,b as insert,ne as isDev,re as isServer,D as lazy,F as memo,ie as mergeProps,G as preconnect,K as prefetchDNS,q as preinit,J as preinitModule,Y as preload,X as preloadModule,I as refTo,W as render,e as setAttribute,t as setAttributeNS,n as setBoolAttribute,Z as setSelectValue,o as setStyleProperty,Q as spread,te as startViewTransition,s as style,$ as template,L as use,R as useHead};
|
package/dist/prod/insert.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
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){x.set(e,(x.get(e)??/* @__PURE__ */ new Set).add(t))}function w(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()}),i.nodeName===`OPTGROUP`&&i.parentNode!==null&&x.get(i.parentNode)?.forEach(e=>{e()})}function T(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}}w(e,_(t))}function E(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 D(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=M(t,r);n.anchor=e.marker=i,n.owner&&o(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,t,n){if(!O(t))return T(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n===!0&&D(e),a(typeof t==`function`?t:()=>t,t=>{if(r=t,O(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=>{w(e,t)})}else T(e,t)}),r}function A(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 j(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function M(e,t){let n=f(e).createTextNode(``);return e.insertBefore(n,t),n}function N(e,n,r,i){let a=r??null;return k(E(e,a,i===void 0?t.current.takeRegion(e,a):i),n,a===null)}export{M as anchor,k as bindRegion,E as createRegion,N as insert,C as keepWatchingCommits,A as moveRegion,j as removeRegion,S as watchCommits};
|
|
2
2
|
//# sourceMappingURL=insert.js.map
|
package/dist/prod/insert.js.map
CHANGED
|
@@ -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","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,M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/B,IAAK,GAAM,CAACmD,EAAIlE,KAASgE,EACnBC,EAAQ,IAAIC,CAAE,IAClBF,EAAM,OAAOE,CAAE,EACfG,EAAarE,CAAI,GAEnB,OAAOW,CACT,EACC,GAAU,CACT0B,EAAOlC,EAAQQ,CAAK,CACtB,CACF,CACF,MACEgC,EAAYxC,EAAQyC,CAAG,CAE3B,CAAC,EACMgB,CACT,CAYA,SAAgBU,EAAW,EAAgB,EAAc,EAAkC,CACzF,IAAM/B,EAAWpC,EAAO,MAAM,OAAQ,GAASH,EAAK,aAAeG,EAAO,MAAM,EAEhFoE,EAAUpE,EAAO,WAAc,CAC7B,IAAK,IAAMH,KAAQuC,EAAUiC,EAAKxE,CAAI,CACxC,CAAC,EAED,EAA6B,OAASkC,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
|
+
{"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","keepWatchingCommits","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/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\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 // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\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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,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOU,EADQZ,EAAab,EAAQ2C,EADlC7B,IAAY,IAAA,GAAY8B,EAAO,QAAQ,WAAW5C,EAAQ2C,CAAc,EAAI7B,CAEvD,EAAGY,EAAOiB,IAAmB,IAAI,CAC1D,C"}
|
package/dist/prod/render.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{attachRootErrors as e}from"./control-flow/root-errors.js";import{bindRegion as t,createRegion as n,removeRegion as r}from"./insert.js";import{claims as i}from"./internal/hydration-hooks.js";import{withScope as a}from"./internal/hydration-scope.js";import{batch as o,createRoot as s,flushSync as c,untrack as l}from"@shadow-js/core";function u(u,d,f){let p=n(d,null,void 0),m,h=!1,g=()=>{h||(h=!0,m?.(),r(p))};try{i.current.withoutClaiming(()=>a(null,()=>o(()=>s(n=>{m=n,f!==void 0&&e(f),t(p,l(u))})))),c()}catch(e){try{g()}catch(t){throw AggregateError([e,t],`SHADOW_RENDER_ERRORS`)}throw e}return g}export{u as render};
|
|
2
2
|
//# sourceMappingURL=render.js.map
|
package/dist/prod/render.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","claims","withScope","batch","createRoot","options","attachRootErrors","bindRegion","untrack","code","
|
|
1
|
+
{"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","disposed","teardown","removeRegion","claims","withScope","batch","createRoot","dispose","options","attachRootErrors","bindRegion","untrack","code","flushSync","error","cleanupError"],"sources":["../../src/render.ts"],"sourcesContent":["import { batch, createRoot, flushSync, untrack } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link render}: the error reporters of the root.\n * @since 1.0.0\n */\nexport type RenderOptions = RootErrorOptions;\n\n/**\n * Mounts `code` into `container`. Creates an owner, inserts the output, flushes the effects, and\n * returns a dispose function that stops the owner and removes the nodes this call inserted. A\n * second render into the same container appends after the first.\n *\n * @param code Runs once, untracked, to build the tree (a component call, a node, text or an array).\n * Return an accessor (for example `() => count`) from it to make the root content reactive.\n * @param container Element, Document or DocumentFragment that receives the output.\n * @param options The root's error reporters (`onUncaughtError`, `onCaughtError`). Undefined sets\n * no reporter.\n * @returns A dispose function, safe to call more than once.\n * @example\n * import { createComponent, render } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const dispose = render(\n * () => createComponent(App, {}),\n * document.getElementById(\"root\") as Element,\n * );\n * dispose(); // stops the root and removes the text it inserted\n * @see hydrate\n * @since 1.0.0\n */\nexport function render(\n code: () => unknown,\n container: Element | Document | DocumentFragment,\n options?: RenderOptions,\n): () => void {\n const region = createRegion(container, null, undefined);\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n // One batch around the build: effects (and anything a resource's batch would flush mid-build)\n // wait until the whole tree exists, so a Suspense boundary knows what is pending before its\n // content's effects are considered.\n // A fresh root never consumes the enclosing hydration pass's nodes or key sequence.\n try {\n claims.current.withoutClaiming(() =>\n withScope(null, () =>\n batch(() =>\n createRoot((dispose) => {\n stop = dispose;\n // An error nothing else took ends here; with onUncaughtError it is reported instead of thrown.\n if (options !== undefined) attachRootErrors(options);\n // The component tree is built once; only accessors inside the result stay reactive.\n bindRegion(region, untrack(code));\n }),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a render that throws (an effect of the first flush failed),\n // so the root must not stay alive with its DOM and effects.\n try {\n teardown();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"render() failed and so did its teardown.\" : \"SHADOW_RENDER_ERRORS\",\n );\n }\n throw error;\n }\n return teardown;\n}\n"],"mappings":"A,mVAsCA,SAAgBA,EACd,EACA,EACA,EACY,CACZ,IAAMC,EAASC,EAAaC,EAAW,KAAM,IAAA,EAAS,EAClDC,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaN,CAAM,EACrB,EAKA,GAAI,CACFO,EAAO,QAAQ,oBACbC,EAAU,SACRC,MACEC,EAAY,GAAY,CACtB,EAAOC,EAEHC,IAAY,IAAA,IAAWC,EAAiBD,CAAO,EAEnDE,EAAWd,EAAQe,EAAQC,CAAI,CAAC,CAClC,CAAC,CACH,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFb,EAAS,CACX,OAASc,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACmC,sBACzD,CACF,CACA,MAAMD,CACR,CACA,OAAOb,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{keepWatchingCommits as e}from"./insert.js";const t=/* @__PURE__ */ new WeakMap;function n(e){return new Set(e.filter(e=>e!=null).map(String))}function r(e){return e==null?``:String(e)}function i(n,r){t.has(n)||e(n,()=>a(n,t.get(n))),t.set(n,r),a(n,r)}function a(e,t){if(e.multiple&&Array.isArray(t)){let r=n(t);for(let t of Array.from(e.options))t.selected=r.has(t.value)}else e.value=r(t)}export{r as plainText,i as setSelectValue};
|
|
2
2
|
//# sourceMappingURL=select-value.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select-value.js","names":["listed","value","item","plainText","setSelectValue","select","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`).\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"select-value.js","names":["bound","listed","value","item","plainText","setSelectValue","select","keepWatchingCommits","apply","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["import { keepWatchingCommits } from \"./insert\";\n\n/** The value each select was last given, which it takes again when its options change (see {@link setSelectValue}). */\nconst bound = new WeakMap<HTMLSelectElement, unknown>();\n\n/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`). The select\n * takes the value again whenever the nodes inside it change (the options of a `<For>`, a `<Show>` or an optgroup), so\n * options that arrive or are replaced after the value keep it selected.\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n // Options that arrive or are replaced after this call (a `<For>` inside the select) leave the browser's own pick, the\n // first option: the select takes its value again after each commit to its children, as React's does.\n if (!bound.has(select)) keepWatchingCommits(select, () => apply(select, bound.get(select)));\n bound.set(select, value);\n apply(select, value);\n}\n\nfunction apply(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"A,kDAGA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAO,EAAwC,CACtD,OAAO,IAAI,IAAIC,EAAM,OAAQ,GAASC,GAAS,IAA0B,CAAC,CAAC,IAAI,MAAM,CAAC,CACxF,CAGA,SAAgBC,EAAU,EAAwB,CAChD,OAAOF,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAwBA,SAAgBG,EAAe,EAA2B,EAAsB,CAGzEL,EAAM,IAAIM,CAAM,GAAGC,EAAoBD,MAAcE,EAAMF,EAAQN,EAAM,IAAIM,CAAM,CAAC,CAAC,EAC1FN,EAAM,IAAIM,EAAQJ,CAAK,EACvBM,EAAMF,EAAQJ,CAAK,CACrB,CAEA,SAASM,EAAM,EAA2B,EAAsB,CAC9D,GAAIF,EAAO,UAAY,MAAM,QAAQJ,CAAK,EAAG,CAC3C,IAAMO,EAASR,EAAOC,CAAK,EAC3B,IAAK,IAAMQ,KAAU,MAAM,KAAKJ,EAAO,OAAO,EAAG,EAAO,SAAWG,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACA,GAAO,MAAQN,EAAUF,CAAK,CAChC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{
|
|
1
|
+
import{cssValueText as e}from"../internal/css-units.js";import{invalid as t}from"./errors.js";import{escapeHtml as n,resolveValue as r}from"./escape.js";import{isSsrNode as i}from"./node.js";const a=/^(--[A-Za-z0-9_-]+|-?[a-z][a-z0-9-]*)$/;function o(e,n){let i=[[e]],a=[0],o=/* @__PURE__ */ new Set;for(;i.length>0;){let e=i.length-1,s=i[e],c=a[e]??0;if(s===void 0||c>=s.length){let e=i.pop();e!==void 0&&o.delete(e),a.pop();continue}a[e]=c+1;let l=r(s[c]);if(Array.isArray(l)){if(o.has(l))throw TypeError(`A class array contains itself.`);o.add(l),i.push(l),a.push(0)}else if(typeof l==`string`)l!==``&&n.push(l);else if(typeof l==`number`)l!==0&&!Number.isNaN(l)&&n.push(String(l));else if(typeof l==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a class name.`);else if(typeof l==`object`&&l){let e=l;for(let t of Object.keys(e))t!==``&&r(e[t])&&n.push(t)}}}function s(e){let t=r(e);if(typeof t==`string`)return t;if(t==null||t===!1)return``;let n=[];return o(t,n),n.join(` `)}function c(e){let t=s(e);return t===``?``:` class="${n(t)}"`}function l(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function u(e){let t=``,n=0,r=!1;for(let i of e)if(r)r=!1;else if(i===`\\`)r=!0;else if(t!==``)i===t&&(t=``);else if(i===`"`||i===`'`)t=i;else if(i===`(`)n+=1;else if(i===`)`)n=Math.max(0,n-1);else if((i===`;`||i===`{`||i===`}`)&&n===0)return!1;return t===``&&n===0&&!r}function d(n,o){let s=r(n);if(s!=null&&s!==!1){if(typeof s==`string`)s!==``&&o.push(s);else{if(typeof s!=`object`||i(s))throw t(`UNRECOGNIZED_INSERT_VALUE`,`A style must be a string, an object or an array of them.`);if(Array.isArray(s))for(let e of s){let t=r(e);if(Array.isArray(t))throw TypeError(`ssrStyle(): a style array may not contain another array.`);d(t,o)}else for(let n of Object.keys(s)){let i=l(n);if(!a.test(i))throw t(`INVALID_STYLE_PROPERTY`,`"${n}" is not a valid CSS property name.`);let c=r(Reflect.get(s,n));if(c==null||c===!1)continue;if(typeof c==`symbol`)throw t(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a style value.`);let d=e(i,c);u(d)&&o.push(`${i}:${d}`)}}}}function f(e){let t=[];return d(e,t),t.join(`;`)}function p(e){let t=f(e);return t===``?``:` style="${n(t)}"`}export{s as classText,o as collectClasses,u as isSafeCssValue,c as ssrClass,p as ssrStyle,f as styleText,l as toCssProperty};
|
|
2
2
|
//# sourceMappingURL=class-style.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n,isFlagAttribute as r}from"../internal/react-names.js";import{
|
|
1
|
+
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n,isFlagAttribute as r}from"../internal/react-names.js";import{isEventName as i,ssrAttribute as a}from"./attributes.js";import{classText as o,ssrStyle as s,styleText as c}from"./class-style.js";import{invalid as l}from"./errors.js";import{escape as u,escapeHtml as d,resolveValue as f}from"./escape.js";import{keepLeadingNewline as p,markSelectedOptions as m,textareaContent as h}from"./form-controls.js";import{SsrNode as g,isSsrNode as _}from"./node.js";import{rawElementContent as v}from"./raw-text.js";const y=/^[A-Za-z][A-Za-z0-9-]*$/,b=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`command`,`embed`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`children`,`ref`]);function S(e){if(typeof e==`object`&&e)return Reflect.get(e,`__html`)}function C(e,...t){if(!Array.isArray(e)||e.length!==t.length+1)throw TypeError(`ssr(): parts must have one more entry than there are holes.`);let n=e[0]??``;for(let r=0;r<t.length;r+=1){let i=t[r];if(typeof i==`string`)n+=i;else if(_(i))n+=i.t;else throw TypeError(`ssr(): a hole must be an escaped string or an SsrNode.`);n+=e[r+1]??``}return new g(n)}function w(e){if(typeof e!=`string`)throw TypeError(`ssrRaw(): the markup must be a string.`);return new g(e)}function T(){let t=e();return t===void 0?``:` data-hk="${d(t)}"`}function E(e,_,C=void 0,w=!1,E=!1){if(typeof e!=`string`||!y.test(e))throw l(`INVALID_TAG_NAME`,`"${String(e)}" is not a valid tag name.`);let A=e.toLowerCase(),j=A===`select`,M=A===`textarea`,N={},P=!1,F=!1,I=w?T():``,L=[],R=``,z;if(typeof _==`object`&&_)for(let e of Object.keys(_)){if(x.has(e)||t.test(e)||e===`ref`||e.startsWith(`on:`)||e.startsWith(`use:`)||e.startsWith(`prop:`)||i(e)||w&&e===`data-hk`)continue;let s=f(Reflect.get(_,e));if(e===`class`||e===`className`){let e=o(s);e!==``&&L.push(e)}else if(e===`classList`)O(s,L);else if(e===`style`)R=c(s);else if(e===`innerHTML`)z=k(s);else if(e===`dangerouslySetInnerHTML`)z=k(f(S(s)));else if((j||M)&&e===`value`)N.value=s,P=!0;else if((j||M)&&e===`defaultValue`)N.fallback=s,F=!0;else if(e.startsWith(`attr:`))I+=a(e.slice(5),s);else if(e.startsWith(`bool:`))I+=a(e.slice(5),s,!0);else if(e===`defaultValue`||e===`defaultChecked`){let t=e===`defaultValue`?`value`:`checked`;Object.hasOwn(_,t)||(I+=a(t,s,t===`checked`))}else{let t=n(e,E);I+=a(t,s,r(t,s))}}if(L.length>0&&(I+=` class="${d(L.join(` `))}"`),R!==``&&(I+=s(R)),b.has(A))return new g(`<${e}${I}>`);let B=!E&&(A===`script`||A===`style`),V=C===void 0?D(_):C,H=z===void 0?B?v(A,V):u(V):z;if(z===void 0&&(P||F)){let e=P?N.value:N.fallback;H=M?h(e):m(e,H)}else(M||A===`pre`||A===`listing`)&&z===void 0&&(H=p(H));return new g(`<${e}${I}>${H}</${e}>`)}function D(e){if(typeof e==`object`&&e)return Reflect.get(e,`children`)}function O(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))for(let n of Object.keys(e))n!==``&&f(Reflect.get(e,n))&&t.push(n)}function k(e){if(e==null)return``;if(_(e))return e.t;if(typeof e==`symbol`)throw l(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be innerHTML.`);return String(e)}export{C as ssr,E as ssrElement,T as ssrHydrationKey,w as ssrRaw};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{invalid as e}from"./errors.js";import{
|
|
2
|
-
`||t===`\r`?`\n${e}`:e}function c(e){return new
|
|
1
|
+
import{invalid as e}from"./errors.js";import{escape as t,escapeHtml as n,resolveValue as r}from"./escape.js";import{SsrNode as i}from"./node.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){return s(n(a(r(e))))}function s(e){let t=e.charAt(0);return t===`
|
|
2
|
+
`||t===`\r`?`\n${e}`:e}function c(e){return new i(o(e))}function l(e){let t=r(e);if(!Array.isArray(t))return{values:/* @__PURE__ */ new Set([a(t)]),many:!1};let n=/* @__PURE__ */ new Set;for(let e of t){let t=r(e);t!=null&&n.add(a(t))}return{values:n,many:!0}}const u=/[ \t\n\f\r]+/g,d=/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi,f={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},p=/<!--[\s\S]*?-->|<[^>]*>/g;function m(e){return e.replace(d,(e,t,n,r)=>{if(r!==void 0)return f[r.toLowerCase()]??e;let i=t===void 0?Number.parseInt(n??``,16):Number(t);return Number.isInteger(i)&&i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e})}function h(e,t){let n=``;for(let r=t;r<e.length;r+=1){let t=e.charAt(r);if(n!==``)t===n&&(n=``);else if(t===`"`||t===`'`)n=t;else if(t===`>`)return r}return-1}function g(e,t,n){n.lastIndex=t;let r=n.exec(e);return m(e.slice(t,r===null?e.length:r.index).replace(p,``)).replace(u,` `).trim()}function _(e,t){let n=``,r=0,i=0,a=!1,o=/* @__PURE__ */ RegExp(`\\s+([^\\s"'<>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+)))?`,`g`),s=/* @__PURE__ */ RegExp(`<\\/?(?:option|optgroup)(?=[\\s/>])`,`gi`);for(;;){let c=e.indexOf(`<option`,i);if(c===-1)break;let l=c+7;if(i=l,!/[\s/>]/.test(e.charAt(l)))continue;let u=h(e,l);if(u===-1)break;let d=e.slice(l,u),f,p=-1,_=-1;o.lastIndex=0;for(let e=o.exec(d);e!==null;e=o.exec(d)){let t=(e[1]??``).toLowerCase();t===`selected`?(p=e.index,_=e.index+e[0].length):t===`value`&&f===void 0&&(f=m(e[2]??e[3]??e[4]??``))}let v=(t.many||!a)&&t.values.has(f??g(e,u+1,s));if(v&&(a=!0),v&&p===-1){let t=d.endsWith(`/`)?d.length-1:d.length;n+=`${e.slice(r,l+t)} selected`,r=l+t}else!v&&p!==-1&&(n+=e.slice(r,l+p),r=l+_);i=u}return r===0?e:n+e.slice(r)}function v(e,n){return new i(y(e,t(n)))}function y(e,t){return _(t,l(e))}export{s as keepLeadingNewline,y as markSelectedOptions,v as ssrSelectValue,c as ssrTextArea,o as textareaContent};
|
|
3
3
|
//# sourceMappingURL=form-controls.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{DEFAULT_EARLY_EVENTS as e,captureScriptBody as t}from"../internal/early-events.js";import{ssrRaw as n}from"./element.js";const r=/^[A-Za-z0-9+/=_-]+$/;function i(n={}){let i=n.nonce,a=i!==void 0&&r.test(i)?` nonce="${i}"`:``,o=n.eventNames??e;return`<script${a}>${t(o)}<\/script>`}function a(e={}){return n(i(e))}export{a as HydrationScript,i as generateHydrationScript};
|
|
2
2
|
//# sourceMappingURL=hydration-script.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{
|
|
1
|
+
import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{PortalContext as n}from"../internal/portal-context.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new r(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}render(e,t){l(e,t,this)}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,r,a){if(a===null||n===void 0)return;let o=t(e(n),()=>i(r()));a.add(n,o)}function u(e,t){return n({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
|
|
2
2
|
//# sourceMappingURL=portals.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{invalid as e}from"./errors.js";import{
|
|
1
|
+
import{invalid as e}from"./errors.js";import{render as t,resolveValue as n}from"./escape.js";import{SsrNode as r,isSsrNode as i}from"./node.js";const a=/* @__PURE__ */ new Set([`script`,`style`]),o={script:/<\/(script)|<!--/gi,style:/<\/(style)/gi};function s(e,t){return t.replace(o[e],e=>e===`<!--`?`<\\u0021--`:`<\\/${e.slice(2)}`)}function c(e,n){return s(e.toLowerCase()===`script`?`script`:`style`,t(n,e=>e))}function l(e,t){let r=n(t);return i(r)?r.t:c(e,r)}function u(t,n){if(typeof t!=`string`||!a.has(t.toLowerCase()))throw e(`INVALID_RAW_TEXT_TAG`,`ssrRawText(): the tag must be script or style.`);return new r(c(t,n))}export{l as rawElementContent,c as rawTextContent,u as ssrRawText};
|
|
2
2
|
//# sourceMappingURL=raw-text.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{attachRootErrors as e}from"../control-flow/root-errors.js";import{runWithServerHead as t}from"../head/server-head.js";import{createRootScope as n,resourceKey as r,withScope as i}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as a,SsrError as o}from"./errors.js";import{escape as s}from"./escape.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(r,a,o,c,d,f){return e(f),l(d,()=>u({value:o,get children(){return t(c,()=>i(n(a),()=>s(r())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=c(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,t,n,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let t=r(e);return s.add(t),t},read:e=>n.has(e)?{value:n.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(n=>(i?.clear(),a?.clear(),{html:h(e,t,p,i,a,u),requested:s,tracked:c,errors:l,dispose:n}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new o(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,i,a,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,i,a,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new o(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:r,maxPasses:i}=C(t),s={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{s.canceled=!0,t(new o(`SSR_TIMEOUT`,`The render did not finish within ${r} ms.`))},Math.min(r,a))});try{let r=c(t?.portals);return await Promise.race([S(e,n,i,s,t?.head,r,m(t)),u])}finally{clearTimeout(l),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
|
|
2
2
|
//# sourceMappingURL=render.js.map
|