@shadow-js/web 1.0.2 → 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 +21 -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.d.ts +10 -5
- package/dist/dev/class-style.js +44 -47
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +2 -2
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.js +2 -2
- package/dist/dev/control-flow/error-boundary.js.map +1 -1
- package/dist/dev/control-flow/portal.d.ts +2 -2
- package/dist/dev/control-flow/portal.js +15 -13
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/suspense-list.js +2 -2
- package/dist/dev/control-flow/suspense-list.js.map +1 -1
- package/dist/dev/control-flow/suspense.js +2 -2
- package/dist/dev/control-flow/suspense.js.map +1 -1
- package/dist/dev/element.js +13 -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.d.ts +2 -2
- package/dist/dev/extend.js +2 -2
- package/dist/dev/insert.d.ts +11 -0
- package/dist/dev/insert.js +99 -100
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/accessor.js +56 -0
- package/dist/dev/internal/accessor.js.map +1 -0
- package/dist/dev/internal/claim.js +0 -1
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +2 -2
- package/dist/dev/internal/css-units.js.map +1 -1
- package/dist/dev/internal/portal-context.d.ts +9 -0
- package/dist/dev/internal/portal-context.js.map +1 -1
- package/dist/dev/internal/react-names.js +22 -12
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +2 -1
- package/dist/dev/internal/reconcile.js +23 -8
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/server/attributes.js +1 -31
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +5 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/index.js +1 -1
- package/dist/dev/server/portals.js +3 -0
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/render.js +1 -1
- package/dist/dev/server/stream.js +1 -1
- package/dist/dev/server.js +1 -1
- package/dist/dev/spread.js +95 -106
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +1 -3
- package/dist/dev/template.js.map +1 -1
- package/dist/dev/view-transition.js +12 -4
- package/dist/dev/view-transition.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/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js +1 -1
- package/dist/prod/control-flow/suspense.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/extend.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js +2 -0
- package/dist/prod/internal/accessor.js.map +1 -0
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server.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/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js +1 -1
- package/dist/prod/view-transition.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/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/control-flow/suspense.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/extend.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js +2 -0
- package/dist/server/internal/accessor.js.map +1 -0
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server.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/template.js.map +1 -1
- package/dist/server/view-transition.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 +44 -47
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +2 -2
- package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +15 -13
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/suspense-list.js +2 -2
- package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/control-flow/suspense.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/extend.js +2 -2
- package/dist/server-dev/insert.js +99 -100
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/accessor.js +56 -0
- package/dist/server-dev/internal/accessor.js.map +1 -0
- package/dist/server-dev/internal/claim.js +0 -1
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +2 -2
- package/dist/server-dev/internal/css-units.js.map +1 -1
- package/dist/server-dev/internal/portal-context.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +22 -12
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +23 -8
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/attributes.js +1 -31
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +5 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/index.js +1 -1
- package/dist/server-dev/server/portals.js +3 -0
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/render.js +1 -1
- package/dist/server-dev/server/stream.js +1 -1
- package/dist/server-dev/server.js +1 -1
- package/dist/server-dev/spread.js +81 -105
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -3
- package/dist/server-dev/template.js.map +1 -1
- package/dist/server-dev/view-transition.js.map +1 -1
- package/package.json +3 -3
package/dist/dev/server.js
CHANGED
|
@@ -4,12 +4,12 @@ import { ssrClass, ssrStyle } from "./server/class-style.js";
|
|
|
4
4
|
import { ssrSelectValue, ssrTextArea } from "./server/form-controls.js";
|
|
5
5
|
import { ssrRawText } from "./server/raw-text.js";
|
|
6
6
|
import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./server/element.js";
|
|
7
|
-
import { createServerPortals } from "./server/portals.js";
|
|
8
7
|
import { normalizeTags } from "./head/validate.js";
|
|
9
8
|
import { createServerHead } from "./head/server-head.js";
|
|
10
9
|
import { createComponent, memo } from "./server/component.js";
|
|
11
10
|
import { derived } from "./server/derived.js";
|
|
12
11
|
import { HydrationScript, generateHydrationScript } from "./server/hydration-script.js";
|
|
12
|
+
import { createServerPortals } from "./server/portals.js";
|
|
13
13
|
import { renderToString, renderToStringAsync } from "./server/render.js";
|
|
14
14
|
import { deserialize, serialize } from "./server/serialize.js";
|
|
15
15
|
import { renderToStream } from "./server/stream.js";
|
package/dist/dev/spread.js
CHANGED
|
@@ -2,59 +2,21 @@ import { setAttribute, setAttributeNS, setBoolAttribute } from "./attributes.js"
|
|
|
2
2
|
import { autoFocus } from "./autofocus.js";
|
|
3
3
|
import { applyClass, asRecord, classList, style } from "./class-style.js";
|
|
4
4
|
import { claims } from "./internal/hydration-hooks.js";
|
|
5
|
-
import { bindRegion, createRegion } from "./insert.js";
|
|
6
|
-
import { IGNORED_KEYS, attributeName, eventPlan } from "./internal/react-names.js";
|
|
5
|
+
import { bindRegion, createRegion, watchCommits } from "./insert.js";
|
|
6
|
+
import { IGNORED_KEYS, attributeName, eventPlan, isFlagAttribute } from "./internal/react-names.js";
|
|
7
7
|
import { bindEvent } from "./events.js";
|
|
8
8
|
import { plainText, setSelectValue } from "./select-value.js";
|
|
9
9
|
import { onCleanup, untrack, useRenderEffect } from "@shadow-js/core";
|
|
10
10
|
// src/spread.ts
|
|
11
11
|
/** The namespace of `xlink:` attributes (SVG's legacy links). */
|
|
12
12
|
const XLINK_NS = "http://www.w3.org/1999/xlink";
|
|
13
|
-
/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */
|
|
14
|
-
function innerHtmlValue(value) {
|
|
15
|
-
if (value === null || typeof value !== "object") return "";
|
|
16
|
-
return plainText(Reflect.get(value, "__html"));
|
|
17
|
-
}
|
|
18
13
|
/** Keys that would reach a prototype if written as properties. Ignored everywhere. */
|
|
19
|
-
const FORBIDDEN_NAMES =
|
|
20
|
-
"__proto__",
|
|
21
|
-
"constructor",
|
|
22
|
-
"prototype"
|
|
23
|
-
]);
|
|
24
|
-
/** True for `on*` keys, which bind event handlers. */
|
|
25
|
-
function isEventKey(key) {
|
|
26
|
-
return key.length > 2 && key.startsWith("on");
|
|
27
|
-
}
|
|
28
|
-
/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */
|
|
29
|
-
function nameOf(key) {
|
|
30
|
-
const colon = key.indexOf(":");
|
|
31
|
-
return colon === -1 ? key : key.slice(colon + 1);
|
|
32
|
-
}
|
|
33
|
-
/** Reads every prop except children, inside the render effect so each read is tracked. */
|
|
34
|
-
function readEntries(props, textarea) {
|
|
35
|
-
const entries = [];
|
|
36
|
-
if (props === null || typeof props !== "object") return entries;
|
|
37
|
-
let value;
|
|
38
|
-
let hasValue = false;
|
|
39
|
-
for (const key of Object.keys(props)) {
|
|
40
|
-
if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;
|
|
41
|
-
if (key === "children") {
|
|
42
|
-
if (textarea) {
|
|
43
|
-
value = Reflect.get(props, key);
|
|
44
|
-
hasValue = true;
|
|
45
|
-
}
|
|
46
|
-
continue;
|
|
47
|
-
}
|
|
48
|
-
entries.push([key, Reflect.get(props, key)]);
|
|
49
|
-
}
|
|
50
|
-
if (hasValue && !entries.some(([key]) => key === "value")) entries.push(["value", value]);
|
|
51
|
-
return entries;
|
|
52
|
-
}
|
|
14
|
+
const FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;
|
|
53
15
|
/** Runs and forgets the cleanup the last ref callback returned, if any. */
|
|
54
16
|
function runRefCleanup(state) {
|
|
55
|
-
const cleanup = state.
|
|
17
|
+
const cleanup = state.unref;
|
|
56
18
|
if (cleanup === void 0) return;
|
|
57
|
-
state.
|
|
19
|
+
state.unref = void 0;
|
|
58
20
|
untrack(cleanup);
|
|
59
21
|
}
|
|
60
22
|
/** Applies one prop that is new or changed. */
|
|
@@ -64,13 +26,13 @@ function applyKey(el, key, value, state, svg) {
|
|
|
64
26
|
if (typeof value === "function") {
|
|
65
27
|
const callRef = value;
|
|
66
28
|
const cleanup = untrack(() => callRef(el));
|
|
67
|
-
if (typeof cleanup === "function") state.
|
|
29
|
+
if (typeof cleanup === "function") state.unref = cleanup;
|
|
68
30
|
}
|
|
69
31
|
return;
|
|
70
32
|
}
|
|
71
33
|
if (key === "autoFocus") {
|
|
72
|
-
if (!state.
|
|
73
|
-
state.
|
|
34
|
+
if (!state.focused) {
|
|
35
|
+
state.focused = true;
|
|
74
36
|
autoFocus(el, value);
|
|
75
37
|
}
|
|
76
38
|
return;
|
|
@@ -80,27 +42,27 @@ function applyKey(el, key, value, state, svg) {
|
|
|
80
42
|
return;
|
|
81
43
|
}
|
|
82
44
|
if (key === "style") {
|
|
83
|
-
state.
|
|
45
|
+
state.styled = style(el, value, state.styled);
|
|
84
46
|
return;
|
|
85
47
|
}
|
|
86
48
|
if (key === "classList") {
|
|
87
|
-
state.
|
|
49
|
+
state.listed = classList(el, asRecord(value), state.listed);
|
|
88
50
|
return;
|
|
89
51
|
}
|
|
90
|
-
if (
|
|
91
|
-
state.
|
|
92
|
-
state.
|
|
52
|
+
if (key.length > 2 && key.startsWith("on")) {
|
|
53
|
+
state.unbind.get(key)?.();
|
|
54
|
+
state.unbind.delete(key);
|
|
93
55
|
const plan = eventPlan(key, el.localName, el.getAttribute("type")?.toLowerCase() ?? null);
|
|
94
56
|
const handler = plan.passive && typeof value === "function" ? {
|
|
95
57
|
handleEvent: value,
|
|
96
58
|
passive: true
|
|
97
59
|
} : value;
|
|
98
60
|
const unbind = bindEvent(el, plan.type, handler, true, plan.capture);
|
|
99
|
-
if (unbind !== void 0) state.
|
|
61
|
+
if (unbind !== void 0) state.unbind.set(key, unbind);
|
|
100
62
|
return;
|
|
101
63
|
}
|
|
102
64
|
if (key === "innerHTML" || key === "dangerouslySetInnerHTML") {
|
|
103
|
-
el.innerHTML = key === "innerHTML" ?
|
|
65
|
+
el.innerHTML = plainText(key === "innerHTML" ? value : value !== null && typeof value === "object" ? Reflect.get(value, "__html") : void 0);
|
|
104
66
|
return;
|
|
105
67
|
}
|
|
106
68
|
if (key === "textContent") {
|
|
@@ -111,67 +73,34 @@ function applyKey(el, key, value, state, svg) {
|
|
|
111
73
|
setSelectValue(el, value);
|
|
112
74
|
return;
|
|
113
75
|
}
|
|
114
|
-
if (!svg && LIVE_PROPERTIES.
|
|
115
|
-
liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.
|
|
76
|
+
if (!svg && LIVE_PROPERTIES.test(key) && key in el) {
|
|
77
|
+
liveDiffers(el, key, value, svg) && Reflect.set(el, key, STRING_PROPERTIES.test(key) ? value ?? "" : Boolean(value));
|
|
116
78
|
if (key === "value" && el instanceof HTMLInputElement) el.defaultValue = plainText(value);
|
|
117
79
|
return;
|
|
118
80
|
}
|
|
119
|
-
writeKey(el, key, value, svg);
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute
|
|
123
|
-
* under its React name. An `undefined` value removes the attribute or resets the property, which is how
|
|
124
|
-
* a prop that disappeared is undone.
|
|
125
|
-
*/
|
|
126
|
-
function writeKey(el, key, value, svg) {
|
|
127
81
|
if (key.startsWith("prop:")) Reflect.set(el, key.slice(5), value);
|
|
128
82
|
else if (key.startsWith("attr:")) setAttribute(el, key.slice(5), value);
|
|
129
83
|
else if (key.startsWith("bool:")) setBoolAttribute(el, key.slice(5), value);
|
|
130
84
|
else {
|
|
131
85
|
const wire = attributeName(key, svg);
|
|
132
|
-
if (wire
|
|
86
|
+
if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);
|
|
87
|
+
else if (wire.startsWith("xlink:")) setAttributeNS(el, XLINK_NS, wire, value);
|
|
133
88
|
else setAttribute(el, wire, value);
|
|
134
89
|
}
|
|
135
90
|
}
|
|
136
91
|
/** Props written as element properties, like the compiler does for the same names in JSX. */
|
|
137
|
-
const LIVE_PROPERTIES =
|
|
138
|
-
"value",
|
|
139
|
-
"checked",
|
|
140
|
-
"selected",
|
|
141
|
-
"muted",
|
|
142
|
-
"indeterminate",
|
|
143
|
-
"defaultValue",
|
|
144
|
-
"defaultChecked"
|
|
145
|
-
]);
|
|
92
|
+
const LIVE_PROPERTIES = /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;
|
|
146
93
|
/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */
|
|
147
|
-
const STRING_PROPERTIES =
|
|
94
|
+
const STRING_PROPERTIES = /^(?:value|defaultValue)$/;
|
|
148
95
|
/**
|
|
149
96
|
* True when a live property (typed value, toggled box) no longer matches the value last applied, so
|
|
150
97
|
* an unchanged prop is written again and the element follows the data.
|
|
151
98
|
*/
|
|
152
99
|
function liveDiffers(el, key, value, svg) {
|
|
153
|
-
if (svg || !LIVE_PROPERTIES.
|
|
100
|
+
if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;
|
|
154
101
|
if (key === "value" && el instanceof HTMLSelectElement) return true;
|
|
155
102
|
const live = Reflect.get(el, key);
|
|
156
|
-
return STRING_PROPERTIES.
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Applies the entries that changed since the last run and undoes the ones that disappeared.
|
|
160
|
-
* Unchanged values are skipped by identity, so only changed keys touch the DOM.
|
|
161
|
-
*/
|
|
162
|
-
function applyEntries(el, entries, state, svg) {
|
|
163
|
-
const current = /* @__PURE__ */ new Set();
|
|
164
|
-
for (const [key, value] of entries) {
|
|
165
|
-
current.add(key);
|
|
166
|
-
if (state.values.has(key) && Object.is(state.values.get(key), value) && !liveDiffers(el, key, value, svg)) continue;
|
|
167
|
-
state.values.set(key, value);
|
|
168
|
-
applyKey(el, key, value, state, svg);
|
|
169
|
-
}
|
|
170
|
-
for (const key of [...state.values.keys()]) {
|
|
171
|
-
if (current.has(key)) continue;
|
|
172
|
-
state.values.delete(key);
|
|
173
|
-
applyKey(el, key, void 0, state, svg);
|
|
174
|
-
}
|
|
103
|
+
return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);
|
|
175
104
|
}
|
|
176
105
|
/**
|
|
177
106
|
* Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for
|
|
@@ -221,28 +150,88 @@ function applyEntries(el, entries, state, svg) {
|
|
|
221
150
|
function spread(el, props, isSVG = false, skipChildren = false) {
|
|
222
151
|
if (props === null || typeof props !== "object" && typeof props !== "function") return;
|
|
223
152
|
const read = () => typeof props === "function" ? props() : props;
|
|
224
|
-
const
|
|
225
|
-
if (!skipChildren &&
|
|
153
|
+
const state = newState();
|
|
154
|
+
if (!skipChildren && el.localName !== "textarea") {
|
|
226
155
|
const initial = claims.current.isClaiming() ? claims.current.takeRegion(el, null) ?? Array.from(el.childNodes) : void 0;
|
|
227
156
|
const region = createRegion(el, null, initial);
|
|
228
157
|
bindRegion(region, () => read()?.children);
|
|
158
|
+
followOptions(el, isSVG, state);
|
|
229
159
|
}
|
|
230
|
-
|
|
160
|
+
applyProps(el, read, isSVG, state);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* New options replace the ones that held the selection, and the value effect does not read
|
|
164
|
+
* `children`: a select spread selects its value again after every commit to its children, as the
|
|
165
|
+
* compiled path does.
|
|
166
|
+
*/
|
|
167
|
+
function followOptions(el, isSVG, state) {
|
|
168
|
+
if (isSVG || !(el instanceof HTMLSelectElement)) return;
|
|
169
|
+
watchCommits(el, () => {
|
|
170
|
+
const key = state.values.has("value") ? "value" : "defaultValue";
|
|
171
|
+
if (state.values.has(key)) setSelectValue(el, state.values.get(key));
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/** The bookkeeping of a spread that has applied nothing yet. */
|
|
175
|
+
function newState() {
|
|
176
|
+
return {
|
|
231
177
|
values: /* @__PURE__ */ new Map(),
|
|
232
|
-
|
|
233
|
-
styleValue: void 0,
|
|
234
|
-
classListValue: void 0,
|
|
235
|
-
refCleanup: void 0
|
|
178
|
+
unbind: /* @__PURE__ */ new Map()
|
|
236
179
|
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Applies the props of `read()` to `el` and keeps them in sync, without a children region: what
|
|
183
|
+
* {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds
|
|
184
|
+
* the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's
|
|
185
|
+
* children. A select still selects its value again when `Dynamic` commits new options.
|
|
186
|
+
* @internal
|
|
187
|
+
*/
|
|
188
|
+
function spreadProps(el, props, isSVG) {
|
|
189
|
+
if (props === null || typeof props !== "object" && typeof props !== "function") return;
|
|
190
|
+
const state = newState();
|
|
191
|
+
followOptions(el, isSVG, state);
|
|
192
|
+
applyProps(el, () => typeof props === "function" ? props() : props, isSVG, state);
|
|
193
|
+
}
|
|
194
|
+
function applyProps(el, read, isSVG, state) {
|
|
195
|
+
const textarea = el.localName === "textarea";
|
|
237
196
|
onCleanup(() => {
|
|
238
|
-
for (const unbind of state.
|
|
239
|
-
state.
|
|
197
|
+
for (const unbind of state.unbind.values()) unbind();
|
|
198
|
+
state.unbind.clear();
|
|
240
199
|
runRefCleanup(state);
|
|
241
200
|
});
|
|
242
|
-
useRenderEffect(() =>
|
|
243
|
-
|
|
201
|
+
useRenderEffect(() => {
|
|
202
|
+
const props = read();
|
|
203
|
+
const entries = [];
|
|
204
|
+
if (props === null || typeof props !== "object") return entries;
|
|
205
|
+
let value;
|
|
206
|
+
let hasValue = false;
|
|
207
|
+
for (const key of Object.keys(props)) {
|
|
208
|
+
if (FORBIDDEN_NAMES.test(key.slice(key.indexOf(":") + 1)) || IGNORED_KEYS.test(key)) continue;
|
|
209
|
+
if (key === "children") {
|
|
210
|
+
if (textarea) {
|
|
211
|
+
value = Reflect.get(props, key);
|
|
212
|
+
hasValue = true;
|
|
213
|
+
}
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
entries.push([key, Reflect.get(props, key)]);
|
|
217
|
+
}
|
|
218
|
+
if (hasValue && !entries.some(([key]) => key === "value")) entries.push(["value", value]);
|
|
219
|
+
return entries;
|
|
220
|
+
}, (entries) => {
|
|
221
|
+
const current = /* @__PURE__ */ new Set();
|
|
222
|
+
for (const [key, value] of entries) {
|
|
223
|
+
current.add(key);
|
|
224
|
+
if (state.values.has(key) && Object.is(state.values.get(key), value) && !liveDiffers(el, key, value, isSVG)) continue;
|
|
225
|
+
state.values.set(key, value);
|
|
226
|
+
applyKey(el, key, value, state, isSVG);
|
|
227
|
+
}
|
|
228
|
+
for (const key of [...state.values.keys()]) {
|
|
229
|
+
if (current.has(key)) continue;
|
|
230
|
+
state.values.delete(key);
|
|
231
|
+
applyKey(el, key, void 0, state, isSVG);
|
|
232
|
+
}
|
|
244
233
|
});
|
|
245
234
|
}
|
|
246
|
-
export { spread };
|
|
235
|
+
export { spread, spreadProps };
|
|
247
236
|
|
|
248
237
|
//# sourceMappingURL=spread.js.map
|
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 } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } 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 = new Set([\"__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.has(nameOf(key)) || IGNORED_KEYS.has(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.has(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.has(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 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: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"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.has(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.has(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 textarea = el.localName === \"textarea\";\n if (!skipChildren && !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 }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\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,kCAAkB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAezE,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,IAAI,OAAO,GAAG,CAAC,KAAK,aAAa,IAAI,GAAG,GAAG;EAC/D,IAAI,QAAQ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AwB,IAAI;CACxF,MAAM,WAAW,GAAG,cAAc;CAClC,IAAI,CAAC,gBAAgB,CAAC,UAAU;EAE9B,MAAM,UAAU,OAAO,QAAQ,WAAW,IACrC,OAAO,QAAQ,WAAW,IAAI,IAAI,KAAK,MAAM,KAAK,GAAG,UAAU,IAChE,KAAA;EACJ,MAAM,SAAS,aAAa,IAAI,MAAM,OAAO;EAC7C,WAAW,cAAe,KAAK,CAAC,EAA6C,QAAQ;CACvF;CACA,MAAM,QAAqB;EACzB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;EACnB,YAAY,KAAA;EACZ,gBAAgB,KAAA;EAChB,YAAY,KAAA;CACd;CAEA,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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G;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/dev/template.js
CHANGED
|
@@ -35,9 +35,7 @@ function inNamespace(source, namespace) {
|
|
|
35
35
|
const root = copyOf(source);
|
|
36
36
|
const stack = [[source, root]];
|
|
37
37
|
while (stack.length > 0) {
|
|
38
|
-
const
|
|
39
|
-
if (pair === void 0) break;
|
|
40
|
-
const [from, to] = pair;
|
|
38
|
+
const [from, to] = stack.pop();
|
|
41
39
|
for (const child of Array.from(from.childNodes)) if (child instanceof Element) {
|
|
42
40
|
const copy = copyOf(child);
|
|
43
41
|
to.appendChild(copy);
|
package/dist/dev/template.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.js","names":[],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const
|
|
1
|
+
{"version":3,"file":"template.js","names":[],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const [from, to] = stack.pop() as [Element, Element];\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,YACJ;;AAEF,MAAM,YAAY;;;;;;AAOlB,SAAS,mBAAmB,MAAoB;CAC9C,KAAK,MAAM,OAAO,KAAK,SAAS,SAAS,GAAG;EAG1C,IADgB,CADI,IAAI,IAAI,MAAM,GAAA,CAAI,SAAS,SAAS,CAC/B,CAAC,CAAC,QAAQ,UAAU,MAAM,EAAE,EAAE,YAAY,MAAM,OAC/D,CAAC,CAAC,SAAS,GAAG;EACxB,MAAM,OAAO,eAAe,KAAK,IAAI,EAAE,CAAC,GAAG,MAAM;EACjD,SACE,6BACA,IAAI,KAAK,0GACX;EACA;CACF;AACF;;;;;AAMA,SAAS,YAAY,QAAiB,WAA4B;CAChE,MAAM,MAAM;CACZ,MAAM,UAAU,YAA8B;EAC5C,MAAM,OAAO,IAAI,gBAAgB,WAAW,QAAQ,SAAS;EAC7D,KAAK,MAAM,aAAa,MAAM,KAAK,QAAQ,UAAU,GACnD,KAAK,aAAa,UAAU,MAAM,UAAU,KAAK;EAEnD,OAAO;CACT;CACA,MAAM,OAAO,OAAO,MAAM;CAC1B,MAAM,QAAmC,CAAC,CAAC,QAAQ,IAAI,CAAC;CACxD,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,CAAC,MAAM,MAAM,MAAM,IAAI;EAC7B,KAAK,MAAM,SAAS,MAAM,KAAK,KAAK,UAAU,GAC5C,IAAI,iBAAiB,SAAS;GAC5B,MAAM,OAAO,OAAO,KAAK;GACzB,GAAG,YAAY,IAAI;GACnB,MAAM,KAAK,CAAC,OAAO,IAAI,CAAC;EAC1B,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AAmB,SAAS;EAClC,IAAI,OAAO,WAAW,GAAG;GACvB,MAAM,CAAC,QAAQ;GACf,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK,IAAI;EAC1C;EACA,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,MAAM,QAAQ,QAAQ,SAAS,YAAY,KAAK,IAAI,CAAC;EAC1D,OAAO;CACT;AACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { watchCommits } from "./insert.js";
|
|
1
2
|
import { flushSync, untrack, useEffect, useId } from "@shadow-js/core";
|
|
2
3
|
// src/view-transition.ts
|
|
3
4
|
/**
|
|
@@ -95,10 +96,17 @@ function ViewTransition(props) {
|
|
|
95
96
|
const end = document.createTextNode("");
|
|
96
97
|
const generated = props.name === true ? `vt-${useId()}` : void 0;
|
|
97
98
|
useEffect(() => {
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
99
|
+
const name = generated ?? (typeof props.name === "string" ? props.name : void 0);
|
|
100
|
+
const transitionClass = props.class;
|
|
101
|
+
const apply = () => {
|
|
102
|
+
const element = firstElementBetween(start, end);
|
|
103
|
+
if (element === null) return;
|
|
104
|
+
setOrClear(element, "view-transition-name", name);
|
|
105
|
+
setOrClear(element, "view-transition-class", transitionClass);
|
|
106
|
+
};
|
|
107
|
+
apply();
|
|
108
|
+
const parent = start.parentNode;
|
|
109
|
+
if (parent !== null) watchCommits(parent, apply);
|
|
102
110
|
});
|
|
103
111
|
return () => [
|
|
104
112
|
start,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-transition.js","names":[],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists
|
|
1
|
+
{"version":3,"file":"view-transition.js","names":[],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\nimport { watchCommits } from \"./insert\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists. The content can change later\n // (a Show that opens, a fallback replaced by content) and the first element is then another one:\n // the name is applied again after each commit to the parent's regions, where that change lands.\n useEffect(() => {\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n const transitionClass = props.class;\n const apply = (): void => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", transitionClass);\n };\n apply();\n const parent = start.parentNode;\n if (parent !== null) watchCommits(parent, apply);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,oBACd,QACA,SACe;CACf,MAAM,MAAM,OAAO,aAAa,cAAc,KAAA,IAAa;CAC3D,IAAI,QAAQ,KAAA,KAAa,OAAO,IAAI,wBAAwB,YAAY;EACtE,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,OAAO,QAAQ,OAAO,KAAK;EAC7B;EACA,OAAO,QAAQ,QAAQ;CACzB;CACA,IAAI;CACJ,MAAM,iBAAuB;EAC3B,IAAI;GACF,UAAU,MAAM;EAClB,SAAS,OAAO;GACd,UAAU,EAAE,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,SAAS;CAIvB,OAHm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,UAAU,KAAK;AAChD"}
|
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 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,IAErBD,EAAqBC,EAAWJ,CAAI,EACP,GAAgCQ,EAAhC,EAG7BE,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,EAAiB,+BAMjBC,EAAiB,4EAMjBC,EAAgB,2DAGhBC,EAAsB,6CAO5B,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACJ,EAAe,KAAKK,CAAI,EAAG,MAAMC,EAAqBD,CAAI,CACjE,CAGA,SAASE,EAAY,EAAwB,CAE3C,OAAOJ,EAAoB,KACzBK,EACG,QAAQ,WAAY,EAAE,CAAC,CACvB,KAAK,CAAC,CACN,YAAY,CACjB,CACF,CAwBA,SAAgBC,EAAqB,EAAc,EAAwB,CACzE,IAAMC,EAAYL,EAAK,YAAY,EAGnC,OAFKJ,EAAe,KAAKS,CAAS,EAE3BA,IAAc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,CACzC,C"}
|
package/dist/prod/class-style.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
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
|