@umber-style/core 0.0.0 → 0.1.0-alpha.0
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/LICENSE +21 -0
- package/README.md +13 -1
- package/dist/index.cjs +2064 -0
- package/dist/index.d.cts +617 -0
- package/dist/index.d.mts +617 -0
- package/dist/index.mjs +2020 -0
- package/package.json +66 -5
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2064 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
// src/alpha.ts
|
|
3
|
+
const BRAND$1 = Symbol.for("umber-style.alpha-color");
|
|
4
|
+
const NUMBER$1 = String.raw`[+-]?(?:\d+\.?\d*|\.\d+)`;
|
|
5
|
+
const HEX_PATTERN = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
6
|
+
const FUNCTION_PATTERNS = [new RegExp(String.raw`^rgba?\(\s*(${NUMBER$1})\s*,\s*(${NUMBER$1})\s*,\s*(${NUMBER$1})\s*(?:,\s*(${NUMBER$1}%?)\s*)?\)$`, "i"), new RegExp(String.raw`^rgba?\(\s*(${NUMBER$1})\s+(${NUMBER$1})\s+(${NUMBER$1})\s*(?:/\s*(${NUMBER$1}%?)\s*)?\)$`, "i")];
|
|
7
|
+
/** Whether `value` was made by `alpha()` as a mix: a plain string is a color, not a fallback pair. */
|
|
8
|
+
function isAlphaColor(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && BRAND$1 in value;
|
|
10
|
+
}
|
|
11
|
+
/** `value` limited to `low` through `high`. */
|
|
12
|
+
function clamp(value, low, high) {
|
|
13
|
+
return Math.min(high, Math.max(low, value));
|
|
14
|
+
}
|
|
15
|
+
/** `value` with four decimals at most, so that float noise (0.1 * 3) does not reach the CSS. */
|
|
16
|
+
function round(value) {
|
|
17
|
+
return Math.round(value * 1e4) / 1e4;
|
|
18
|
+
}
|
|
19
|
+
/** The channels of `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, or undefined for another string. */
|
|
20
|
+
function readHex(color) {
|
|
21
|
+
if (!HEX_PATTERN.test(color)) return void 0;
|
|
22
|
+
const digits = color.slice(1);
|
|
23
|
+
const full = digits.length <= 4 ? [...digits].map((digit) => digit + digit).join("") : digits;
|
|
24
|
+
const [red, green, blue, opacity = 255] = [
|
|
25
|
+
0,
|
|
26
|
+
2,
|
|
27
|
+
4,
|
|
28
|
+
6
|
|
29
|
+
].slice(0, full.length / 2).map((start) => Number.parseInt(full.slice(start, start + 2), 16));
|
|
30
|
+
return {
|
|
31
|
+
red,
|
|
32
|
+
green,
|
|
33
|
+
blue,
|
|
34
|
+
opacity: opacity / 255
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** The channels of `rgb()` or `rgba()` with numbers (comma or space syntax), or undefined for another string. */
|
|
38
|
+
function readFunction(color) {
|
|
39
|
+
for (const pattern of FUNCTION_PATTERNS) {
|
|
40
|
+
const match = pattern.exec(color);
|
|
41
|
+
if (match === null) continue;
|
|
42
|
+
const [red, green, blue] = [
|
|
43
|
+
1,
|
|
44
|
+
2,
|
|
45
|
+
3
|
|
46
|
+
].map((index) => Math.round(clamp(Number.parseFloat(match[index]), 0, 255)));
|
|
47
|
+
const given = match[4] ?? "1";
|
|
48
|
+
return {
|
|
49
|
+
red,
|
|
50
|
+
green,
|
|
51
|
+
blue,
|
|
52
|
+
opacity: clamp(given.endsWith("%") ? Number.parseFloat(given) / 100 : Number.parseFloat(given), 0, 1)
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* `color` at `opacity` as `rgba(r, g, b, a)`, when `color` is a literal that can be read (`#rgb`, `#rgba`,
|
|
58
|
+
* `#rrggbb`, `#rrggbbaa`, `rgb()` or `rgba()` with numbers; its own alpha is multiplied), else undefined.
|
|
59
|
+
*/
|
|
60
|
+
function toRgba(color, opacity) {
|
|
61
|
+
const channels = readHex(color.trim()) ?? readFunction(color.trim());
|
|
62
|
+
if (channels === void 0) return void 0;
|
|
63
|
+
const { red, green, blue } = channels;
|
|
64
|
+
return `rgba(${red}, ${green}, ${blue}, ${round(channels.opacity * opacity)})`;
|
|
65
|
+
}
|
|
66
|
+
/** Throws what `alpha()` throws: a `TypeError` for a color that is not a string or an opacity that is not a number, a `RangeError` for an opacity outside 0 to 1 or NaN. */
|
|
67
|
+
function assertAlphaInput(color, opacity) {
|
|
68
|
+
if (typeof color !== "string") throw new TypeError(`alpha(): the color must be a string, got ${typeof color}`);
|
|
69
|
+
if (typeof opacity !== "number") throw new TypeError(`alpha(): the opacity must be a number, got ${typeof opacity}`);
|
|
70
|
+
if (!(opacity >= 0 && opacity <= 1)) throw new RangeError(`alpha(): the opacity must be from 0 to 1, got ${opacity}`);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* `color` at `opacity` (0 to 1). Between 0 and 1 the result is an `AlphaColor`: written as a fallback
|
|
74
|
+
* (`rgba()` for a literal colour, else the colour itself) followed by `color-mix(in srgb, <color> <n>%,
|
|
75
|
+
* transparent)`, which works with var(--x) colors. 1 returns `color` and 0 returns `transparent`. A
|
|
76
|
+
* fallback is only written when the result is the whole value of a property; in a longer string
|
|
77
|
+
* (`1px solid ${alpha(c, 0.5)}`) it is the color-mix() form alone. Throws a `TypeError` for a color
|
|
78
|
+
* that is not a string or an opacity that is not a number, a `RangeError` for an opacity outside 0 to 1.
|
|
79
|
+
*/
|
|
80
|
+
function alpha(color, opacity) {
|
|
81
|
+
assertAlphaInput(color, opacity);
|
|
82
|
+
if (opacity === 1) return color;
|
|
83
|
+
if (opacity === 0) return "transparent";
|
|
84
|
+
const value = `color-mix(in srgb, ${color} ${Math.round(opacity * 1e4) / 100}%, transparent)`;
|
|
85
|
+
const mix = {};
|
|
86
|
+
Object.defineProperties(mix, {
|
|
87
|
+
fallback: {
|
|
88
|
+
value: toRgba(color, opacity) ?? color,
|
|
89
|
+
enumerable: true
|
|
90
|
+
},
|
|
91
|
+
value: {
|
|
92
|
+
value,
|
|
93
|
+
enumerable: true
|
|
94
|
+
},
|
|
95
|
+
toString: { value: () => value },
|
|
96
|
+
[BRAND$1]: { value: true }
|
|
97
|
+
});
|
|
98
|
+
return Object.freeze(mix);
|
|
99
|
+
}
|
|
100
|
+
// src/at.ts
|
|
101
|
+
/**
|
|
102
|
+
* `{ [key]: style }` typed so that it can be spread into a web style. A key that is computed in an
|
|
103
|
+
* object literal has the type `string`, and the web style type rejects it (its custom property
|
|
104
|
+
* signature takes no style); the key here keeps its template literal type, and `style` is checked as a
|
|
105
|
+
* style of its own: `{ ...at(`@media (width >= ${breakpoint})`, { gap: 16 }) }`.
|
|
106
|
+
*/
|
|
107
|
+
function at(key, style) {
|
|
108
|
+
return { [key]: style };
|
|
109
|
+
}
|
|
110
|
+
// src/hash.ts
|
|
111
|
+
const MULTIPLIER = 0x5bd1e995;
|
|
112
|
+
/** Multiplies `value` by the hash constant, kept to 32 bits. */
|
|
113
|
+
function multiply$1(value) {
|
|
114
|
+
return (value & 65535) * MULTIPLIER + ((value >>> 16) * 59797 << 16);
|
|
115
|
+
}
|
|
116
|
+
/** A short, stable hash of `text`, in base 36. */
|
|
117
|
+
function hashString(text) {
|
|
118
|
+
let hash = 0;
|
|
119
|
+
let index = 0;
|
|
120
|
+
let remaining = text.length;
|
|
121
|
+
const codeAt = (position) => text.codePointAt(position) & 255;
|
|
122
|
+
for (; remaining >= 4; index += 4, remaining -= 4) {
|
|
123
|
+
let chunk = codeAt(index) | codeAt(index + 1) << 8 | codeAt(index + 2) << 16 | codeAt(index + 3) << 24;
|
|
124
|
+
chunk = multiply$1(chunk);
|
|
125
|
+
chunk ^= chunk >>> 24;
|
|
126
|
+
hash = multiply$1(chunk) ^ multiply$1(hash);
|
|
127
|
+
}
|
|
128
|
+
if (remaining === 3) hash ^= codeAt(index + 2) << 16;
|
|
129
|
+
if (remaining >= 2) hash ^= codeAt(index + 1) << 8;
|
|
130
|
+
if (remaining >= 1) hash = multiply$1(hash ^ codeAt(index));
|
|
131
|
+
hash ^= hash >>> 13;
|
|
132
|
+
hash = multiply$1(hash);
|
|
133
|
+
return ((hash ^ hash >>> 15) >>> 0).toString(36);
|
|
134
|
+
}
|
|
135
|
+
// src/findMissingStyles.ts
|
|
136
|
+
const STATE_PATTERN = /:(hover|focus|active|focus-visible|focus-within)\b/;
|
|
137
|
+
const NAME_CODES = /[a-z0-9_-]/;
|
|
138
|
+
/** The prefix named by the first style element of an engine on the page, or undefined. */
|
|
139
|
+
function findPrefix() {
|
|
140
|
+
const element = document.querySelector("style[data-style], style[data-precedence]");
|
|
141
|
+
return element?.dataset.style ?? element?.dataset.precedence;
|
|
142
|
+
}
|
|
143
|
+
/** The style rules under `list`, groups included. */
|
|
144
|
+
function collectStyleRules(list, found) {
|
|
145
|
+
for (const rule of list) if (rule instanceof CSSStyleRule) found.push(rule);
|
|
146
|
+
else if ("cssRules" in rule) collectStyleRules(rule.cssRules, found);
|
|
147
|
+
return found;
|
|
148
|
+
}
|
|
149
|
+
/** The classes that start with `start` in `selector`. */
|
|
150
|
+
function readClassNames(selector, start) {
|
|
151
|
+
const names = [];
|
|
152
|
+
let from = selector.indexOf(`.${start}`);
|
|
153
|
+
while (from !== -1) {
|
|
154
|
+
let end = from + 1 + start.length;
|
|
155
|
+
while (end < selector.length && NAME_CODES.test(selector[end])) end++;
|
|
156
|
+
names.push(selector.slice(from + 1, end));
|
|
157
|
+
from = selector.indexOf(`.${start}`, end);
|
|
158
|
+
}
|
|
159
|
+
return names;
|
|
160
|
+
}
|
|
161
|
+
/** The variables that `text` refers to without a fallback: `var(--prefix-x)`. */
|
|
162
|
+
function readBareVariables(text, start) {
|
|
163
|
+
const names = [];
|
|
164
|
+
let from = text.indexOf("var(");
|
|
165
|
+
while (from !== -1) {
|
|
166
|
+
const begin = from + 4;
|
|
167
|
+
let end = begin + start.length;
|
|
168
|
+
if (text.startsWith(start, begin)) {
|
|
169
|
+
while (end < text.length && NAME_CODES.test(text[end])) end++;
|
|
170
|
+
if (text[end] === ")") names.push(text.slice(begin, end));
|
|
171
|
+
}
|
|
172
|
+
from = text.indexOf("var(", begin);
|
|
173
|
+
}
|
|
174
|
+
return names;
|
|
175
|
+
}
|
|
176
|
+
/** A short name of `element` for a message. */
|
|
177
|
+
function describe(element) {
|
|
178
|
+
const label = element.attributes.getNamedItem("data-testid")?.value ?? element.id;
|
|
179
|
+
return `${element.tagName.toLowerCase()}[${label}]`;
|
|
180
|
+
}
|
|
181
|
+
/** Whether `element` matches the selector of `rule`; a selector the browser cannot parse matches nothing. */
|
|
182
|
+
function isMatched(element, rule) {
|
|
183
|
+
try {
|
|
184
|
+
return element.matches(rule.selectorText);
|
|
185
|
+
} catch {
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** The rules of the engine's style elements, each with the variables it uses without a fallback. */
|
|
190
|
+
function collectRules(prefix) {
|
|
191
|
+
const selector = `style[data-style="${prefix}"], style[data-precedence="${prefix}"]`;
|
|
192
|
+
const rules = [];
|
|
193
|
+
for (const element of document.querySelectorAll(selector)) if (element.sheet) collectStyleRules(element.sheet.cssRules, rules);
|
|
194
|
+
return rules.map((rule) => ({
|
|
195
|
+
rule,
|
|
196
|
+
variables: readBareVariables(rule.cssText, `--${prefix}-`),
|
|
197
|
+
isState: STATE_PATTERN.test(rule.selectorText)
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
/** The classes of the engine on the element called `label` that no rule names. */
|
|
201
|
+
function findClassProblems(label, classes, named, problems) {
|
|
202
|
+
for (const name of classes) {
|
|
203
|
+
if (named.has(name)) continue;
|
|
204
|
+
const message = `${label} has the class ${name}, which no rule names`;
|
|
205
|
+
problems.push({
|
|
206
|
+
kind: "class-without-rule",
|
|
207
|
+
name,
|
|
208
|
+
element: label,
|
|
209
|
+
message,
|
|
210
|
+
key: `class:${name}`
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** The variables used by a rule that matches `element` and that have no value on it. */
|
|
215
|
+
function findVariableProblems(element, label, rules, problems) {
|
|
216
|
+
const computed = getComputedStyle(element);
|
|
217
|
+
for (const { rule, variables, isState } of rules) {
|
|
218
|
+
if (variables.length === 0 || isState || !isMatched(element, rule)) continue;
|
|
219
|
+
for (const name of variables) {
|
|
220
|
+
if (computed.getPropertyValue(name).trim() !== "") continue;
|
|
221
|
+
const message = `${label} has no value for ${name}, which ${rule.selectorText} uses`;
|
|
222
|
+
const key = `variable:${name}:${rule.selectorText}`;
|
|
223
|
+
problems.push({
|
|
224
|
+
kind: "variable-without-value",
|
|
225
|
+
name,
|
|
226
|
+
element: label,
|
|
227
|
+
message,
|
|
228
|
+
key
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Looks at a page that an engine styled, and lists what is missing. For each element under `root`
|
|
235
|
+
* (the document by default): every class of the engine on it is named by at least one rule of the
|
|
236
|
+
* engine's style elements (its own, and the ones React hoists), and every variable of the engine that
|
|
237
|
+
* a rule matching the element uses, without a fallback, has a value on the element. The classes that
|
|
238
|
+
* are markers (`<prefix>-boundary`, `<prefix>-scheme-light` and `-dark`) have no rule of their own and
|
|
239
|
+
* are left out, and so are the rules for `:hover`, `:focus` and the like. An empty list means nothing
|
|
240
|
+
* is missing. Where there is no document, or no style element of an engine, the list is empty.
|
|
241
|
+
*/
|
|
242
|
+
function findMissingStyles(root, options = {}) {
|
|
243
|
+
if (typeof document === "undefined") return [];
|
|
244
|
+
const prefix = options.prefix ?? findPrefix();
|
|
245
|
+
if (prefix === void 0) return [];
|
|
246
|
+
const scope = root ?? document;
|
|
247
|
+
const rules = collectRules(prefix);
|
|
248
|
+
const named = new Set(rules.flatMap(({ rule }) => readClassNames(rule.selectorText, `${prefix}-`)));
|
|
249
|
+
const markers = /* @__PURE__ */ new Set([
|
|
250
|
+
`${prefix}-boundary`,
|
|
251
|
+
`${prefix}-scheme-light`,
|
|
252
|
+
`${prefix}-scheme-dark`
|
|
253
|
+
]);
|
|
254
|
+
const problems = [];
|
|
255
|
+
const elements = [...scope instanceof Element ? [scope] : [], ...scope.querySelectorAll("*")];
|
|
256
|
+
for (const element of elements) {
|
|
257
|
+
const classes = [...element.classList].filter((name) => name.startsWith(`${prefix}-`) && !markers.has(name));
|
|
258
|
+
if (classes.length === 0) continue;
|
|
259
|
+
const label = describe(element);
|
|
260
|
+
findClassProblems(label, classes, named, problems);
|
|
261
|
+
findVariableProblems(element, label, rules, problems);
|
|
262
|
+
}
|
|
263
|
+
return problems;
|
|
264
|
+
}
|
|
265
|
+
// src/devChecks.ts
|
|
266
|
+
/** How long a check waits after the last insertion, in milliseconds: rules arrive in bursts while a page renders. */
|
|
267
|
+
const CHECK_DELAY = 250;
|
|
268
|
+
/** Whether this is a development build: `process.env.NODE_ENV` is `development`. Where `process` does not exist (a browser, no bundler) it is not. */
|
|
269
|
+
function isDevelopment() {
|
|
270
|
+
try {
|
|
271
|
+
return process.env.NODE_ENV === "development";
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* The function that asks for a check of the page: it runs `findMissingStyles` once, after the calls
|
|
278
|
+
* have stopped for a short while, and warns once for each problem (never again for the same one).
|
|
279
|
+
*/
|
|
280
|
+
function createDevChecker(prefix, delay = CHECK_DELAY) {
|
|
281
|
+
const warned = /* @__PURE__ */ new Set();
|
|
282
|
+
let timer;
|
|
283
|
+
const run = () => {
|
|
284
|
+
timer = void 0;
|
|
285
|
+
for (const problem of findMissingStyles(document, { prefix })) {
|
|
286
|
+
if (warned.has(problem.key)) continue;
|
|
287
|
+
warned.add(problem.key);
|
|
288
|
+
console.warn(`[${prefix}] ${problem.message}`);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
return () => {
|
|
292
|
+
timer ??= setTimeout(run, delay);
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
// src/fingerprint.ts
|
|
296
|
+
/** The short code each option has in the stamp, in the order they are written. */
|
|
297
|
+
const CODES = [
|
|
298
|
+
["p", "prefix"],
|
|
299
|
+
["x", "suffix"],
|
|
300
|
+
["l", "hasLabels"],
|
|
301
|
+
["y", "hasLayers"],
|
|
302
|
+
["r", "hasPruning"],
|
|
303
|
+
["b", "hasBaseClass"],
|
|
304
|
+
["s", "hasScope"],
|
|
305
|
+
["f", "hasColorFallbacks"],
|
|
306
|
+
["t", "tokens"]
|
|
307
|
+
];
|
|
308
|
+
/** The text of one option in the stamp: a flag is 1 or 0, a string is encoded. */
|
|
309
|
+
function toStampValue(value) {
|
|
310
|
+
if (typeof value !== "boolean") return encodeURIComponent(value);
|
|
311
|
+
return value ? "1" : "0";
|
|
312
|
+
}
|
|
313
|
+
/** The stamp of `options`, short enough for an attribute: `p=umber;x=;l=1;y=1;...`. */
|
|
314
|
+
function createFingerprint(options) {
|
|
315
|
+
return CODES.map(([code, name]) => `${code}=${toStampValue(options[name])}`).join(";");
|
|
316
|
+
}
|
|
317
|
+
/** The values of a stamp, by short code. */
|
|
318
|
+
function parseFingerprint(stamp) {
|
|
319
|
+
return new Map(stamp.split(";").map((part) => {
|
|
320
|
+
const at = part.indexOf("=");
|
|
321
|
+
return [part.slice(0, at), part.slice(at + 1)];
|
|
322
|
+
}));
|
|
323
|
+
}
|
|
324
|
+
/** The message that says which options differ between the stamp of the server and that of the browser, or '' when none. */
|
|
325
|
+
function describeFingerprintDifferences(server, browser) {
|
|
326
|
+
const theirs = parseFingerprint(server);
|
|
327
|
+
const ours = parseFingerprint(browser);
|
|
328
|
+
const differences = CODES.filter(([code]) => theirs.get(code) !== ours.get(code)).map(([code, name]) => `${name} (server: ${decodeURIComponent(theirs.get(code) ?? "")}, browser: ${decodeURIComponent(ours.get(code))})`);
|
|
329
|
+
if (differences.length === 0) return "";
|
|
330
|
+
return `UmberStyle: the server rendered this page with other options than the browser uses. Differing options: ${differences.join("; ")}. Create the style with the same options on both sides.`;
|
|
331
|
+
}
|
|
332
|
+
// src/codeAt.ts
|
|
333
|
+
/** The code point at `index` of `text`; NaN past the end, so that every comparison with a code is false. */
|
|
334
|
+
function codeAt(text, index) {
|
|
335
|
+
return text.codePointAt(index) ?? NaN;
|
|
336
|
+
}
|
|
337
|
+
// src/variables.ts
|
|
338
|
+
const VARIABLE_OPEN = "var(";
|
|
339
|
+
/** Whether `code` is a character of a variable name: a lowercase letter, a digit, '-' or '_'. */
|
|
340
|
+
function isNameCode$1(code) {
|
|
341
|
+
return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
|
|
342
|
+
}
|
|
343
|
+
/** The index of the first character at or after `index` that is not whitespace. */
|
|
344
|
+
function skipSpaces$1(text, index) {
|
|
345
|
+
let position = index;
|
|
346
|
+
while (codeAt(text, position) <= 32) position++;
|
|
347
|
+
return position;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* The names of the variables that `css` refers to and that start with `start` (`--<prefix>-`), in order
|
|
351
|
+
* of appearance, with repeats. A reference may have a fallback, which may refer to others. One pass.
|
|
352
|
+
*/
|
|
353
|
+
function scanVariables(css, start) {
|
|
354
|
+
const names = [];
|
|
355
|
+
let from = css.indexOf(VARIABLE_OPEN);
|
|
356
|
+
while (from !== -1) {
|
|
357
|
+
const begin = skipSpaces$1(css, from + 4);
|
|
358
|
+
let end = begin + start.length;
|
|
359
|
+
if (css.startsWith(start, begin)) {
|
|
360
|
+
while (isNameCode$1(codeAt(css, end))) end++;
|
|
361
|
+
names.push(css.slice(begin, end));
|
|
362
|
+
}
|
|
363
|
+
from = css.indexOf(VARIABLE_OPEN, begin);
|
|
364
|
+
}
|
|
365
|
+
return names;
|
|
366
|
+
}
|
|
367
|
+
// src/scanStyleText.ts
|
|
368
|
+
/** Makes findings that hold nothing. */
|
|
369
|
+
function createEmptyFindings() {
|
|
370
|
+
return {
|
|
371
|
+
hasLayerOrder: false,
|
|
372
|
+
classes: /* @__PURE__ */ new Set(),
|
|
373
|
+
themes: /* @__PURE__ */ new Map(),
|
|
374
|
+
properties: /* @__PURE__ */ new Map(),
|
|
375
|
+
variables: /* @__PURE__ */ new Set()
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
const PROPERTY_AT_RULE = "@property";
|
|
379
|
+
/** Whether `code` is a character of a class name: a lowercase letter, a digit, '-' or '_'. */
|
|
380
|
+
function isNameCode(code) {
|
|
381
|
+
return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
|
|
382
|
+
}
|
|
383
|
+
/** The classes in `selector` whose name starts with `start` (`<prefix>-`), without the dot. */
|
|
384
|
+
function readClasses(selector, start) {
|
|
385
|
+
const names = [];
|
|
386
|
+
let from = selector.indexOf(`.${start}`);
|
|
387
|
+
while (from !== -1) {
|
|
388
|
+
let end = from + 1 + start.length;
|
|
389
|
+
while (isNameCode(codeAt(selector, end))) end++;
|
|
390
|
+
names.push(selector.slice(from + 1, end));
|
|
391
|
+
from = selector.indexOf(`.${start}`, end);
|
|
392
|
+
}
|
|
393
|
+
return names;
|
|
394
|
+
}
|
|
395
|
+
/** The names of the variables that `body`, the declarations of a rule, declares. */
|
|
396
|
+
function readDeclared(body) {
|
|
397
|
+
const names = /* @__PURE__ */ new Set();
|
|
398
|
+
for (const part of body.split(";")) {
|
|
399
|
+
const text = part.trimStart();
|
|
400
|
+
if (text.startsWith("--")) names.add(text.slice(0, text.indexOf(":")));
|
|
401
|
+
}
|
|
402
|
+
return names;
|
|
403
|
+
}
|
|
404
|
+
/** The index after the string that starts at `index`, which is a quote. */
|
|
405
|
+
function skipString(text, index) {
|
|
406
|
+
const quote = text[index];
|
|
407
|
+
let position = index + 1;
|
|
408
|
+
while (position < text.length && text[position] !== quote) position += text[position] === "\\" ? 2 : 1;
|
|
409
|
+
return position + 1;
|
|
410
|
+
}
|
|
411
|
+
/** Records the innermost rule `prelude{body}` of a style element in `found`. */
|
|
412
|
+
function record(found, prefix, prelude, body) {
|
|
413
|
+
if (prelude.startsWith(PROPERTY_AT_RULE)) {
|
|
414
|
+
found.properties.set(prelude.slice(9).trim(), `${prelude}{${body}}`);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
if (prelude.startsWith("@")) return;
|
|
418
|
+
const themeStart = `${prefix}-theme-`;
|
|
419
|
+
const classes = readClasses(prelude, `${prefix}-`);
|
|
420
|
+
const themeId = classes.length === 1 && prelude === `.${classes[0]}` ? classes[0] : void 0;
|
|
421
|
+
if (themeId?.startsWith(themeStart)) {
|
|
422
|
+
const declared = found.themes.get(themeId) ?? /* @__PURE__ */ new Set();
|
|
423
|
+
for (const name of readDeclared(body)) declared.add(name);
|
|
424
|
+
found.themes.set(themeId, declared);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const markers = /* @__PURE__ */ new Set([
|
|
428
|
+
`${prefix}-boundary`,
|
|
429
|
+
`${prefix}-scheme-light`,
|
|
430
|
+
`${prefix}-scheme-dark`
|
|
431
|
+
]);
|
|
432
|
+
for (const name of classes) if (!name.startsWith(themeStart) && !markers.has(name)) found.classes.add(name);
|
|
433
|
+
for (const name of scanVariables(body, `--${prefix}-`)) found.variables.add(name);
|
|
434
|
+
}
|
|
435
|
+
/** Opens a block at `index`, a `{`: its prelude is the text since `boundary`. */
|
|
436
|
+
function openBlock(stack, text, boundary, index) {
|
|
437
|
+
const parent = stack.at(-1);
|
|
438
|
+
if (parent) parent.hasChild = true;
|
|
439
|
+
stack.push({
|
|
440
|
+
prelude: text.slice(boundary, index).trim(),
|
|
441
|
+
bodyStart: index + 1,
|
|
442
|
+
hasChild: false
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
/** Closes the innermost block at `index`, a `}`; a block without a block of its own is a rule to record. */
|
|
446
|
+
function closeBlock(stack, found, prefix, text, index) {
|
|
447
|
+
const block = stack.pop();
|
|
448
|
+
if (block && !block.hasChild) record(found, prefix, block.prelude, text.slice(block.bodyStart, index));
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Reads the CSS that an engine wrote (compact, no comments) in one pass and adds what it holds to
|
|
452
|
+
* `found`: the layer order statement, the classes with a rule, each theme class with the variables it
|
|
453
|
+
* declares, the `@property` rules and the variables that rules use.
|
|
454
|
+
*/
|
|
455
|
+
function scanStyleText(prefix, text, found = createEmptyFindings()) {
|
|
456
|
+
const stack = [];
|
|
457
|
+
let boundary = 0;
|
|
458
|
+
let index = 0;
|
|
459
|
+
while (index < text.length) {
|
|
460
|
+
const char = text[index];
|
|
461
|
+
if (char === "\"" || char === "'") {
|
|
462
|
+
index = skipString(text, index);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
if (char === "{") {
|
|
466
|
+
openBlock(stack, text, boundary, index);
|
|
467
|
+
boundary = index + 1;
|
|
468
|
+
} else if (char === "}") {
|
|
469
|
+
closeBlock(stack, found, prefix, text, index);
|
|
470
|
+
boundary = index + 1;
|
|
471
|
+
} else if (char === ";" && stack.length === 0) {
|
|
472
|
+
if (text.slice(boundary, index).trim().startsWith("@layer")) found.hasLayerOrder = true;
|
|
473
|
+
boundary = index + 1;
|
|
474
|
+
}
|
|
475
|
+
index++;
|
|
476
|
+
}
|
|
477
|
+
return found;
|
|
478
|
+
}
|
|
479
|
+
// src/sheetEntry.ts
|
|
480
|
+
const BRAND = Symbol.for("umber-style.sheet-entry");
|
|
481
|
+
const SOURCE = Symbol.for("umber-style.sheet-entry-source");
|
|
482
|
+
const ENTRY_KEY_PREFIX = "--umber-entry-";
|
|
483
|
+
/**
|
|
484
|
+
* Makes the entry of a class name: a frozen object that `isSheetEntry` knows and that prints as the
|
|
485
|
+
* class name. Its one enumerable key is a custom property named after the class, with the value `null`,
|
|
486
|
+
* so that a framework that merges the style objects of an array (Vue does) keeps every entry, and
|
|
487
|
+
* `flattenStyle` finds them by the key. Both frameworks skip a `null` style value on a plain element, on
|
|
488
|
+
* the client and on the server, so an entry given to a plain element renders no style attribute. With a
|
|
489
|
+
* `source` (a cache made it) the class name is read through it, so that the rule is written when the entry
|
|
490
|
+
* is used, not when it is made; without one the entry is just the name.
|
|
491
|
+
*/
|
|
492
|
+
function createSheetEntry(className, source) {
|
|
493
|
+
const entry = {
|
|
494
|
+
[`${ENTRY_KEY_PREFIX}${className}`]: null,
|
|
495
|
+
[BRAND]: true
|
|
496
|
+
};
|
|
497
|
+
const read = () => source?.use("components") ?? className;
|
|
498
|
+
Object.defineProperties(entry, {
|
|
499
|
+
className: { get: read },
|
|
500
|
+
toString: { value: read },
|
|
501
|
+
...source ? { [SOURCE]: { value: source } } : {}
|
|
502
|
+
});
|
|
503
|
+
return Object.freeze(entry);
|
|
504
|
+
}
|
|
505
|
+
/** Whether `value` was made by `createSheetEntry`: a class name is a plain string, a style object has no brand. */
|
|
506
|
+
function isSheetEntry(value) {
|
|
507
|
+
return typeof value === "object" && value !== null && BRAND in value;
|
|
508
|
+
}
|
|
509
|
+
/** What a cache gave `entry` to make its classes, or undefined for an entry that is only a name. */
|
|
510
|
+
function readEntrySource(entry) {
|
|
511
|
+
return entry[SOURCE];
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* What a `style` prop holds, as a flat list in order, for the cache to merge into one class: sheet
|
|
515
|
+
* entries and plain style objects, with arrays flattened and what is empty dropped. An object in which a
|
|
516
|
+
* framework merged entries and plain keys (Vue does) is split back into its entries, then the rest; an
|
|
517
|
+
* entry is looked up by its class name with `findEntry` (a cache's `findEntry`), else it is only the name.
|
|
518
|
+
* A string is an error: a text style cannot be merged into a class.
|
|
519
|
+
*/
|
|
520
|
+
function flattenStyle(style, findEntry) {
|
|
521
|
+
const flat = [];
|
|
522
|
+
const visit = (value) => {
|
|
523
|
+
if (Array.isArray(value)) value.forEach(visit);
|
|
524
|
+
else if (typeof value === "string" && value) throw new Error("A style given as a string cannot be merged into a class: use a sheet entry or an object.");
|
|
525
|
+
else if (isSheetEntry(value) && readEntrySource(value)) flat.push(value);
|
|
526
|
+
else if (typeof value === "object" && value !== null) {
|
|
527
|
+
const rest = {};
|
|
528
|
+
for (const [key, item] of Object.entries(value)) if (key.startsWith(ENTRY_KEY_PREFIX)) {
|
|
529
|
+
const name = key.slice(14);
|
|
530
|
+
flat.push(findEntry?.(name) ?? createSheetEntry(name));
|
|
531
|
+
} else rest[key] = item;
|
|
532
|
+
if (Object.keys(rest).length > 0) flat.push(rest);
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
visit(style);
|
|
536
|
+
return flat;
|
|
537
|
+
}
|
|
538
|
+
// src/scope.ts
|
|
539
|
+
/** The scoping of a cache that gave none: the default prefix, with `@scope`. */
|
|
540
|
+
const DEFAULT_SCOPING = {
|
|
541
|
+
prefix: "css",
|
|
542
|
+
hasScope: true
|
|
543
|
+
};
|
|
544
|
+
const THEME_KEY = "@theme ";
|
|
545
|
+
const SCHEME_KEY = "@scheme ";
|
|
546
|
+
/** The key for "the nearest theme is the one of this theme class". */
|
|
547
|
+
function createThemeKey(themeClass) {
|
|
548
|
+
return `${THEME_KEY}${themeClass}`;
|
|
549
|
+
}
|
|
550
|
+
/** The key for "the nearest color scheme is this one". */
|
|
551
|
+
function createSchemeKey(scheme) {
|
|
552
|
+
return `${SCHEME_KEY}${scheme}`;
|
|
553
|
+
}
|
|
554
|
+
/** The condition a style key stands for, or undefined for any other key. */
|
|
555
|
+
function readCondition(key) {
|
|
556
|
+
if (key.startsWith(THEME_KEY)) return {
|
|
557
|
+
kind: "theme",
|
|
558
|
+
id: key.slice(7)
|
|
559
|
+
};
|
|
560
|
+
if (key.startsWith(SCHEME_KEY)) {
|
|
561
|
+
const scheme = key.slice(8);
|
|
562
|
+
if (scheme === "light" || scheme === "dark") return {
|
|
563
|
+
kind: "scheme",
|
|
564
|
+
scheme
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
/** The class that every element with a theme carries, so that it can be a scope limit. */
|
|
569
|
+
function getBoundaryClass(prefix) {
|
|
570
|
+
return `${prefix}-boundary`;
|
|
571
|
+
}
|
|
572
|
+
/** The class of an element whose theme has a color scheme of its own. */
|
|
573
|
+
function getSchemeClass(prefix, scheme) {
|
|
574
|
+
return `${prefix}-scheme-${scheme}`;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* The class string of a theme: its theme class, the boundary marker, and, when its color scheme is
|
|
578
|
+
* `light` or `dark`, the scheme marker. `light dark` and no scheme have no scheme marker.
|
|
579
|
+
*/
|
|
580
|
+
function createThemeClassName(prefix, id, colorScheme) {
|
|
581
|
+
const scheme = colorScheme === "light" || colorScheme === "dark" ? colorScheme : void 0;
|
|
582
|
+
return [
|
|
583
|
+
id,
|
|
584
|
+
getBoundaryClass(prefix),
|
|
585
|
+
scheme && getSchemeClass(prefix, scheme)
|
|
586
|
+
].filter(Boolean).join(" ");
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* `rules` for the elements below the elements that match `start`, down to but not into the elements
|
|
590
|
+
* that match `limits`: `@scope (start) to (limits){rules}`. A limit is relative to the scope root, so
|
|
591
|
+
* the root is never cut off by its own marker (checked in a browser: `to (.x)` and `to (:scope .x)` agree).
|
|
592
|
+
*/
|
|
593
|
+
function createScopeRule(start, limits, rules) {
|
|
594
|
+
return `@scope (${start}) to (${limits}){${rules.join("")}}`;
|
|
595
|
+
}
|
|
596
|
+
/** The selector that matches an element with no scheme marker on it or above it. Its specificity is 0. */
|
|
597
|
+
function createNoSchemeGuard(prefix) {
|
|
598
|
+
const markers = [getSchemeClass(prefix, "light"), getSchemeClass(prefix, "dark")].map((name) => `.${name}`);
|
|
599
|
+
const nested = markers.map((marker) => `${marker} *`);
|
|
600
|
+
return `:where(:not(${[...markers, ...nested].join(",")}))`;
|
|
601
|
+
}
|
|
602
|
+
// src/serialize.ts
|
|
603
|
+
const UNITLESS = /* @__PURE__ */ new Set([
|
|
604
|
+
"animationIterationCount",
|
|
605
|
+
"aspectRatio",
|
|
606
|
+
"columnCount",
|
|
607
|
+
"columns",
|
|
608
|
+
"flex",
|
|
609
|
+
"flexGrow",
|
|
610
|
+
"flexShrink",
|
|
611
|
+
"fontWeight",
|
|
612
|
+
"gridArea",
|
|
613
|
+
"gridColumn",
|
|
614
|
+
"gridColumnEnd",
|
|
615
|
+
"gridColumnStart",
|
|
616
|
+
"gridRow",
|
|
617
|
+
"gridRowEnd",
|
|
618
|
+
"gridRowStart",
|
|
619
|
+
"lineHeight",
|
|
620
|
+
"opacity",
|
|
621
|
+
"order",
|
|
622
|
+
"orphans",
|
|
623
|
+
"scale",
|
|
624
|
+
"tabSize",
|
|
625
|
+
"widows",
|
|
626
|
+
"zIndex",
|
|
627
|
+
"zoom",
|
|
628
|
+
"fillOpacity",
|
|
629
|
+
"floodOpacity",
|
|
630
|
+
"stopOpacity",
|
|
631
|
+
"strokeDasharray",
|
|
632
|
+
"strokeDashoffset",
|
|
633
|
+
"strokeMiterlimit",
|
|
634
|
+
"strokeOpacity",
|
|
635
|
+
"strokeWidth"
|
|
636
|
+
]);
|
|
637
|
+
const propertyNames = /* @__PURE__ */ new Map();
|
|
638
|
+
/** Whether `value` is a nested style object, not an array, an `alpha()` result or a plain value. */
|
|
639
|
+
function isStyleObject(value) {
|
|
640
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !isAlphaColor(value);
|
|
641
|
+
}
|
|
642
|
+
/** The CSS name of a style key: kebab-case, custom properties as written. */
|
|
643
|
+
function toPropertyName(key) {
|
|
644
|
+
if (key.startsWith("--")) return key;
|
|
645
|
+
let name = propertyNames.get(key);
|
|
646
|
+
if (name === void 0) {
|
|
647
|
+
name = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`).replace(/^ms-/, "-ms-");
|
|
648
|
+
propertyNames.set(key, name);
|
|
649
|
+
}
|
|
650
|
+
return name;
|
|
651
|
+
}
|
|
652
|
+
/** The CSS text of one declared value. */
|
|
653
|
+
function toValue(key, value) {
|
|
654
|
+
return typeof value === "number" && value !== 0 && !key.startsWith("--") && !UNITLESS.has(key) ? `${value}px` : String(value);
|
|
655
|
+
}
|
|
656
|
+
/** Splits `selector` on the commas that are not inside brackets or parentheses. */
|
|
657
|
+
function splitSelectors(selector) {
|
|
658
|
+
const parts = [];
|
|
659
|
+
let depth = 0;
|
|
660
|
+
let start = 0;
|
|
661
|
+
for (let index = 0; index < selector.length; index++) {
|
|
662
|
+
const char = selector[index];
|
|
663
|
+
if (char === "(" || char === "[") depth++;
|
|
664
|
+
else if (char === ")" || char === "]") depth--;
|
|
665
|
+
else if (char === "," && depth === 0) {
|
|
666
|
+
parts.push(selector.slice(start, index).trim());
|
|
667
|
+
start = index + 1;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
parts.push(selector.slice(start).trim());
|
|
671
|
+
return parts;
|
|
672
|
+
}
|
|
673
|
+
/** The selector of one part of a key inside one parent: `&` is the parent, a leading colon is the parent itself, anything else is a descendant. */
|
|
674
|
+
function joinSelector(one, part) {
|
|
675
|
+
if (part.includes("&")) return part.replaceAll("&", one);
|
|
676
|
+
return part.startsWith(":") ? one + part : `${one} ${part}`;
|
|
677
|
+
}
|
|
678
|
+
/** The selector a nested key makes inside `parent`, with `&` standing for the parent. */
|
|
679
|
+
function resolveSelector(parent, key) {
|
|
680
|
+
const parents = splitSelectors(parent);
|
|
681
|
+
return splitSelectors(key).flatMap((part) => parents.map((one) => joinSelector(one, part))).join(",");
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* `style` for the web: a style written for both platforms has a `web` part, which is merged over the
|
|
685
|
+
* rest, and a `native` part, which is dropped.
|
|
686
|
+
*/
|
|
687
|
+
function resolveWebParts(style) {
|
|
688
|
+
if (!("web" in style) && !("native" in style)) return style;
|
|
689
|
+
const { web, native: _native, ...rest } = style;
|
|
690
|
+
return isStyleObject(web) ? mergeStyles([rest, web]) : rest;
|
|
691
|
+
}
|
|
692
|
+
/** Merges style objects left to right; a later key wins and moves to the end; nested objects merge the same way. */
|
|
693
|
+
function mergeStyles(styles) {
|
|
694
|
+
const merged = {};
|
|
695
|
+
for (const style of styles) for (const [key, value] of Object.entries(resolveWebParts(style))) {
|
|
696
|
+
const earlier = merged[key];
|
|
697
|
+
delete merged[key];
|
|
698
|
+
merged[key] = isStyleObject(earlier) && isStyleObject(value) ? mergeStyles([earlier, value]) : value;
|
|
699
|
+
}
|
|
700
|
+
return merged;
|
|
701
|
+
}
|
|
702
|
+
/** `selector`, a list or one, with `text` in front of each of its parts. */
|
|
703
|
+
function prefixSelector(selector, text) {
|
|
704
|
+
return splitSelectors(selector).map((part) => text + part).join(",");
|
|
705
|
+
}
|
|
706
|
+
/** `selector`, a list or one, with `text` at the end of each of its parts. */
|
|
707
|
+
function suffixSelector(selector, text) {
|
|
708
|
+
return splitSelectors(selector).map((part) => part + text).join(",");
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* The rules of `value` for the elements below `start`, down to the elements that match `limits`: one
|
|
712
|
+
* `@scope` rule, or, without `hasScope`, the plain descendant selector (which does not stop at a limit).
|
|
713
|
+
*/
|
|
714
|
+
function compileScoped(selector, value, context, start, limits) {
|
|
715
|
+
if (!context.scoping.hasScope) return compileStyle(prefixSelector(selector, `:where(${start}) `), value, context);
|
|
716
|
+
const rules = compileStyle(selector, value, context);
|
|
717
|
+
return rules.length > 0 ? [createScopeRule(start, limits, rules)] : [];
|
|
718
|
+
}
|
|
719
|
+
/** The rules of a condition key: the style applies where the nearest theme, or the nearest color scheme, is the one named. */
|
|
720
|
+
function compileCondition(selector, condition, value, context) {
|
|
721
|
+
const { prefix } = context.scoping;
|
|
722
|
+
if (condition.kind === "theme") {
|
|
723
|
+
const limit = `.${getBoundaryClass(prefix)}`;
|
|
724
|
+
return compileScoped(selector, value, context, `.${condition.id}`, limit);
|
|
725
|
+
}
|
|
726
|
+
const limits = ["light", "dark"].map((name) => `.${getSchemeClass(prefix, name)}`);
|
|
727
|
+
const scoped = compileScoped(selector, value, context, `.${getSchemeClass(prefix, condition.scheme)}`, limits.join(","));
|
|
728
|
+
const guarded = compileStyle(suffixSelector(selector, createNoSchemeGuard(prefix)), value, context);
|
|
729
|
+
const query = `@media (prefers-color-scheme: ${condition.scheme}){${guarded.join("")}}`;
|
|
730
|
+
return guarded.length > 0 ? [...scoped, query] : scoped;
|
|
731
|
+
}
|
|
732
|
+
/** The rules of the nested style `value` under `key`: a condition scopes them, an at-rule wraps them, any other key is a selector inside `selector`. */
|
|
733
|
+
function compileNested(selector, key, value, context) {
|
|
734
|
+
const condition = readCondition(key);
|
|
735
|
+
if (condition) return compileCondition(selector, condition, value, context);
|
|
736
|
+
if (!key.startsWith("@")) return compileStyle(resolveSelector(selector, key), value, context);
|
|
737
|
+
return compileStyle(selector, value, context).map((rule) => `${key}{${rule}}`);
|
|
738
|
+
}
|
|
739
|
+
/** The declarations of one item: a custom property takes any text, so a fallback would always win there, and is not written. */
|
|
740
|
+
function toItemDeclarations(key, name, item, hasColorFallbacks) {
|
|
741
|
+
if (!isAlphaColor(item)) return `${name}:${toValue(key, item)};`;
|
|
742
|
+
return `${hasColorFallbacks && !key.startsWith("--") ? `${name}:${item.fallback};` : ""}${name}:${item.value};`;
|
|
743
|
+
}
|
|
744
|
+
/** The declarations of one property: one for a value, one for each item of a fallback list. */
|
|
745
|
+
function toDeclarations(key, value, hasColorFallbacks) {
|
|
746
|
+
const name = toPropertyName(key);
|
|
747
|
+
return (Array.isArray(value) ? value : [value]).map((item) => toItemDeclarations(key, name, item, hasColorFallbacks)).join("");
|
|
748
|
+
}
|
|
749
|
+
/** The rules of `style` for `selector`, with the options of `context`. */
|
|
750
|
+
function compileStyle(selector, style, context) {
|
|
751
|
+
let declarations = "";
|
|
752
|
+
const nested = [];
|
|
753
|
+
for (const [key, value] of Object.entries(style)) {
|
|
754
|
+
if (key === "label" || value === null || value === void 0 || value === false) continue;
|
|
755
|
+
if (isStyleObject(value)) nested.push(...compileNested(selector, key, value, context));
|
|
756
|
+
else declarations += toDeclarations(key, value, context.hasColorFallbacks);
|
|
757
|
+
}
|
|
758
|
+
return declarations ? [`${selector}{${declarations}}`, ...nested] : nested;
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* The flat CSS rules of `style` for `selector`; without `hasColorFallbacks` an `alpha()` result is
|
|
762
|
+
* written as its mix alone. A `when()` or `whenScheme()` key becomes a scoped rule, written as
|
|
763
|
+
* `scoping` says.
|
|
764
|
+
*/
|
|
765
|
+
function compileRules(selector, style, hasColorFallbacks = true, scoping = DEFAULT_SCOPING) {
|
|
766
|
+
return compileStyle(selector, style, {
|
|
767
|
+
hasColorFallbacks,
|
|
768
|
+
scoping
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
/** The label of `style` (its `label` key), or ''. */
|
|
772
|
+
function readLabel(style) {
|
|
773
|
+
const { label } = style;
|
|
774
|
+
return typeof label === "string" ? label : "";
|
|
775
|
+
}
|
|
776
|
+
// src/theme.ts
|
|
777
|
+
/** The CSS declarations `name:value;` of `entries`. */
|
|
778
|
+
function toDeclarationText(entries) {
|
|
779
|
+
let text = "";
|
|
780
|
+
for (const [name, value] of entries) text += `${name}:${value};`;
|
|
781
|
+
return text;
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Registers the theme class of `declarations` and returns it: the scope of a theme. Its name is the
|
|
785
|
+
* hash of all the declarations, whatever the cache writes of them (see `hasPruning`).
|
|
786
|
+
*/
|
|
787
|
+
function createThemeClass(cache, declarations, options = {}) {
|
|
788
|
+
const { colorScheme } = options;
|
|
789
|
+
const variables = toDeclarationText(Object.entries(declarations));
|
|
790
|
+
const body = colorScheme ? `${variables}color-scheme:${colorScheme};` : variables;
|
|
791
|
+
const className = `${cache.prefix}-theme-${hashString(body)}`;
|
|
792
|
+
cache.insertTheme(className, declarations, colorScheme);
|
|
793
|
+
return className;
|
|
794
|
+
}
|
|
795
|
+
// src/cache.ts
|
|
796
|
+
/** The cascade layers of a cache, from the lowest priority to the highest. */
|
|
797
|
+
const RULE_LAYERS = [
|
|
798
|
+
"theme",
|
|
799
|
+
"global",
|
|
800
|
+
"components",
|
|
801
|
+
"overrides"
|
|
802
|
+
];
|
|
803
|
+
/** The start of every variable name, and of the ids that mark a used variable. */
|
|
804
|
+
const VARIABLE_START = "--";
|
|
805
|
+
const PREFIX_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
806
|
+
/** A sheet that keeps its rules in memory, for a server render or a test. */
|
|
807
|
+
function createMemorySheet() {
|
|
808
|
+
const rules = [];
|
|
809
|
+
return {
|
|
810
|
+
rules,
|
|
811
|
+
insert(rule) {
|
|
812
|
+
rules.push(rule);
|
|
813
|
+
},
|
|
814
|
+
replace(index, rule) {
|
|
815
|
+
rules[index] = rule;
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
/** A sheet in the style element marked `data-style="<key>"`, which it creates when there is none. */
|
|
820
|
+
function createDomSheet(key, container = document.head) {
|
|
821
|
+
let element = document.querySelector(`style[data-style="${key}"]`);
|
|
822
|
+
if (!element) {
|
|
823
|
+
element = document.createElement("style");
|
|
824
|
+
element.dataset.style = key;
|
|
825
|
+
container.appendChild(element);
|
|
826
|
+
}
|
|
827
|
+
const sheet = element.sheet;
|
|
828
|
+
const rules = [];
|
|
829
|
+
return {
|
|
830
|
+
rules,
|
|
831
|
+
insert(rule) {
|
|
832
|
+
try {
|
|
833
|
+
sheet.insertRule(rule, sheet.cssRules.length);
|
|
834
|
+
rules.push(rule);
|
|
835
|
+
} catch {}
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
/** The selector of the style elements that hold engine rules: the cache's own, and the ones React hoists for the same prefix. */
|
|
840
|
+
function createStyleSelector(prefix) {
|
|
841
|
+
return `style[data-style="${prefix}"], style[data-precedence="${prefix}"]`;
|
|
842
|
+
}
|
|
843
|
+
/** The stamp of the options that the server wrote: on a style element, or on the `<meta>` that a server component renders. */
|
|
844
|
+
function readServerStamp(prefix) {
|
|
845
|
+
const element = document.querySelector(`style[data-style="${prefix}"][data-options], meta[name="${prefix}-options"]`);
|
|
846
|
+
return element?.dataset.options ?? element?.getAttribute("content") ?? void 0;
|
|
847
|
+
}
|
|
848
|
+
/** The class names in `value`, a class string or a sheet entry. */
|
|
849
|
+
function splitClassNames(value) {
|
|
850
|
+
return (typeof value === "string" ? value : value.className).split(/\s+/).filter(Boolean);
|
|
851
|
+
}
|
|
852
|
+
/** Sorts the class names of a class string or sheet entry: a registered class is a style to merge, the rest pass through. */
|
|
853
|
+
function sortClassNames(value, registered, styles, rawClasses) {
|
|
854
|
+
for (const name of splitClassNames(value)) {
|
|
855
|
+
const style = registered.get(name);
|
|
856
|
+
if (style) styles.push(style);
|
|
857
|
+
else rawClasses.push(name);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
/** Orders distinct strings by UTF-16 code unit, what a sort without a compare function does. */
|
|
861
|
+
function compareCodeUnits(first, second) {
|
|
862
|
+
return first < second ? -1 : 1;
|
|
863
|
+
}
|
|
864
|
+
/** Adds to `names` every variable that the theme values of `themeIds` bring in for a name already in it. */
|
|
865
|
+
function addThemeReferences(names, themeIds, themes) {
|
|
866
|
+
const queue = [...names];
|
|
867
|
+
for (const queued of queue) for (const id of themeIds) {
|
|
868
|
+
const value = themes.get(id)?.declarations[queued];
|
|
869
|
+
if (value === void 0) continue;
|
|
870
|
+
for (const name of scanVariables(value, VARIABLE_START)) {
|
|
871
|
+
if (!names.has(name)) queue.push(name);
|
|
872
|
+
names.add(name);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Splits `values` into the styles to merge (the style of an entry a cache made, registered classes
|
|
878
|
+
* resolved back) and the class names to pass through. `sole` is the entry when the one style is its own.
|
|
879
|
+
*/
|
|
880
|
+
function sortClassValues(values, registered) {
|
|
881
|
+
const styles = [];
|
|
882
|
+
const rawClasses = [];
|
|
883
|
+
let entry;
|
|
884
|
+
for (const value of values) {
|
|
885
|
+
if (!value) continue;
|
|
886
|
+
if (typeof value !== "string" && !isSheetEntry(value)) {
|
|
887
|
+
styles.push(value);
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
const source = typeof value === "string" ? void 0 : readEntrySource(value);
|
|
891
|
+
if (source) {
|
|
892
|
+
styles.push(source.style);
|
|
893
|
+
entry = source;
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
sortClassNames(value, registered, styles, rawClasses);
|
|
897
|
+
}
|
|
898
|
+
return {
|
|
899
|
+
styles,
|
|
900
|
+
rawClasses,
|
|
901
|
+
sole: styles.length === 1 ? entry : void 0
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
/** Makes a cache: it turns styles into classes and inserts each class's rules once. */
|
|
905
|
+
function createCache(options = {}) {
|
|
906
|
+
const { prefix = "css", suffix = "", hasLabels = true, hasLayers = true, hasPruning = true, hasColorFallbacks = true, hasScope = true, hasBaseClass = true } = options;
|
|
907
|
+
if (!PREFIX_PATTERN.test(prefix)) throw new Error(`Invalid cache prefix "${prefix}": use lowercase letters, digits and hyphens.`);
|
|
908
|
+
const fingerprint = createFingerprint({
|
|
909
|
+
prefix,
|
|
910
|
+
suffix,
|
|
911
|
+
hasLabels,
|
|
912
|
+
hasLayers,
|
|
913
|
+
hasPruning,
|
|
914
|
+
hasBaseClass,
|
|
915
|
+
hasScope,
|
|
916
|
+
hasColorFallbacks,
|
|
917
|
+
tokens: options.tokenSignature ?? ""
|
|
918
|
+
});
|
|
919
|
+
const hasDocument = typeof document !== "undefined";
|
|
920
|
+
if (hasDocument) {
|
|
921
|
+
const stamp = readServerStamp(prefix);
|
|
922
|
+
const difference = stamp === void 0 ? "" : describeFingerprintDifferences(stamp, fingerprint);
|
|
923
|
+
if (difference !== "") throw new Error(difference);
|
|
924
|
+
}
|
|
925
|
+
const { hasDevChecks = hasDocument && isDevelopment() } = options;
|
|
926
|
+
const checkLater = hasDevChecks ? createDevChecker(prefix) : void 0;
|
|
927
|
+
const insertedIds = /* @__PURE__ */ new Set();
|
|
928
|
+
const used = /* @__PURE__ */ new Set();
|
|
929
|
+
const pinned = /* @__PURE__ */ new Set();
|
|
930
|
+
const pageThemes = /* @__PURE__ */ new Map();
|
|
931
|
+
const afters = /* @__PURE__ */ new Map();
|
|
932
|
+
const sheet = options.sheet ?? (typeof document === "undefined" ? createMemorySheet() : createDomSheet(prefix));
|
|
933
|
+
const registered = /* @__PURE__ */ new Map();
|
|
934
|
+
const entries = /* @__PURE__ */ new Map();
|
|
935
|
+
const scoping = {
|
|
936
|
+
prefix,
|
|
937
|
+
hasScope
|
|
938
|
+
};
|
|
939
|
+
const insertedRules = /* @__PURE__ */ new Map();
|
|
940
|
+
let propertyRules = {};
|
|
941
|
+
const themeNames = /* @__PURE__ */ new Map();
|
|
942
|
+
const layerNames = RULE_LAYERS.map((layer) => `${prefix}-${layer}`).join(",");
|
|
943
|
+
const layerOrder = hasLayers ? `@layer ${layerNames};` : "";
|
|
944
|
+
const layerOrderId = `${prefix}-layers`;
|
|
945
|
+
const wrapInLayer = (rules, layer) => hasLayers && layer ? rules.map((rule) => `@layer ${prefix}-${layer}{${rule}}`) : rules;
|
|
946
|
+
const insertLayered = (layered) => {
|
|
947
|
+
if (hasLayers && layered.length > 0 && !insertedIds.has(layerOrderId)) {
|
|
948
|
+
insertedIds.add(layerOrderId);
|
|
949
|
+
sheet.insert(layerOrder);
|
|
950
|
+
}
|
|
951
|
+
for (const rule of layered) sheet.insert(rule);
|
|
952
|
+
if (layered.length > 0) checkLater?.();
|
|
953
|
+
};
|
|
954
|
+
const themes = /* @__PURE__ */ new Map();
|
|
955
|
+
/** Writes `names` for a theme class: a rule of its own, or in place of the rule it has when the sheet can replace. */
|
|
956
|
+
const writeTheme = (className, entry, names) => {
|
|
957
|
+
const added = toDeclarationText(names.map((name) => [name, entry.declarations[name]]));
|
|
958
|
+
const ownScheme = entry.isSent ? "" : entry.schemeText;
|
|
959
|
+
const first = entry.isStarted ? "" : ownScheme;
|
|
960
|
+
if (added + first === "") return;
|
|
961
|
+
entry.isStarted = true;
|
|
962
|
+
for (const name of names) entry.written.add(name);
|
|
963
|
+
entry.variables += added;
|
|
964
|
+
const { index } = entry;
|
|
965
|
+
const body = index === void 0 ? added + first : entry.variables + ownScheme;
|
|
966
|
+
const rules = wrapInLayer([`.${className}{${body}}`], "theme");
|
|
967
|
+
if (sheet.replace && index !== void 0) {
|
|
968
|
+
sheet.replace(index, rules[0]);
|
|
969
|
+
entry.rules = rules;
|
|
970
|
+
} else {
|
|
971
|
+
const before = sheet.rules.length;
|
|
972
|
+
insertLayered(rules);
|
|
973
|
+
if (sheet.replace && sheet.rules.length > before) entry.index = sheet.rules.length - 1;
|
|
974
|
+
entry.rules = [...entry.rules, ...rules];
|
|
975
|
+
}
|
|
976
|
+
insertedRules.set(className, entry.rules);
|
|
977
|
+
};
|
|
978
|
+
/** Writes the `@property` rule of the variable `name`, once; the rule of the same text is never written twice, a changed one is written after it and wins. */
|
|
979
|
+
const writeProperty = (name) => {
|
|
980
|
+
const rule = propertyRules[name];
|
|
981
|
+
if (rule === void 0) return;
|
|
982
|
+
if (insertOnce(`@property:${name}:${hashString(rule)}`, [rule])) insertedRules.set(name, [rule]);
|
|
983
|
+
};
|
|
984
|
+
const registerProperties = (rules) => {
|
|
985
|
+
propertyRules = rules;
|
|
986
|
+
for (const name of Object.keys(rules)) if (!hasPruning || used.has(name)) writeProperty(name);
|
|
987
|
+
};
|
|
988
|
+
const markUsed = (names) => {
|
|
989
|
+
if (!hasPruning) return;
|
|
990
|
+
const queue = [...names];
|
|
991
|
+
const fresh = [];
|
|
992
|
+
for (const name of queue) {
|
|
993
|
+
if (used.has(name)) continue;
|
|
994
|
+
used.add(name);
|
|
995
|
+
fresh.push(name);
|
|
996
|
+
for (const { declarations } of themes.values()) {
|
|
997
|
+
const value = declarations[name];
|
|
998
|
+
if (value !== void 0) queue.push(...scanVariables(value, VARIABLE_START));
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
if (fresh.length === 0) return;
|
|
1002
|
+
fresh.forEach(writeProperty);
|
|
1003
|
+
for (const [className, entry] of themes) writeTheme(className, entry, fresh.filter((name) => entry.declarations[name] !== void 0 && !entry.written.has(name)));
|
|
1004
|
+
};
|
|
1005
|
+
const insertTheme = (className, declarations, colorScheme) => {
|
|
1006
|
+
const schemeText = colorScheme ? `color-scheme:${colorScheme};` : "";
|
|
1007
|
+
themeNames.set(className, Object.keys(declarations));
|
|
1008
|
+
const body = toDeclarationText(Object.entries(declarations)) + schemeText;
|
|
1009
|
+
if (!hasPruning) {
|
|
1010
|
+
insertOnce(className, body ? [`.${className}{${body}}`] : [], "theme");
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (themes.has(className)) return;
|
|
1014
|
+
const sent = pageThemes.get(className);
|
|
1015
|
+
const isSent = sent !== void 0;
|
|
1016
|
+
insertedIds.add(className);
|
|
1017
|
+
const names = Object.keys(declarations);
|
|
1018
|
+
const entry = {
|
|
1019
|
+
declarations,
|
|
1020
|
+
schemeText,
|
|
1021
|
+
isSent,
|
|
1022
|
+
isStarted: false,
|
|
1023
|
+
written: new Set(isSent ? names.filter((name) => sent.has(name)) : []),
|
|
1024
|
+
variables: "",
|
|
1025
|
+
index: void 0,
|
|
1026
|
+
rules: []
|
|
1027
|
+
};
|
|
1028
|
+
themes.set(className, entry);
|
|
1029
|
+
insertedRules.set(className, []);
|
|
1030
|
+
markUsed(names.filter((name) => used.has(name)).flatMap((name) => scanVariables(declarations[name], VARIABLE_START)));
|
|
1031
|
+
writeTheme(className, entry, names.filter((name) => used.has(name) && !entry.written.has(name)));
|
|
1032
|
+
};
|
|
1033
|
+
function insertOnce(id, rules, layer) {
|
|
1034
|
+
if (insertedIds.has(id)) return false;
|
|
1035
|
+
insertedIds.add(id);
|
|
1036
|
+
const layered = wrapInLayer(rules, layer);
|
|
1037
|
+
insertedRules.set(id, layered);
|
|
1038
|
+
insertLayered(layered);
|
|
1039
|
+
if (hasPruning) markUsed(rules.flatMap((rule) => scanVariables(rule, VARIABLE_START)));
|
|
1040
|
+
return true;
|
|
1041
|
+
}
|
|
1042
|
+
const getFullRules = (id) => {
|
|
1043
|
+
const entry = themes.get(id);
|
|
1044
|
+
const properties = (themeNames.get(id) ?? []).flatMap((name) => propertyRules[name] ?? []);
|
|
1045
|
+
if (entry === void 0) return [...properties, ...insertedRules.get(id) ?? []];
|
|
1046
|
+
const body = toDeclarationText(Object.entries(entry.declarations)) + entry.schemeText;
|
|
1047
|
+
return [...properties, ...body ? wrapInLayer([`.${id}{${body}}`], "theme") : []];
|
|
1048
|
+
};
|
|
1049
|
+
/** The name of a class: the layer and `after` are part of the hash, so that the same styles in two layers, or after two classes, are two classes. */
|
|
1050
|
+
const nameClass = (layer, merged, rules, after) => {
|
|
1051
|
+
const label = hasLabels ? readLabel(merged) : "";
|
|
1052
|
+
const hash = hashString((hasLayers && layer === "overrides" ? layer : "") + after + rules.join(""));
|
|
1053
|
+
return [
|
|
1054
|
+
prefix,
|
|
1055
|
+
label,
|
|
1056
|
+
hash
|
|
1057
|
+
].filter(Boolean).join("-") + suffix;
|
|
1058
|
+
};
|
|
1059
|
+
const cssWith = (options, ...values) => {
|
|
1060
|
+
const { layer = "components", label, after = "" } = options;
|
|
1061
|
+
const { styles, rawClasses, sole } = sortClassValues(values, registered);
|
|
1062
|
+
if (sole && after === "") return [...rawClasses, sole.use(layer)].filter(Boolean).join(" ");
|
|
1063
|
+
if (styles.length === 0) return rawClasses.join(" ");
|
|
1064
|
+
const merged = mergeStyles(label ? [...styles, { label }] : styles);
|
|
1065
|
+
const rules = compileRules("&", merged, hasColorFallbacks, scoping);
|
|
1066
|
+
if (rules.length === 0) return rawClasses.join(" ");
|
|
1067
|
+
const className = nameClass(layer, merged, rules, after);
|
|
1068
|
+
registered.set(className, merged);
|
|
1069
|
+
if (after !== "") afters.set(className, after);
|
|
1070
|
+
insertOnce(className, compileRules(`.${className}`, merged, hasColorFallbacks, scoping), layer);
|
|
1071
|
+
return [...rawClasses, className].join(" ");
|
|
1072
|
+
};
|
|
1073
|
+
const cssIn = (layer, ...values) => cssWith({ layer }, ...values);
|
|
1074
|
+
const createEntry = (style) => {
|
|
1075
|
+
const merged = mergeStyles([style]);
|
|
1076
|
+
const rules = compileRules("&", merged, hasColorFallbacks, scoping);
|
|
1077
|
+
const names = {};
|
|
1078
|
+
const nameFor = (role) => {
|
|
1079
|
+
names[role] ??= rules.length === 0 ? "" : nameClass(role, merged, rules, "");
|
|
1080
|
+
return names[role];
|
|
1081
|
+
};
|
|
1082
|
+
const source = {
|
|
1083
|
+
style: merged,
|
|
1084
|
+
use(role) {
|
|
1085
|
+
const name = nameFor(role);
|
|
1086
|
+
if (name !== "" && !registered.has(name)) {
|
|
1087
|
+
registered.set(name, merged);
|
|
1088
|
+
insertOnce(name, compileRules(`.${name}`, merged, hasColorFallbacks, scoping), role);
|
|
1089
|
+
}
|
|
1090
|
+
return name;
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
const entry = createSheetEntry(nameFor("components"), source);
|
|
1094
|
+
entries.set(nameFor("components"), entry);
|
|
1095
|
+
return entry;
|
|
1096
|
+
};
|
|
1097
|
+
/** Takes in what rules on the page say: the classes, the layer order, the `@property` rules and the themes that are written, and the variables the rules use. */
|
|
1098
|
+
const absorb = (found) => {
|
|
1099
|
+
if (found.hasLayerOrder) insertedIds.add(layerOrderId);
|
|
1100
|
+
for (const name of found.classes) insertedIds.add(name);
|
|
1101
|
+
for (const [name, rule] of found.properties) insertedIds.add(`@property:${name}:${hashString(rule)}`);
|
|
1102
|
+
for (const [className, names] of found.themes) {
|
|
1103
|
+
insertedIds.add(className);
|
|
1104
|
+
const known = pageThemes.get(className) ?? /* @__PURE__ */ new Set();
|
|
1105
|
+
for (const name of names) known.add(name);
|
|
1106
|
+
pageThemes.set(className, known);
|
|
1107
|
+
const entry = themes.get(className);
|
|
1108
|
+
if (entry === void 0) continue;
|
|
1109
|
+
entry.isSent = true;
|
|
1110
|
+
for (const name of names) entry.written.add(name);
|
|
1111
|
+
}
|
|
1112
|
+
markUsed(found.variables);
|
|
1113
|
+
};
|
|
1114
|
+
if (hasDocument) {
|
|
1115
|
+
const selector = createStyleSelector(prefix);
|
|
1116
|
+
const scanned = /* @__PURE__ */ new WeakSet();
|
|
1117
|
+
const scan = (element) => {
|
|
1118
|
+
if (scanned.has(element)) return;
|
|
1119
|
+
scanned.add(element);
|
|
1120
|
+
absorb(scanStyleText(prefix, element.textContent));
|
|
1121
|
+
};
|
|
1122
|
+
for (const element of document.querySelectorAll(selector)) scan(element);
|
|
1123
|
+
new MutationObserver((records) => {
|
|
1124
|
+
for (const { addedNodes } of records) for (const node of addedNodes) if (node instanceof Element && node.matches(selector)) scan(node);
|
|
1125
|
+
checkLater?.();
|
|
1126
|
+
}).observe(document.head, { childList: true });
|
|
1127
|
+
checkLater?.();
|
|
1128
|
+
}
|
|
1129
|
+
/** What orders the classes of a page: a props class is right after its base class (its `after`), the rest by name. */
|
|
1130
|
+
const sortKey = (id) => `${afters.get(id) ?? id}|${afters.has(id) ? "1" : "0"}${id}`;
|
|
1131
|
+
/** The variables that the theme class `id` declares. */
|
|
1132
|
+
const readNames = (id) => themeNames.get(id);
|
|
1133
|
+
/** The rules that the cache wrote under `id`, a class or a theme class it made. */
|
|
1134
|
+
const readRules = (id) => insertedRules.get(id);
|
|
1135
|
+
/** The variables a page needs declared: those its rules refer to, those marked from outside, and what the values of the themes in play refer to. */
|
|
1136
|
+
const collectPageVariables = (classIds, themeIds) => {
|
|
1137
|
+
const names = new Set(pinned);
|
|
1138
|
+
for (const id of classIds) for (const rule of readRules(id)) for (const name of scanVariables(rule, VARIABLE_START)) names.add(name);
|
|
1139
|
+
addThemeReferences(names, themeIds, themes);
|
|
1140
|
+
return names;
|
|
1141
|
+
};
|
|
1142
|
+
/** The rule of a theme class for a page: with pruning, only the variables in `names`, and its color-scheme. */
|
|
1143
|
+
const createPageThemeRules = (id, names) => {
|
|
1144
|
+
const entry = themes.get(id);
|
|
1145
|
+
if (entry === void 0) return readRules(id);
|
|
1146
|
+
const body = toDeclarationText(Object.keys(entry.declarations).filter((name) => names.has(name)).map((name) => [name, entry.declarations[name]])) + entry.schemeText;
|
|
1147
|
+
return body === "" ? [] : wrapInLayer([`.${id}{${body}}`], "theme");
|
|
1148
|
+
};
|
|
1149
|
+
const extractPage = (classNames, pageOptions = {}) => {
|
|
1150
|
+
const { themes: offered = [], carried = /* @__PURE__ */ new Set() } = pageOptions;
|
|
1151
|
+
const wanted = /* @__PURE__ */ new Set([...classNames, ...offered]);
|
|
1152
|
+
const themeIds = [...wanted].filter((name) => themeNames.has(name)).sort(compareCodeUnits);
|
|
1153
|
+
const classIds = [...wanted].filter((name) => name.startsWith(`${prefix}-`) && !themeNames.has(name)).filter((name) => insertedRules.has(name)).sort((first, second) => sortKey(first) < sortKey(second) ? -1 : 1);
|
|
1154
|
+
const names = hasPruning ? collectPageVariables(classIds, themeIds) : /* @__PURE__ */ new Set();
|
|
1155
|
+
const covered = new Set(themeIds.filter((id) => carried.has(id)).flatMap(readNames));
|
|
1156
|
+
const declared = hasPruning ? names : themeIds.flatMap(readNames);
|
|
1157
|
+
const properties = [...new Set(declared)].filter((name) => propertyRules[name] !== void 0 && !covered.has(name)).sort(compareCodeUnits);
|
|
1158
|
+
const newThemes = themeIds.filter((id) => !carried.has(id));
|
|
1159
|
+
const newClasses = classIds.filter((id) => !carried.has(id));
|
|
1160
|
+
const themeRules = newThemes.flatMap((id) => createPageThemeRules(id, names));
|
|
1161
|
+
const classRules = newClasses.flatMap(readRules);
|
|
1162
|
+
const hasLayered = themeRules.length + classRules.length > 0;
|
|
1163
|
+
return {
|
|
1164
|
+
css: [
|
|
1165
|
+
hasLayers && hasLayered ? layerOrder : "",
|
|
1166
|
+
...properties.map((name) => propertyRules[name]),
|
|
1167
|
+
...themeRules,
|
|
1168
|
+
...classRules
|
|
1169
|
+
].join(""),
|
|
1170
|
+
ids: [...newThemes, ...newClasses]
|
|
1171
|
+
};
|
|
1172
|
+
};
|
|
1173
|
+
return {
|
|
1174
|
+
prefix,
|
|
1175
|
+
hasLayers,
|
|
1176
|
+
layerOrder,
|
|
1177
|
+
registered,
|
|
1178
|
+
css: (...values) => cssIn("components", ...values),
|
|
1179
|
+
cssIn,
|
|
1180
|
+
cssWith,
|
|
1181
|
+
createEntry,
|
|
1182
|
+
findEntry: (className) => entries.get(className),
|
|
1183
|
+
hasBaseClass,
|
|
1184
|
+
hasScope,
|
|
1185
|
+
hasPruning,
|
|
1186
|
+
usedVariables: used,
|
|
1187
|
+
markUsed: (names) => {
|
|
1188
|
+
const list = [...names];
|
|
1189
|
+
for (const name of list) pinned.add(name);
|
|
1190
|
+
markUsed(list);
|
|
1191
|
+
},
|
|
1192
|
+
insertTheme,
|
|
1193
|
+
registerProperties,
|
|
1194
|
+
insertOnce,
|
|
1195
|
+
getRules: (id) => insertedRules.get(id) ?? [],
|
|
1196
|
+
getFullRules,
|
|
1197
|
+
extract: () => ({
|
|
1198
|
+
css: sheet.rules.join(""),
|
|
1199
|
+
ids: [...insertedIds, ...used]
|
|
1200
|
+
}),
|
|
1201
|
+
extractPage,
|
|
1202
|
+
fingerprint
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
// src/calc.ts
|
|
1206
|
+
const LENGTH_PATTERN$1 = /^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z]+|%)$/i;
|
|
1207
|
+
const CALC_PREFIX = "calc(";
|
|
1208
|
+
/** `value` rounded so that float noise (0.1 * 3) does not reach the CSS; `-0` is `0`. */
|
|
1209
|
+
function tidy(value) {
|
|
1210
|
+
return Math.round(value * 1e6) / 1e6 + 0;
|
|
1211
|
+
}
|
|
1212
|
+
/** Throws unless `value` is a finite number; `what` names the argument in the message. */
|
|
1213
|
+
function assertFinite(name, what, value) {
|
|
1214
|
+
if (typeof value !== "number") throw new TypeError(`${name}(): ${what} must be a number, got ${typeof value}`);
|
|
1215
|
+
if (!Number.isFinite(value)) throw new RangeError(`${name}(): ${what} must be finite, got ${value}`);
|
|
1216
|
+
}
|
|
1217
|
+
/** Throws unless `value` is a string or a finite number. */
|
|
1218
|
+
function assertOperand(name, value) {
|
|
1219
|
+
if (isAlphaColor(value)) throw new TypeError(`${name}(): an alpha() color is not a length or a number, so it cannot be an operand`);
|
|
1220
|
+
if (typeof value !== "string") assertFinite(name, "a value", value);
|
|
1221
|
+
}
|
|
1222
|
+
/** The inside of `value` when the whole of it is one `calc(...)`, else undefined. */
|
|
1223
|
+
function unwrapCalc(value) {
|
|
1224
|
+
if (!value.startsWith(CALC_PREFIX) || !value.endsWith(")")) return void 0;
|
|
1225
|
+
let depth = 0;
|
|
1226
|
+
for (let index = 4; index < value.length; index += 1) {
|
|
1227
|
+
if (value[index] === "(") depth += 1;
|
|
1228
|
+
if (value[index] === ")") depth -= 1;
|
|
1229
|
+
if (depth === 0 && index < value.length - 1) return void 0;
|
|
1230
|
+
}
|
|
1231
|
+
return value.slice(5, -1);
|
|
1232
|
+
}
|
|
1233
|
+
/** `operand` as a part of a calc expression: a number is a length in px, an inner calc gets parentheses. */
|
|
1234
|
+
function toTerm(operand) {
|
|
1235
|
+
if (typeof operand === "number") return `${tidy(operand)}px`;
|
|
1236
|
+
const inner = unwrapCalc(operand);
|
|
1237
|
+
return inner === void 0 ? operand : `(${inner})`;
|
|
1238
|
+
}
|
|
1239
|
+
/** `operand` as a literal length (a number is in px), or undefined when it is not one. */
|
|
1240
|
+
function toLength(operand) {
|
|
1241
|
+
if (typeof operand === "number") return {
|
|
1242
|
+
value: operand,
|
|
1243
|
+
unit: "px"
|
|
1244
|
+
};
|
|
1245
|
+
const match = LENGTH_PATTERN$1.exec(operand.trim());
|
|
1246
|
+
return match ? {
|
|
1247
|
+
value: Number.parseFloat(match[1]),
|
|
1248
|
+
unit: match[2].toLowerCase()
|
|
1249
|
+
} : void 0;
|
|
1250
|
+
}
|
|
1251
|
+
const OPERATIONS = {
|
|
1252
|
+
"*": (value, factor) => value * factor,
|
|
1253
|
+
"/": (value, factor) => value / factor
|
|
1254
|
+
};
|
|
1255
|
+
/** `value` multiplied or divided by `factor`, as a number, a literal length or a calc. */
|
|
1256
|
+
function scale(name, value, factor, operator) {
|
|
1257
|
+
assertOperand(name, value);
|
|
1258
|
+
assertFinite(name, operator === "*" ? "the factor" : "the divisor", factor);
|
|
1259
|
+
if (factor === 0) {
|
|
1260
|
+
if (operator === "/") throw new RangeError(`${name}(): the divisor must not be 0`);
|
|
1261
|
+
return 0;
|
|
1262
|
+
}
|
|
1263
|
+
if (factor === 1) return value;
|
|
1264
|
+
if (typeof value === "number") return tidy(OPERATIONS[operator](value, factor));
|
|
1265
|
+
const length = toLength(value);
|
|
1266
|
+
return length === void 0 ? `${CALC_PREFIX}${toTerm(value)} ${operator} ${factor})` : `${tidy(OPERATIONS[operator](length.value, factor))}${length.unit}`;
|
|
1267
|
+
}
|
|
1268
|
+
/** The sum of `terms` when they are all numbers, else undefined. */
|
|
1269
|
+
function sumNumbers(terms) {
|
|
1270
|
+
let total = 0;
|
|
1271
|
+
for (const { operand, sign } of terms) {
|
|
1272
|
+
if (typeof operand !== "number") return void 0;
|
|
1273
|
+
total += sign * operand;
|
|
1274
|
+
}
|
|
1275
|
+
return tidy(total);
|
|
1276
|
+
}
|
|
1277
|
+
/** The sum of `terms` when they are literal lengths of one unit, else undefined. */
|
|
1278
|
+
function sumLengths(terms) {
|
|
1279
|
+
const lengths = terms.map(({ operand }) => toLength(operand));
|
|
1280
|
+
const unit = lengths[0]?.unit;
|
|
1281
|
+
let total = 0;
|
|
1282
|
+
for (const [index, length] of lengths.entries()) {
|
|
1283
|
+
if (length === void 0 || length.unit !== unit) return void 0;
|
|
1284
|
+
total += terms[index].sign * length.value;
|
|
1285
|
+
}
|
|
1286
|
+
return `${tidy(total)}${unit}`;
|
|
1287
|
+
}
|
|
1288
|
+
/** `terms` as one calc: the first term, then each with its sign. */
|
|
1289
|
+
function toCalc(terms) {
|
|
1290
|
+
const body = terms.map(({ operand, sign }, index) => {
|
|
1291
|
+
const term = toTerm(operand);
|
|
1292
|
+
if (index === 0) return term;
|
|
1293
|
+
return `${sign === 1 ? "+" : "-"} ${term}`;
|
|
1294
|
+
}).join(" ");
|
|
1295
|
+
return `${CALC_PREFIX}${body})`;
|
|
1296
|
+
}
|
|
1297
|
+
/** `terms` added and subtracted, as a number, a literal length or one calc. */
|
|
1298
|
+
function sum(terms) {
|
|
1299
|
+
if (terms.length === 1) return terms[0].operand;
|
|
1300
|
+
return sumNumbers(terms) ?? sumLengths(terms) ?? toCalc(terms);
|
|
1301
|
+
}
|
|
1302
|
+
/** The terms of `values` with `sign`, without the zeros that change nothing; each is checked. */
|
|
1303
|
+
function toTerms(name, values, sign) {
|
|
1304
|
+
for (const value of values) assertOperand(name, value);
|
|
1305
|
+
return values.filter((value) => value !== 0).map((operand) => ({
|
|
1306
|
+
operand,
|
|
1307
|
+
sign
|
|
1308
|
+
}));
|
|
1309
|
+
}
|
|
1310
|
+
function multiply(value, factor) {
|
|
1311
|
+
return scale("multiply", value, factor, "*");
|
|
1312
|
+
}
|
|
1313
|
+
function divide(value, divisor) {
|
|
1314
|
+
return scale("divide", value, divisor, "/");
|
|
1315
|
+
}
|
|
1316
|
+
function add(...values) {
|
|
1317
|
+
const terms = toTerms("add", values, 1);
|
|
1318
|
+
return terms.length === 0 ? 0 : sum(terms);
|
|
1319
|
+
}
|
|
1320
|
+
function subtract(value, ...values) {
|
|
1321
|
+
assertOperand("subtract", value);
|
|
1322
|
+
return sum([{
|
|
1323
|
+
operand: value,
|
|
1324
|
+
sign: 1
|
|
1325
|
+
}, ...toTerms("subtract", values, -1)]);
|
|
1326
|
+
}
|
|
1327
|
+
function negate(value) {
|
|
1328
|
+
return scale("negate", value, -1, "*");
|
|
1329
|
+
}
|
|
1330
|
+
// src/lazyRecord.ts
|
|
1331
|
+
/**
|
|
1332
|
+
* An object with one key for each of `keys`, whose value is made by `make` the first time the key is
|
|
1333
|
+
* read, and kept. `Object.keys` and a spread list the keys (a spread reads every one); nothing is made
|
|
1334
|
+
* until then. The object is frozen.
|
|
1335
|
+
*/
|
|
1336
|
+
function createLazyRecord(keys, make) {
|
|
1337
|
+
const record = {};
|
|
1338
|
+
for (const key of keys) {
|
|
1339
|
+
let value;
|
|
1340
|
+
let isMade = false;
|
|
1341
|
+
Object.defineProperty(record, key, {
|
|
1342
|
+
enumerable: true,
|
|
1343
|
+
get() {
|
|
1344
|
+
if (!isMade) {
|
|
1345
|
+
value = make(key);
|
|
1346
|
+
isMade = true;
|
|
1347
|
+
}
|
|
1348
|
+
return value;
|
|
1349
|
+
}
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
return Object.freeze(record);
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* `createLazyRecord` for the keys of `source`, with every value taken from the record that `build` makes,
|
|
1356
|
+
* which is called once, when the first key is read: for a sheet whose engine must not be made, or whose
|
|
1357
|
+
* platform call must not run, before it is used.
|
|
1358
|
+
*/
|
|
1359
|
+
function createDeferredRecord(source, build) {
|
|
1360
|
+
let built;
|
|
1361
|
+
return createLazyRecord(Object.keys(source), (key) => {
|
|
1362
|
+
built ??= build();
|
|
1363
|
+
return built[key];
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
// src/styleBase.ts
|
|
1367
|
+
/** Whether `style` is a function style. */
|
|
1368
|
+
function isStyleFunction(style) {
|
|
1369
|
+
return typeof style === "function";
|
|
1370
|
+
}
|
|
1371
|
+
/** Whether a style result adds no declaration of its own: nothing, or an object with no key but `label`. */
|
|
1372
|
+
function isEmptyResult(result) {
|
|
1373
|
+
return !result || Object.keys(result).every((key) => key === "label");
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Calls `style` with the props and the theme view, the props wrapped so that every read of a key other
|
|
1377
|
+
* than `theme` is noted, and so is every way of listing them (a spread, `Object.keys`, `in`): such a
|
|
1378
|
+
* function may depend on the props. The view is passed as it is, never wrapped. What the function reads
|
|
1379
|
+
* is the real props, so what it does (a throw included) is unchanged.
|
|
1380
|
+
*/
|
|
1381
|
+
function callTracked(style, props, view) {
|
|
1382
|
+
let isDependent = false;
|
|
1383
|
+
const note = (key) => {
|
|
1384
|
+
if (key !== "theme") isDependent = true;
|
|
1385
|
+
};
|
|
1386
|
+
return {
|
|
1387
|
+
result: style(new Proxy({
|
|
1388
|
+
...props,
|
|
1389
|
+
theme: view
|
|
1390
|
+
}, {
|
|
1391
|
+
get(target, key, receiver) {
|
|
1392
|
+
note(key);
|
|
1393
|
+
return Reflect.get(target, key, receiver);
|
|
1394
|
+
},
|
|
1395
|
+
has(target, key) {
|
|
1396
|
+
note(key);
|
|
1397
|
+
return Reflect.has(target, key);
|
|
1398
|
+
},
|
|
1399
|
+
ownKeys(target) {
|
|
1400
|
+
isDependent = true;
|
|
1401
|
+
return Reflect.ownKeys(target);
|
|
1402
|
+
},
|
|
1403
|
+
getOwnPropertyDescriptor(target, key) {
|
|
1404
|
+
note(key);
|
|
1405
|
+
return Reflect.getOwnPropertyDescriptor(target, key);
|
|
1406
|
+
}
|
|
1407
|
+
})),
|
|
1408
|
+
isDependent
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* The base of a style list, for one theme view: the longest run from the start of items that do not
|
|
1413
|
+
* depend on props, which are plain objects and functions that read nothing but `theme` (each is called
|
|
1414
|
+
* once here, with the props of this call, and its result is what goes into the base). `propsFrom` is the
|
|
1415
|
+
* index of the first item that depends on props, or the length of the list when none does. When there is
|
|
1416
|
+
* a props part, the empty results at the end of the base (the label of the component, which stands right
|
|
1417
|
+
* before it) are left out, so that the base is the same one for a component and for one that wraps it.
|
|
1418
|
+
*/
|
|
1419
|
+
function splitLeading(list, props, view) {
|
|
1420
|
+
const base = [];
|
|
1421
|
+
let propsFrom = 0;
|
|
1422
|
+
for (; propsFrom < list.length; propsFrom++) {
|
|
1423
|
+
const style = list[propsFrom];
|
|
1424
|
+
if (!isStyleFunction(style)) {
|
|
1425
|
+
base.push(style);
|
|
1426
|
+
continue;
|
|
1427
|
+
}
|
|
1428
|
+
const { result, isDependent } = callTracked(style, props, view);
|
|
1429
|
+
if (isDependent) break;
|
|
1430
|
+
base.push(result);
|
|
1431
|
+
}
|
|
1432
|
+
if (propsFrom < list.length) while (base.length > 0 && isEmptyResult(base.at(-1))) base.pop();
|
|
1433
|
+
return {
|
|
1434
|
+
base,
|
|
1435
|
+
propsFrom
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
// src/registered.ts
|
|
1439
|
+
const SYNTAXES = [
|
|
1440
|
+
"<color>",
|
|
1441
|
+
"<length>",
|
|
1442
|
+
"<number>",
|
|
1443
|
+
"<percentage>",
|
|
1444
|
+
"<length-percentage>",
|
|
1445
|
+
"<angle>",
|
|
1446
|
+
"<time>",
|
|
1447
|
+
"*"
|
|
1448
|
+
];
|
|
1449
|
+
const NUMBER = String.raw`[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?`;
|
|
1450
|
+
/** The units that depend on the element or the viewport: a value in them cannot be an initial value. */
|
|
1451
|
+
const RELATIVE_UNIT = "r?em|r?ex|r?cap|r?ch|r?ic|r?lh|[sld]?v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max)";
|
|
1452
|
+
const LENGTH_UNIT = `px|cm|mm|q|in|pt|pc|${RELATIVE_UNIT}`;
|
|
1453
|
+
const NUMBER_PATTERN = new RegExp(`^${NUMBER}$`, "i");
|
|
1454
|
+
const LENGTH_PATTERN = new RegExp(`^${NUMBER}(?:${LENGTH_UNIT})$`, "i");
|
|
1455
|
+
const PERCENTAGE_PATTERN = new RegExp(`^${NUMBER}%$`, "i");
|
|
1456
|
+
const ANGLE_PATTERN = new RegExp(`^${NUMBER}(?:deg|grad|rad|turn)$`, "i");
|
|
1457
|
+
const TIME_PATTERN = new RegExp(`^${NUMBER}(?:ms|s)$`, "i");
|
|
1458
|
+
const HEX_COLOR_PATTERN = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
1459
|
+
const COLOR_FUNCTION_PATTERN = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color(?:-mix)?)\(.*\)$/i;
|
|
1460
|
+
const TRANSPARENT_PATTERN = /^transparent$/i;
|
|
1461
|
+
const KEYWORD_PATTERN = /^[a-z]+$/i;
|
|
1462
|
+
const MATH_PATTERN = /^(?:calc|min|max|clamp)\(.*\)$/i;
|
|
1463
|
+
const RELATIVE_PATTERN = new RegExp(String.raw`[\d.](?:${RELATIVE_UNIT})(?![a-z])`, "i");
|
|
1464
|
+
const DEPENDENT_PATTERN = /\b(?:var|env|attr)\(|currentcolor/i;
|
|
1465
|
+
/** Whether `value` is a color literal: a hex color, a color function or `transparent`. */
|
|
1466
|
+
const isColor = (value) => HEX_COLOR_PATTERN.test(value) || COLOR_FUNCTION_PATTERN.test(value) || TRANSPARENT_PATTERN.test(value);
|
|
1467
|
+
/** Whether `value` is a length: 0, or a number with a length unit. */
|
|
1468
|
+
const isLength = (value) => value === "0" || LENGTH_PATTERN.test(value);
|
|
1469
|
+
/** Whether `value` is a length or a percentage. */
|
|
1470
|
+
const isLengthPercentage = (value) => isLength(value) || PERCENTAGE_PATTERN.test(value);
|
|
1471
|
+
/** The test of each syntax but `*`; a keyword counts as a color. */
|
|
1472
|
+
const MATCHERS = {
|
|
1473
|
+
"<color>": (value) => isColor(value) || KEYWORD_PATTERN.test(value),
|
|
1474
|
+
"<length>": isLength,
|
|
1475
|
+
"<number>": (value) => NUMBER_PATTERN.test(value),
|
|
1476
|
+
"<percentage>": (value) => PERCENTAGE_PATTERN.test(value),
|
|
1477
|
+
"<length-percentage>": isLengthPercentage,
|
|
1478
|
+
"<angle>": (value) => ANGLE_PATTERN.test(value),
|
|
1479
|
+
"<time>": (value) => TIME_PATTERN.test(value)
|
|
1480
|
+
};
|
|
1481
|
+
/** Whether `value` is a literal of the syntax; a math function (calc, min, max, clamp) is taken on trust for a number, a length, a percentage, an angle or a time. */
|
|
1482
|
+
function isOfSyntax(syntax, value) {
|
|
1483
|
+
return syntax !== "<color>" && MATH_PATTERN.test(value) || MATCHERS[syntax](value);
|
|
1484
|
+
}
|
|
1485
|
+
/** The syntax that a base theme value says: a length, a percentage, a time, an angle, a color or a number; undefined for anything else. */
|
|
1486
|
+
function inferFromText(value) {
|
|
1487
|
+
if (LENGTH_PATTERN.test(value)) return "<length>";
|
|
1488
|
+
if (PERCENTAGE_PATTERN.test(value)) return "<percentage>";
|
|
1489
|
+
if (TIME_PATTERN.test(value)) return "<time>";
|
|
1490
|
+
if (ANGLE_PATTERN.test(value)) return "<angle>";
|
|
1491
|
+
if (isColor(value)) return "<color>";
|
|
1492
|
+
return NUMBER_PATTERN.test(value) ? "<number>" : void 0;
|
|
1493
|
+
}
|
|
1494
|
+
/** The syntax that the base value of a token says: a number is a length under a length key; undefined for text that says none. */
|
|
1495
|
+
function inferFromSource(source, isLength) {
|
|
1496
|
+
if (typeof source === "string") return inferFromText(source.trim());
|
|
1497
|
+
return isLength ? "<length>" : "<number>";
|
|
1498
|
+
}
|
|
1499
|
+
/** The syntax for a token registered with `true`: the one that its base value says, or a `TypeError` that asks for one. */
|
|
1500
|
+
function inferSyntax({ path, source, isLength }) {
|
|
1501
|
+
const inferred = inferFromSource(source, isLength);
|
|
1502
|
+
if (inferred === void 0) throw new TypeError(`registered: the syntax of "${path}" cannot be inferred from ${JSON.stringify(source)}: give an explicit syntax ('<color>', '<length>', '<number>', '<percentage>', '<length-percentage>', '<angle>', '<time>') or '*'.`);
|
|
1503
|
+
return inferred;
|
|
1504
|
+
}
|
|
1505
|
+
/** Throws a `TypeError` unless `declared` can be the initial value of a property of `syntax`. */
|
|
1506
|
+
function assertInitialValue(token, syntax) {
|
|
1507
|
+
const { path, value: declared } = token;
|
|
1508
|
+
if (DEPENDENT_PATTERN.test(declared) || RELATIVE_PATTERN.test(declared)) throw new TypeError(`registered: "${path}" is ${JSON.stringify(declared)}, which cannot be the initial value of a registered property: it depends on the element (var(), em, rem, vw, currentcolor and the like). Give it a value that does not, or register it as '*'.`);
|
|
1509
|
+
if (!isOfSyntax(syntax, declared)) throw new TypeError(`registered: "${path}" is ${JSON.stringify(declared)}, which is not a ${syntax} value. Register it with the syntax it has, or as '*'.`);
|
|
1510
|
+
}
|
|
1511
|
+
/**
|
|
1512
|
+
* The `@property` rule of a registered token. The initial value is its base value; `inherits` is true,
|
|
1513
|
+
* which a variable set on a theme wrapper needs to reach what is inside. The universal syntax `*` needs
|
|
1514
|
+
* no initial value and gets none. Throws a `TypeError` for a syntax that is unknown, or cannot be
|
|
1515
|
+
* inferred, or a value that cannot be the initial value.
|
|
1516
|
+
*/
|
|
1517
|
+
function createPropertyRule(token, syntax) {
|
|
1518
|
+
if (syntax !== true && !SYNTAXES.includes(syntax)) throw new TypeError(`registered: "${token.path}" has the unknown syntax ${JSON.stringify(syntax)}: use one of ${SYNTAXES.join(", ")}.`);
|
|
1519
|
+
const resolved = syntax === true ? inferSyntax(token) : syntax;
|
|
1520
|
+
if (resolved === "*") return `@property ${token.name}{syntax:"*";inherits:true;}`;
|
|
1521
|
+
assertInitialValue(token, resolved);
|
|
1522
|
+
return `@property ${token.name}{syntax:"${resolved}";inherits:true;initial-value:${token.value};}`;
|
|
1523
|
+
}
|
|
1524
|
+
// src/tokens.ts
|
|
1525
|
+
const DEFAULT_RAW_KEYS = ["breakpoints", "components"];
|
|
1526
|
+
const DEFAULT_LENGTH_KEYS = [
|
|
1527
|
+
"space",
|
|
1528
|
+
"sizes",
|
|
1529
|
+
"radii",
|
|
1530
|
+
"fontSizes",
|
|
1531
|
+
"borderWidths"
|
|
1532
|
+
];
|
|
1533
|
+
/** Whether `value` is an object made by a literal, not a class instance. */
|
|
1534
|
+
function isPlainObject$1(value) {
|
|
1535
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1536
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1537
|
+
return prototype === Object.prototype || prototype === null;
|
|
1538
|
+
}
|
|
1539
|
+
/** Whether `value` is a string or a number, the values that get a variable. */
|
|
1540
|
+
function isLeaf(value) {
|
|
1541
|
+
return typeof value === "string" || typeof value === "number";
|
|
1542
|
+
}
|
|
1543
|
+
/** A theme key as one part of a variable name. */
|
|
1544
|
+
function toSegment(key) {
|
|
1545
|
+
return key.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
1546
|
+
}
|
|
1547
|
+
/** The value of the longest dotted path in `entries` that `path` starts with, or undefined. */
|
|
1548
|
+
function findByPath(entries, path) {
|
|
1549
|
+
for (let length = path.length; length > 0; length--) {
|
|
1550
|
+
const value = entries.get(path.slice(0, length).join("."));
|
|
1551
|
+
if (value !== void 0) return value;
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
/** The dotted paths above each key of `modes`: 'a.b.c' gives 'a' and 'a.b'. */
|
|
1555
|
+
function collectParents(modes) {
|
|
1556
|
+
const parents = /* @__PURE__ */ new Set();
|
|
1557
|
+
for (const key of modes.keys()) {
|
|
1558
|
+
let index = key.indexOf(".");
|
|
1559
|
+
while (index !== -1) {
|
|
1560
|
+
parents.add(key.slice(0, index));
|
|
1561
|
+
index = key.indexOf(".", index + 1);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
return parents;
|
|
1565
|
+
}
|
|
1566
|
+
/** Turns a theme into variable references and the declarations that give them values. */
|
|
1567
|
+
function createTokens(theme, options = {}) {
|
|
1568
|
+
const { prefix = "", rawKeys = DEFAULT_RAW_KEYS, lengthKeys = DEFAULT_LENGTH_KEYS } = options;
|
|
1569
|
+
const modes = new Map(Object.entries(options.modes ?? {}));
|
|
1570
|
+
const registered = new Map(Object.entries(options.registered ?? {}));
|
|
1571
|
+
const parents = collectParents(modes);
|
|
1572
|
+
const toName = (path) => `--${[prefix, ...path.map(toSegment)].filter(Boolean).join("-")}`;
|
|
1573
|
+
/** The mode of the token at `path`: the longest path in `modes`, else `rawKeys`, else variable. */
|
|
1574
|
+
const readMode = (path) => {
|
|
1575
|
+
const mode = findByPath(modes, path);
|
|
1576
|
+
if (mode !== void 0) return mode;
|
|
1577
|
+
return rawKeys.includes(path[0]) ? "raw" : "variable";
|
|
1578
|
+
};
|
|
1579
|
+
/** Whether everything under `path` keeps its real value: one mode that writes no variable, and no entry deeper down. */
|
|
1580
|
+
const isKept = (path) => {
|
|
1581
|
+
const mode = readMode(path);
|
|
1582
|
+
return (mode === "raw" || mode === "inline") && !parents.has(path.join("."));
|
|
1583
|
+
};
|
|
1584
|
+
/** Whether `value` is a number under a length key: it is a length, written in px unless it is 0. */
|
|
1585
|
+
const isLengthValue = (path, value) => typeof value === "number" && lengthKeys.includes(path[0]);
|
|
1586
|
+
/** The value a variable at `path` holds: a number under a length key is in px. */
|
|
1587
|
+
const toDeclared = (path, value) => isLengthValue(path, value) && value !== 0 ? `${value}px` : String(value);
|
|
1588
|
+
const collect = (node, path, found) => {
|
|
1589
|
+
if (path.length > 0 && isKept(path)) return;
|
|
1590
|
+
if (Array.isArray(node)) node.forEach((item, index) => collect(item, [...path, String(index)], found));
|
|
1591
|
+
else if (isPlainObject$1(node)) for (const [key, value] of Object.entries(node)) collect(value, [...path, key], found);
|
|
1592
|
+
else if (isLeaf(node)) {
|
|
1593
|
+
const mode = readMode(path);
|
|
1594
|
+
if (mode === "variable" || mode === "reference") found.push({
|
|
1595
|
+
name: toName(path),
|
|
1596
|
+
path: path.join("."),
|
|
1597
|
+
value: toDeclared(path, node),
|
|
1598
|
+
source: node,
|
|
1599
|
+
isLength: isLengthValue(path, node)
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
};
|
|
1603
|
+
const list = (partial) => {
|
|
1604
|
+
const found = [];
|
|
1605
|
+
collect(partial, [], found);
|
|
1606
|
+
return found;
|
|
1607
|
+
};
|
|
1608
|
+
const declare = (partial) => Object.fromEntries(list(partial).map(({ name, value }) => [name, value]));
|
|
1609
|
+
const baseTokens = list(theme);
|
|
1610
|
+
const baseDeclarations = Object.fromEntries(baseTokens.map(({ name, value }) => [name, value]));
|
|
1611
|
+
const registrations = {};
|
|
1612
|
+
for (const token of baseTokens) {
|
|
1613
|
+
const syntax = findByPath(registered, token.path.split("."));
|
|
1614
|
+
if (syntax === void 0) continue;
|
|
1615
|
+
registrations[token.name] = createPropertyRule(token, syntax);
|
|
1616
|
+
}
|
|
1617
|
+
const toRef = (path, node) => {
|
|
1618
|
+
const mode = readMode(path);
|
|
1619
|
+
const name = toName(path);
|
|
1620
|
+
if (mode === "variable") return `var(${name})`;
|
|
1621
|
+
if (mode !== "reference") return node;
|
|
1622
|
+
const fallback = baseDeclarations[name];
|
|
1623
|
+
return fallback === void 0 ? `var(${name})` : `var(${name}, ${fallback})`;
|
|
1624
|
+
};
|
|
1625
|
+
const toRefs = (node, path) => {
|
|
1626
|
+
if (path.length > 0 && isKept(path)) return node;
|
|
1627
|
+
if (Array.isArray(node)) return node.map((item, index) => toRefs(item, [...path, String(index)]));
|
|
1628
|
+
if (isPlainObject$1(node)) return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, toRefs(value, [...path, key])]));
|
|
1629
|
+
return isLeaf(node) ? toRef(path, node) : node;
|
|
1630
|
+
};
|
|
1631
|
+
return {
|
|
1632
|
+
refs: toRefs(theme, []),
|
|
1633
|
+
declare,
|
|
1634
|
+
registrations,
|
|
1635
|
+
createView: (realTheme) => toRefs(realTheme, []),
|
|
1636
|
+
findNames: (wanted) => baseTokens.filter(({ path }) => wanted.some((one) => path === one || path.startsWith(`${one}.`))).map(({ name }) => name)
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
// src/createEngine.ts
|
|
1640
|
+
/** Whether `sheet` is a sheet made from a function of the theme, which `resolve` turns into entries; an object sheet is its entries, none of which is a function. */
|
|
1641
|
+
function isThemedSheet(sheet) {
|
|
1642
|
+
return typeof sheet.resolve === "function";
|
|
1643
|
+
}
|
|
1644
|
+
/** What is thrown when something needs the shape of the theme before any theme is known. */
|
|
1645
|
+
const NO_THEME_MESSAGE = "There is no theme yet: render a ThemeProvider with the full theme first, or call setTheme (or configure({ theme })) before a function style, a sheet or useTheme is used.";
|
|
1646
|
+
/** `text` in kebab-case: ButtonBase gives button-base. */
|
|
1647
|
+
function toKebabCase(text) {
|
|
1648
|
+
return text.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
1649
|
+
}
|
|
1650
|
+
/** The label of a styled component: `name-slot`, or '' without a name. */
|
|
1651
|
+
function createLabel({ name, slot = "root" }) {
|
|
1652
|
+
return name ? `${toKebabCase(name)}-${toKebabCase(slot)}` : "";
|
|
1653
|
+
}
|
|
1654
|
+
/** A short text for the token options of an engine, or '' when it has none of its own: they are part of what the server and the browser must agree on. */
|
|
1655
|
+
function createTokenSignature(values) {
|
|
1656
|
+
return values.every((value) => value === void 0 || Array.isArray(value) && value.length === 0) ? "" : hashString(JSON.stringify(values));
|
|
1657
|
+
}
|
|
1658
|
+
/** Makes an engine that has no theme yet: it takes one from `setTheme`, or from the first `themeClass`. It needs no framework. */
|
|
1659
|
+
function createLazyEngine(options = {}) {
|
|
1660
|
+
const { cache: given, suffix, hasLabels, hasLayers, hasPruning, hasColorFallbacks } = options;
|
|
1661
|
+
const { hasScope, hasBaseClass, hasDevChecks } = options;
|
|
1662
|
+
const { alwaysDeclare = [] } = options;
|
|
1663
|
+
const { rawKeys, lengthKeys, modes, registered } = options;
|
|
1664
|
+
if (given && options.prefix !== void 0 && options.prefix !== given.prefix) throw new TypeError(`the engine options give the prefix "${options.prefix}", which differs from the prefix "${given.prefix}" of the given cache; variables and classes would use two prefixes. Leave out \`prefix\`, or give the same one.`);
|
|
1665
|
+
const prefix = given?.prefix ?? options.prefix ?? "css";
|
|
1666
|
+
const cache = given ?? createCache({
|
|
1667
|
+
prefix,
|
|
1668
|
+
suffix,
|
|
1669
|
+
hasLabels,
|
|
1670
|
+
hasLayers,
|
|
1671
|
+
hasPruning,
|
|
1672
|
+
hasColorFallbacks,
|
|
1673
|
+
hasScope,
|
|
1674
|
+
hasBaseClass,
|
|
1675
|
+
hasDevChecks,
|
|
1676
|
+
tokenSignature: createTokenSignature([
|
|
1677
|
+
rawKeys,
|
|
1678
|
+
lengthKeys,
|
|
1679
|
+
modes,
|
|
1680
|
+
registered,
|
|
1681
|
+
alwaysDeclare
|
|
1682
|
+
])
|
|
1683
|
+
});
|
|
1684
|
+
const tokenOptions = {
|
|
1685
|
+
prefix,
|
|
1686
|
+
rawKeys,
|
|
1687
|
+
lengthKeys,
|
|
1688
|
+
modes,
|
|
1689
|
+
registered
|
|
1690
|
+
};
|
|
1691
|
+
let baseTheme;
|
|
1692
|
+
let tokens;
|
|
1693
|
+
let version = 0;
|
|
1694
|
+
const readTokens = () => {
|
|
1695
|
+
if (!tokens) throw new Error(NO_THEME_MESSAGE);
|
|
1696
|
+
return tokens;
|
|
1697
|
+
};
|
|
1698
|
+
const setTheme = (theme) => {
|
|
1699
|
+
if (theme === baseTheme) return;
|
|
1700
|
+
baseTheme = theme;
|
|
1701
|
+
tokens = createTokens(theme, tokenOptions);
|
|
1702
|
+
views = /* @__PURE__ */ new WeakMap();
|
|
1703
|
+
cache.registerProperties(tokens.registrations);
|
|
1704
|
+
cache.markUsed(tokens.findNames(alwaysDeclare));
|
|
1705
|
+
version++;
|
|
1706
|
+
};
|
|
1707
|
+
let views = /* @__PURE__ */ new WeakMap();
|
|
1708
|
+
const createThemeView = (realTheme) => {
|
|
1709
|
+
let view = views.get(realTheme);
|
|
1710
|
+
if (view === void 0) {
|
|
1711
|
+
view = (tokens ?? createTokens(realTheme, tokenOptions)).createView(realTheme);
|
|
1712
|
+
views.set(realTheme, view);
|
|
1713
|
+
}
|
|
1714
|
+
return view;
|
|
1715
|
+
};
|
|
1716
|
+
const themeClasses = /* @__PURE__ */ new WeakMap();
|
|
1717
|
+
const themeId = (partial, colorScheme) => {
|
|
1718
|
+
if (!tokens) setTheme(partial);
|
|
1719
|
+
const key = colorScheme ?? "";
|
|
1720
|
+
const known = themeClasses.get(partial) ?? /* @__PURE__ */ new Map();
|
|
1721
|
+
themeClasses.set(partial, known);
|
|
1722
|
+
let className = known.get(key);
|
|
1723
|
+
if (className === void 0) {
|
|
1724
|
+
className = createThemeClass(cache, readTokens().declare(partial), { colorScheme });
|
|
1725
|
+
known.set(key, className);
|
|
1726
|
+
}
|
|
1727
|
+
return className;
|
|
1728
|
+
};
|
|
1729
|
+
const findThemeIds = (partial) => [...themeClasses.get(partial)?.values() ?? []];
|
|
1730
|
+
const themeClass = (partial, colorScheme) => createThemeClassName(cache.prefix, themeId(partial, colorScheme), colorScheme);
|
|
1731
|
+
const when = (partial, colorScheme) => createThemeKey(themeId(partial, colorScheme));
|
|
1732
|
+
const scopeName = `${cache.prefix}-scope`;
|
|
1733
|
+
const scopeClass = () => {
|
|
1734
|
+
cache.insertOnce(scopeName, [`.${scopeName}{display:contents;}`], "theme");
|
|
1735
|
+
return scopeName;
|
|
1736
|
+
};
|
|
1737
|
+
/** The entries of `source`, each made on first access; nothing is written until an entry is used. */
|
|
1738
|
+
const createEntries = (source) => createLazyRecord(Object.keys(source), (key) => cache.createEntry(source[key]));
|
|
1739
|
+
const createThemedSheet = (styles) => {
|
|
1740
|
+
let baseEntries;
|
|
1741
|
+
let madeAt = 0;
|
|
1742
|
+
const viewEntries = /* @__PURE__ */ new WeakMap();
|
|
1743
|
+
return { resolve(theme) {
|
|
1744
|
+
if (theme !== void 0) {
|
|
1745
|
+
let entries = viewEntries.get(theme);
|
|
1746
|
+
if (entries === void 0) {
|
|
1747
|
+
entries = createEntries(styles(theme));
|
|
1748
|
+
viewEntries.set(theme, entries);
|
|
1749
|
+
}
|
|
1750
|
+
return entries;
|
|
1751
|
+
}
|
|
1752
|
+
if (baseEntries === void 0 || madeAt !== version) {
|
|
1753
|
+
baseEntries = createEntries(styles(readTokens().refs));
|
|
1754
|
+
madeAt = version;
|
|
1755
|
+
}
|
|
1756
|
+
return baseEntries;
|
|
1757
|
+
} };
|
|
1758
|
+
};
|
|
1759
|
+
function createSheet(styles) {
|
|
1760
|
+
return typeof styles === "function" ? createThemedSheet(styles) : createEntries(styles);
|
|
1761
|
+
}
|
|
1762
|
+
const createStyler = (stylerOptions, styles, inherited = []) => {
|
|
1763
|
+
const label = createLabel(stylerOptions);
|
|
1764
|
+
const list = [
|
|
1765
|
+
...inherited,
|
|
1766
|
+
...label ? [{ label }] : [],
|
|
1767
|
+
...styles
|
|
1768
|
+
];
|
|
1769
|
+
const hasFunction = list.some(isStyleFunction);
|
|
1770
|
+
const resolveStyle = (style, props, theme) => typeof style === "function" ? style({
|
|
1771
|
+
...props,
|
|
1772
|
+
theme: theme ?? readTokens().refs
|
|
1773
|
+
}) : style;
|
|
1774
|
+
const resolveAll = (source, props, theme) => source.map((style) => resolveStyle(style, props, theme));
|
|
1775
|
+
let fixed;
|
|
1776
|
+
const getFixed = () => fixed ??= hasFunction ? {
|
|
1777
|
+
baseClass: "",
|
|
1778
|
+
propsStyles: list
|
|
1779
|
+
} : {
|
|
1780
|
+
baseClass: cache.css(...list),
|
|
1781
|
+
propsStyles: []
|
|
1782
|
+
};
|
|
1783
|
+
const plans = /* @__PURE__ */ new WeakMap();
|
|
1784
|
+
const makePlan = (props, view) => {
|
|
1785
|
+
const { base, propsFrom } = splitLeading(list, props, view);
|
|
1786
|
+
const hasProps = propsFrom < list.length;
|
|
1787
|
+
const lead = label ? [{ label }] : [];
|
|
1788
|
+
return {
|
|
1789
|
+
baseClass: base.some(Boolean) ? cache.css(...base) : "",
|
|
1790
|
+
propsStyles: hasProps ? [...lead, ...list.slice(propsFrom)] : []
|
|
1791
|
+
};
|
|
1792
|
+
};
|
|
1793
|
+
const getPlan = (props, theme) => {
|
|
1794
|
+
if (!cache.hasBaseClass || !hasFunction) return getFixed();
|
|
1795
|
+
const view = theme ?? readTokens().refs;
|
|
1796
|
+
let plan = plans.get(view);
|
|
1797
|
+
if (plan === void 0) {
|
|
1798
|
+
plan = makePlan(props, view);
|
|
1799
|
+
plans.set(view, plan);
|
|
1800
|
+
}
|
|
1801
|
+
return plan;
|
|
1802
|
+
};
|
|
1803
|
+
/** The classes of the styles: the base, then the props class that is made after it. */
|
|
1804
|
+
const getOwn = (plan, props, theme) => {
|
|
1805
|
+
if (plan.propsStyles.length === 0) return plan.baseClass;
|
|
1806
|
+
const resolved = resolveAll(plan.propsStyles, props, theme);
|
|
1807
|
+
const second = cache.cssWith({ after: plan.baseClass }, ...resolved);
|
|
1808
|
+
return [plan.baseClass, second].filter(Boolean).join(" ");
|
|
1809
|
+
};
|
|
1810
|
+
/** Without layers there is no override class and no order between classes to rely on: what comes in is merged with all of the styles, into the one class. */
|
|
1811
|
+
const getMerged = (props, theme, extras) => cache.css(...resolveAll(list, props, theme), ...extras);
|
|
1812
|
+
return {
|
|
1813
|
+
styles: list,
|
|
1814
|
+
isDynamic: hasFunction,
|
|
1815
|
+
getClassName(props, extra, theme) {
|
|
1816
|
+
const extras = Array.isArray(extra) ? extra : [extra];
|
|
1817
|
+
const hasExtras = extras.some(Boolean);
|
|
1818
|
+
if (hasExtras && !cache.hasLayers) return getMerged(props, theme, extras);
|
|
1819
|
+
const own = getOwn(getPlan(props, theme), props, theme);
|
|
1820
|
+
if (!hasExtras) return own;
|
|
1821
|
+
return [own, cache.cssWith({
|
|
1822
|
+
layer: "overrides",
|
|
1823
|
+
label: label || void 0
|
|
1824
|
+
}, ...extras)].filter(Boolean).join(" ");
|
|
1825
|
+
}
|
|
1826
|
+
};
|
|
1827
|
+
};
|
|
1828
|
+
return {
|
|
1829
|
+
cache,
|
|
1830
|
+
css: cache.css,
|
|
1831
|
+
get hasTheme() {
|
|
1832
|
+
return baseTheme !== void 0;
|
|
1833
|
+
},
|
|
1834
|
+
get baseTheme() {
|
|
1835
|
+
return baseTheme;
|
|
1836
|
+
},
|
|
1837
|
+
get refs() {
|
|
1838
|
+
return readTokens().refs;
|
|
1839
|
+
},
|
|
1840
|
+
scopeClass,
|
|
1841
|
+
setTheme,
|
|
1842
|
+
createThemeView,
|
|
1843
|
+
themeClass,
|
|
1844
|
+
themeId,
|
|
1845
|
+
findThemeIds,
|
|
1846
|
+
when,
|
|
1847
|
+
whenScheme: createSchemeKey,
|
|
1848
|
+
createSheet,
|
|
1849
|
+
createStyler
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
/** Makes the engine of one theme shape: a cache, the theme as variables, and what the bindings build on. It needs no framework. */
|
|
1853
|
+
function createEngine(theme, options = {}) {
|
|
1854
|
+
const engine = createLazyEngine(options);
|
|
1855
|
+
engine.setTheme(theme);
|
|
1856
|
+
return engine;
|
|
1857
|
+
}
|
|
1858
|
+
// src/scanHtml.ts
|
|
1859
|
+
/** The elements whose content is text, not markup: nothing in them is an attribute. */
|
|
1860
|
+
const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set([
|
|
1861
|
+
"script",
|
|
1862
|
+
"style",
|
|
1863
|
+
"textarea",
|
|
1864
|
+
"title"
|
|
1865
|
+
]);
|
|
1866
|
+
/** Whether `code` is whitespace in HTML: tab, line feed, vertical tab, form feed, carriage return, space. */
|
|
1867
|
+
function isSpace(code) {
|
|
1868
|
+
return code === 32 || code >= 9 && code <= 13;
|
|
1869
|
+
}
|
|
1870
|
+
/** Whether `code` ends an attribute name: whitespace, '=', '>' or '/'. */
|
|
1871
|
+
function isNameEnd(code) {
|
|
1872
|
+
return isSpace(code) || code === 61 || code === 62 || code === 47;
|
|
1873
|
+
}
|
|
1874
|
+
/** Whether `code` is an ASCII letter. */
|
|
1875
|
+
function isLetter(code) {
|
|
1876
|
+
return code >= 97 && code <= 122 || code >= 65 && code <= 90;
|
|
1877
|
+
}
|
|
1878
|
+
/** The index of the first character at or after `index` that is not whitespace. */
|
|
1879
|
+
function skipSpaces(html, index) {
|
|
1880
|
+
let position = index;
|
|
1881
|
+
while (position < html.length && isSpace(codeAt(html, position))) position++;
|
|
1882
|
+
return position;
|
|
1883
|
+
}
|
|
1884
|
+
/** Adds the whitespace-separated tokens of `value` to `target`. */
|
|
1885
|
+
function addTokens(target, value) {
|
|
1886
|
+
for (const token of value.split(/\s+/)) if (token !== "") target.add(token);
|
|
1887
|
+
}
|
|
1888
|
+
/** The value that starts at `index` (quoted with ' or ", or bare) and the index after it. */
|
|
1889
|
+
function readValue(html, index) {
|
|
1890
|
+
const quote = html[index];
|
|
1891
|
+
if (quote === "\"" || quote === "'") {
|
|
1892
|
+
const close = html.indexOf(quote, index + 1);
|
|
1893
|
+
const end = close === -1 ? html.length : close;
|
|
1894
|
+
return {
|
|
1895
|
+
value: html.slice(index + 1, end),
|
|
1896
|
+
end: end + 1
|
|
1897
|
+
};
|
|
1898
|
+
}
|
|
1899
|
+
let end = index;
|
|
1900
|
+
while (end < html.length && !isSpace(codeAt(html, end)) && html[end] !== ">") end++;
|
|
1901
|
+
return {
|
|
1902
|
+
value: html.slice(index, end),
|
|
1903
|
+
end
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
/** Reads the attributes of the tag whose name ended at `index`, adds what matters to `found`, and returns the index after the `>`. */
|
|
1907
|
+
function readAttributes(html, index, found) {
|
|
1908
|
+
let position = index;
|
|
1909
|
+
while (position < html.length) {
|
|
1910
|
+
const code = codeAt(html, position);
|
|
1911
|
+
if (code === 62) return position + 1;
|
|
1912
|
+
if (isSpace(code) || code === 47) {
|
|
1913
|
+
position++;
|
|
1914
|
+
continue;
|
|
1915
|
+
}
|
|
1916
|
+
const nameStart = position;
|
|
1917
|
+
while (position < html.length && !isNameEnd(codeAt(html, position))) position++;
|
|
1918
|
+
if (position === nameStart) position++;
|
|
1919
|
+
const name = html.slice(nameStart, position).toLowerCase();
|
|
1920
|
+
position = skipSpaces(html, position);
|
|
1921
|
+
if (html[position] !== "=") continue;
|
|
1922
|
+
const { value, end } = readValue(html, skipSpaces(html, position + 1));
|
|
1923
|
+
position = end;
|
|
1924
|
+
if (name === "class" || name === "classname") addTokens(found.classes, value);
|
|
1925
|
+
else if (name === "data-href") addTokens(found.carried, value);
|
|
1926
|
+
}
|
|
1927
|
+
return html.length;
|
|
1928
|
+
}
|
|
1929
|
+
/** The index of the `</name` that closes a raw text element, or the end of the document. */
|
|
1930
|
+
function findClosingTag(html, index, name) {
|
|
1931
|
+
let at = html.indexOf("</", index);
|
|
1932
|
+
while (at !== -1 && html.slice(at + 2, at + 2 + name.length).toLowerCase() !== name) at = html.indexOf("</", at + 2);
|
|
1933
|
+
return at === -1 ? html.length : at;
|
|
1934
|
+
}
|
|
1935
|
+
/** The index of the end of the tag name that starts at `index`. */
|
|
1936
|
+
function readTagNameEnd(html, index) {
|
|
1937
|
+
let end = index;
|
|
1938
|
+
while (end < html.length && !isNameEnd(codeAt(html, end))) end++;
|
|
1939
|
+
return end;
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* The class tokens of `html`: the values of the `class` and `className` attributes, in one pass over
|
|
1943
|
+
* the markup. Comments and the content of `script`, `style`, `textarea` and `title` are skipped, so
|
|
1944
|
+
* a class name inside a script or a text is not taken for a class. Quoted and bare values are read;
|
|
1945
|
+
* a class name in any other attribute is not looked at. The pass moves forward only: its time is
|
|
1946
|
+
* linear in the length of the document, and there is no pattern to backtrack.
|
|
1947
|
+
*/
|
|
1948
|
+
function scanHtml(html) {
|
|
1949
|
+
const found = {
|
|
1950
|
+
classes: /* @__PURE__ */ new Set(),
|
|
1951
|
+
carried: /* @__PURE__ */ new Set()
|
|
1952
|
+
};
|
|
1953
|
+
let at = html.indexOf("<");
|
|
1954
|
+
while (at !== -1) {
|
|
1955
|
+
if (html.startsWith("<!--", at)) {
|
|
1956
|
+
const close = html.indexOf("-->", at + 4);
|
|
1957
|
+
at = close === -1 ? html.length : close + 3;
|
|
1958
|
+
} else if (isLetter(codeAt(html, at + 1))) {
|
|
1959
|
+
const nameEnd = readTagNameEnd(html, at + 1);
|
|
1960
|
+
const name = html.slice(at + 1, nameEnd).toLowerCase();
|
|
1961
|
+
at = readAttributes(html, nameEnd, found);
|
|
1962
|
+
if (RAW_TEXT_ELEMENTS.has(name)) at = findClosingTag(html, at, name);
|
|
1963
|
+
} else at++;
|
|
1964
|
+
at = html.indexOf("<", at);
|
|
1965
|
+
}
|
|
1966
|
+
return found;
|
|
1967
|
+
}
|
|
1968
|
+
// src/extractStyles.ts
|
|
1969
|
+
/** The style element of `css`: the cache's key, and the stamp of its options for the browser to compare. */
|
|
1970
|
+
function createTag(cache, css) {
|
|
1971
|
+
return `<style data-style="${cache.prefix}" data-options="${cache.fingerprint}">${css}</style>`;
|
|
1972
|
+
}
|
|
1973
|
+
/**
|
|
1974
|
+
* The style element of a static page or a server render: everything `cache` inserted, whatever page
|
|
1975
|
+
* inserted it. A cache that renders more than one page (a server process) should use `extractPageStyles`,
|
|
1976
|
+
* which carries only what one page uses. The element is stamped with the options of the cache
|
|
1977
|
+
* (`data-options`), which a cache made in the browser compares with its own; it holds no list of ids,
|
|
1978
|
+
* because the browser reads the rules themselves.
|
|
1979
|
+
*/
|
|
1980
|
+
function createStyleTag(cache) {
|
|
1981
|
+
return createTag(cache, cache.extract().css);
|
|
1982
|
+
}
|
|
1983
|
+
/**
|
|
1984
|
+
* The CSS of one page, decided from the page: the finished `html` is scanned for the class names it
|
|
1985
|
+
* holds (the values of its `class` and `className` attributes only; scripts, styles, comments and other
|
|
1986
|
+
* attributes are not looked at), and only those classes are written, with the theme classes
|
|
1987
|
+
* trimmed to the variables that the page uses. Nothing depends on what else the cache holds, on the
|
|
1988
|
+
* order pages were rendered in, or on pages being rendered at the same time, and the cache is not changed.
|
|
1989
|
+
* The `<style href precedence>` elements that `html` carries already (React's server render of the
|
|
1990
|
+
* client build emits them) are not written again.
|
|
1991
|
+
*/
|
|
1992
|
+
function extractPageStyles(cache, html, options = {}) {
|
|
1993
|
+
const { classes, carried } = scanHtml(html);
|
|
1994
|
+
const themes = (options.themes ?? []).flatMap((value) => value.split(/\s+/));
|
|
1995
|
+
const { css, ids } = cache.extractPage(classes, {
|
|
1996
|
+
themes,
|
|
1997
|
+
carried
|
|
1998
|
+
});
|
|
1999
|
+
return {
|
|
2000
|
+
css,
|
|
2001
|
+
ids,
|
|
2002
|
+
options: cache.fingerprint,
|
|
2003
|
+
tag: createTag(cache, css)
|
|
2004
|
+
};
|
|
2005
|
+
}
|
|
2006
|
+
// src/mergeDeep.ts
|
|
2007
|
+
/** Whether `value` is an object made by a literal, not a class instance. */
|
|
2008
|
+
function isPlainObject(value) {
|
|
2009
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2010
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2011
|
+
return prototype === Object.prototype || prototype === null;
|
|
2012
|
+
}
|
|
2013
|
+
/** `override` over `base`: plain objects merge key by key, everything else is replaced, undefined keeps `base`. */
|
|
2014
|
+
function mergeDeep(base, override) {
|
|
2015
|
+
if (override === void 0) return base;
|
|
2016
|
+
if (!isPlainObject(base) || !isPlainObject(override)) return override;
|
|
2017
|
+
const merged = { ...base };
|
|
2018
|
+
for (const [key, value] of Object.entries(override)) merged[key] = mergeDeep(base[key], value);
|
|
2019
|
+
return merged;
|
|
2020
|
+
}
|
|
2021
|
+
exports.DEFAULT_SCOPING = DEFAULT_SCOPING;
|
|
2022
|
+
exports.NO_THEME_MESSAGE = NO_THEME_MESSAGE;
|
|
2023
|
+
exports.RULE_LAYERS = RULE_LAYERS;
|
|
2024
|
+
exports.add = add;
|
|
2025
|
+
exports.alpha = alpha;
|
|
2026
|
+
exports.assertAlphaInput = assertAlphaInput;
|
|
2027
|
+
exports.at = at;
|
|
2028
|
+
exports.compileRules = compileRules;
|
|
2029
|
+
exports.createCache = createCache;
|
|
2030
|
+
exports.createDeferredRecord = createDeferredRecord;
|
|
2031
|
+
exports.createDomSheet = createDomSheet;
|
|
2032
|
+
exports.createEngine = createEngine;
|
|
2033
|
+
exports.createLazyEngine = createLazyEngine;
|
|
2034
|
+
exports.createLazyRecord = createLazyRecord;
|
|
2035
|
+
exports.createMemorySheet = createMemorySheet;
|
|
2036
|
+
exports.createNoSchemeGuard = createNoSchemeGuard;
|
|
2037
|
+
exports.createSchemeKey = createSchemeKey;
|
|
2038
|
+
exports.createScopeRule = createScopeRule;
|
|
2039
|
+
exports.createSheetEntry = createSheetEntry;
|
|
2040
|
+
exports.createStyleTag = createStyleTag;
|
|
2041
|
+
exports.createThemeClass = createThemeClass;
|
|
2042
|
+
exports.createThemeClassName = createThemeClassName;
|
|
2043
|
+
exports.createThemeKey = createThemeKey;
|
|
2044
|
+
exports.createTokens = createTokens;
|
|
2045
|
+
exports.divide = divide;
|
|
2046
|
+
exports.extractPageStyles = extractPageStyles;
|
|
2047
|
+
exports.findMissingStyles = findMissingStyles;
|
|
2048
|
+
exports.flattenStyle = flattenStyle;
|
|
2049
|
+
exports.getBoundaryClass = getBoundaryClass;
|
|
2050
|
+
exports.getSchemeClass = getSchemeClass;
|
|
2051
|
+
exports.hashString = hashString;
|
|
2052
|
+
exports.isAlphaColor = isAlphaColor;
|
|
2053
|
+
exports.isSheetEntry = isSheetEntry;
|
|
2054
|
+
exports.isThemedSheet = isThemedSheet;
|
|
2055
|
+
exports.mergeDeep = mergeDeep;
|
|
2056
|
+
exports.mergeStyles = mergeStyles;
|
|
2057
|
+
exports.multiply = multiply;
|
|
2058
|
+
exports.negate = negate;
|
|
2059
|
+
exports.readCondition = readCondition;
|
|
2060
|
+
exports.readEntrySource = readEntrySource;
|
|
2061
|
+
exports.readLabel = readLabel;
|
|
2062
|
+
exports.subtract = subtract;
|
|
2063
|
+
exports.toDeclarationText = toDeclarationText;
|
|
2064
|
+
exports.toRgba = toRgba;
|