@shadow-js/web 1.0.3 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -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 +15 -13
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +4 -4
- package/dist/dev/control-flow/no-hydration.js +1 -1
- package/dist/dev/control-flow/portal.js +1 -1
- package/dist/dev/element.js +10 -27
- 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/extend.js +6 -6
- package/dist/dev/head/use-head.js +1 -1
- package/dist/dev/head/validate.js +1 -1
- package/dist/dev/hydration.js +21 -13
- package/dist/dev/hydration.js.map +1 -1
- package/dist/dev/index.d.ts +5 -5
- package/dist/dev/index.js +6 -6
- package/dist/dev/insert.js +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/jsx/global.d.ts +2 -2
- package/dist/dev/jsx/html.d.ts +1 -1
- package/dist/dev/jsx/intrinsic.d.ts +1 -1
- package/dist/dev/jsx/mathml.d.ts +1 -1
- package/dist/dev/jsx/svg.d.ts +1 -1
- package/dist/dev/jsx-runtime.d.ts +3 -3
- package/dist/dev/render.js +22 -11
- package/dist/dev/render.js.map +1 -1
- package/dist/dev/server/class-style.js +1 -1
- package/dist/dev/server/element.js +3 -3
- package/dist/dev/server/form-controls.js +1 -1
- package/dist/dev/server/hydration-script.js +1 -1
- package/dist/dev/server/portals.js +1 -1
- package/dist/dev/server/raw-text.js +1 -1
- package/dist/dev/server/render.js +2 -2
- package/dist/dev/server/stream.js +3 -3
- package/dist/dev/spread.js +59 -84
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +3 -3
- 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/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/no-hydration.js +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/extend.js +1 -1
- package/dist/prod/head/use-head.js +1 -1
- package/dist/prod/head/validate.js +1 -1
- package/dist/prod/hydration.js +1 -1
- package/dist/prod/hydration.js.map +1 -1
- package/dist/prod/index.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/render.js +1 -1
- package/dist/prod/render.js.map +1 -1
- package/dist/prod/server/class-style.js +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/hydration-script.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/raw-text.js +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js +1 -1
- package/dist/server/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/control-flow/dynamic.js +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/element.js +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/extend.js +1 -1
- package/dist/server/head/use-head.js +1 -1
- package/dist/server/head/validate.js +1 -1
- package/dist/server/hydration.js +1 -1
- package/dist/server/hydration.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/render.js +1 -1
- package/dist/server/render.js.map +1 -1
- package/dist/server/server/class-style.js +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/hydration-script.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/raw-text.js +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js +1 -1
- package/dist/server-dev/attributes.js +1 -5
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +15 -13
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +1 -1
- package/dist/server-dev/control-flow/portal.js +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/element.js +1 -1
- package/dist/server-dev/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/extend.js +6 -6
- package/dist/server-dev/head/use-head.js +1 -1
- package/dist/server-dev/head/validate.js +1 -1
- package/dist/server-dev/hydration.js +21 -13
- package/dist/server-dev/hydration.js.map +1 -1
- package/dist/server-dev/index.js +6 -6
- package/dist/server-dev/insert.js +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/render.js +22 -11
- package/dist/server-dev/render.js.map +1 -1
- package/dist/server-dev/server/class-style.js +1 -1
- package/dist/server-dev/server/element.js +3 -3
- package/dist/server-dev/server/form-controls.js +1 -1
- package/dist/server-dev/server/hydration-script.js +1 -1
- package/dist/server-dev/server/portals.js +1 -1
- package/dist/server-dev/server/raw-text.js +1 -1
- package/dist/server-dev/server/render.js +2 -2
- package/dist/server-dev/server/stream.js +3 -3
- package/dist/server-dev/spread.js +59 -84
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +3 -3
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.5
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- A style array skips `null`, `undefined` and `false` values like the server does, so an earlier entry's property is no longer removed on the client.
|
|
8
|
+
- When `render()` or `hydrate()` throws during its first flush, the root, its effects and (for `render`) its partial DOM are torn down and the error is rethrown; `hydrate` keeps the server markup.
|
|
9
|
+
- `value` on `progress`, `meter` and `li` is written as an attribute through `spread`, so `undefined` leaves no `value="0"` and matches the server.
|
|
10
|
+
|
|
11
|
+
## 1.0.4
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- Smaller bundles with the same behavior.
|
|
16
|
+
- A keyed list reorder no longer drops the focus in WebKit. Safari has no `moveBefore`, so moving a row with `insertBefore` blurred an input inside it. When the list is reordered without `moveBefore`, the focused element is now focused again after the move, without scrolling. The same applies when a `Portal` moves its content to a new mount.
|
|
17
|
+
|
|
3
18
|
## 1.0.3
|
|
4
19
|
|
|
5
20
|
### Fixed
|
package/README.md
CHANGED
|
@@ -25,8 +25,7 @@ you. In `tsconfig.json`, point JSX at this package:
|
|
|
25
25
|
}
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
repository.
|
|
28
|
+
To try a change that is not released yet, install from a local checkout of this repository.
|
|
30
29
|
|
|
31
30
|
## Example
|
|
32
31
|
|
|
@@ -176,7 +175,7 @@ type tests are in `packages/web/test-types`.
|
|
|
176
175
|
## Dependencies
|
|
177
176
|
|
|
178
177
|
- Runtime: none.
|
|
179
|
-
- Peers: `@shadow-js/core` `^1.0.
|
|
178
|
+
- Peers: `@shadow-js/core` `^1.0.5`: the reactive primitives the renderer is built on.
|
|
180
179
|
|
|
181
180
|
## Types
|
|
182
181
|
|
package/dist/dev/attributes.js
CHANGED
|
@@ -22,13 +22,9 @@ const UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\/html|vbscript:)/;
|
|
|
22
22
|
function assertAttributeName(name) {
|
|
23
23
|
if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);
|
|
24
24
|
}
|
|
25
|
-
/** Removes C0 and C1 control characters (`\p{Cc}`), which browsers ignore inside a URL scheme. */
|
|
26
|
-
function stripControls(text) {
|
|
27
|
-
return text.replace(/\p{Cc}/gu, "");
|
|
28
|
-
}
|
|
29
25
|
/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */
|
|
30
26
|
function isUnsafeUrl(value) {
|
|
31
|
-
return UNSAFE_URL_PREFIXES.test(
|
|
27
|
+
return UNSAFE_URL_PREFIXES.test(value.replace(/\p{Cc}/gu, "").trim().toLowerCase());
|
|
32
28
|
}
|
|
33
29
|
/**
|
|
34
30
|
* Reports whether writing `value` to the attribute `name` would run script: the URL check that
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iBAAiB;;;;;AAMvB,MAAM,gBAAgB;;AAGtB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;AAGA,SAAS,YAAY,OAAwB;CAC3C,OAAO,oBAAoB,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;AAC3E;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,qBAAqB,MAAc,OAAwB;CACzE,MAAM,Y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AI,MAAM,MAAM,KAAK;AAC9B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,IAAa,WAAmB,MAAc,OAAsB;CACjG,oBAAoB,IAAI;CACxB,OAAO,IAAI,cAAc,KAAK,OAAO,WAAW,MAAM,KAAK;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,IAAa,MAAc,OAAsB;CAChF,oBAAoB,IAAI;CACxB,GAAG,gBAAgB,MAAM,QAAQ,KAAK,CAAC;AACzC"}
|
|
1
|
+
{"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n // C0 and C1 control characters (`\\p{Cc}`) are removed: browsers ignore them inside a URL scheme.\n return UNSAFE_URL_PREFIXES.test(\n value\n .replace(/\\p{Cc}/gu, \"\")\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iBAAiB;;;;;AAMvB,MAAM,gBAAgB;;AAGtB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,YAAY,OAAwB;CAE3C,OAAO,oBAAoB,KACzB,MACG,QAAQ,YAAY,EAAE,CAAC,CACvB,KAAK,CAAC,CACN,YAAY,CACjB;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,qBAAqB,MAAc,OAAwB;CACzE,MAAM,YAAY,KAAK,YAAY;CACnC,IAAI,CAAC,eAAe,KAAK,SAAS,GAAG,OAAO;CAE5C,OAAO,cAAc,WAAW,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,WAAW,IAAI,YAAY,KAAK;AACxF;;AAGA,SAAS,cAAc,WAAmB,OAA+B;CACvE,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,OAAO,OAAO,cAAc,KAAK,SAAS,IAAI,UAAU;CACtE,IAAI,UAAU,MAAM,OAAO,cAAc,KAAK,SAAS,IAAI,SAAS;CACpE,OAAO,OAAO,KAAK;AACrB;;AAGA,SAAS,UAAU,WAA2B;CAC5C,MAAM,QAAQ,UAAU,QAAQ,GAAG;CACnC,OAAO,UAAU,KAAK,YAAY,UAAU,MAAM,QAAQ,CAAC;AAC7D;;AAGA,SAAS,OAAO,IAAa,WAA0B,WAAmB,OAAsB;CAC9F,MAAM,YAAY,UAAU,YAAY;CACxC,MAAM,OAAO,cAAc,WAAW,KAAK;CAC3C,IAAI,SAAS,MAAM;EACjB,IAAI,cAAc,MAAM,GAAG,gBAAgB,SAAS;OAC/C,GAAG,kBAAkB,WAAW,UAAU,SAAS,CAAC;EACzD;CACF;CAGA,IAAI,OAAO,KAAK,SAAS,GAAG;CAC5B,IAAe,cAAc,UAAU,SAAS,kBAAkB,qBAAqB;CACvF,IAAI,qBAAqB,WAAW,IAAI,GAAG;EAEvC,SAAS,sBAAsB,gCAAgC,UAAU,aAAa;EACxF;CACF;CACA,IAAI,cAAc,MACZ;MAAA,GAAG,aAAa,SAAS,MAAM,MAAM,GAAG,aAAa,WAAW,IAAI;CAAA,OACnE,IAAI,GAAG,eAAe,WAAW,UAAU,SAAS,CAAC,MAAM,MAChE,GAAG,eAAe,WAAW,WAAW,IAAI;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,aAAa,IAAa,MAAc,OAAsB;CAC5E,oBAAoB,IAAI;CACxB,OAAO,IAAI,MAAM,MAAM,KAAK;AAC9B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,IAAa,WAAmB,MAAc,OAAsB;CACjG,oBAAoB,IAAI;CACxB,OAAO,IAAI,cAAc,KAAK,OAAO,WAAW,MAAM,KAAK;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,IAAa,MAAc,OAAsB;CAChF,oBAAoB,IAAI;CACxB,GAAG,gBAAgB,MAAM,QAAQ,KAAK,CAAC;AACzC"}
|
package/dist/dev/class-style.js
CHANGED
|
@@ -2,16 +2,6 @@ import { leaves, unwrap } from "./internal/accessor.js";
|
|
|
2
2
|
import { cssValueText } from "./internal/css-units.js";
|
|
3
3
|
import { HTML_NS } from "./internal/names.js";
|
|
4
4
|
// src/class-style.ts
|
|
5
|
-
/** `map` itself, or a copy in which accessor values are resolved, so a later diff compares what was applied. */
|
|
6
|
-
function resolveMap(map) {
|
|
7
|
-
let out = map;
|
|
8
|
-
for (const key of Object.keys(map)) {
|
|
9
|
-
if (typeof map[key] !== "function") continue;
|
|
10
|
-
if (out === map) out = { ...map };
|
|
11
|
-
out[key] = unwrap(map[key]);
|
|
12
|
-
}
|
|
13
|
-
return out;
|
|
14
|
-
}
|
|
15
5
|
/** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */
|
|
16
6
|
function collectClasses(root, parts) {
|
|
17
7
|
for (const item of leaves(root, "className(): a class array contains itself.")) if (typeof item === "string") {
|
|
@@ -105,7 +95,13 @@ function enabled(map, key) {
|
|
|
105
95
|
* @since 1.0.0
|
|
106
96
|
*/
|
|
107
97
|
function classList(el, value, prev) {
|
|
108
|
-
const
|
|
98
|
+
const source = value ?? {};
|
|
99
|
+
let next = source;
|
|
100
|
+
for (const key of Object.keys(source)) {
|
|
101
|
+
if (typeof source[key] !== "function") continue;
|
|
102
|
+
if (next === source) next = { ...source };
|
|
103
|
+
next[key] = unwrap(source[key]);
|
|
104
|
+
}
|
|
109
105
|
const before = prev ?? {};
|
|
110
106
|
const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
|
|
111
107
|
for (const key of keys) {
|
|
@@ -193,12 +189,18 @@ function style(el, value, prev) {
|
|
|
193
189
|
if (typeof item === "string") el.style.cssText += `;${item}`;
|
|
194
190
|
else if (item !== null && item !== void 0 && item !== false) {
|
|
195
191
|
if (typeof item !== "object" || Array.isArray(item)) throw new TypeError("style(): an array holds only strings and objects.");
|
|
196
|
-
|
|
192
|
+
const declared = {};
|
|
193
|
+
for (const key of Object.keys(item)) {
|
|
194
|
+
const part = unwrap(item[key]);
|
|
195
|
+
if (part !== null && part !== void 0 && part !== false) declared[key] = part;
|
|
196
|
+
}
|
|
197
|
+
style(el, declared, {});
|
|
197
198
|
}
|
|
198
199
|
}
|
|
199
200
|
return resolved;
|
|
200
201
|
}
|
|
201
|
-
const next =
|
|
202
|
+
const next = { ...resolved };
|
|
203
|
+
for (const key of Object.keys(next)) next[key] = unwrap(next[key]);
|
|
202
204
|
const before = asRecord(prev) ?? {};
|
|
203
205
|
if (typeof prev === "string" || Array.isArray(prev)) el.style.cssText = "";
|
|
204
206
|
const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-style.js","names":[],"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 return next;\n}\n"],"mappings":";;;;;AAKA,SAAS,WAAW,KAAuD;CACzE,IAAI,MAAM;CACV,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAAG;EAClC,IAAI,OAAO,IAAI,SAAS,YAAY;EACpC,IAAI,QAAQ,KAAK,MAAM,EAAE,GAAG,IAAI;EAChC,IAAI,OAAO,OAAO,IAAI,IAAI;CAC5B;CACA,OAAO;AACT;;AAGA,SAAS,eAAe,MAAe,OAAuB;CAE5D,KAAK,MAAM,QAAQ,OAAO,MAAM,6CAAK,GACnC,IAAI,OAAO,SAAS,UACd;MAAA,SAAS,IAAI,MAAM,KAAK,IAAI;CAAA,OAC3B,IAAI,OAAO,SAAS,UACrB;MAAA,SAAS,KAAK,CAAC,OAAO,MAAM,IAAI,GAAG,MAAM,KAAK,OAAO,IAAI,CAAC;CAAA,OACzD,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU;EACpD,MAAM,SAAS;EACf,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,IAAI,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,KAAK,GAAG;CAEzD;AAEJ;;AAG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,SAAqC,CAAC;CACpE,MAAM,SAAS,SAAS,IAAI,KAAK,CAAC;CAElC,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,GAAG,MAAM,UAAU;CACxE,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,GAAG;EACvC,iBAAiB,IAAI,KAAK,KAAK,IAAI;CACrC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"class-style.js","names":[],"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 // A null, undefined or false value declares nothing here, as on the server: `style` would remove\n // the property, which erases what an earlier source of the array wrote.\n const declared: Record<string, unknown> = {};\n for (const key of Object.keys(item)) {\n const part = unwrap((item as Record<string, unknown>)[key]);\n if (part !== null && part !== undefined && part !== false) declared[key] = part;\n }\n style(el, declared, {});\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":";;;;;AAKA,SAAS,eAAe,MAAe,OAAuB;CAE5D,KAAK,MAAM,QAAQ,OAAO,MAAM,6CAAK,GACnC,IAAI,OAAO,SAAS,UACd;MAAA,SAAS,IAAI,MAAM,KAAK,IAAI;CAAA,OAC3B,IAAI,OAAO,SAAS,UACrB;MAAA,SAAS,KAAK,CAAC,OAAO,MAAM,IAAI,GAAG,MAAM,KAAK,OAAO,IAAI,CAAC;CAAA,OACzD,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU;EACpD,MAAM,SAAS;EACf,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,IAAI,OAAO,OAAO,IAAI,KAAK,QA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nB,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,SAAS,OAAO;IAChE,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAChD,MAAM,IAAI,UACE,mDACZ;IAIF,MAAM,WAAoC,CAAC;IAC3C,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAAG;KACnC,MAAM,OAAO,OAAQ,KAAiC,IAAI;KAC1D,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,SAAS,OAAO,SAAS,OAAO;IAC7E;IACA,MAAM,IAAI,UAAU,CAAC,CAAC;GACxB;EACF;EACA,OAAO;CACT;CACA,MAAM,OAAgC,EAAE,GAAI,SAAqC;CACjF,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAAG,KAAK,OAAO,OAAO,KAAK,IAAI;CACjE,MAAM,SAAS,SAAS,IAAI,KAAK,CAAC;CAElC,IAAI,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,GAAG,MAAM,UAAU;CACxE,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,OAAO,MAAM;EACtB,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,IAAI,GAAG;EACvC,iBAAiB,IAAI,KAAK,KAAK,IAAI;CACrC;CACA,OAAO;AACT"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { warnOnce } from "../internal/diagnostics.js";
|
|
2
|
-
import { MATHML_NS, SVG_NS } from "../internal/names.js";
|
|
3
|
-
import { nextKey } from "../internal/hydration-scope.js";
|
|
4
1
|
import { createComponent } from "../component.js";
|
|
5
|
-
import { claims } from "../internal/hydration-hooks.js";
|
|
6
2
|
import { bindRegion, createRegion } from "../insert.js";
|
|
3
|
+
import { claims } from "../internal/hydration-hooks.js";
|
|
4
|
+
import { MATHML_NS, SVG_NS } from "../internal/names.js";
|
|
5
|
+
import { nextKey } from "../internal/hydration-scope.js";
|
|
6
|
+
import { warnOnce } from "../internal/diagnostics.js";
|
|
7
7
|
import { spreadProps } from "../spread.js";
|
|
8
8
|
import { mergeProps, splitProps, untrack, useMemo } from "@shadow-js/core";
|
|
9
9
|
// src/control-flow/dynamic.ts
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { nextKey } from "../internal/hydration-scope.js";
|
|
2
1
|
import { claims } from "../internal/hydration-hooks.js";
|
|
2
|
+
import { nextKey } from "../internal/hydration-scope.js";
|
|
3
3
|
// src/control-flow/no-hydration.ts
|
|
4
4
|
/** The nodes between `<!--nh:KEY-->` and its `<!--/nh-->` in the lifted regions, or undefined when the server sent none. */
|
|
5
5
|
function findStatic(key, regions) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { bindRegion, createRegion, moveRegion, removeRegion } from "../insert.js";
|
|
1
2
|
import { childScope, nextKey, withScope } from "../internal/hydration-scope.js";
|
|
2
3
|
import { claims } from "../internal/hydration-hooks.js";
|
|
3
|
-
import { bindRegion, createRegion, moveRegion, removeRegion } from "../insert.js";
|
|
4
4
|
import { PortalContext } from "../internal/portal-context.js";
|
|
5
5
|
import { createRoot, getOwner, isServer, onCleanup, runWithOwner, useContext, useRenderEffect } from "@shadow-js/core";
|
|
6
6
|
// src/control-flow/portal.ts
|
package/dist/dev/element.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { setAttribute, setBoolAttribute } from "./attributes.js";
|
|
2
2
|
import { style } from "./class-style.js";
|
|
3
|
-
import {
|
|
3
|
+
import { insert } from "./insert.js";
|
|
4
4
|
import { checkClaimedTag } from "./internal/claim.js";
|
|
5
5
|
import { claims } from "./internal/hydration-hooks.js";
|
|
6
|
-
import {
|
|
6
|
+
import { nextKey } from "./internal/hydration-scope.js";
|
|
7
7
|
import { isFlagAttribute } from "./internal/react-names.js";
|
|
8
8
|
import { batch, untrack, useRenderEffect } from "@shadow-js/core";
|
|
9
9
|
// src/element.ts
|
|
@@ -18,28 +18,6 @@ import { batch, untrack, useRenderEffect } from "@shadow-js/core";
|
|
|
18
18
|
*/
|
|
19
19
|
/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */
|
|
20
20
|
const TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;
|
|
21
|
-
/** `onClick` to `click`, when the key is an event handler name. */
|
|
22
|
-
function eventNameOf(key) {
|
|
23
|
-
return key.length > 2 && key.startsWith("on") && /^[A-Z]/.test(key.charAt(2)) ? key.slice(2).toLowerCase() : void 0;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple
|
|
27
|
-
* receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and
|
|
28
|
-
* untracked, as the event binding of `Dynamic` runs them.
|
|
29
|
-
*/
|
|
30
|
-
function bindListener(el, name, handler) {
|
|
31
|
-
let call;
|
|
32
|
-
if (typeof handler === "function") call = (event) => handler.call(el, event);
|
|
33
|
-
else if (Array.isArray(handler)) {
|
|
34
|
-
const [fn, data] = handler;
|
|
35
|
-
if (typeof fn === "function") call = (event) => fn.call(el, data, event);
|
|
36
|
-
}
|
|
37
|
-
if (call === void 0) return;
|
|
38
|
-
const run = call;
|
|
39
|
-
el.addEventListener(name, (event) => {
|
|
40
|
-
batch(() => untrack(() => run(event)));
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
21
|
/**
|
|
44
22
|
* Creates one HTML element from a tag name and a props object, without the generic prop runtime of
|
|
45
23
|
* `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants
|
|
@@ -84,9 +62,14 @@ function element(tag, props) {
|
|
|
84
62
|
const el = claimed ?? document.createElement(tag);
|
|
85
63
|
for (const key of Object.keys(props)) {
|
|
86
64
|
if (key === "children" || key === "ref") continue;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
65
|
+
if (/^on[A-Z]/.test(key)) {
|
|
66
|
+
const handler = read[key];
|
|
67
|
+
const tuple = Array.isArray(handler);
|
|
68
|
+
const [fn, data] = tuple ? handler : [handler];
|
|
69
|
+
if (typeof fn === "function") el.addEventListener(key.slice(2).toLowerCase(), (event) => {
|
|
70
|
+
batch(() => untrack(() => tuple ? fn.call(el, data, event) : fn.call(el, event)));
|
|
71
|
+
});
|
|
72
|
+
} else if (key === "style") {
|
|
90
73
|
let applied;
|
|
91
74
|
useRenderEffect(() => read[key], (value) => {
|
|
92
75
|
applied = style(el, value, applied);
|
package/dist/dev/element.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":[],"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
|
|
1
|
+
{"version":3,"file":"element.js","names":[],"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":";;;;;;;;;;;;;;;;;;;AAsBA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,SAAgB,QAAQ,KAAa,OAAwB;CAC3D,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,IAAI,YAAY,MAAM,UAClD,MAAM,IAAI,UAAoB,+BAAsD;CAEtF,MAAM,OAAO;CAeb,MAAM,UAAU,OAAO,QAAQ,aAAa,QAAQ,CAAC;CACrD,IAAI,YAAY,QAAA,MAAiB,gBAAgB,SAAS,GAAG;CAC7D,MAAM,KAAK,WAAW,SAAS,cAAc,GAAG;CAChD,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GAAG;EACpC,IAAI,QAAQ,cAAc,QAAQ,OAAO;EACzC,IAAI,WAAW,KAAK,GAAG,GAAG;GAIxB,MAAM,UAAU,KAAK;GACrB,MAAM,QAAQ,MAAM,QAAQ,OAAO;GAEnC,MAAM,CAAC,IAAI,QAA4B,QAAQ,UAAU,CAAC,OAAO;GACjE,IAAI,OAAO,OAAO,YAChB,GAAG,iBAAiB,IAAI,MAAM,CAAC,CAAC,CAAC,YAAY,IAAI,UAAuB;IACtE,YAAY,cAAe,QAAQ,GAAG,KAAK,IAAI,MAAM,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,CAAE,CAAC;GACpF,CAAC;EAEL,OAAO,IAAI,QAAQ,SAAS;GAE1B,IAAI;GACJ,sBACQ,KAAK,OACV,UAAU;IACT,UAAU,MAAM,IAAmB,OAAO,OAAO;GACnD,CACF;EACF,OACE,sBACQ,KAAK,OACV,UAAU;GAGT,MAAM,OAAO,IAAI,YAAY;GAC7B,IAAI,gBAAgB,MAAM,KAAK,GAAG,iBAAiB,IAAI,MAAM,KAAK;QAC7D,aAAa,IAAI,KAAK,KAAK;EAClC,CACF;CAEJ;CACA,MAAM,MAAM,KAAK;CACjB,IAAI,OAAO,QAAQ,YAAY,cAAc,IAAI,EAAE,CAAC;CACpD,OAAO,UAAU,KAAK,WAAW;CACjC,OAAO;AACT"}
|
package/dist/dev/events.js
CHANGED
|
@@ -7,77 +7,60 @@ import { batch, getOwner, onCleanup, untrack } from "@shadow-js/core";
|
|
|
7
7
|
const DELEGATED_EVENTS = /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;
|
|
8
8
|
/** Documents that already carry the delegated listener for a given event name. */
|
|
9
9
|
const installed = /* @__PURE__ */ new WeakMap();
|
|
10
|
-
/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */
|
|
11
|
-
function invoke(fn, node, event, args) {
|
|
12
|
-
Object.defineProperty(event, "currentTarget", {
|
|
13
|
-
configurable: true,
|
|
14
|
-
get: () => node
|
|
15
|
-
});
|
|
16
|
-
try {
|
|
17
|
-
untrack(() => fn.call(node, ...args));
|
|
18
|
-
} finally {
|
|
19
|
-
Reflect.deleteProperty(event, "currentTarget");
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
10
|
/**
|
|
23
11
|
* The one listener per (document, event). It walks `composedPath()` from the target outward,
|
|
24
|
-
* calling `node.$$<type>` with `this = node
|
|
12
|
+
* calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the
|
|
13
|
+
* duration of the call. Stops when a handler stops propagation.
|
|
25
14
|
*/
|
|
26
15
|
function dispatchDelegated(event) {
|
|
27
|
-
batch(() =>
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
16
|
+
batch(() => {
|
|
17
|
+
const key = `$$${event.type}`;
|
|
18
|
+
const dataKey = `${key}Data`;
|
|
19
|
+
const errors = [];
|
|
20
|
+
for (const node of event.composedPath()) {
|
|
21
|
+
if (event.cancelBubble) break;
|
|
22
|
+
const fn = Reflect.get(node, key);
|
|
23
|
+
if (typeof fn !== "function") continue;
|
|
24
|
+
const data = Reflect.get(node, dataKey);
|
|
25
|
+
try {
|
|
26
|
+
Object.defineProperty(event, "currentTarget", {
|
|
27
|
+
configurable: true,
|
|
28
|
+
get: () => node
|
|
29
|
+
});
|
|
30
|
+
untrack(() => fn.call(node, ...data === void 0 ? [event] : [data, event]));
|
|
31
|
+
} catch (error) {
|
|
32
|
+
errors.push(error);
|
|
33
|
+
} finally {
|
|
34
|
+
Reflect.deleteProperty(event, "currentTarget");
|
|
35
|
+
}
|
|
42
36
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
37
|
+
const [first] = errors;
|
|
38
|
+
if (errors.length === 1) throw first;
|
|
39
|
+
if (errors.length > 1) throw new AggregateError(errors, "Several event handlers threw.");
|
|
40
|
+
});
|
|
47
41
|
}
|
|
48
42
|
function isListenerObject(handler) {
|
|
49
43
|
return typeof handler === "object" && handler !== null && typeof handler.handleEvent === "function";
|
|
50
44
|
}
|
|
51
|
-
/**
|
|
52
|
-
function
|
|
53
|
-
const { once, passive, signal } = object;
|
|
54
|
-
const options = {
|
|
55
|
-
capture: object.capture === true || capture,
|
|
56
|
-
once,
|
|
57
|
-
passive,
|
|
58
|
-
signal
|
|
59
|
-
};
|
|
45
|
+
/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */
|
|
46
|
+
function listen(el, name, run, options) {
|
|
60
47
|
const listener = (event) => {
|
|
61
|
-
batch(() => untrack(() =>
|
|
48
|
+
batch(() => untrack(() => run(event)));
|
|
62
49
|
};
|
|
63
50
|
el.addEventListener(name, listener, options);
|
|
64
51
|
return () => {
|
|
65
52
|
el.removeEventListener(name, listener, options);
|
|
66
53
|
};
|
|
67
54
|
}
|
|
68
|
-
/**
|
|
69
|
-
function
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
data: handler[1],
|
|
78
|
-
tuple: true
|
|
79
|
-
};
|
|
80
|
-
throw new TypeError("addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.");
|
|
55
|
+
/** Binds a listener object natively (never delegated), honoring its options. */
|
|
56
|
+
function bindListenerObject(el, name, object, capture) {
|
|
57
|
+
const { once, passive, signal } = object;
|
|
58
|
+
return listen(el, name, (event) => object.handleEvent(event), {
|
|
59
|
+
capture: object.capture === true || capture,
|
|
60
|
+
once,
|
|
61
|
+
passive,
|
|
62
|
+
signal
|
|
63
|
+
});
|
|
81
64
|
}
|
|
82
65
|
/**
|
|
83
66
|
* Combines several handlers for one event name on one element into one handler that calls them in
|
|
@@ -103,6 +86,17 @@ function chainEvents(...handlers) {
|
|
|
103
86
|
for (const handler of handlers) handler.call(this, event);
|
|
104
87
|
};
|
|
105
88
|
}
|
|
89
|
+
/** Installs the delegated listener for one event name on `target`, unless it is there already. */
|
|
90
|
+
function installDelegate(name, target) {
|
|
91
|
+
let known = installed.get(target);
|
|
92
|
+
if (known === void 0) {
|
|
93
|
+
known = /* @__PURE__ */ new Set();
|
|
94
|
+
installed.set(target, known);
|
|
95
|
+
}
|
|
96
|
+
if (known.has(name)) return;
|
|
97
|
+
known.add(name);
|
|
98
|
+
target.addEventListener(name, dispatchDelegated);
|
|
99
|
+
}
|
|
106
100
|
/**
|
|
107
101
|
* Installs the document listener that runs delegated handlers for each event name, once per
|
|
108
102
|
* document and name; repeated calls do nothing. Compiled modules call it for the events they
|
|
@@ -121,16 +115,7 @@ function chainEvents(...handlers) {
|
|
|
121
115
|
* @since 1.0.0
|
|
122
116
|
*/
|
|
123
117
|
function delegateEvents(names, target = globalThis.document) {
|
|
124
|
-
|
|
125
|
-
if (known === void 0) {
|
|
126
|
-
known = /* @__PURE__ */ new Set();
|
|
127
|
-
installed.set(target, known);
|
|
128
|
-
}
|
|
129
|
-
for (const name of names) {
|
|
130
|
-
if (known.has(name)) continue;
|
|
131
|
-
known.add(name);
|
|
132
|
-
target.addEventListener(name, dispatchDelegated);
|
|
133
|
-
}
|
|
118
|
+
for (const name of names) installDelegate(name, target);
|
|
134
119
|
}
|
|
135
120
|
/**
|
|
136
121
|
* Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop
|
|
@@ -174,30 +159,29 @@ function delegationDocument(el) {
|
|
|
174
159
|
function bindEvent(el, name, handler, delegate, capture = false) {
|
|
175
160
|
if (handler === null || handler === void 0 || handler === false) return void 0;
|
|
176
161
|
if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);
|
|
177
|
-
|
|
162
|
+
let fn = handler;
|
|
163
|
+
let data;
|
|
164
|
+
let tuple = false;
|
|
165
|
+
if (Array.isArray(handler) && typeof handler[0] === "function") {
|
|
166
|
+
fn = handler[0];
|
|
167
|
+
data = handler[1];
|
|
168
|
+
tuple = true;
|
|
169
|
+
} else if (typeof handler !== "function") throw new TypeError("addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.");
|
|
178
170
|
const slot = `$$${name}`;
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
delegateEvents([name], delegationDocument(el));
|
|
171
|
+
if (delegate && (!tuple || data !== void 0) && !capture && DELEGATED_EVENTS.test(name) && Reflect.get(el, slot) === void 0) {
|
|
172
|
+
installDelegate(name, delegationDocument(el));
|
|
182
173
|
const dataKey = `${slot}Data`;
|
|
183
|
-
Reflect.set(el, slot,
|
|
184
|
-
if (
|
|
174
|
+
Reflect.set(el, slot, fn);
|
|
175
|
+
if (tuple) Reflect.set(el, dataKey, data);
|
|
185
176
|
else Reflect.deleteProperty(el, dataKey);
|
|
186
177
|
return () => {
|
|
187
|
-
if (Reflect.get(el, slot) ===
|
|
178
|
+
if (Reflect.get(el, slot) === fn) {
|
|
188
179
|
Reflect.deleteProperty(el, slot);
|
|
189
180
|
Reflect.deleteProperty(el, dataKey);
|
|
190
181
|
}
|
|
191
182
|
};
|
|
192
183
|
}
|
|
193
|
-
|
|
194
|
-
const args = binding.tuple ? [binding.data, event] : [event];
|
|
195
|
-
batch(() => untrack(() => binding.fn.call(el, ...args)));
|
|
196
|
-
};
|
|
197
|
-
el.addEventListener(name, listener, capture);
|
|
198
|
-
return () => {
|
|
199
|
-
el.removeEventListener(name, listener, capture);
|
|
200
|
-
};
|
|
184
|
+
return listen(el, name, (event) => fn.call(el, ...tuple ? [data, event] : [event]), capture);
|
|
201
185
|
}
|
|
202
186
|
/**
|
|
203
187
|
* Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`
|