@shadow-js/web 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +2 -3
- package/dist/dev/attributes.js +1 -5
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.js +9 -12
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/element.js +8 -25
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +64 -80
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/insert.js +50 -68
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +2 -1
- package/dist/dev/internal/reconcile.js +19 -2
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/spread.js +47 -80
- package/dist/dev/spread.js.map +1 -1
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server-dev/attributes.js +1 -5
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +9 -12
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +64 -80
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/insert.js +50 -68
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +19 -2
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/spread.js +47 -80
- package/dist/server-dev/spread.js.map +1 -1
- package/package.json +2 -2
package/dist/dev/spread.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,SAAS,eAAe,OAAwB;CAC9C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,OAAO,UAAU,QAAQ,IAAI,OAAO,QAAQ,CAAC;AAC/C;;AAGA,MAAM,kBAAkB;;AAexB,SAAS,WAAW,KAAsB;CACxC,OAAO,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI;AAC9C;;AAGA,SAAS,OAAO,KAAqB;CACnC,MAAM,QAAQ,IAAI,QAAQ,GAAG;CAC7B,OAAO,UAAU,KAAK,MAAM,IAAI,MAAM,QAAQ,CAAC;AACjD;;AAGA,SAAS,YAAY,OAAgB,UAA6C;CAChF,MAAM,UAAoC,CAAC;CAC3C,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI;CACJ,IAAI,WAAW;CACf,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG;EACpC,IAAI,gBAAgB,KAAK,OAAO,GAAG,CAAC,KAAK,aAAa,KAAK,GAAG,GAAG;EACjE,IAAI,QAAQ,YAAY;GAGtB,IAAI,UAAU;IACZ,QAAQ,QAAQ,IAAI,OAAO,GAAG;IAC9B,WAAW;GACb;GACA;EACF;EACA,QAAQ,KAAK,CAAC,KAAK,QAAQ,IAAI,OAAO,GAAG,CAAC,CAAC;CAC7C;CACA,IAAI,YAAY,CAAC,QAAQ,MAAM,CAAC,SAAS,QAAQ,OAAO,GAAG,QAAQ,KAAK,CAAC,SAAS,KAAK,CAAC;CACxF,OAAO;AACT;;AAGA,SAAS,cAAc,OAA0B;CAC/C,MAAM,UAAU,MAAM;CACt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OA,SAAS,cAAc,IAAa,OAAgB,OAA0B;CAC5E,IAAI,SAAS,EAAE,cAAc,oBAAoB;CACjD,aAAa,UAAU;EACrB,MAAM,MAAM,MAAM,OAAO,IAAI,OAAO,IAAI,UAAU;EAClD,IAAI,MAAM,OAAO,IAAI,GAAG,GAAG,eAAe,IAAI,MAAM,OAAO,IAAI,GAAG,CAAC;CACrE,CAAC;AACH;;AAGA,SAAS,WAAwB;CAC/B,OAAO;EACL,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;AACF;;;;;;;;AASA,SAAgB,YAAY,IAAa,OAAgB,OAAsB;CAC7E,IAAI,UAAU,QAAS,OAAO,UAAU,YAAY,OAAO,UAAU,YAAa;CAClF,MAAM,QAAQ,SAAS;CACvB,cAAc,IAAI,OAAO,KAAK;CAC9B,WACE,UACO,OAAO,UAAU,aAAc,MAAwB,IAAI,OAClE,OACA,KACF;AACF;AAEA,SAAS,WAAW,IAAa,MAAqB,OAAgB,OAA0B;CAC9F,MAAM,WAAW,GAAG,cAAc;CAElC,gBAAgB;EACd,KAAK,MAAM,UAAU,MAAM,UAAU,OAAO,GAAG,OAAO;EACtD,MAAM,UAAU,MAAM;EACtB,cAAc,KAAK;CACrB,CAAC;CACD,sBACQ,YAAY,KAAK,GAAG,QAAQ,IACjC,YAAY;EACX,aAAa,IAAI,SAAS,OAAO,KAAK;CACxC,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"spread.js","names":[],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbind: Map<string, () => void>;\n styled?: unknown;\n listed?: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n unref?: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n focused?: boolean;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.unref;\n if (cleanup === undefined) return;\n state.unref = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.unref = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.focused) {\n state.focused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styled = style(el as HTMLElement | SVGElement, value, state.styled);\n return;\n }\n if (key === \"classList\") {\n state.listed = classList(el, asRecord(value), state.listed);\n return;\n }\n if (key.length > 2 && key.startsWith(\"on\")) {\n state.unbind.get(key)?.();\n state.unbind.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbind.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n // `dangerouslySetInnerHTML` holds `{ __html }`; null and undefined mean empty.\n el.innerHTML = plainText(\n key === \"innerHTML\"\n ? value\n : value !== null && typeof value === \"object\"\n ? Reflect.get(value, \"__html\")\n : undefined,\n );\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n // A `prop:` property, an `attr:` or `bool:` attribute, or an attribute under its React name. An `undefined`\n // value removes the attribute or resets the property, which is how a prop that disappeared is undone.\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return { values: new Map(), unbind: new Map() };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbind.values()) unbind();\n state.unbind.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n // Reads every prop except children, inside the render effect so each read is tracked.\n () => {\n const props = read();\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(\":\") + 1)) || IGNORED_KEYS.test(key))\n continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n },\n // Applies the entries that changed since the last run and undoes the ones that disappeared.\n // Unchanged values are skipped by identity, so only changed keys touch the DOM.\n (entries) => {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, isSVG)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, isSVG);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref\n // cleanup runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, isSVG);\n }\n },\n );\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAW;;AAGjB,MAAM,kBAAkB;;AAexB,SAAS,cAAc,OAA0B;CAC/C,MAAM,UAAU,MAAM;CACtB,IAAI,YAAY,KAAA,GAAW;CAC3B,MAAM,QAAQ,KAAA;CACd,QAAQ,OAAO;AACjB;;AAGA,SAAS,SACP,IACA,KACA,OACA,OACA,KACM;CACN,IAAI,QAAQ,OAAO;EAEjB,cAAc,KAAK;EACnB,IAAI,OAAO,UAAU,YAAY;GAC/B,MAAM,UAAU;GAChB,MAAM,UAAU,cAAc,QAAQ,EAAE,CAAC;GACzC,IAAI,OAAO,YAAY,YAAY,MAAM,QAAQ;EACnD;EACA;CACF;CACA,IAAI,QAAQ,aAAa;EACvB,IAAI,CAAC,MAAM,SAAS;GAClB,MAAM,UAAU;GAChB,UAAU,IAAI,KAAK;EACrB;EACA;CACF;CACA,IAAI,QAAQ,WAAW,QAAQ,aAAa;EAC1C,WAAW,IAAI,OAAO,GAAG;EACzB;CACF;CACA,IAAI,QAAQ,SAAS;EACnB,MAAM,SAAS,MAAM,IAAgC,OAAO,MAAM,MAAM;EACxE;CACF;CACA,IAAI,QAAQ,aAAa;EACvB,MAAM,SAAS,UAAU,IAAI,SAAS,KAAK,GAAG,MAAM,MAAM;EAC1D;CACF;CACA,IAAI,IAAI,SAAS,KAAK,IAAI,WAAW,IAAI,GAAG;EAC1C,MAAM,OAAO,IAAI,GAAG,CAAC,GAAG;EACxB,MAAM,OAAO,OAAO,GAAG;EAEvB,MAAM,OAAO,UAAU,KAAK,GAAG,WAAW,GAAG,aAAa,MAAM,CAAC,EAAE,YAAY,KAAK,IAAI;EACxF,MAAM,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AG;GACf,IACE,MAAM,OAAO,IAAI,GAAG,KACpB,OAAO,GAAG,MAAM,OAAO,IAAI,GAAG,GAAG,KAAK,KACtC,CAAC,YAAY,IAAI,KAAK,OAAO,KAAK,GAElC;GACF,MAAM,OAAO,IAAI,KAAK,KAAK;GAC3B,SAAS,IAAI,KAAK,OAAO,OAAO,KAAK;EACvC;EACA,KAAK,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,KAAK,CAAC,GAAG;GAC1C,IAAI,QAAQ,IAAI,GAAG,GAAG;GACtB,MAAM,OAAO,OAAO,GAAG;GAGvB,SAAS,IAAI,KAAK,KAAA,GAAW,OAAO,KAAK;EAC3C;CACF,CACF;AACF"}
|
package/dist/prod/attributes.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n=/^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/,r=/^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/,i=/^(?:javascript:|data:text\/html|vbscript:)/;function a(n){if(!t.test(n))throw e(n)}function o(e){return e.replace(/\p{Cc}/gu,``)
|
|
1
|
+
import{invalidAttributeName as e}from"./internal/diagnostics.js";const t=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,n=/^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/,r=/^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/,i=/^(?:javascript:|data:text\/html|vbscript:)/;function a(n){if(!t.test(n))throw e(n)}function o(e){return i.test(e.replace(/\p{Cc}/gu,``).trim().toLowerCase())}function s(e,t){let r=e.toLowerCase();return n.test(r)?r===`values`?t.split(`;`).some(o):o(t):!1}function c(e,t){return t==null?null:t===!1?r.test(e)?`false`:null:t===!0?r.test(e)?`true`:``:String(t)}function l(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function u(e,t,n,r){let i=n.toLowerCase(),a=c(i,r);a===null?t===null?e.removeAttribute(n):e.removeAttributeNS(t,l(n)):/^on./.test(i)||s(i,a)||(t===null?e.getAttribute(n)!==a&&e.setAttribute(n,a):e.getAttributeNS(t,l(n))!==a&&e.setAttributeNS(t,n,a))}function d(e,t,n){a(t),u(e,null,t,n)}function f(e,t,n,r){a(n),u(e,t===``?null:t,n,r)}function p(e,t,n){a(t),e.toggleAttribute(t,!!n)}export{a as assertAttributeName,s as isUnsafeUrlAttribute,d as setAttribute,f as setAttributeNS,p as setBoolAttribute};
|
|
2
2
|
//# sourceMappingURL=attributes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","stripControls","text","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAc,EAAsB,CAC3C,OAAOC,EAAK,QAAQ,WAAY,EAAE,CACpC,CAGA,SAASC,EAAY,EAAwB,CAC3C,OAAON,EAAoB,KAAKI,EAAcG,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,CAC3E,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYP,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKW,CAAS,EAE3BA,IAAc,SAAWF,EAAM,MAAM,GAAG,CAAC,CAAC,KAAKD,CAAW,EAAIA,EAAYC,CAAK,EAF1C,EAG9C,CAGA,SAASG,EAAc,EAAmB,EAA+B,CAIvE,OAHIH,GAAU,KAAoC,KAC9CA,IAAU,GAAcR,EAAc,KAAKU,CAAS,EAAI,QAAU,KAClEF,IAAU,GAAaR,EAAc,KAAKU,CAAS,EAAI,OAAS,GAC7D,OAAOF,CAAK,CACrB,CAGA,SAASI,EAAU,EAA2B,CAC5C,IAAMC,EAAQC,EAAU,QAAQ,GAAG,EACnC,OAAOD,IAAU,GAAKC,EAAYA,EAAU,MAAMD,EAAQ,CAAC,CAC7D,CAGA,SAASE,EAAO,EAAa,EAA0B,EAAmB,EAAsB,CAC9F,IAAML,EAAYI,EAAU,YAAY,EAClCR,EAAOK,EAAcD,EAAWF,CAAK,EACvCF,IAAS,KACPU,IAAc,KAAMC,EAAG,gBAAgBH,CAAS,EAC/CG,EAAG,kBAAkBD,EAAWJ,EAAUE,CAAS,CAAC,EAKvD,OAAO,KAAKJ,CAAS,GAErBD,EAAqBC,EAAWJ,CAAI,IAKpCU,IAAc,KACZC,EAAG,aAAaH,CAAS,IAAMR,GAAMW,EAAG,aAAaH,EAAWR,CAAI,EAC/DW,EAAG,eAAeD,EAAWJ,EAAUE,CAAS,CAAC,IAAMR,GAChEW,EAAG,eAAeD,EAAWF,EAAWR,CAAI,EAEhD,CA+BA,SAAgBY,EAAa,EAAa,EAAc,EAAsB,CAC5EhB,EAAoBC,CAAI,EACxBY,EAAOE,EAAI,KAAMd,EAAMK,CAAK,CAC9B,CAuBA,SAAgBW,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGjB,EAAoBC,CAAI,EACxBY,EAAOE,EAAID,IAAc,GAAK,KAAOA,EAAWb,EAAMK,CAAK,CAC7D,CAoBA,SAAgBY,EAAiB,EAAa,EAAc,EAAsB,CAChFlB,EAAoBC,CAAI,EACxBc,EAAG,gBAAgBd,EAAM,EAAQK,CAAM,CACzC,C"}
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","STRING_VALUED","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalidAttributeName","isUnsafeUrl","value","isUnsafeUrlAttribute","lowerName","attributeText","localPart","colon","qualified","commit","text","namespace","el","setAttribute","setAttributeNS","setBoolAttribute"],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":"A,iEAGA,MAAMA,EAA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EAAG,eAAeD,EAAWH,EAAWE,CAAI,EAEhD,CA+BA,SAAgBG,EAAa,EAAa,EAAc,EAAsB,CAC5Ef,EAAoBC,CAAI,EACxBU,EAAOG,EAAI,KAAMb,EAAMG,CAAK,CAC9B,CAuBA,SAAgBY,EAAe,EAAa,EAAmB,EAAc,EAAsB,CACjGhB,EAAoBC,CAAI,EACxBU,EAAOG,EAAID,IAAc,GAAK,KAAOA,EAAWZ,EAAMG,CAAK,CAC7D,CAoBA,SAAgBa,EAAiB,EAAa,EAAc,EAAsB,CAChFjB,EAAoBC,CAAI,EACxBa,EAAG,gBAAgBb,EAAM,EAAQG,CAAM,CACzC,C"}
|
package/dist/prod/class-style.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{leaves as e,unwrap as t}from"./internal/accessor.js";import{cssValueText as n}from"./internal/css-units.js";import{HTML_NS as r}from"./internal/names.js";function i(
|
|
1
|
+
import{leaves as e,unwrap as t}from"./internal/accessor.js";import{cssValueText as n}from"./internal/css-units.js";import{HTML_NS as r}from"./internal/names.js";function i(n,r){for(let i of e(n,`SHADOW_CLASS_CYCLE`))if(typeof i==`string`)i!==``&&r.push(i);else if(typeof i==`number`)i!==0&&!Number.isNaN(i)&&r.push(String(i));else if(typeof i==`object`&&i){let e=i;for(let n of Object.keys(e))t(e[n])&&n!==``&&r.push(n)}}function a(e){let n=t(e);if(typeof n==`string`)return n;if(n==null||n===!1)return null;let r=[];return i(n,r),r.join(` `)}function o(e,t,n){let r=a(t);r===null?e.removeAttribute(`class`):n?e.getAttribute(`class`)!==r&&e.setAttribute(`class`,r):e.className!==r&&(e.className=r)}function s(e,t){o(e,t,e.namespaceURI!==r)}function c(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function l(e,t){return Object.hasOwn(e,t)&&!!e[t]}function u(e,n,r){let i=n??{},a=i;for(let e of Object.keys(i))typeof i[e]==`function`&&(a===i&&(a={...i}),a[e]=t(i[e]));let o=r??{},s=/* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(a)]);for(let t of s){let n=l(a,t);if(n!==l(o,t))for(let r of t.split(/\s+/))r!==``&&e.classList.toggle(r,n)}return a}function d(e){if(e.startsWith(`--`))return e;let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);return t.startsWith(`ms-`)?`-${t}`:t}function f(e,t,r){let i=d(t);r==null||r===!1?e.style.removeProperty(i):e.style.setProperty(i,n(i,r))}function p(e,n,r){let i=t(n);if(i==null||i===!1)return e.removeAttribute(`style`),i;if(typeof i!=`object`)return e.style.cssText=String(i),i;if(Array.isArray(i)){e.style.cssText=``;for(let n of i){let r=t(n);if(typeof r==`string`)e.style.cssText+=`;${r}`;else if(r!=null&&r!==!1){if(typeof r!=`object`||Array.isArray(r))throw TypeError(`SHADOW_STYLE_ITEM`);p(e,r,{})}}return i}let a={...i};for(let e of Object.keys(a))a[e]=t(a[e]);let o=c(r)??{};(typeof r==`string`||Array.isArray(r))&&(e.style.cssText=``);let s=/* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(a)]);for(let t of s)Object.is(o[t],a[t])||f(e,t,a[t]);return a}export{o as applyClass,c as asRecord,u as classList,s as className,f as setStyleProperty,p as style,d as toCssProperty};
|
|
2
2
|
//# sourceMappingURL=class-style.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-style.js","names":["resolveMap","out","map","key","unwrap","collectClasses","item","leaves","root","parts","record","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","classList","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved","source"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** `map` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied. */\nfunction resolveMap(map: Record<string, unknown>): Record<string, unknown> {\n let out = map;\n for (const key of Object.keys(map)) {\n if (typeof map[key] !== \"function\") continue;\n if (out === map) out = { ...map };\n out[key] = unwrap(map[key]);\n }\n return out;\n}\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n const next = resolveMap(value ?? {});\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return resolved;\n }\n const next = resolveMap({ ...(resolved as Record<string, unknown>) });\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n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D,OADArB,EAAG,gBAAgB,OAAO,EACnBqB,EAET,GAAI,OAAOA,GAAa,SAEtB,MADA,GAAG,MAAM,QAAU,OAAOA,CAAQ,EAC3BA,EAET,GAAI,MAAM,QAAQA,CAAQ,EAAG,CAG3B,EAAG,MAAM,QAAU,GACnB,IAAK,IAAMC,KAAUD,EAAU,CAC7B,IAAM/B,EAAOF,EAAOkC,CAAM,EAC1B,GAAI,OAAOhC,GAAS,SAClB,EAAG,MAAM,SAAW,IAAIA,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAEF8B,EAAMpB,EAAIV,EAAM,CAAC,CAAC,CACpB,CACF,CACA,OAAO+B,CACT,CACA,IAAMd,EAAOvB,EAAW,CAAE,GAAIqC,CAAqC,CAAC,EAC9Db,EAASJ,EAASK,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMpB,KAAOuB,EACZ,OAAO,GAAGF,EAAOrB,GAAMoB,EAAKpB,EAAI,GACpC8B,EAAiBjB,EAAIb,EAAKoB,EAAKpB,EAAI,EAErC,OAAOoB,CACT,C"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":["collectClasses","item","leaves","root","parts","record","key","unwrap","classText","value","input","applyClass","text","el","svg","className","HTML_NS","asRecord","enabled","map","classList","source","next","before","prev","keys","now","token","toCssProperty","name","kebab","letter","setStyleProperty","property","cssValueText","style","resolved"],"sources":["../../src/class-style.ts"],"sourcesContent":["import { leaves, unwrap } from \"./internal/accessor\";\nimport { cssValueText } from \"./internal/css-units\";\nimport { HTML_NS } from \"./internal/names\";\n\n/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */\nfunction collectClasses(root: unknown, parts: string[]): void {\n const cycle = __DEV__ ? \"className(): a class array contains itself.\" : \"SHADOW_CLASS_CYCLE\";\n for (const item of leaves(root, cycle)) {\n if (typeof item === \"string\") {\n if (item !== \"\") parts.push(item);\n } else if (typeof item === \"number\") {\n if (item !== 0 && !Number.isNaN(item)) parts.push(String(item));\n } else if (item !== null && typeof item === \"object\") {\n const record = item as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (unwrap(record[key]) && key !== \"\") parts.push(key);\n }\n }\n }\n}\n\n/** Class text for `value`, or null when the class attribute must be removed. */\nfunction classText(input: unknown): string | null {\n const value = unwrap(input);\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined || value === false) return null;\n const parts: string[] = [];\n collectClasses(value, parts);\n return parts.join(\" \");\n}\n\n/**\n * Writes a class value. `svg` selects the attribute path, which SVG and MathML need because their\n * `className` is not a plain string.\n * @internal\n */\nexport function applyClass(el: Element, value: unknown, svg: boolean): void {\n const text = classText(value);\n if (text === null) {\n el.removeAttribute(\"class\");\n return;\n }\n if (svg) {\n if (el.getAttribute(\"class\") !== text) el.setAttribute(\"class\", text);\n } else if (el.className !== text) {\n el.className = text;\n }\n}\n\n/**\n * Replaces the whole `class` of an element: the helper compiled templates call for `class` and\n * `className`. HTML elements are written through `className`; SVG and MathML elements (whose\n * `className` is not a plain string) through the `class` attribute. The DOM is touched only when\n * the text changes.\n *\n * @param el Target element.\n * @param value A string is used as is. Arrays and objects are clsx-style: non-empty strings,\n * numbers other than `0` and `NaN`, nested arrays, and the keys of objects whose value is truthy,\n * joined with spaces. `null`, `undefined` and `false` remove the attribute. Accessors, also inside\n * arrays and as object values, are called (as on the server); the signals they read are tracked by\n * the effect that applies the class.\n * @throws TypeError `SHADOW_CLASS_CYCLE` when an array contains itself (directly or through a nested\n * array), and `SHADOW_INSERT_DEPTH` when an accessor returns accessors more than 10,000 levels deep.\n * @example\n * import { className } from \"@shadow-js/web\";\n *\n * const card = document.createElement(\"div\");\n * className(card, [\"card\", { \"card--active\": true, \"card--muted\": false }]);\n * card.className; // \"card card--active\"\n * @see classList\n * @since 1.0.0\n */\nexport function className(el: Element, value: unknown): void {\n applyClass(el, value, el.namespaceURI !== HTML_NS);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */\nfunction enabled(map: Record<string, unknown>, key: string): boolean {\n return Object.hasOwn(map, key) && Boolean(map[key]);\n}\n\n/**\n * Toggles individual classes from an object: the helper compiled templates call for `classList`.\n * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness\n * changed relative to `prev` are touched. A key may hold several space-separated names. Keys that\n * disappeared from `value` are switched off.\n *\n * @param el Target element.\n * @param value Map from class names to truthiness; a value that is an accessor is called. `undefined`\n * switches off every class `prev` had on.\n * @param prev The map returned by the previous call. Undefined (the first call) means no class was\n * on yet.\n * @returns The map now in effect (`value`, or `{}` for undefined; a copy with the accessors resolved\n * when `value` has any), to pass back as `prev` next time.\n * @example\n * import { classList } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"li\");\n * let prev = classList(el, { active: true, \"is-new pulse\": true });\n * prev = classList(el, { active: false }, prev); // removes active, is-new and pulse\n * @see className\n * @since 1.0.0\n */\nexport function classList(\n el: Element,\n value: Record<string, unknown> | undefined,\n prev?: Record<string, unknown>,\n): Record<string, unknown> {\n // `value` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied.\n const source = value ?? {};\n let next = source;\n for (const key of Object.keys(source)) {\n if (typeof source[key] !== \"function\") continue;\n if (next === source) next = { ...source };\n next[key] = unwrap(source[key]);\n }\n const before: Record<string, unknown> = prev ?? {};\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n // Own properties only: `next[\"constructor\"]` would otherwise read Object.prototype's function\n // and a class with that name could never be switched on.\n const now = enabled(next, key);\n const was = enabled(before, key);\n if (now === was) continue;\n for (const token of key.split(/\\s+/)) {\n if (token !== \"\") el.classList.toggle(token, now);\n }\n }\n return next;\n}\n\n/**\n * Converts a camelCase style name to a CSS property name. Custom properties are kept as they are,\n * and vendor prefixes map to `-webkit-` and `-ms-`.\n * @internal\n */\nexport function toCssProperty(name: string): string {\n if (name.startsWith(\"--\")) return name;\n const kebab = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n return kebab.startsWith(\"ms-\") ? `-${kebab}` : kebab;\n}\n\n/**\n * Sets or removes one inline style property: the helper compiled templates call for the `style:`\n * prefix. Other inline properties are left alone.\n *\n * @param el HTML or SVG element.\n * @param name CSS property in camelCase (`backgroundColor`, `msTransform` gives `-ms-transform`) or\n * kebab-case, or a custom property (`--accent`, kept as is).\n * @param value `null`, `undefined` and `false` remove the property. A number is in pixels, as in\n * React, unless it is `0`, the property is unitless (`opacity`, `zIndex`, `flexGrow`, `lineHeight`,\n * ...) or a custom property. Any other value is written as `String(value)`.\n * @example\n * import { setStyleProperty } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * setStyleProperty(el, \"marginTop\", 8); // margin-top: 8px\n * setStyleProperty(el, \"--accent\", \"rebeccapurple\");\n * setStyleProperty(el, \"opacity\", 0.5); // unitless\n * @see style\n * @since 1.0.0\n */\nexport function setStyleProperty(el: HTMLElement | SVGElement, name: string, value: unknown): void {\n const property = toCssProperty(name);\n if (value === null || value === undefined || value === false) {\n el.style.removeProperty(property);\n } else {\n el.style.setProperty(property, cssValueText(property, value));\n }\n}\n\n/**\n * Sets the inline style of an element: the helper compiled templates call for a `style` attribute.\n * An object is diffed against `prev` so that only changed properties are written, each with the\n * rules of {@link setStyleProperty}; properties that disappeared are removed.\n *\n * @param el HTML or SVG element.\n * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces\n * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `\"\"`\n * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it\n * on the server. `null`, `undefined` and `false` remove the `style` attribute. Accessors (the value,\n * array items and property values) are called, as on the server.\n * @param prev The value returned by the previous call. Undefined (the first call) diffs against an\n * empty style. When it is a string or an array, `cssText` is cleared before the object is written.\n * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise\n * `value` itself.\n * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a\n * value that is not a string or an object.\n * @example\n * import { style } from \"@shadow-js/web\";\n *\n * const el = document.createElement(\"div\");\n * let prev = style(el, { color: \"red\", width: 120 }); // width: 120px\n * prev = style(el, { color: \"blue\" }, prev); // writes color, removes width\n * @see setStyleProperty\n * @since 1.0.0\n */\nexport function style(el: HTMLElement | SVGElement, value: unknown, prev?: unknown): unknown {\n const resolved = unwrap(value);\n if (resolved === null || resolved === undefined || resolved === false) {\n el.removeAttribute(\"style\");\n return resolved;\n }\n if (typeof resolved !== \"object\") {\n el.style.cssText = String(resolved);\n return resolved;\n }\n if (Array.isArray(resolved)) {\n // Not diffed: a string in the array can set any property, so the whole style is written again, in\n // order (a later declaration wins, as on the server).\n el.style.cssText = \"\";\n for (const source of resolved) {\n const item = unwrap(source);\n if (typeof item === \"string\") {\n el.style.cssText += `;${item}`;\n } else if (item !== null && item !== undefined && item !== false) {\n if (typeof item !== \"object\" || Array.isArray(item)) {\n throw new TypeError(\n __DEV__ ? \"style(): an array holds only strings and objects.\" : \"SHADOW_STYLE_ITEM\",\n );\n }\n style(el, item, {});\n }\n }\n return resolved;\n }\n const next: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };\n for (const key of Object.keys(next)) next[key] = unwrap(next[key]);\n const before = asRecord(prev) ?? {};\n // What a string or an array wrote is unknown, so it is cleared before the object is written.\n if (typeof prev === \"string\" || Array.isArray(prev)) el.style.cssText = \"\";\n const keys = new Set([...Object.keys(before), ...Object.keys(next)]);\n for (const key of keys) {\n if (Object.is(before[key], next[key])) continue;\n setStyleProperty(el, key, next[key]);\n }\n return next;\n}\n"],"mappings":"A,iKAKA,SAASA,EAAe,EAAe,EAAuB,CAE5D,IAAK,IAAMC,KAAQC,EAAOC,EAAM,oBAAK,EACnC,GAAI,OAAOF,GAAS,SACdA,IAAS,IAAIG,EAAM,KAAKH,CAAI,OAC3B,GAAI,OAAOA,GAAS,SACrBA,IAAS,GAAK,CAAC,OAAO,MAAMA,CAAI,GAAGG,EAAM,KAAK,OAAOH,CAAI,CAAC,OACzD,GAAqB,OAAOA,GAAS,UAAjCA,EAA2C,CACpD,IAAMI,EAASJ,EACf,IAAK,IAAMK,KAAO,OAAO,KAAKD,CAAM,EAC9BE,EAAOF,EAAOC,EAAI,GAAKA,IAAQ,IAAIF,EAAM,KAAKE,CAAG,CAEzD,CAEJ,CAGA,SAASE,EAAU,EAA+B,CAChD,IAAMC,EAAQF,EAAOG,CAAK,EAC1B,GAAI,OAAOD,GAAU,SAAU,OAAOA,EACtC,GAAIA,GAAU,MAA+BA,IAAU,GAAO,OAAO,KACrE,IAAML,EAAkB,CAAC,EAEzB,OADAJ,EAAeS,EAAOL,CAAK,EACpBA,EAAM,KAAK,GAAG,CACvB,CAOA,SAAgBO,EAAW,EAAa,EAAgB,EAAoB,CAC1E,IAAMC,EAAOJ,EAAUC,CAAK,EACxBG,IAAS,KACXC,EAAG,gBAAgB,OAAO,EAGxBC,EACED,EAAG,aAAa,OAAO,IAAMD,GAAMC,EAAG,aAAa,QAASD,CAAI,EAC3DC,EAAG,YAAcD,IAC1B,EAAG,UAAYA,EAEnB,CAyBA,SAAgBG,EAAU,EAAa,EAAsB,CAC3DJ,EAAWE,EAAIJ,EAAOI,EAAG,eAAiBG,CAAO,CACnD,CAGA,SAAgBC,EAAS,EAAqD,CAC5E,GAAsB,OAAOR,GAAU,UAAnCA,GAA+C,OAAM,QAAQA,CAAK,EACtE,OAAOA,CACT,CAGA,SAASS,EAA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kCA,IAAa,GAE9D,OADAvB,EAAG,gBAAgB,OAAO,EACnBuB,EAET,GAAI,OAAOA,GAAa,SAEtB,MADA,GAAG,MAAM,QAAU,OAAOA,CAAQ,EAC3BA,EAET,GAAI,MAAM,QAAQA,CAAQ,EAAG,CAG3B,EAAG,MAAM,QAAU,GACnB,IAAK,IAAMf,KAAUe,EAAU,CAC7B,IAAMnC,EAAOM,EAAOc,CAAM,EAC1B,GAAI,OAAOpB,GAAS,SAClB,EAAG,MAAM,SAAW,IAAIA,SACnB,GAAIA,GAAS,MAA8BA,IAAS,GAAO,CAChE,GAAI,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,EAChD,MAAU,UACwD,mBAClE,EAEFkC,EAAMtB,EAAIZ,EAAM,CAAC,CAAC,CACpB,CACF,CACA,OAAOmC,CACT,CACA,IAAMd,EAAgC,CAAE,GAAIc,CAAqC,EACjF,IAAK,IAAM9B,KAAO,OAAO,KAAKgB,CAAI,EAAG,EAAKhB,GAAOC,EAAOe,EAAKhB,EAAI,EACjE,IAAMiB,EAASN,EAASO,CAAI,GAAK,CAAC,GAE9B,OAAOA,GAAS,UAAY,MAAM,QAAQA,CAAI,KAAG,EAAG,MAAM,QAAU,IACxE,IAAMC,kBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKF,CAAM,EAAG,GAAG,OAAO,KAAKD,CAAI,CAAC,CAAC,EACnE,IAAK,IAAMhB,KAAOmB,EACZ,OAAO,GAAGF,EAAOjB,GAAMgB,EAAKhB,EAAI,GACpC0B,EAAiBnB,EAAIP,EAAKgB,EAAKhB,EAAI,EAErC,OAAOgB,CACT,C"}
|
package/dist/prod/element.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{setAttribute as e,setBoolAttribute as t}from"./attributes.js";import{style as n}from"./class-style.js";import{nextKey as r}from"./internal/hydration-scope.js";import{claims as i}from"./internal/hydration-hooks.js";import{insert as a}from"./insert.js";import{isFlagAttribute as o}from"./internal/react-names.js";import{batch as s,untrack as c,useRenderEffect as l}from"@shadow-js/core";const u=/^[a-z][a-z0-9-]*$/i;function d(
|
|
1
|
+
import{setAttribute as e,setBoolAttribute as t}from"./attributes.js";import{style as n}from"./class-style.js";import{nextKey as r}from"./internal/hydration-scope.js";import{claims as i}from"./internal/hydration-hooks.js";import{insert as a}from"./insert.js";import{isFlagAttribute as o}from"./internal/react-names.js";import{batch as s,untrack as c,useRenderEffect as l}from"@shadow-js/core";const u=/^[a-z][a-z0-9-]*$/i;function d(d,f){if(!u.test(d)||d.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let p=f,m=i.current.claimElement(r())??document.createElement(d);for(let r of Object.keys(f))if(r!==`children`&&r!==`ref`){if(/^on[A-Z]/.test(r)){let e=p[r],t=Array.isArray(e),[n,i]=t?e:[e];typeof n==`function`&&m.addEventListener(r.slice(2).toLowerCase(),e=>{s(()=>c(()=>t?n.call(m,i,e):n.call(m,e)))})}else if(r===`style`){let e;l(()=>p[r],t=>{e=n(m,t,e)})}else l(()=>p[r],n=>{let i=r.toLowerCase();o(i,n)?t(m,i,n):e(m,r,n)})}let h=p.ref;return typeof h==`function`&&c(()=>h(m)),a(m,()=>p.children),m}export{d as element};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|
package/dist/prod/element.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":["TAG_PATTERN","
|
|
1
|
+
{"version":3,"file":"element.js","names":["TAG_PATTERN","element","tag","read","props","el","claims","nextKey","key","handler","tuple","fn","data","batch","untrack","event","applied","useRenderEffect","style","value","name","isFlagAttribute","setBoolAttribute","setAttribute","ref","\"ref\"","insert","\"children\""],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setBoolAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { isFlagAttribute } from \"./internal/react-names\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n if (/^on[A-Z]/.test(key)) {\n // Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n // receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n // untracked, as the event binding of `Dynamic` runs them.\n const handler = read[key];\n const tuple = Array.isArray(handler);\n // The tuple's data is read once, at bind time, like the handler.\n const [fn, data]: readonly unknown[] = tuple ? handler : [handler];\n if (typeof fn === \"function\") {\n el.addEventListener(key.slice(2).toLowerCase(), (event: Event): void => {\n batch(() => untrack(() => (tuple ? fn.call(el, data, event) : fn.call(el, event))));\n });\n }\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n // The server writes a boolean attribute by truthiness; the client does the same. A name\n // that is a flag has no React spelling, so lower case is its attribute name.\n const name = key.toLowerCase();\n if (isFlagAttribute(name, value)) setBoolAttribute(el, name, value);\n else setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":"A,wYAsBA,MAAMA,EAAc,qBAsCpB,SAAgBC,EAAQ,EAAa,EAAwB,CAC3D,GAAI,CAACD,EAAY,KAAKE,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAMC,EAAOC,EAiBPC,EAFUC,EAAO,QAAQ,aAAaC,EAAQ,CAEnC,GAAK,SAAS,cAAcL,CAAG,EAChD,IAAK,IAAMM,KAAO,OAAO,KAAKJ,CAAK,EACjC,GAAII,IAAQ,YAAcA,IAAQ,MAClC,IAAI,WAAW,KAAKA,CAAG,EAAG,CAIxB,IAAMC,EAAUN,EAAKK,GACfE,EAAQ,MAAM,QAAQD,CAAO,EAE7B,CAACE,EAAIC,GAA4BF,EAAQD,EAAU,CAACA,CAAO,EAC7D,OAAOE,GAAO,YAChBN,EAAG,iBAAiBG,EAAI,MAAM,CAAC,CAAC,CAAC,YAAY,EAAI,GAAuB,CACtEK,MAAYC,MAAeJ,EAAQC,EAAG,KAAKN,EAAIO,EAAMG,CAAK,EAAIJ,EAAG,KAAKN,EAAIU,CAAK,CAAE,CAAC,CACpF,CAAC,CAEL,MAAO,GAAIP,IAAQ,QAAS,CAE1B,IAAIQ,EACJC,MACQd,EAAKK,GACV,GAAU,CACT,EAAUU,EAAMb,EAAmBc,EAAOH,CAAO,CACnD,CACF,CACF,MACEC,MACQd,EAAKK,GACV,GAAU,CAGT,IAAMY,EAAOZ,EAAI,YAAY,EACzBa,EAAgBD,EAAMD,CAAK,EAAGG,EAAiBjB,EAAIe,EAAMD,CAAK,EAC7DI,EAAalB,EAAIG,EAAKW,CAAK,CAClC,CACF,CAAA,CAGJ,IAAMK,EAAMrB,EAAKsB,IAGjB,OAFI,OAAOD,GAAQ,YAAYV,MAAcU,EAAInB,CAAE,CAAC,EACpDqB,EAAOrB,MAAUF,EAAKwB,QAAW,EAC1BtB,CACT,C"}
|
package/dist/prod/events.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/,a=/* @__PURE__ */ new WeakMap;function o(
|
|
1
|
+
import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/,a=/* @__PURE__ */ new WeakMap;function o(t){e(()=>{let e=`$$${t.type}`,n=`${e}Data`,i=[];for(let a of t.composedPath()){if(t.cancelBubble)break;let o=Reflect.get(a,e);if(typeof o!=`function`)continue;let s=Reflect.get(a,n);try{Object.defineProperty(t,"currentTarget",{configurable:!0,get:()=>a}),r(()=>o.call(a,...s===void 0?[t]:[s,t]))}catch(e){i.push(e)}finally{Reflect.deleteProperty(t,`currentTarget`)}}let[a]=i;if(i.length===1)throw a;if(i.length>1)throw AggregateError(i,`SHADOW_EVENT_ERRORS`)})}function s(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function c(t,n,i,a){let o=t=>{e(()=>r(()=>i(t)))};return t.addEventListener(n,o,a),()=>{t.removeEventListener(n,o,a)}}function l(e,t,n,r){let{once:i,passive:a,signal:o}=n;return c(e,t,e=>n.handleEvent(e),{capture:n.capture===!0||r,once:i,passive:a,signal:o})}function u(...e){return function(t){for(let n of e)n.call(this,t)}}function d(e,t){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n)),!n.has(e)&&(n.add(e),t.addEventListener(e,o))}function f(e,t=globalThis.document){for(let n of e)d(n,t)}function p(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,o);a.delete(e)}}function m(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function h(e,t,n,r,a=!1){if(n==null||n===!1)return;if(s(n))return l(e,t,n,a);let o=n,u,f=!1;if(Array.isArray(n)&&typeof n[0]==`function`)o=n[0],u=n[1],f=!0;else if(typeof n!=`function`)throw TypeError(`SHADOW_EVENT_HANDLER`);let p=`$$${t}`;if(r&&(!f||u!==void 0)&&!a&&i.test(t)&&Reflect.get(e,p)===void 0){d(t,m(e));let n=`${p}Data`;return Reflect.set(e,p,o),f?Reflect.set(e,n,u):Reflect.deleteProperty(e,n),()=>{Reflect.get(e,p)===o&&(Reflect.deleteProperty(e,p),Reflect.deleteProperty(e,n))}}return c(e,t,t=>o.call(e,...f?[u,t]:[t]),a)}function g(e,r,i,a,o){let s=h(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{g as addEventListener,h as bindEvent,u as chainEvents,p as clearDelegatedEvents,f as delegateEvents};
|
|
2
2
|
//# sourceMappingURL=events.js.map
|
package/dist/prod/events.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","invoke","event","node","untrack","fn","args","dispatchDelegated","batch","dispatchPath","key","dataKey","errors","data","error","first","isListenerObject","handler","bindListenerObject","object","options","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","binding","slot","plain","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(fn: Binding[\"fn\"], node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n invoke(fn as Binding[\"fn\"], node, event, data === undefined ? [event] : [data, event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n const options = {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n const plain = !binding.tuple || binding.data !== undefined;\n if (\n delegate &&\n plain &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAO,EAAmB,EAAmB,EAAc,EAAuB,CACzF,OAAO,eAAeC,EAAO,gBAAiB,CAAE,aAAc,GAAM,QAAWC,CAAK,CAAC,EACrF,GAAI,CACFC,MAAcC,EAAG,KAAKF,EAAM,GAAGG,CAAI,CAAC,CACtC,QAAU,CACR,QAAQ,eAAeJ,EAAO,eAAe,CAC/C,CACF,CAMA,SAASK,EAAkB,EAAoB,CAG7CC,MAAYC,EAAaP,CAAK,CAAC,CACjC,CAEA,SAASO,EAAa,EAAoB,CACxC,IAAMC,EAAM,KAAKR,EAAM,OACjBS,EAAU,GAAGD,EAAI,MACjBE,EAAoB,CAAC,EAC3B,IAAK,IAAMT,KAAQD,EAAM,aAAa,EAAG,CACvC,GAAIA,EAAM,aAAc,MACxB,IAAMG,EAAK,QAAQ,IAAIF,EAAMO,CAAG,EA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1B,CACP,QAAQ,IAAIY,EAAIc,CAAI,IAAMD,EAAQ,KACpC,QAAQ,eAAeb,EAAIc,CAAI,EAC/B,QAAQ,eAAed,EAAIZ,CAAO,EAEtC,CACF,CACA,IAAMW,EAAY,GAAuB,CACvC,IAAMhB,EAAkB8B,EAAQ,MAAQ,CAACA,EAAQ,KAAMlC,CAAK,EAAI,CAACA,CAAK,EACtEM,MAAYJ,MAAcgC,EAAQ,GAAG,KAAKb,EAAI,GAAGjB,CAAI,CAAC,CAAC,CACzD,EAEA,OADAiB,EAAG,iBAAiBC,EAAMF,EAAUD,CAAO,MAC9B,CACXE,EAAG,oBAAoBC,EAAMF,EAAUD,CAAO,CAChD,CACF,CA6BA,SAAgBmB,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASN,EAAUZ,EAAIC,EAAMP,EAASsB,IAAa,GAAMlB,IAAY,EAAI,EAE3EoB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
|
|
1
|
+
{"version":3,"file":"events.js","names":["DELEGATED_EVENTS","installed","dispatchDelegated","batch","key","event","dataKey","errors","node","fn","data","untrack","error","first","isListenerObject","handler","listen","listener","run","el","name","options","bindListenerObject","object","capture","chainEvents","handlers","installDelegate","known","target","delegateEvents","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","tuple","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A bound handler: called with `this` = the node. */\ntype Handler = (this: EventTarget, ...args: unknown[]) => unknown;\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the\n * duration of the call. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n untrack(() =>\n (fn as Handler).call(node, ...(data === undefined ? [event] : [data, event])),\n );\n } catch (error) {\n errors.push(error);\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n });\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */\nfunction listen(\n el: Element,\n name: string,\n run: (event: Event) => unknown,\n options: AddEventListenerOptions | boolean,\n): () => void {\n const listener = (event: Event): void => {\n batch(() => untrack(() => run(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n return listen(el, name, (event) => object.handleEvent(event), {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions);\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/** Installs the delegated listener for one event name on `target`, unless it is there already. */\nfunction installDelegate(name: string, target: Document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n if (known.has(name)) return;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n for (const name of names) installDelegate(name, target);\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n let fn = handler as Handler;\n let data: unknown;\n let tuple = false;\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n fn = handler[0] as Handler;\n data = handler[1];\n tuple = true;\n } else if (typeof handler !== \"function\") {\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n }\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n if (\n delegate &&\n (!tuple || data !== undefined) &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n installDelegate(name, delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, fn);\n if (tuple) Reflect.set(el, dataKey, data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n return listen(el, name, (event) => fn.call(el, ...(tuple ? [data, event] : [event])), capture);\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMA,EACJ,6JAGIC,kBAAY,IAAI,QAUtB,SAASC,EAAkB,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,CACF,OAASO,EAAO,CACdL,EAAO,KAAKK,CAAK,CACnB,QAAU,CACR,QAAQ,eAAeP,EAAO,eAAe,CAC/C,CACF,CACA,GAAM,CAACQ,GAASN,EAChB,GAAIA,EAAO,SAAW,EAAG,MAAMM,EAC/B,GAAIN,EAAO,OAAS,EAClB,MAAU,eACRA,EAC4C,qBAC9C,CACJ,CAAC,CACH,CAWA,SAASO,EAAiB,EAA6C,CACrE,OACE,OAAOC,GAAY,YACnBA,GACA,OAAQA,EAAsC,aAAgB,UAElE,CAGA,SAASC,EACP,EACA,EACA,EACA,EACY,CACZ,IAAMC,EAAY,GAAuB,CACvCd,MAAYQ,MAAcO,EAAIb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}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{reconcileNodes as
|
|
1
|
+
import{leaves as e}from"./internal/accessor.js";import{claims as t}from"./internal/hydration-hooks.js";import{keepFocus as n,reconcileNodes as r}from"./internal/reconcile.js";import{onCleanup as i,useRenderEffect as a}from"@shadow-js/core";import{addCleanup as o,createComputation as s,currentOwner as c,disposeOwner as l,readComputation as u}from"@shadow-js/core/extend";const d=/* @__PURE__ */ new WeakMap;function f(e){return e instanceof Document?e:e.ownerDocument??document}function p(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function m(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function h(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}const g=/* @__PURE__ */ new WeakMap;function _(t,n){let r=[];for(let i of e(t,`SHADOW_INSERT_CYCLE`,n))if(i!=null&&typeof i!=`boolean`){if(i instanceof DocumentFragment){let e=g.get(i)??[...i.childNodes];g.set(i,e);for(let t of e)r.push(t)}else r.push(i instanceof Node?i:String(i))}return r}function v(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!p(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function y(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&p(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=v(e);let t=o.get(n)?.pop();t===void 0&&(t=f(e.parent).createTextNode(n),m(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function b(e,t){if(e.anchor!==null)return e.anchor;if(t!==void 0)return t.nextSibling;let n=e.marker;return n===null?e.parent.firstChild:n.parentNode===e.parent?n.nextSibling:null}const x=/* @__PURE__ */ new WeakMap;function S(e,t){let n=x.get(e)??/* @__PURE__ */ new Set;x.set(e,n.add(t)),i(()=>{n.delete(t)})}function C(e,t){let n=y(e,t),i=e.parent,a=e.nodes.filter(e=>e.parentNode===i),o=a[0],s=b(e,a.at(-1));n.length===0&&o!==void 0&&(e.marker=o.previousSibling),r(i,a,n,s),e.nodes=n,h(e,n),x.get(i)?.forEach(e=>{e()})}function w(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&p(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=f(e.parent).createTextNode(r);m(e,t),e.parent.insertBefore(t,b(e,void 0)),e.nodes=[t];return}}C(e,_(t))}function T(e,t,n){let r=[];if(n!==void 0){let t=/* @__PURE__ */ new Set;for(let i of _(n))typeof i==`string`||t.has(i)||i.parentNode!==e||(t.add(i),r.push(i))}let i={parent:e,anchor:t,marker:r.length>0?r[0].previousSibling:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&m(i,e);return i}function E(e){let t=e.parent,n=d.get(t);e.owner=c(),d.set(t,e);let r=e.nodes[0]??null;if(n===void 0||n.owner?.disposed||b(n,n.nodes.at(-1))!==r)return;let i=j(t,r);n.anchor=e.marker=i,n.owner&&o(n.owner,()=>i.remove())}function D(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop();for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function O(e,t,n){if(!D(t))return w(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n===!0&&E(e),a(typeof t==`function`?t:()=>t,t=>{if(r=t,D(t)){let n=c(),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,o=e=>{i.add(e);let t=r.get(e);return t===void 0&&(t=s({kind:`memo`,fn:()=>e(),allowWrites:!0,owner:n}),r.set(e,t)),u(t)};a(()=>{i=/* @__PURE__ */ new Set;let e=_(t,o);for(let[e,t]of r)i.has(e)||(r.delete(e),l(t));return e},t=>{C(e,t)})}else w(e,t)}),r}function k(e,t,r){let i=e.nodes.filter(t=>t.parentNode===e.parent);n(e.parent,()=>{for(let e of i)r(e)}),e.parent=t,e.marker=i[0]?.previousSibling??t.lastChild}function A(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function j(e,t){let n=f(e).createTextNode(``);return e.insertBefore(n,t),n}function M(e,n,r,i){let a=r??null;return O(T(e,a,i===void 0?t.current.takeRegion(e,a):i),n,a===null)}export{j as anchor,O as bindRegion,T as createRegion,M as insert,k as moveRegion,A as removeRegion,S as watchCommits};
|
|
2
2
|
//# sourceMappingURL=insert.js.map
|