@umber-style/core 0.1.0-alpha.0 → 0.1.0-alpha.1

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/dist/index.cjs CHANGED
@@ -1,12 +1,46 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/standIn.ts
3
+ const BRAND$3 = Symbol.for("umber-style.stand-in");
4
+ /**
5
+ * A stand-in for the theme at `path` (a dotted path, '' for the theme itself): any key read from it is
6
+ * a stand-in one level down, a call is a stand-in for `path(arguments)` (a helper of the theme such as
7
+ * `breakpoints.up('md')`), a symbol reads as undefined, listing its keys throws, calling it with a function throws, and as text it is its path. `keyframes` and
8
+ * `globalStyles` name the styles of a function of the theme with it, so that the name does not depend on
9
+ * the theme's values.
10
+ */
11
+ function createStandIn(path) {
12
+ const call = (...values) => {
13
+ if (values.some((value) => typeof value === "function" && !isStandIn(value))) throw new TypeError(`A function of the theme given to keyframes() or globalStyles() cannot pass a function to "${path}": its name is made before the theme is known. Read each token by its key.`);
14
+ return createStandIn(`${path}(${values.map(String).join(",")})`);
15
+ };
16
+ return new Proxy(call, {
17
+ get: (_target, key) => {
18
+ if (key === Symbol.toPrimitive) return () => path;
19
+ if (typeof key === "symbol") return void 0;
20
+ return createStandIn(path === "" ? key : `${path}.${key}`);
21
+ },
22
+ has: (_target, key) => key === BRAND$3,
23
+ ownKeys: () => {
24
+ throw new TypeError(`A function of the theme given to keyframes() or globalStyles() cannot list the keys of "${path}" (Object.keys, a spread, for...in): its name is made before the theme is known. Read each token by its key.`);
25
+ }
26
+ });
27
+ }
28
+ /** Whether `value` was made by `createStandIn`. */
29
+ function isStandIn(value) {
30
+ return typeof value === "function" && BRAND$3 in value;
31
+ }
32
+ /** `value` as its path when it is a stand-in, else `value` itself: a helper that computes with a token takes a stand-in as the text of a reference. */
33
+ function readStandIn(value) {
34
+ return isStandIn(value) ? String(value) : value;
35
+ }
2
36
  // src/alpha.ts
3
- const BRAND$1 = Symbol.for("umber-style.alpha-color");
37
+ const BRAND$2 = Symbol.for("umber-style.alpha-color");
4
38
  const NUMBER$1 = String.raw`[+-]?(?:\d+\.?\d*|\.\d+)`;
5
39
  const HEX_PATTERN = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
6
40
  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
41
  /** Whether `value` was made by `alpha()` as a mix: a plain string is a color, not a fallback pair. */
8
42
  function isAlphaColor(value) {
9
- return typeof value === "object" && value !== null && BRAND$1 in value;
43
+ return typeof value === "object" && value !== null && BRAND$2 in value;
10
44
  }
11
45
  /** `value` limited to `low` through `high`. */
12
46
  function clamp(value, low, high) {
@@ -78,14 +112,15 @@ function assertAlphaInput(color, opacity) {
78
112
  * that is not a string or an opacity that is not a number, a `RangeError` for an opacity outside 0 to 1.
79
113
  */
80
114
  function alpha(color, opacity) {
81
- assertAlphaInput(color, opacity);
82
- if (opacity === 1) return color;
115
+ const text = readStandIn(color);
116
+ assertAlphaInput(text, opacity);
117
+ if (opacity === 1) return text;
83
118
  if (opacity === 0) return "transparent";
84
- const value = `color-mix(in srgb, ${color} ${Math.round(opacity * 1e4) / 100}%, transparent)`;
119
+ const value = `color-mix(in srgb, ${text} ${Math.round(opacity * 1e4) / 100}%, transparent)`;
85
120
  const mix = {};
86
121
  Object.defineProperties(mix, {
87
122
  fallback: {
88
- value: toRgba(color, opacity) ?? color,
123
+ value: toRgba(text, opacity) ?? text,
89
124
  enumerable: true
90
125
  },
91
126
  value: {
@@ -93,7 +128,7 @@ function alpha(color, opacity) {
93
128
  enumerable: true
94
129
  },
95
130
  toString: { value: () => value },
96
- [BRAND$1]: { value: true }
131
+ [BRAND$2]: { value: true }
97
132
  });
98
133
  return Object.freeze(mix);
99
134
  }
@@ -107,6 +142,26 @@ function alpha(color, opacity) {
107
142
  function at(key, style) {
108
143
  return { [key]: style };
109
144
  }
145
+ // src/cacheRegistry.ts
146
+ const registry$1 = /* @__PURE__ */ new WeakMap();
147
+ /** Records `cache` as the cache of its prefix in `page`, unless a cache of that prefix was recorded there before. */
148
+ function registerCache(page, cache) {
149
+ let caches = registry$1.get(page);
150
+ if (caches === void 0) {
151
+ caches = /* @__PURE__ */ new Map();
152
+ registry$1.set(page, caches);
153
+ }
154
+ if (!caches.has(cache.prefix)) caches.set(cache.prefix, cache);
155
+ }
156
+ /**
157
+ * The cache of `prefix` in `page`: the first cache of that prefix made with a sheet in a style element of
158
+ * that document (`createCache` records it), or undefined where none was made. It is how code that has no
159
+ * engine of its own (a component that a server component renders, in the browser) reaches the cache of the
160
+ * page, for example to release a global rule that a server sent.
161
+ */
162
+ function findCache(prefix, page) {
163
+ return registry$1.get(page)?.get(prefix);
164
+ }
110
165
  // src/hash.ts
111
166
  const MULTIPLIER = 0x5bd1e995;
112
167
  /** Multiplies `value` by the hash constant, kept to 32 bits. */
@@ -135,14 +190,20 @@ function hashString(text) {
135
190
  // src/findMissingStyles.ts
136
191
  const STATE_PATTERN = /:(hover|focus|active|focus-visible|focus-within)\b/;
137
192
  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]");
193
+ /** A selector that names the root element or the body: `html`, `body` or `:root` as a whole word. */
194
+ const ROOT_PATTERN = /(?:^|[\s>+~(,])(?:html|body)(?![\w-])|:root(?![\w-])/;
195
+ /** The prefix named by the first style element of an engine in `page`, or undefined. */
196
+ function findPrefix(page) {
197
+ const element = page.querySelector("style[data-style], style[data-precedence]");
141
198
  return element?.dataset.style ?? element?.dataset.precedence;
142
199
  }
200
+ /** Whether `rule` is a style rule. A rule of another document (an iframe's) is not an instance of this window's `CSSStyleRule`, so the name of its class is read instead. */
201
+ function isStyleRule(rule) {
202
+ return rule.constructor.name === "CSSStyleRule";
203
+ }
143
204
  /** The style rules under `list`, groups included. */
144
205
  function collectStyleRules(list, found) {
145
- for (const rule of list) if (rule instanceof CSSStyleRule) found.push(rule);
206
+ for (const rule of list) if (isStyleRule(rule)) found.push(rule);
146
207
  else if ("cssRules" in rule) collectStyleRules(rule.cssRules, found);
147
208
  return found;
148
209
  }
@@ -186,11 +247,11 @@ function isMatched(element, rule) {
186
247
  return false;
187
248
  }
188
249
  }
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}"]`;
250
+ /** The rules of the engine's style elements in `page` (those of `data-umber` too), each with the variables it uses without a fallback. */
251
+ function collectRules(page, prefix) {
252
+ const selector = `style[data-style="${prefix}"], style[data-precedence="${prefix}"], style[data-umber~="${prefix}"], style[data-umber~="${prefix}-global"]`;
192
253
  const rules = [];
193
- for (const element of document.querySelectorAll(selector)) if (element.sheet) collectStyleRules(element.sheet.cssRules, rules);
254
+ for (const element of page.querySelectorAll(selector)) if (element.sheet) collectStyleRules(element.sheet.cssRules, rules);
194
255
  return rules.map((rule) => ({
195
256
  rule,
196
257
  variables: readBareVariables(rule.cssText, `--${prefix}-`),
@@ -231,37 +292,209 @@ function findVariableProblems(element, label, rules, problems) {
231
292
  }
232
293
  }
233
294
  /**
295
+ * The global rules (rules that name no class of the engine) for `html`, `body` or `:root` that match
296
+ * `element`, `<html>` or `<body>` without a class of the engine, and use variables that have no value
297
+ * on it: one problem for each rule, with all of those variables. A variable is declared on the element
298
+ * that carries a theme class and below it, so a rule for `html` or `body` sees the variables of a theme
299
+ * only when they are declared on `:root` (what the outermost provider does) or the theme class is on
300
+ * `<html>`; then there is no problem.
301
+ */
302
+ function findRootProblems(element, label, rules, start, problems) {
303
+ const computed = getComputedStyle(element);
304
+ for (const { rule, variables, isState } of rules) {
305
+ const selector = rule.selectorText;
306
+ const isGlobal = readClassNames(selector, start).length === 0 && ROOT_PATTERN.test(selector);
307
+ if (variables.length === 0 || isState || !isGlobal || !isMatched(element, rule)) continue;
308
+ const missing = variables.filter((name) => computed.getPropertyValue(name).trim() === "");
309
+ if (missing.length === 0) continue;
310
+ const message = `${label} has no value for ${missing.join(", ")}, which the global rule ${selector} uses: a rule for html or body sees the variables of a theme declared on :root (the outermost provider) or on <html> (its theme class)`;
311
+ problems.push({
312
+ kind: "root-without-theme",
313
+ name: missing[0],
314
+ element: label,
315
+ message,
316
+ key: `root:${selector}`
317
+ });
318
+ }
319
+ }
320
+ /**
234
321
  * 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
322
+ * (the document by default; the style elements are read in the document of `root`): every class of the engine on it is named by at least one rule of the
236
323
  * engine's style elements (its own, and the ones React hoists), and every variable of the engine that
237
324
  * a rule matching the element uses, without a fallback, has a value on the element. The classes that
238
325
  * 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.
326
+ * are left out, and so is `<prefix>-theme-0`, the theme class of a theme that declares nothing, which has
327
+ * no rule by design; and so are the rules for `:hover`, `:focus` and the like. `<html>` and `<body>` without
328
+ * a class of the engine are checked for the global rules that name them (see `root-without-theme`). An
329
+ * empty list means nothing is missing. Where there is no document, or no style element of an engine,
330
+ * the list is empty.
241
331
  */
242
332
  function findMissingStyles(root, options = {}) {
243
333
  if (typeof document === "undefined") return [];
244
- const prefix = options.prefix ?? findPrefix();
245
- if (prefix === void 0) return [];
246
334
  const scope = root ?? document;
247
- const rules = collectRules(prefix);
335
+ const page = scope.ownerDocument ?? scope;
336
+ const prefix = options.prefix ?? findPrefix(page);
337
+ if (prefix === void 0) return [];
338
+ const rules = collectRules(page, prefix);
248
339
  const named = new Set(rules.flatMap(({ rule }) => readClassNames(rule.selectorText, `${prefix}-`)));
249
340
  const markers = /* @__PURE__ */ new Set([
250
341
  `${prefix}-boundary`,
251
342
  `${prefix}-scheme-light`,
252
- `${prefix}-scheme-dark`
343
+ `${prefix}-scheme-dark`,
344
+ `${prefix}-theme-0`
253
345
  ]);
254
346
  const problems = [];
255
- const elements = [...scope instanceof Element ? [scope] : [], ...scope.querySelectorAll("*")];
347
+ const elements = [...scope.nodeType === 1 ? [scope] : [], ...scope.querySelectorAll("*")];
256
348
  for (const element of elements) {
257
349
  const classes = [...element.classList].filter((name) => name.startsWith(`${prefix}-`) && !markers.has(name));
258
- if (classes.length === 0) continue;
350
+ if (classes.length === 0) {
351
+ if (element === page.documentElement || element === page.body) findRootProblems(element, describe(element), rules, `${prefix}-`, problems);
352
+ continue;
353
+ }
259
354
  const label = describe(element);
260
355
  findClassProblems(label, classes, named, problems);
261
356
  findVariableProblems(element, label, rules, problems);
262
357
  }
263
358
  return problems;
264
359
  }
360
+ // src/findUnsupportedDeclarations.ts
361
+ const KEYFRAMES_AT_RULE$1 = "@keyframes";
362
+ const IMPORTANT = "important";
363
+ /** A value that starts with a vendor prefix: a keyword or a function written for another browser. */
364
+ const VENDOR_VALUE = /^-(?:webkit|moz|ms|o)-/i;
365
+ /**
366
+ * `CSS.supports` of the browser, or undefined where there is none to trust: no `CSS` (a server), one
367
+ * that throws or answers two plain questions wrong, or jsdom, which answers from a table of its own and
368
+ * not from what a browser renders. The checker of a cache asks once, when it is made.
369
+ */
370
+ function findBrowserSupports() {
371
+ try {
372
+ return !navigator.userAgent.includes("jsdom") && CSS.supports("color", "red") && !CSS.supports("color", "not-a-color") ? (property, value) => CSS.supports(property, value) : void 0;
373
+ } catch {
374
+ return;
375
+ }
376
+ }
377
+ /** The index after the string that starts at `index`, which is a quote. */
378
+ function skipString$1(text, index) {
379
+ const quote = text[index];
380
+ let position = index + 1;
381
+ while (position < text.length && text[position] !== quote) position += text[position] === "\\" ? 2 : 1;
382
+ return position + 1;
383
+ }
384
+ /** Opens a block at `index`, a `{`: its prelude is the text since `boundary`. */
385
+ function openBlock$2(stack, text, boundary, index) {
386
+ const parent = stack.at(-1);
387
+ if (parent) parent.hasChild = true;
388
+ stack.push({
389
+ prelude: text.slice(boundary, index).trim(),
390
+ bodyStart: index + 1,
391
+ hasChild: false
392
+ });
393
+ }
394
+ /** Closes the innermost block at `index`, a `}`: a block without a block of its own that is not an at-rule is a rule to add to `rules`. */
395
+ function closeBlock$2(stack, text, index, rules) {
396
+ const block = stack.pop();
397
+ if (!block || block.hasChild || block.prelude.startsWith("@")) return;
398
+ const parent = stack.at(-1)?.prelude ?? "";
399
+ rules.push({
400
+ selector: block.prelude,
401
+ parent,
402
+ body: text.slice(block.bodyStart, index)
403
+ });
404
+ }
405
+ /** The innermost blocks of `text` that are not at-rules: the rules that hold declarations. */
406
+ function readStyleRules(text) {
407
+ const rules = [];
408
+ const stack = [];
409
+ let boundary = 0;
410
+ let index = 0;
411
+ while (index < text.length) {
412
+ const char = text[index];
413
+ if (char === "\"" || char === "'") {
414
+ index = skipString$1(text, index);
415
+ continue;
416
+ }
417
+ if (char === ";") boundary = index + 1;
418
+ else if (char === "{") {
419
+ openBlock$2(stack, text, boundary, index);
420
+ boundary = index + 1;
421
+ } else if (char === "}") {
422
+ closeBlock$2(stack, text, index, rules);
423
+ boundary = index + 1;
424
+ }
425
+ index++;
426
+ }
427
+ return rules;
428
+ }
429
+ /** Adds the declaration `declaration` (`property:value`) to `declarations`, unless it has no ':'. */
430
+ function addDeclaration(declarations, declaration) {
431
+ const colon = declaration.indexOf(":");
432
+ if (colon === -1) return;
433
+ declarations.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).trim());
434
+ }
435
+ /** The declarations of `body` by property, the last one of each: the items before it in a fallback list are meant to be dropped. */
436
+ function readLastDeclarations(body) {
437
+ const declarations = /* @__PURE__ */ new Map();
438
+ let depth = 0;
439
+ let start = 0;
440
+ let index = 0;
441
+ while (index <= body.length) {
442
+ const char = body[index];
443
+ if (char === "\"" || char === "'") {
444
+ index = skipString$1(body, index);
445
+ continue;
446
+ }
447
+ if (char === "(") depth++;
448
+ else if (char === ")") depth--;
449
+ else if (index === body.length || char === ";" && depth === 0) {
450
+ addDeclaration(declarations, body.slice(start, index));
451
+ start = index + 1;
452
+ }
453
+ index++;
454
+ }
455
+ return declarations;
456
+ }
457
+ /**
458
+ * `value` without a `!important` at its end (in any case, with whitespace around the `!`), and without
459
+ * the whitespace before it. A scan from the end: nothing is tried twice, so it takes linear time.
460
+ */
461
+ function stripImportant(value) {
462
+ const trimmed = value.trimEnd();
463
+ if (trimmed.slice(-9).toLowerCase() !== IMPORTANT) return value;
464
+ const before = trimmed.slice(0, -9).trimEnd();
465
+ return before.endsWith("!") ? before.slice(0, -1).trimEnd() : value;
466
+ }
467
+ /** What a message names a rule by: its `@keyframes` rule, the last class of the engine in its selector, or its selector for a global rule. */
468
+ function describeRule({ selector, parent }, classPattern) {
469
+ if (parent.startsWith(KEYFRAMES_AT_RULE$1)) return `the keyframes ${parent.slice(10).trim()}`;
470
+ const name = [...selector.matchAll(classPattern)].at(-1)?.[1];
471
+ return name === void 0 ? `the global rule ${selector}` : `the class ${name}`;
472
+ }
473
+ /**
474
+ * Asks the browser about each declaration of `texts`, rules that an engine wrote, and returns a message
475
+ * for each one that it does not support. Only the last declaration of a property in a rule is asked
476
+ * about. A property that starts with a hyphen is left out: a custom property takes any value, and one
477
+ * with a vendor prefix is written for another browser, as is a value that starts with a vendor prefix
478
+ * (`-moz-available`, `-webkit-linear-gradient(...)`). For a value with `var(`, which is valid until it
479
+ * is used, the browser is asked whether it knows the property at all. `!important` is not part of the
480
+ * question. At-rules with descriptors (`@property`, `@font-face`) are not asked about.
481
+ */
482
+ function findUnsupportedDeclarations(texts, prefix, supports) {
483
+ const classPattern = new RegExp(String.raw`\.(${prefix}-[a-z0-9_-]*)`, "g");
484
+ const messages = [];
485
+ for (const text of texts) for (const rule of readStyleRules(text)) addRuleMessages(rule, classPattern, supports, messages);
486
+ return messages;
487
+ }
488
+ /** Adds to `messages` a message for each last declaration of `rule` that the browser does not support (see `findUnsupportedDeclarations`). */
489
+ function addRuleMessages(rule, classPattern, supports, messages) {
490
+ for (const [name, value] of readLastDeclarations(rule.body)) {
491
+ const plain = stripImportant(value);
492
+ if (name.startsWith("-") || VENDOR_VALUE.test(plain)) continue;
493
+ if (supports(name, plain.includes("var(") ? "inherit" : plain)) continue;
494
+ const owner = describeRule(rule, classPattern);
495
+ messages.push(`${owner} declares ${name}:${value}, which this browser does not support`);
496
+ }
497
+ }
265
498
  // src/devChecks.ts
266
499
  /** How long a check waits after the last insertion, in milliseconds: rules arrive in bursts while a page renders. */
267
500
  const CHECK_DELAY = 250;
@@ -274,26 +507,39 @@ function isDevelopment() {
274
507
  }
275
508
  }
276
509
  /**
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).
510
+ * The function that asks for a check of `page` (the document by default): it runs `findMissingStyles` once, after the calls
511
+ * have stopped for a short while, and warns once for each problem (never again for the same one). The
512
+ * rules given to it are asked about in the same run: a declaration that the browser does not support
513
+ * (`findUnsupportedDeclarations`) is warned about once for each message. Where the browser cannot be
514
+ * asked (no `CSS.supports`, or jsdom) the rules are not kept.
279
515
  */
280
- function createDevChecker(prefix, delay = CHECK_DELAY) {
516
+ function createDevChecker(prefix, delay = CHECK_DELAY, page = document) {
281
517
  const warned = /* @__PURE__ */ new Set();
518
+ const supports = findBrowserSupports();
519
+ const written = [];
282
520
  let timer;
521
+ const warn = (key, message) => {
522
+ if (warned.has(key)) return;
523
+ warned.add(key);
524
+ console.warn(`[${prefix}] ${message}`);
525
+ };
283
526
  const run = () => {
284
527
  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
- }
528
+ for (const problem of findMissingStyles(page, { prefix })) warn(problem.key, problem.message);
529
+ if (!supports) return;
530
+ for (const message of findUnsupportedDeclarations(written.splice(0), prefix, supports)) warn(`declaration:${message}`, message);
290
531
  };
291
- return () => {
532
+ return (rules) => {
533
+ if (supports && rules) written.push(...rules);
292
534
  timer ??= setTimeout(run, delay);
293
535
  };
294
536
  }
295
537
  // src/fingerprint.ts
296
- /** The short code each option has in the stamp, in the order they are written. */
538
+ /**
539
+ * The short code each option has in the stamp, in the order they are written. An option added later has
540
+ * a third entry, the value it is left out with: the stamp of a page that does not turn it on stays the
541
+ * same text as before, and a stamp that lacks it reads as that value.
542
+ */
297
543
  const CODES = [
298
544
  ["p", "prefix"],
299
545
  ["x", "suffix"],
@@ -303,6 +549,11 @@ const CODES = [
303
549
  ["b", "hasBaseClass"],
304
550
  ["s", "hasScope"],
305
551
  ["f", "hasColorFallbacks"],
552
+ [
553
+ "v",
554
+ "hasValueRepair",
555
+ "0"
556
+ ],
306
557
  ["t", "tokens"]
307
558
  ];
308
559
  /** The text of one option in the stamp: a flag is 1 or 0, a string is encoded. */
@@ -312,7 +563,10 @@ function toStampValue(value) {
312
563
  }
313
564
  /** The stamp of `options`, short enough for an attribute: `p=umber;x=;l=1;y=1;...`. */
314
565
  function createFingerprint(options) {
315
- return CODES.map(([code, name]) => `${code}=${toStampValue(options[name])}`).join(";");
566
+ return CODES.flatMap(([code, name, omitted]) => {
567
+ const value = toStampValue(options[name]);
568
+ return value === omitted ? [] : [`${code}=${value}`];
569
+ }).join(";");
316
570
  }
317
571
  /** The values of a stamp, by short code. */
318
572
  function parseFingerprint(stamp) {
@@ -325,215 +579,142 @@ function parseFingerprint(stamp) {
325
579
  function describeFingerprintDifferences(server, browser) {
326
580
  const theirs = parseFingerprint(server);
327
581
  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))})`);
582
+ const differences = CODES.filter(([code, , omitted]) => (theirs.get(code) ?? omitted) !== (ours.get(code) ?? omitted)).map(([code, name, omitted]) => `${name} (server: ${decodeURIComponent(theirs.get(code) ?? omitted ?? "")}, browser: ${decodeURIComponent(ours.get(code) ?? omitted)})`);
329
583
  if (differences.length === 0) return "";
330
584
  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
585
  }
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;
586
+ // src/calc.ts
587
+ const LENGTH_PATTERN$1 = /^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z]+|%)$/i;
588
+ const CALC_PREFIX = "calc(";
589
+ /** `value` rounded so that float noise (0.1 * 3) does not reach the CSS; `-0` is `0`. */
590
+ function tidy(value) {
591
+ return Math.round(value * 1e6) / 1e6 + 0;
336
592
  }
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;
593
+ /** Throws unless `value` is a finite number; `what` names the argument in the message. */
594
+ function assertFinite(name, what, value) {
595
+ if (typeof value !== "number") throw new TypeError(`${name}(): ${what} must be a number, got ${typeof value}`);
596
+ if (!Number.isFinite(value)) throw new RangeError(`${name}(): ${what} must be finite, got ${value}`);
342
597
  }
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;
598
+ /** Throws unless `value` is a string or a finite number. */
599
+ function assertOperand(name, value) {
600
+ if (isAlphaColor(value)) throw new TypeError(`${name}(): an alpha() color is not a length or a number, so it cannot be an operand`);
601
+ if (typeof value !== "string") assertFinite(name, "a value", value);
348
602
  }
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);
603
+ /** The inside of `value` when the whole of it is one `calc(...)`, else undefined. */
604
+ function unwrapCalc(value) {
605
+ if (!value.startsWith(CALC_PREFIX) || !value.endsWith(")")) return void 0;
606
+ let depth = 0;
607
+ for (let index = 4; index < value.length; index += 1) {
608
+ if (value[index] === "(") depth += 1;
609
+ if (value[index] === ")") depth -= 1;
610
+ if (depth === 0 && index < value.length - 1) return void 0;
364
611
  }
365
- return names;
612
+ return value.slice(5, -1);
366
613
  }
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
- };
614
+ /** `operand` as a part of a calc expression: a number is a length in px, an inner calc gets parentheses. */
615
+ function toTerm(operand) {
616
+ if (typeof operand === "number") return `${tidy(operand)}px`;
617
+ const inner = unwrapCalc(operand);
618
+ return inner === void 0 ? operand : `(${inner})`;
377
619
  }
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;
620
+ /** `operand` as a literal length (a number is in px), or undefined when it is not one. */
621
+ function toLength(operand) {
622
+ if (typeof operand === "number") return {
623
+ value: operand,
624
+ unit: "px"
625
+ };
626
+ const match = LENGTH_PATTERN$1.exec(operand.trim());
627
+ return match ? {
628
+ value: Number.parseFloat(match[1]),
629
+ unit: match[2].toLowerCase()
630
+ } : void 0;
382
631
  }
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);
632
+ const OPERATIONS = {
633
+ "*": (value, factor) => value * factor,
634
+ "/": (value, factor) => value / factor
635
+ };
636
+ /** `value` (a stand-in of `keyframes` as its path) multiplied or divided by `factor`, as a number, a literal length or a calc. */
637
+ function scale(name, given, factor, operator) {
638
+ const value = readStandIn(given);
639
+ assertOperand(name, value);
640
+ assertFinite(name, operator === "*" ? "the factor" : "the divisor", factor);
641
+ if (factor === 0) {
642
+ if (operator === "/") throw new RangeError(`${name}(): the divisor must not be 0`);
643
+ return 0;
392
644
  }
393
- return names;
645
+ if (factor === 1) return value;
646
+ if (typeof value === "number") return tidy(OPERATIONS[operator](value, factor));
647
+ const length = toLength(value);
648
+ return length === void 0 ? `${CALC_PREFIX}${toTerm(value)} ${operator} ${factor})` : `${tidy(OPERATIONS[operator](length.value, factor))}${length.unit}`;
394
649
  }
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(":")));
650
+ /** The sum of `terms` when they are all numbers, else undefined. */
651
+ function sumNumbers(terms) {
652
+ let total = 0;
653
+ for (const { operand, sign } of terms) {
654
+ if (typeof operand !== "number") return void 0;
655
+ total += sign * operand;
401
656
  }
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;
657
+ return tidy(total);
410
658
  }
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;
659
+ /** The sum of `terms` when they are literal lengths of one unit, else undefined. */
660
+ function sumLengths(terms) {
661
+ const lengths = terms.map(({ operand }) => toLength(operand));
662
+ const unit = lengths[0]?.unit;
663
+ let total = 0;
664
+ for (const [index, length] of lengths.entries()) {
665
+ if (length === void 0 || length.unit !== unit) return void 0;
666
+ total += terms[index].sign * length.value;
426
667
  }
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);
668
+ return `${tidy(total)}${unit}`;
434
669
  }
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
- });
670
+ /** `terms` as one calc: the first term, then each with its sign. */
671
+ function toCalc(terms) {
672
+ const body = terms.map(({ operand, sign }, index) => {
673
+ const term = toTerm(operand);
674
+ if (index === 0) return term;
675
+ return `${sign === 1 ? "+" : "-"} ${term}`;
676
+ }).join(" ");
677
+ return `${CALC_PREFIX}${body})`;
444
678
  }
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));
679
+ /** `terms` added and subtracted, as a number, a literal length or one calc. */
680
+ function sum(terms) {
681
+ if (terms.length === 1) return terms[0].operand;
682
+ return sumNumbers(terms) ?? sumLengths(terms) ?? toCalc(terms);
449
683
  }
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;
684
+ /** The terms of `values` with `sign`, without the zeros that change nothing; each is checked, a stand-in as its path. */
685
+ function toTerms(name, given, sign) {
686
+ const values = given.map((value) => readStandIn(value));
687
+ for (const value of values) assertOperand(name, value);
688
+ return values.filter((value) => value !== 0).map((operand) => ({
689
+ operand,
690
+ sign
691
+ }));
478
692
  }
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);
693
+ function multiply(value, factor) {
694
+ return scale("multiply", value, factor, "*");
504
695
  }
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;
696
+ function divide(value, divisor) {
697
+ return scale("divide", value, divisor, "/");
508
698
  }
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];
699
+ function add(...values) {
700
+ const terms = toTerms("add", values, 1);
701
+ return terms.length === 0 ? 0 : sum(terms);
512
702
  }
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;
703
+ function subtract(value, ...values) {
704
+ const first = readStandIn(value);
705
+ assertOperand("subtract", first);
706
+ return sum([{
707
+ operand: first,
708
+ sign: 1
709
+ }, ...toTerms("subtract", values, -1)]);
710
+ }
711
+ function negate(value) {
712
+ return scale("negate", value, -1, "*");
713
+ }
714
+ // src/codeAt.ts
715
+ /** The code point at `index` of `text`; NaN past the end, so that every comparison with a code is false. */
716
+ function codeAt(text, index) {
717
+ return text.codePointAt(index) ?? NaN;
537
718
  }
538
719
  // src/scope.ts
539
720
  /** The scoping of a cache that gave none: the default prefix, with `@scope`. */
@@ -634,6 +815,13 @@ const UNITLESS = /* @__PURE__ */ new Set([
634
815
  "strokeOpacity",
635
816
  "strokeWidth"
636
817
  ]);
818
+ /** The properties whose value is a time: a number is in milliseconds. */
819
+ const TIMES = /* @__PURE__ */ new Set([
820
+ "animationDelay",
821
+ "animationDuration",
822
+ "transitionDelay",
823
+ "transitionDuration"
824
+ ]);
637
825
  const propertyNames = /* @__PURE__ */ new Map();
638
826
  /** Whether `value` is a nested style object, not an array, an `alpha()` result or a plain value. */
639
827
  function isStyleObject(value) {
@@ -649,9 +837,78 @@ function toPropertyName(key) {
649
837
  }
650
838
  return name;
651
839
  }
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);
840
+ const REFERENCE = "var(";
841
+ const HEX_PAIR = /^[0-9a-f]{2}$/i;
842
+ /** The units that make a reference a time: `var(--x)ms` is `calc(var(--x) * 1ms)`. */
843
+ const TIME_UNITS = ["ms", "s"];
844
+ /** Whether the character code `code` can be part of an identifier: a letter, a digit, `-`, `_` or any non-ASCII character. NaN (past either end of the text) cannot. */
845
+ function isNameCode$2(code) {
846
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 45 || code === 95 || code >= 128;
847
+ }
848
+ /** Whether the character at `at` is a minus that stands alone before a reference: at the start of the value, or after a space, a comma or `(`. */
849
+ function isLoneMinus(value, at) {
850
+ return value[at] === "-" && (at === 0 || " ,(".includes(value[at - 1]));
851
+ }
852
+ /** The index just after the parenthesis that closes the one before `start`, or -1 when none does. */
853
+ function findClose(value, start) {
854
+ let depth = 1;
855
+ for (let index = start; index < value.length; index++) if (value[index] === "(") depth++;
856
+ else if (value[index] === ")" && --depth === 0) return index + 1;
857
+ return -1;
858
+ }
859
+ /**
860
+ * `reference` with what follows it at `at` taken in, and where the rest of the value starts: two hex
861
+ * digits of alpha are what `alpha()` writes for that opacity, a time unit makes a `calc()` of a time.
862
+ * The digits or the unit must end there: `var(--x)1Fa` is left alone.
863
+ */
864
+ function repairSuffix(value, at, reference) {
865
+ const pair = value.slice(at, at + 2);
866
+ if (HEX_PAIR.test(pair) && !isNameCode$2(codeAt(value, at + 2))) return [String(alpha(reference, Number.parseInt(pair, 16) / 255)), at + 2];
867
+ for (const unit of TIME_UNITS) {
868
+ const end = at + unit.length;
869
+ if (value.slice(at, end).toLowerCase() === unit && !isNameCode$2(codeAt(value, end))) return [`calc(${reference} * 1${unit})`, end];
870
+ }
871
+ return [reference, at];
872
+ }
873
+ /**
874
+ * `value` with the string forms of token maths that are never valid CSS rewritten: a reference followed
875
+ * by two hex digits (`var(--x)1F`) as `alpha()` writes it, a minus before a reference (`-var(--x)`) as
876
+ * `negate()` writes it, and a reference followed by `ms` or `s` as a `calc()` of a time. A reference may
877
+ * have a fallback, which is repaired too. Any other text is kept as it is.
878
+ */
879
+ function repairValue(value) {
880
+ let repaired = "";
881
+ let from = 0;
882
+ let index = value.indexOf(REFERENCE);
883
+ while (index !== -1) {
884
+ const hasMinus = isLoneMinus(value, index - 1);
885
+ if (isNameCode$2(codeAt(value, index - 1)) && !hasMinus) {
886
+ index = value.indexOf(REFERENCE, index + 4);
887
+ continue;
888
+ }
889
+ const close = findClose(value, index + 4);
890
+ if (close === -1) break;
891
+ const inner = value.slice(index + 4, close - 1);
892
+ const [text, end] = repairSuffix(value, close, `${REFERENCE}${repairValue(inner)})`);
893
+ const start = hasMinus ? index - 1 : index;
894
+ repaired += value.slice(from, start) + (hasMinus ? String(negate(text)) : text);
895
+ from = end;
896
+ index = value.indexOf(REFERENCE, end);
897
+ }
898
+ return repaired + value.slice(from);
899
+ }
900
+ /**
901
+ * The CSS text of one declared value: a number is a time in `ms` (0 too: a time needs its unit), or a
902
+ * length in `px` unless it is 0 or the property takes a plain number. With `hasValueRepair` a string
903
+ * that holds a reference, outside a custom property, has its string forms of token maths rewritten.
904
+ */
905
+ function toValue(key, value, hasValueRepair) {
906
+ if (typeof value === "string") {
907
+ if (!hasValueRepair || !value.includes(REFERENCE) || key.startsWith("--")) return value;
908
+ return repairValue(value);
909
+ }
910
+ if (TIMES.has(key)) return `${value}ms`;
911
+ return value !== 0 && !key.startsWith("--") && !UNITLESS.has(key) ? `${value}px` : String(value);
655
912
  }
656
913
  /** Splits `selector` on the commas that are not inside brackets or parentheses. */
657
914
  function splitSelectors(selector) {
@@ -737,14 +994,14 @@ function compileNested(selector, key, value, context) {
737
994
  return compileStyle(selector, value, context).map((rule) => `${key}{${rule}}`);
738
995
  }
739
996
  /** 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};`;
997
+ function toItemDeclarations(key, name, item, context) {
998
+ if (!isAlphaColor(item)) return `${name}:${toValue(key, item, context.hasValueRepair)};`;
999
+ return `${context.hasColorFallbacks && !key.startsWith("--") ? `${name}:${item.fallback};` : ""}${name}:${item.value};`;
743
1000
  }
744
1001
  /** The declarations of one property: one for a value, one for each item of a fallback list. */
745
- function toDeclarations(key, value, hasColorFallbacks) {
1002
+ function toDeclarations(key, value, context) {
746
1003
  const name = toPropertyName(key);
747
- return (Array.isArray(value) ? value : [value]).map((item) => toItemDeclarations(key, name, item, hasColorFallbacks)).join("");
1004
+ return (Array.isArray(value) ? value : [value]).map((item) => toItemDeclarations(key, name, item, context)).join("");
748
1005
  }
749
1006
  /** The rules of `style` for `selector`, with the options of `context`. */
750
1007
  function compileStyle(selector, style, context) {
@@ -753,18 +1010,20 @@ function compileStyle(selector, style, context) {
753
1010
  for (const [key, value] of Object.entries(style)) {
754
1011
  if (key === "label" || value === null || value === void 0 || value === false) continue;
755
1012
  if (isStyleObject(value)) nested.push(...compileNested(selector, key, value, context));
756
- else declarations += toDeclarations(key, value, context.hasColorFallbacks);
1013
+ else declarations += toDeclarations(key, value, context);
757
1014
  }
758
1015
  return declarations ? [`${selector}{${declarations}}`, ...nested] : nested;
759
1016
  }
760
1017
  /**
761
1018
  * The flat CSS rules of `style` for `selector`; without `hasColorFallbacks` an `alpha()` result is
762
1019
  * written as its mix alone. A `when()` or `whenScheme()` key becomes a scoped rule, written as
763
- * `scoping` says.
1020
+ * `scoping` says. With `hasValueRepair` the string forms of token maths that are never valid CSS
1021
+ * (`var(--x)1F`, `-var(--x)`, `var(--x)ms`) are rewritten in each value.
764
1022
  */
765
- function compileRules(selector, style, hasColorFallbacks = true, scoping = DEFAULT_SCOPING) {
1023
+ function compileRules(selector, style, hasColorFallbacks = true, scoping = DEFAULT_SCOPING, hasValueRepair = false) {
766
1024
  return compileStyle(selector, style, {
767
1025
  hasColorFallbacks,
1026
+ hasValueRepair,
768
1027
  scoping
769
1028
  });
770
1029
  }
@@ -773,13 +1032,789 @@ function readLabel(style) {
773
1032
  const { label } = style;
774
1033
  return typeof label === "string" ? label : "";
775
1034
  }
1035
+ // src/sheetEntry.ts
1036
+ const BRAND$1 = Symbol.for("umber-style.sheet-entry");
1037
+ const SOURCE = Symbol.for("umber-style.sheet-entry-source");
1038
+ const ENTRY_KEY_PREFIX = "--umber-entry-";
1039
+ /**
1040
+ * Makes the entry of a class name: a frozen object that `isSheetEntry` knows and that prints as the
1041
+ * class name. Its one enumerable key is a custom property named after the class, with the value `null`,
1042
+ * so that a framework that merges the style objects of an array (Vue does) keeps every entry, and
1043
+ * `flattenStyle` finds them by the key. Both frameworks skip a `null` style value on a plain element, on
1044
+ * the client and on the server, so an entry given to a plain element renders no style attribute. With a
1045
+ * `source` (a cache made it) the class name is read through it, so that the rule is written when the entry
1046
+ * is used, not when it is made; without one the entry is just the name.
1047
+ */
1048
+ function createSheetEntry(className, source) {
1049
+ const entry = {
1050
+ [`${ENTRY_KEY_PREFIX}${className}`]: null,
1051
+ [BRAND$1]: true
1052
+ };
1053
+ const read = () => source?.use("components") ?? className;
1054
+ Object.defineProperties(entry, {
1055
+ className: { get: read },
1056
+ toString: { value: read },
1057
+ ...source ? { [SOURCE]: { value: source } } : {}
1058
+ });
1059
+ return Object.freeze(entry);
1060
+ }
1061
+ /** Whether `value` was made by `createSheetEntry`: a class name is a plain string, a style object has no brand. */
1062
+ function isSheetEntry(value) {
1063
+ return typeof value === "object" && value !== null && BRAND$1 in value;
1064
+ }
1065
+ /** What a cache gave `entry` to make its classes, or undefined for an entry that is only a name. */
1066
+ function readEntrySource(entry) {
1067
+ return entry[SOURCE];
1068
+ }
1069
+ /** The cache that made the first entry among `values` that a cache made, or undefined when there is none. */
1070
+ function findEntryCache(values) {
1071
+ for (const value of values) {
1072
+ const source = isSheetEntry(value) ? readEntrySource(value) : void 0;
1073
+ if (source) return source.cache;
1074
+ }
1075
+ }
1076
+ /**
1077
+ * The style of `value` when it is a sheet entry, else `value` as it is: for a place that takes a style
1078
+ * object and so also an entry. Throws a `TypeError`, that names `caller`, for an entry that is only a class
1079
+ * name (one that no cache made), whose style is not known.
1080
+ */
1081
+ function readEntryStyle(value, caller) {
1082
+ if (!isSheetEntry(value)) return value;
1083
+ const source = readEntrySource(value);
1084
+ if (!source) throw new TypeError(`${caller}(): the sheet entry "${value.className}" is only a class name, so its style cannot be merged.`);
1085
+ return source.style;
1086
+ }
1087
+ /**
1088
+ * What a `style` prop holds, as a flat list in order, for the cache to merge into one class: sheet
1089
+ * entries and plain style objects, with arrays flattened and what is empty dropped. An object in which a
1090
+ * framework merged entries and plain keys (Vue does) is split back into its entries, then the rest; an
1091
+ * entry is looked up by its class name with `findEntry` (a cache's `findEntry`), else it is only the name.
1092
+ * A string is an error: a text style cannot be merged into a class.
1093
+ */
1094
+ function flattenStyle(style, findEntry) {
1095
+ const flat = [];
1096
+ const visit = (value) => {
1097
+ if (Array.isArray(value)) value.forEach(visit);
1098
+ 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.");
1099
+ else if (isSheetEntry(value) && readEntrySource(value)) flat.push(value);
1100
+ else if (typeof value === "object" && value !== null) {
1101
+ const rest = {};
1102
+ for (const [key, item] of Object.entries(value)) if (key.startsWith(ENTRY_KEY_PREFIX)) {
1103
+ const name = key.slice(14);
1104
+ flat.push(findEntry?.(name) ?? createSheetEntry(name));
1105
+ } else rest[key] = item;
1106
+ if (Object.keys(rest).length > 0) flat.push(rest);
1107
+ }
1108
+ };
1109
+ visit(style);
1110
+ return flat;
1111
+ }
1112
+ // src/templateStyle.ts
1113
+ /** The character that stands for an interpolation in the joined text of a template: CSS never holds it. */
1114
+ const HOLE = "\0";
1115
+ /**
1116
+ * After an interpolation that starts a statement: a newline before anything but spaces and a line
1117
+ * comment, then a character that does not go on with a selector or a property name. The interpolation is
1118
+ * then a statement of its own, as `${mixin}` alone on its line is.
1119
+ */
1120
+ const OWN_LINE = /[^\S\n]*(?:\/\/.*)?\n\s*[^\s{,:>+~]/y;
1121
+ const templates = /* @__PURE__ */ new WeakMap();
1122
+ /** Throws the `TypeError` of a template that cannot be read: `problem`, with the line and the text around `at`. */
1123
+ function fail(text, at, problem) {
1124
+ const line = text.slice(0, at).split("\n").length;
1125
+ const around = text.slice(Math.max(0, at - 30), at + 10).replaceAll(HOLE, `\${}`).replace(/\s+/g, " ").trim();
1126
+ throw new TypeError(`parseStyleTemplate(): ${problem} at line ${line}: "${around}"`);
1127
+ }
1128
+ /** The style key of a CSS property name: camelCase (`-webkit-x` is `WebkitX`, written back as it was); a custom property as it is. */
1129
+ function toKey(name) {
1130
+ if (name.startsWith("--")) return name;
1131
+ return name.toLowerCase().replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
1132
+ }
1133
+ /** `pieces` as one text: adjacent static text joined, trimmed at both ends; a string when no interpolation is left. */
1134
+ function join(pieces) {
1135
+ const joined = [];
1136
+ let text = "";
1137
+ for (const piece of pieces) if (typeof piece === "string") text += piece;
1138
+ else {
1139
+ joined.push(text, piece);
1140
+ text = "";
1141
+ }
1142
+ joined.push(text);
1143
+ joined[0] = joined[0].trimStart();
1144
+ joined[joined.length - 1] = joined.at(-1).trimEnd();
1145
+ return joined.length === 1 ? joined[0] : joined.filter((piece) => piece !== "");
1146
+ }
1147
+ /** Ends the text not yet in the pieces of the statement: it becomes a piece unless it is only whitespace at the start. */
1148
+ function flush(state) {
1149
+ if (state.pieces.length > 0 || state.chunk.trim()) state.pieces.push(state.chunk);
1150
+ state.chunk = "";
1151
+ }
1152
+ /** Adds a space to the statement, unless it already ends with one. */
1153
+ function space(state) {
1154
+ if (!state.chunk.endsWith(" ")) state.chunk += " ";
1155
+ }
1156
+ /** Counts the holes from `from` to `to` as read: they are in a comment, and stand for nothing. */
1157
+ function skip(state, from, to) {
1158
+ state.hole += state.text.slice(from, to).split(HOLE).length - 1;
1159
+ }
1160
+ /** Adds the next interpolation to the pieces of the statement. */
1161
+ function addHole(state) {
1162
+ flush(state);
1163
+ state.pieces.push(state.hole++);
1164
+ }
1165
+ /** Adds the declaration that was read to the block: the pieces before its first ':' are its key, the rest its value. */
1166
+ function endDeclaration(state, at) {
1167
+ const key = join(state.pieces.slice(0, state.split));
1168
+ if (key === "") fail(state.text, at, "a declaration without a property");
1169
+ state.body.push({
1170
+ key: typeof key === "string" ? toKey(key) : key,
1171
+ value: join(state.pieces.slice(state.split + 1))
1172
+ });
1173
+ }
1174
+ /** Adds the interpolations that were read without a ':' to the block, each a statement of its own; any other text is a declaration without one. */
1175
+ function endInterpolations(state, at) {
1176
+ for (const piece of state.pieces) if (typeof piece === "number") state.body.push(piece);
1177
+ else if (piece.trim()) fail(state.text, at, "a declaration without \":\"");
1178
+ }
1179
+ /** Ends the statement being read at `at`, and starts the next one. */
1180
+ function end(state, at) {
1181
+ flush(state);
1182
+ if (state.split >= 0) endDeclaration(state, at);
1183
+ else endInterpolations(state, at);
1184
+ state.pieces = [];
1185
+ state.split = -1;
1186
+ }
1187
+ /** Reads the interpolation at `index`; one that starts a statement and stands on its own line ends it. Returns the index after it. */
1188
+ function readHole(state, index) {
1189
+ addHole(state);
1190
+ if (state.pieces.length === 1) {
1191
+ OWN_LINE.lastIndex = index + 1;
1192
+ if (OWN_LINE.test(state.text)) end(state, index);
1193
+ }
1194
+ return index + 1;
1195
+ }
1196
+ /** Copies the character at `index` into the statement, and the next one when it is an escape: `HOLE` and past the end are not above it, so a hole is not kept. Returns the index after them. */
1197
+ function readEscaped(state, index) {
1198
+ const { text } = state;
1199
+ const length = text[index] === "\\" && text[index + 1] > HOLE ? 2 : 1;
1200
+ state.chunk += text.slice(index, index + length);
1201
+ return index + length;
1202
+ }
1203
+ /** Reads the string that starts at `index`, with the interpolations in it. Returns the index after its closing quote. */
1204
+ function readString(state, index) {
1205
+ const { text } = state;
1206
+ const quote = text[index];
1207
+ state.chunk += quote;
1208
+ let at = index + 1;
1209
+ while (text[at] !== quote) {
1210
+ if (at >= text.length) fail(text, index, "an unclosed string");
1211
+ if (text[at] === HOLE) {
1212
+ addHole(state);
1213
+ at++;
1214
+ } else at = readEscaped(state, at);
1215
+ }
1216
+ state.chunk += quote;
1217
+ return at + 1;
1218
+ }
1219
+ /** Reads the comment that starts at `index`: it is a space. Returns the index after its `*` and `/`. */
1220
+ function readComment$1(state, index) {
1221
+ const close = state.text.indexOf("*/", index + 2);
1222
+ if (close < 0) fail(state.text, index, "an unclosed comment");
1223
+ skip(state, index, close);
1224
+ space(state);
1225
+ return close + 2;
1226
+ }
1227
+ /** Reads the line comment that starts at `index`. Returns the index of the newline that ends it, or the end of the text. */
1228
+ function readLineComment(state, index) {
1229
+ const stop = state.text.indexOf("\n", index);
1230
+ const close = stop < 0 ? state.text.length : stop;
1231
+ skip(state, index, close);
1232
+ return close;
1233
+ }
1234
+ /** Reads the `/` at `index`: the start of a comment, or a character of the statement. Returns the index after what it read. */
1235
+ function readSlash(state, index) {
1236
+ const next = state.text[index + 1];
1237
+ if (next === "*") return readComment$1(state, index);
1238
+ if (next === "/" && state.depth === 0) return readLineComment(state, index);
1239
+ state.chunk += "/";
1240
+ return index + 1;
1241
+ }
1242
+ /** Reads `char` at `index` inside parentheses, or the `(` that opens them: it is a character of the statement. */
1243
+ function readParenthesized(state, char, index) {
1244
+ if (char === "(" && state.depth++ === 0) state.parenAt = index;
1245
+ else if (char === ")") state.depth--;
1246
+ state.chunk += char;
1247
+ }
1248
+ /** Reads the first ':' of a statement: what is before it is the key of a declaration. */
1249
+ function readColon(state) {
1250
+ flush(state);
1251
+ state.split = state.pieces.length;
1252
+ state.pieces.push(":");
1253
+ }
1254
+ /** Reads the `{` at `index`: the statement read so far is the prelude of a block, which is open until its `}`. */
1255
+ function openBlock$1(state, index) {
1256
+ flush(state);
1257
+ const prelude = join(state.pieces);
1258
+ if (prelude === "") fail(state.text, index, "a block without a selector");
1259
+ const block = {
1260
+ prelude,
1261
+ body: []
1262
+ };
1263
+ state.body.push(block);
1264
+ state.open.push([state.body, index]);
1265
+ state.body = block.body;
1266
+ state.pieces = [];
1267
+ state.split = -1;
1268
+ }
1269
+ /** Reads the `}` at `index`: it ends the statement being read and the innermost open block. */
1270
+ function closeBlock$1(state, index) {
1271
+ end(state, index);
1272
+ const parent = state.open.pop();
1273
+ if (!parent) fail(state.text, index, "a \"}\" without a \"{\"");
1274
+ state.body = parent[0];
1275
+ }
1276
+ /** Reads `char` at `index`, outside strings, comments and parentheses. */
1277
+ function readStatementChar(state, char, index) {
1278
+ switch (char) {
1279
+ case ":":
1280
+ if (state.split < 0) readColon(state);
1281
+ else state.chunk += char;
1282
+ break;
1283
+ case ";":
1284
+ end(state, index);
1285
+ break;
1286
+ case "{":
1287
+ openBlock$1(state, index);
1288
+ break;
1289
+ case "}":
1290
+ closeBlock$1(state, index);
1291
+ break;
1292
+ default: state.chunk += char;
1293
+ }
1294
+ }
1295
+ /** Reads `char` at `index`, which starts nothing longer: whitespace, a character in parentheses, or one of a statement. */
1296
+ function readChar(state, char, index) {
1297
+ if (char <= " ") space(state);
1298
+ else if (state.depth > 0 || char === "(") readParenthesized(state, char, index);
1299
+ else readStatementChar(state, char, index);
1300
+ }
1301
+ /** Reads what starts at `index`: an interpolation, a string, an escape, a comment, or one character. Returns the index after it. */
1302
+ function readNext(state, index) {
1303
+ const char = state.text[index];
1304
+ switch (char) {
1305
+ case HOLE: return readHole(state, index);
1306
+ case "\"":
1307
+ case "'": return readString(state, index);
1308
+ case "\\": return readEscaped(state, index);
1309
+ case "/": return readSlash(state, index);
1310
+ default:
1311
+ readChar(state, char, index);
1312
+ return index + 1;
1313
+ }
1314
+ }
1315
+ /**
1316
+ * The statements of `text`, a template's strings joined with `HOLE`, in one pass. Outside strings and
1317
+ * comments a run of whitespace is one space; a comment is a space; the holes in a comment are skipped.
1318
+ */
1319
+ function parse(text) {
1320
+ const root = [];
1321
+ const state = {
1322
+ text,
1323
+ open: [],
1324
+ body: root,
1325
+ pieces: [],
1326
+ chunk: "",
1327
+ split: -1,
1328
+ hole: 0,
1329
+ depth: 0,
1330
+ parenAt: 0
1331
+ };
1332
+ let index = 0;
1333
+ while (index < text.length) index = readNext(state, index);
1334
+ if (state.depth > 0) fail(text, state.parenAt, "an unclosed \"(\"");
1335
+ end(state, text.length);
1336
+ const unclosed = state.open.pop();
1337
+ if (unclosed) fail(text, unclosed[1], "an unclosed block");
1338
+ return root;
1339
+ }
1340
+ /** Whether `value` is a function of the props: not one that prints as text of its own (a stand-in for the theme, a component that is a selector). */
1341
+ function isCallable(value) {
1342
+ return typeof value === "function" && value.toString === Function.prototype.toString;
1343
+ }
1344
+ /** Whether `value`, or an item of it, is a function of the props. */
1345
+ function isDynamic(value) {
1346
+ return isCallable(value) || Array.isArray(value) && value.some(isDynamic);
1347
+ }
1348
+ /** `value` with each function called with `props`, until it is not a function. */
1349
+ function resolve(value, props) {
1350
+ let resolved = value;
1351
+ while (isCallable(resolved)) resolved = resolved(props);
1352
+ return resolved;
1353
+ }
1354
+ /** Whether `value` is a plain object, not one with a text of its own (a sheet entry, an `alpha()` result). */
1355
+ function isPlainObject$2(value) {
1356
+ return typeof value === "object" && value !== null && value.toString === Object.prototype.toString;
1357
+ }
1358
+ /** An interpolation as text in a value, a selector or a property name. */
1359
+ function toText$1(value, props) {
1360
+ const resolved = resolve(value, props);
1361
+ if (Array.isArray(resolved)) return resolved.map((item) => toText$1(item, props)).join("");
1362
+ if (resolved === null || resolved === void 0 || typeof resolved === "boolean") return "";
1363
+ if (isPlainObject$2(resolved)) throw new TypeError("parseStyleTemplate(): a style object can stand only between declarations, not in a value, a selector or a property name.");
1364
+ return String(resolved);
1365
+ }
1366
+ /** `text` with its interpolations filled in, trimmed. */
1367
+ function fill(text, values, props) {
1368
+ if (typeof text === "string") return text;
1369
+ let filled = "";
1370
+ for (const piece of text) filled += typeof piece === "string" ? piece : toText$1(values[piece], props);
1371
+ return filled.trim();
1372
+ }
1373
+ /** A declared value: an `alpha()` result that is the whole value is kept, so that its fallback is written; anything else is text. */
1374
+ function fillValue(text, values, props) {
1375
+ if (typeof text === "string" || text.length > 1) return fill(text, values, props);
1376
+ const value = resolve(values[text[0]], props);
1377
+ return isAlphaColor(value) ? value : toText$1(value, props).trim();
1378
+ }
1379
+ /** Whether `value` is a nested style, not a declared value. */
1380
+ function isNested(value) {
1381
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !isAlphaColor(value);
1382
+ }
1383
+ /**
1384
+ * Sets `key` of `style` to `value`, at the end: a nested style is merged into the one before it; a value
1385
+ * declared again is added to the one before it as a fallback list, as CSS writes both.
1386
+ */
1387
+ function put(style, key, value) {
1388
+ const earlier = style[key];
1389
+ delete style[key];
1390
+ if (isNested(value)) style[key] = isNested(earlier) ? mergeStyles([earlier, value]) : value;
1391
+ else if (earlier === void 0 || earlier === null || earlier === false || isNested(earlier)) style[key] = value;
1392
+ else style[key] = [earlier, value].flat();
1393
+ }
1394
+ /** `style` with the interpolation `value` that stands between declarations merged in. */
1395
+ function include(style, value, props) {
1396
+ const resolved = resolve(value, props);
1397
+ if (Array.isArray(resolved)) return resolved.reduce((merged, item) => include(merged, item, props), style);
1398
+ if (resolved === null || resolved === void 0 || typeof resolved === "boolean") return style;
1399
+ if (isSheetEntry(resolved)) {
1400
+ const source = readEntrySource(resolved);
1401
+ if (!source) throw new TypeError(`parseStyleTemplate(): the sheet entry "${resolved.className}" is only a class name, so its style cannot be merged.`);
1402
+ return mergeStyles([style, source.style]);
1403
+ }
1404
+ if (isPlainObject$2(resolved)) return mergeStyles([style, resolved]);
1405
+ return build(parse(String(resolved)), [], props, style);
1406
+ }
1407
+ /** The style of `nodes`, with `values` for the interpolations and `props` for the functions among them, added to `style`. */
1408
+ function build(nodes, values, props, style = {}) {
1409
+ let built = style;
1410
+ for (const node of nodes) if (typeof node === "number") built = include(built, values[node], props);
1411
+ else if ("body" in node) put(built, fill(node.prelude, values, props), build(node.body, values, props));
1412
+ else {
1413
+ const key = typeof node.key === "string" ? node.key : toKey(fill(node.key, values, props));
1414
+ put(built, key, fillValue(node.value, values, props));
1415
+ }
1416
+ return built;
1417
+ }
1418
+ /** Whether `value` is the strings of a tagged template: an array with `raw`, which a call with styles never is. */
1419
+ function isTemplateStrings(value) {
1420
+ return Array.isArray(value) && Object.hasOwn(value, "raw");
1421
+ }
1422
+ /**
1423
+ * The style of a tagged template, `strings` and `values` as a tag is given them: CSS text with
1424
+ * declarations, nested rules (`&:hover { }`, `> p { }`), at-rules (`@media (...) { }`) and comments.
1425
+ * A value is kept as text (`padding: 8px` is `'8px'`); a property is a camelCase key; a property declared
1426
+ * twice in a block is a fallback list. An interpolation in a value, a selector or a property name is
1427
+ * text; one alone between declarations is merged in: a style object, a sheet entry, CSS text, or a list
1428
+ * of them. `null`, `undefined`, `true` and `false` are nothing. When an interpolation is a function, the
1429
+ * result is a function of the props that calls it with them (what it returns is an interpolation too);
1430
+ * else it is the style. The text is split once for each `strings` array. Throws a `TypeError` with the
1431
+ * text around the place for a template that cannot be read.
1432
+ */
1433
+ function parseStyleTemplate(strings, values) {
1434
+ const nodes = templates.get(strings) ?? parse(strings.join(HOLE));
1435
+ templates.set(strings, nodes);
1436
+ return values.some(isDynamic) ? (props) => build(nodes, values, props) : build(nodes, values, void 0);
1437
+ }
1438
+ /**
1439
+ * The steps of an animation from a tagged template: `from { ... } 50% { ... } to { ... }`, read as
1440
+ * `parseStyleTemplate` reads a style. When an interpolation is a function, the result is a function of
1441
+ * the theme, and the function is called with `{ theme }`, as a function in a style is.
1442
+ */
1443
+ function parseKeyframesTemplate(strings, values) {
1444
+ const steps = parseStyleTemplate(strings, values);
1445
+ return typeof steps === "function" ? (theme) => steps({ theme }) : steps;
1446
+ }
1447
+ // src/globalStyles.ts
1448
+ const BRAND = Symbol.for("umber-style.global-styles");
1449
+ /** The at-rules that hold rules (selectors as keys); every other at-rule holds declarations. */
1450
+ const GROUP_AT_RULE = /^@(?:media|supports|container|layer|scope|starting-style|document)(?![\w-])/;
1451
+ /** `value` for the id of a handle: a stand-in as its path, everything else as it is. */
1452
+ function toText(_key, value) {
1453
+ return readStandIn(value);
1454
+ }
1455
+ function globalStyles(first, ...values) {
1456
+ if (isTemplateStrings(first)) {
1457
+ const parsed = parseStyleTemplate(first, values);
1458
+ return globalStyles(typeof parsed === "function" ? (theme) => parsed({ theme }) : parsed);
1459
+ }
1460
+ const styles = first;
1461
+ if (typeof styles === "function") {
1462
+ const hash = hashString(`theme:${JSON.stringify(styles(createStandIn("")), toText)}`);
1463
+ return Object.freeze({
1464
+ [BRAND]: true,
1465
+ id: `global-${hash}`,
1466
+ resolve: (readTheme) => styles(readTheme())
1467
+ });
1468
+ }
1469
+ if (typeof styles !== "object" || styles === null || Array.isArray(styles)) throw new TypeError("globalStyles(): the styles must be an object, or a function that returns one.");
1470
+ return Object.freeze({
1471
+ [BRAND]: true,
1472
+ id: `global-${hashString(JSON.stringify(styles))}`,
1473
+ resolve: () => styles
1474
+ });
1475
+ }
1476
+ /** Whether `value` is a handle that `globalStyles` made. */
1477
+ function isGlobalStyles(value) {
1478
+ return typeof value === "object" && value !== null && BRAND in value;
1479
+ }
1480
+ /** The styles of one item of a `GlobalInput`: a handle resolves itself, a function is called with the theme that `readTheme` gives. */
1481
+ function readGlobalStyles(item, readTheme) {
1482
+ if (isGlobalStyles(item)) return item.resolve(readTheme);
1483
+ return typeof item === "function" ? item(readTheme()) : item;
1484
+ }
1485
+ /** The style of one item under `key` (a sheet entry is read as its style); a `TypeError` for anything that is not a style object. */
1486
+ function readGlobalItem(key, each) {
1487
+ const item = readEntryStyle(each, "globalStyles");
1488
+ if (typeof item !== "object" || item === null || Array.isArray(item)) throw new TypeError(`globalStyles(): "${key}" must hold a style object, or a list of them.`);
1489
+ return item;
1490
+ }
1491
+ /** Adds to `rules` the rules of the style `item` under `key`: an at-rule that holds rules around the rules of its keys, any other key compiled as a class's style is. */
1492
+ function addGlobalItemRules(rules, key, item, hasColorFallbacks, scoping, hasValueRepair) {
1493
+ if (!GROUP_AT_RULE.test(key)) {
1494
+ rules.push(...compileRules(key, item, hasColorFallbacks, scoping, hasValueRepair));
1495
+ return;
1496
+ }
1497
+ const inner = compileGlobalRules(item, hasColorFallbacks, scoping, hasValueRepair);
1498
+ if (inner.length > 0) rules.push(`${key}{${inner.join("")}}`);
1499
+ }
1500
+ /**
1501
+ * The flat CSS rules of global styles, in the order of their keys: a selector's style compiled as a
1502
+ * class's is, an at-rule that holds rules as one rule around the rules of its keys, any other at-rule as
1503
+ * a rule of declarations (one for each item of a list). Throws a `TypeError` for styles that are not an
1504
+ * object, and for a key that holds no style.
1505
+ */
1506
+ function compileGlobalRules(styles, hasColorFallbacks, scoping, hasValueRepair) {
1507
+ if (typeof styles !== "object" || styles === null || Array.isArray(styles)) throw new TypeError("globalStyles(): the styles must be an object, or a function that returns one.");
1508
+ const rules = [];
1509
+ for (const [key, value] of Object.entries(styles)) {
1510
+ if (value === null || value === void 0 || value === false) continue;
1511
+ for (const each of Array.isArray(value) ? value : [value]) addGlobalItemRules(rules, key, readGlobalItem(key, each), hasColorFallbacks, scoping, hasValueRepair);
1512
+ }
1513
+ return rules;
1514
+ }
1515
+ // src/keyframes.ts
1516
+ const DEFAULT_LABEL = "keyframes";
1517
+ const LABEL_PATTERN = /^[A-Za-z_][\w-]*$/;
1518
+ const OFFSET_PATTERN = /^(?:\d+(?:\.\d+)?|\.\d+)%$/;
1519
+ const ANIMATION = "animation";
1520
+ const NAME_SUFFIX = "-name:";
1521
+ const NONE = [];
1522
+ const registry = /* @__PURE__ */ new Map();
1523
+ /** The value of `key` in a step, with a stand-in (alone or in a list) turned into its path; a nested style is a `TypeError`. */
1524
+ function readStepValue(offset, key, value) {
1525
+ if (Array.isArray(value)) return value.map((item) => readStandIn(item));
1526
+ const read = readStandIn(value);
1527
+ if (typeof read !== "object" || read === null || isAlphaColor(read)) return read;
1528
+ throw new TypeError(`keyframes(): the step "${offset}" holds "${key}", a nested style (a selector or an at-rule). A step is flat: it holds declarations only.`);
1529
+ }
1530
+ /** The offset of one part of a step key, from 0 to 100; a `TypeError` for anything else. */
1531
+ function readOffset(part, key) {
1532
+ if (part === "from") return 0;
1533
+ if (part === "to") return 100;
1534
+ const offset = OFFSET_PATTERN.test(part) ? Number.parseFloat(part) : NaN;
1535
+ if (Number.isNaN(offset) || offset > 100) throw new TypeError(`keyframes(): "${key}" is not a step: use from, to, a percentage from 0% to 100%, or a comma list of them.`);
1536
+ return offset;
1537
+ }
1538
+ /** The steps by offset, sorted: comma lists expanded, `from` and `to` as 0% and 100%, steps of one offset merged with the later one winning. */
1539
+ function normalizeSteps(steps) {
1540
+ if (typeof steps !== "object" || steps === null) throw new TypeError("keyframes(): the steps must be an object, or a function that returns one.");
1541
+ const merged = /* @__PURE__ */ new Map();
1542
+ for (const [key, step] of Object.entries(steps)) {
1543
+ if (typeof step !== "object" || step === null) throw new TypeError(`keyframes(): the step "${key}" must be an object of declarations.`);
1544
+ const flat = {};
1545
+ for (const [name, value] of Object.entries(step)) flat[name] = readStepValue(key, name, value);
1546
+ for (const part of key.split(",")) {
1547
+ const offset = readOffset(part.trim(), key);
1548
+ const earlier = merged.get(offset);
1549
+ merged.set(offset, earlier ? mergeStyles([earlier, flat]) : flat);
1550
+ }
1551
+ }
1552
+ return [...merged].sort(([first], [second]) => first - second);
1553
+ }
1554
+ /** The body of a `@keyframes` rule: each step that declares something, sorted, written as the rule of a class. */
1555
+ function compileSteps(steps, hasColorFallbacks, hasValueRepair) {
1556
+ return normalizeSteps(steps).flatMap(([offset, step]) => compileRules(`${offset}%`, step, hasColorFallbacks, DEFAULT_SCOPING, hasValueRepair)).join("");
1557
+ }
1558
+ function keyframes(first, ...rest) {
1559
+ if (isTemplateStrings(first)) return keyframes(parseKeyframesTemplate(first, rest));
1560
+ const steps = first;
1561
+ const { label = DEFAULT_LABEL } = rest[0] ?? {};
1562
+ if (!LABEL_PATTERN.test(label)) throw new TypeError(`keyframes(): the label "${label}" is not an identifier: use letters, digits, '-' and '_', not starting with a digit or '-'.`);
1563
+ const isThemed = typeof steps === "function";
1564
+ const resolved = isThemed ? steps(createStandIn("")) : steps;
1565
+ const name = `${label}-${hashString((isThemed ? "theme:" : "") + compileSteps(resolved, true, false))}`;
1566
+ if (!registry.has(name)) registry.set(name, steps);
1567
+ return name;
1568
+ }
1569
+ /** Whether `name` is a name that `keyframes` returned. */
1570
+ function isKeyframesName(name) {
1571
+ return registry.has(name);
1572
+ }
1573
+ /**
1574
+ * The `@keyframes` rule of the registered `name`: steps given as a function are resolved against the
1575
+ * theme that `readTheme` gives, which is read only then.
1576
+ */
1577
+ function createKeyframesRule(name, readTheme, hasColorFallbacks, hasValueRepair) {
1578
+ const steps = registry.get(name);
1579
+ return `@keyframes ${name}{${compileSteps(typeof steps === "function" ? steps(readTheme()) : steps, hasColorFallbacks, hasValueRepair)}}`;
1580
+ }
1581
+ /** Adds to `names` each identifier of `value` that is a registered name. */
1582
+ function addRegistered(value, names) {
1583
+ for (const word of value.split(/[^\w-]+/)) if (registry.has(word) && !names.includes(word)) names.push(word);
1584
+ }
1585
+ /** Where the value starts when the `animation` at `index` of `rule` begins an `animation` or `animation-name` declaration, else -1. */
1586
+ function findValueStart(rule, index) {
1587
+ const before = rule[index - 1];
1588
+ if (before !== "{" && before !== ";") return -1;
1589
+ const after = index + 9;
1590
+ if (rule[after] === ":") return after + 1;
1591
+ return rule.startsWith(NAME_SUFFIX, after) ? after + 6 : -1;
1592
+ }
1593
+ /**
1594
+ * The registered names that the `animation` and `animation-name` declarations of `rules` (compiled rules,
1595
+ * whose declarations each end with `;`) use, in nested selectors and at-rules too, matched as whole
1596
+ * identifiers. Nothing is read while no name is registered.
1597
+ */
1598
+ function findAnimationNames(rules) {
1599
+ if (registry.size === 0) return NONE;
1600
+ const names = [];
1601
+ for (const rule of rules) {
1602
+ let index = rule.indexOf(ANIMATION);
1603
+ while (index !== -1) {
1604
+ const start = findValueStart(rule, index);
1605
+ if (start !== -1) {
1606
+ index = rule.indexOf(";", start);
1607
+ addRegistered(rule.slice(start, index), names);
1608
+ }
1609
+ index = rule.indexOf(ANIMATION, index + 1);
1610
+ }
1611
+ }
1612
+ return names;
1613
+ }
1614
+ // src/variables.ts
1615
+ const VARIABLE_OPEN = "var(";
1616
+ /** Whether `code` is a character of a variable name: a lowercase letter, a digit, '-' or '_'. */
1617
+ function isNameCode$1(code) {
1618
+ return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
1619
+ }
1620
+ /** The index of the first character at or after `index` that is not whitespace. */
1621
+ function skipSpaces$1(text, index) {
1622
+ let position = index;
1623
+ while (codeAt(text, position) <= 32) position++;
1624
+ return position;
1625
+ }
1626
+ /**
1627
+ * The names of the variables that `css` refers to and that start with `start` (`--<prefix>-`), in order
1628
+ * of appearance, with repeats. A reference may have a fallback, which may refer to others. One pass.
1629
+ */
1630
+ function scanVariables(css, start) {
1631
+ const names = [];
1632
+ let from = css.indexOf(VARIABLE_OPEN);
1633
+ while (from !== -1) {
1634
+ const begin = skipSpaces$1(css, from + 4);
1635
+ let end = begin + start.length;
1636
+ if (css.startsWith(start, begin)) {
1637
+ while (isNameCode$1(codeAt(css, end))) end++;
1638
+ names.push(css.slice(begin, end));
1639
+ }
1640
+ from = css.indexOf(VARIABLE_OPEN, begin);
1641
+ }
1642
+ return names;
1643
+ }
1644
+ // src/scanStyleText.ts
1645
+ /** Makes findings that hold nothing. */
1646
+ function createEmptyFindings() {
1647
+ return {
1648
+ hasLayerOrder: false,
1649
+ classes: /* @__PURE__ */ new Set(),
1650
+ themes: /* @__PURE__ */ new Map(),
1651
+ properties: /* @__PURE__ */ new Map(),
1652
+ keyframes: /* @__PURE__ */ new Set(),
1653
+ variables: /* @__PURE__ */ new Set(),
1654
+ ruleCount: 0,
1655
+ globals: [],
1656
+ roots: []
1657
+ };
1658
+ }
1659
+ const LAYER_AT_RULE = "@layer";
1660
+ const ROOT_SELECTOR$1 = ":where(:root)";
1661
+ const PROPERTY_AT_RULE = "@property";
1662
+ const KEYFRAMES_AT_RULE = "@keyframes";
1663
+ /** Whether `code` is a character of a class name: a lowercase letter, a digit, '-' or '_'. */
1664
+ function isNameCode(code) {
1665
+ return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
1666
+ }
1667
+ /** The classes in `selector` whose name starts with `start` (`<prefix>-`), without the dot. */
1668
+ function readClasses(selector, start) {
1669
+ const names = [];
1670
+ let from = selector.indexOf(`.${start}`);
1671
+ while (from !== -1) {
1672
+ let end = from + 1 + start.length;
1673
+ while (isNameCode(codeAt(selector, end))) end++;
1674
+ names.push(selector.slice(from + 1, end));
1675
+ from = selector.indexOf(`.${start}`, end);
1676
+ }
1677
+ return names;
1678
+ }
1679
+ /** The names of the variables that `body`, the declarations of a rule, declares. */
1680
+ function readDeclared(body) {
1681
+ const names = /* @__PURE__ */ new Set();
1682
+ for (const part of body.split(";")) {
1683
+ const text = part.trimStart();
1684
+ if (text.startsWith("--")) names.add(text.slice(0, text.indexOf(":")));
1685
+ }
1686
+ return names;
1687
+ }
1688
+ /** The index after the string that starts at `index`, which is a quote. */
1689
+ function skipString(text, index) {
1690
+ const quote = text[index];
1691
+ let position = index + 1;
1692
+ while (position < text.length && text[position] !== quote) position += text[position] === "\\" ? 2 : 1;
1693
+ return position + 1;
1694
+ }
1695
+ /** Records the innermost rule `prelude{body}` of a style element in `found`. */
1696
+ function record(found, prefix, prelude, body) {
1697
+ if (prelude.startsWith(PROPERTY_AT_RULE)) {
1698
+ found.properties.set(prelude.slice(9).trim(), `${prelude}{${body}}`);
1699
+ return;
1700
+ }
1701
+ if (prelude.startsWith("@") || prelude === ROOT_SELECTOR$1) return;
1702
+ const themeStart = `${prefix}-theme-`;
1703
+ const classes = readClasses(prelude, `${prefix}-`);
1704
+ const themeId = classes.length === 1 && prelude === `.${classes[0]}` ? classes[0] : void 0;
1705
+ if (themeId?.startsWith(themeStart)) {
1706
+ const declared = found.themes.get(themeId) ?? /* @__PURE__ */ new Set();
1707
+ for (const name of readDeclared(body)) declared.add(name);
1708
+ found.themes.set(themeId, declared);
1709
+ return;
1710
+ }
1711
+ const markers = /* @__PURE__ */ new Set([
1712
+ `${prefix}-boundary`,
1713
+ `${prefix}-scheme-light`,
1714
+ `${prefix}-scheme-dark`
1715
+ ]);
1716
+ for (const name of classes) if (!name.startsWith(themeStart) && !markers.has(name)) found.classes.add(name);
1717
+ for (const name of scanVariables(body, `--${prefix}-`)) found.variables.add(name);
1718
+ }
1719
+ /** Opens a block at `index`, a `{`: its prelude is the text since `boundary`. */
1720
+ function openBlock(stack, text, boundary, index) {
1721
+ const parent = stack.at(-1);
1722
+ if (parent) parent.hasChild = true;
1723
+ stack.push({
1724
+ prelude: text.slice(boundary, index).trim(),
1725
+ bodyStart: index + 1,
1726
+ hasChild: false
1727
+ });
1728
+ }
1729
+ /** Closes the innermost block at `index`, a `}`, and returns it: a `@keyframes` rule records its name, and a block without a block of its own is a rule to record. */
1730
+ function closeBlock(stack, found, prefix, text, index) {
1731
+ const block = stack.pop();
1732
+ if (block?.prelude.startsWith(KEYFRAMES_AT_RULE)) found.keyframes.add(block.prelude.slice(10).trim());
1733
+ else if (block && !block.hasChild) record(found, prefix, block.prelude, text.slice(block.bodyStart, index));
1734
+ return block;
1735
+ }
1736
+ /** Whether a top-level rule with `prelude` may be a global rule: in the global layer, or in none and not a rule that the engine writes for something else. */
1737
+ function isGlobalPrelude(prefix, prelude) {
1738
+ if (prelude.startsWith(LAYER_AT_RULE)) return prelude === `${LAYER_AT_RULE} ${prefix}-global`;
1739
+ return !prelude.startsWith(PROPERTY_AT_RULE) && !prelude.startsWith(KEYFRAMES_AT_RULE) && !prelude.startsWith(`.${prefix}-`);
1740
+ }
1741
+ /** Whether the top-level rule `text` is the rule of a root theme, in the theme layer or in none. */
1742
+ function isRootRule(prefix, text) {
1743
+ return text.startsWith(`${ROOT_SELECTOR$1}{`) || text.startsWith(`${LAYER_AT_RULE} ${prefix}-theme{${ROOT_SELECTOR$1}{`);
1744
+ }
1745
+ /** Closes the innermost block at `index`, a `}`; when it is a top-level rule (which started at `ruleStart`), records its place in `found`, and whether it is the rule of a root theme or may be a global rule. */
1746
+ function closeRule(stack, found, prefix, text, ruleStart, index) {
1747
+ const block = closeBlock(stack, found, prefix, text, index);
1748
+ if (!block || stack.length > 0) return;
1749
+ const place = found.ruleCount++;
1750
+ const rule = text.slice(ruleStart, index + 1).trimStart();
1751
+ if (isRootRule(prefix, rule)) found.roots.push(place);
1752
+ else if (isGlobalPrelude(prefix, block.prelude)) found.globals.push([place, rule]);
1753
+ }
1754
+ /** Records the top-level statement `statement` (the text before a `;`, trimmed) in `found`: a rule unless it is empty, and the layer order statement when it is one. */
1755
+ function recordStatement(found, statement) {
1756
+ if (statement.startsWith(LAYER_AT_RULE)) found.hasLayerOrder = true;
1757
+ if (statement !== "") found.ruleCount++;
1758
+ }
1759
+ /**
1760
+ * Reads the CSS that an engine wrote (compact, no comments) in one pass and adds what it holds to
1761
+ * `found`: the layer order statement, the classes with a rule, each theme class with the variables it
1762
+ * declares, the `@property` rules, the names of the `@keyframes` rules, the variables that rules use, how
1763
+ * many rules are at the top level, the top-level rules that may be global rules, and the places of the
1764
+ * rules of a root theme.
1765
+ */
1766
+ function scanStyleText(prefix, text, found = createEmptyFindings()) {
1767
+ const stack = [];
1768
+ let boundary = 0;
1769
+ let ruleStart = 0;
1770
+ let index = 0;
1771
+ while (index < text.length) {
1772
+ const char = text[index];
1773
+ if (char === "\"" || char === "'") {
1774
+ index = skipString(text, index);
1775
+ continue;
1776
+ }
1777
+ if (char === "{") {
1778
+ if (stack.length === 0) ruleStart = boundary;
1779
+ openBlock(stack, text, boundary, index);
1780
+ boundary = index + 1;
1781
+ } else if (char === "}") {
1782
+ closeRule(stack, found, prefix, text, ruleStart, index);
1783
+ boundary = index + 1;
1784
+ } else if (char === ";" && stack.length === 0) {
1785
+ recordStatement(found, text.slice(boundary, index).trim());
1786
+ boundary = index + 1;
1787
+ }
1788
+ index++;
1789
+ }
1790
+ return found;
1791
+ }
776
1792
  // src/theme.ts
1793
+ /** The selector of the rule of the root theme: the document root, with no specificity. */
1794
+ const ROOT_SELECTOR = ":where(:root)";
1795
+ /** The rule `selector{body}` of a theme, inside the theme layer of `prefix` when there are layers. */
1796
+ function createThemeRule(prefix, hasLayers, selector, body) {
1797
+ const rule = `${selector}{${body}}`;
1798
+ return hasLayers ? `@layer ${prefix}-theme{${rule}}` : rule;
1799
+ }
777
1800
  /** The CSS declarations `name:value;` of `entries`. */
778
1801
  function toDeclarationText(entries) {
779
1802
  let text = "";
780
1803
  for (const [name, value] of entries) text += `${name}:${value};`;
781
1804
  return text;
782
1805
  }
1806
+ /** The hash of all the declarations of a theme, as text, and of its color-scheme: what names its class or root rule. */
1807
+ function hashTheme(variables, colorScheme) {
1808
+ return hashString(colorScheme ? `${variables}color-scheme:${colorScheme};` : variables);
1809
+ }
1810
+ /**
1811
+ * The theme class of the declarations `variables` (the text of `toDeclarationText`, as `readThemeText`
1812
+ * gives it) and of `colorScheme`, `<prefix>-theme-<hash>`, without registering it: the name that
1813
+ * `createThemeClass` gives the same declarations.
1814
+ */
1815
+ function createThemeId(prefix, variables, colorScheme) {
1816
+ return `${prefix}-theme-${hashTheme(variables, colorScheme)}`;
1817
+ }
783
1818
  /**
784
1819
  * Registers the theme class of `declarations` and returns it: the scope of a theme. Its name is the
785
1820
  * hash of all the declarations, whatever the cache writes of them (see `hasPruning`).
@@ -787,11 +1822,21 @@ function toDeclarationText(entries) {
787
1822
  function createThemeClass(cache, declarations, options = {}) {
788
1823
  const { colorScheme } = options;
789
1824
  const variables = toDeclarationText(Object.entries(declarations));
790
- const body = colorScheme ? `${variables}color-scheme:${colorScheme};` : variables;
791
- const className = `${cache.prefix}-theme-${hashString(body)}`;
1825
+ const className = createThemeId(cache.prefix, variables, colorScheme);
792
1826
  cache.insertTheme(className, declarations, colorScheme);
793
1827
  return className;
794
1828
  }
1829
+ /**
1830
+ * Makes `declarations` the root theme, the one declared on `:root` (see `Cache.insertRoot`), and returns
1831
+ * its id, `<prefix>-root-<hash>`: like a theme class, named by the hash of all its declarations.
1832
+ */
1833
+ function declareRootTheme(cache, declarations, options = {}) {
1834
+ const { colorScheme } = options;
1835
+ const variables = toDeclarationText(Object.entries(declarations));
1836
+ const id = `${cache.prefix}-root-${hashTheme(variables, colorScheme)}`;
1837
+ cache.insertRoot(id, declarations, colorScheme);
1838
+ return id;
1839
+ }
795
1840
  // src/cache.ts
796
1841
  /** The cascade layers of a cache, from the lowest priority to the highest. */
797
1842
  const RULE_LAYERS = [
@@ -813,36 +1858,62 @@ function createMemorySheet() {
813
1858
  },
814
1859
  replace(index, rule) {
815
1860
  rules[index] = rule;
1861
+ },
1862
+ remove(index) {
1863
+ rules.splice(index, 1);
816
1864
  }
817
1865
  };
818
1866
  }
819
- /** A sheet in the style element marked `data-style="<key>"`, which it creates when there is none. */
1867
+ /** Deletes `rule` from the style sheet that holds it, found by its place now; a rule that is held by none any more is left. */
1868
+ function deleteCssRule(rule) {
1869
+ const parent = rule.parentStyleSheet;
1870
+ if (parent) parent.deleteRule(Array.prototype.indexOf.call(parent.cssRules, rule));
1871
+ }
1872
+ /**
1873
+ * A sheet in the style element marked `data-style="<key>"` of the document of `container`, which it
1874
+ * creates in `container` when that document has none. It keeps the browser's object of each rule it
1875
+ * inserts, and removes a rule by finding where that object is at the time, so rules that others insert
1876
+ * into or delete from the element do not confuse it. Its `document` is that document: a cache over it
1877
+ * reads that one (an iframe's, for a container in the iframe).
1878
+ */
820
1879
  function createDomSheet(key, container = document.head) {
821
- let element = document.querySelector(`style[data-style="${key}"]`);
1880
+ const owner = container.ownerDocument;
1881
+ let element = owner.querySelector(`style[data-style="${key}"]`);
822
1882
  if (!element) {
823
- element = document.createElement("style");
1883
+ element = owner.createElement("style");
824
1884
  element.dataset.style = key;
825
1885
  container.appendChild(element);
826
1886
  }
827
1887
  const sheet = element.sheet;
828
1888
  const rules = [];
1889
+ const objects = [];
829
1890
  return {
830
1891
  rules,
1892
+ document: owner,
831
1893
  insert(rule) {
832
1894
  try {
833
- sheet.insertRule(rule, sheet.cssRules.length);
1895
+ const index = sheet.insertRule(rule, sheet.cssRules.length);
1896
+ objects.push(sheet.cssRules[index]);
834
1897
  rules.push(rule);
835
1898
  } catch {}
1899
+ },
1900
+ remove(index) {
1901
+ rules.splice(index, 1);
1902
+ deleteCssRule(objects.splice(index, 1)[0]);
836
1903
  }
837
1904
  };
838
1905
  }
839
- /** The selector of the style elements that hold engine rules: the cache's own, and the ones React hoists for the same prefix. */
1906
+ /**
1907
+ * The selector of the style elements that hold engine rules: the cache's own, the ones React hoists for
1908
+ * the same prefix, and the `data-umber="<prefix> <ids>"` and `data-umber="<prefix>-global <ids>"` elements
1909
+ * of `@umber-style/server` and of an app's own registry.
1910
+ */
840
1911
  function createStyleSelector(prefix) {
841
- return `style[data-style="${prefix}"], style[data-precedence="${prefix}"]`;
1912
+ return `style[data-style="${prefix}"], style[data-precedence="${prefix}"], style[data-umber~="${prefix}"], style[data-umber~="${prefix}-global"]`;
842
1913
  }
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"]`);
1914
+ /** The stamp of the options that the server wrote in `page`: on a style element, or on the `<meta>` that a server component renders. */
1915
+ function readServerStamp(page, prefix) {
1916
+ const element = page.querySelector(`style[data-style="${prefix}"][data-options], meta[name="${prefix}-options"]`);
846
1917
  return element?.dataset.options ?? element?.getAttribute("content") ?? void 0;
847
1918
  }
848
1919
  /** The class names in `value`, a class string or a sheet entry. */
@@ -862,10 +1933,10 @@ function compareCodeUnits(first, second) {
862
1933
  return first < second ? -1 : 1;
863
1934
  }
864
1935
  /** 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) {
1936
+ function addThemeReferences(names, themeIds, readDeclarations) {
866
1937
  const queue = [...names];
867
1938
  for (const queued of queue) for (const id of themeIds) {
868
- const value = themes.get(id)?.declarations[queued];
1939
+ const value = readDeclarations(id)?.[queued];
869
1940
  if (value === void 0) continue;
870
1941
  for (const name of scanVariables(value, VARIABLE_START)) {
871
1942
  if (!names.has(name)) queue.push(name);
@@ -875,9 +1946,10 @@ function addThemeReferences(names, themeIds, themes) {
875
1946
  }
876
1947
  /**
877
1948
  * 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.
1949
+ * resolved back) and the class names to pass through. `sole` is the entry when the one style is its own;
1950
+ * an entry of another cache is first made this cache's own with `adopt`.
879
1951
  */
880
- function sortClassValues(values, registered) {
1952
+ function sortClassValues(values, registered, adopt) {
881
1953
  const styles = [];
882
1954
  const rawClasses = [];
883
1955
  let entry;
@@ -887,7 +1959,7 @@ function sortClassValues(values, registered) {
887
1959
  styles.push(value);
888
1960
  continue;
889
1961
  }
890
- const source = typeof value === "string" ? void 0 : readEntrySource(value);
1962
+ const source = typeof value === "string" ? void 0 : readEntrySource(adopt(value));
891
1963
  if (source) {
892
1964
  styles.push(source.style);
893
1965
  entry = source;
@@ -903,7 +1975,7 @@ function sortClassValues(values, registered) {
903
1975
  }
904
1976
  /** Makes a cache: it turns styles into classes and inserts each class's rules once. */
905
1977
  function createCache(options = {}) {
906
- const { prefix = "css", suffix = "", hasLabels = true, hasLayers = true, hasPruning = true, hasColorFallbacks = true, hasScope = true, hasBaseClass = true } = options;
1978
+ const { prefix = "css", suffix = "", hasLabels = true, hasLayers = true, hasPruning = true, hasColorFallbacks = true, hasValueRepair = false, hasScope = true, hasBaseClass = true } = options;
907
1979
  if (!PREFIX_PATTERN.test(prefix)) throw new Error(`Invalid cache prefix "${prefix}": use lowercase letters, digits and hyphens.`);
908
1980
  const fingerprint = createFingerprint({
909
1981
  prefix,
@@ -914,22 +1986,23 @@ function createCache(options = {}) {
914
1986
  hasBaseClass,
915
1987
  hasScope,
916
1988
  hasColorFallbacks,
1989
+ hasValueRepair,
917
1990
  tokens: options.tokenSignature ?? ""
918
1991
  });
919
- const hasDocument = typeof document !== "undefined";
920
- if (hasDocument) {
921
- const stamp = readServerStamp(prefix);
1992
+ const page = options.sheet?.document ?? (typeof document === "undefined" ? void 0 : document);
1993
+ if (page) {
1994
+ const stamp = readServerStamp(page, prefix);
922
1995
  const difference = stamp === void 0 ? "" : describeFingerprintDifferences(stamp, fingerprint);
923
1996
  if (difference !== "") throw new Error(difference);
924
1997
  }
925
- const { hasDevChecks = hasDocument && isDevelopment() } = options;
926
- const checkLater = hasDevChecks ? createDevChecker(prefix) : void 0;
1998
+ const { hasDevChecks = page !== void 0 && isDevelopment() } = options;
1999
+ const checkLater = hasDevChecks ? createDevChecker(prefix, void 0, page) : void 0;
927
2000
  const insertedIds = /* @__PURE__ */ new Set();
928
2001
  const used = /* @__PURE__ */ new Set();
929
2002
  const pinned = /* @__PURE__ */ new Set();
930
2003
  const pageThemes = /* @__PURE__ */ new Map();
931
2004
  const afters = /* @__PURE__ */ new Map();
932
- const sheet = options.sheet ?? (typeof document === "undefined" ? createMemorySheet() : createDomSheet(prefix));
2005
+ const sheet = options.sheet ?? (page ? createDomSheet(prefix, page.head) : createMemorySheet());
933
2006
  const registered = /* @__PURE__ */ new Map();
934
2007
  const entries = /* @__PURE__ */ new Map();
935
2008
  const scoping = {
@@ -943,35 +2016,69 @@ function createCache(options = {}) {
943
2016
  const layerOrder = hasLayers ? `@layer ${layerNames};` : "";
944
2017
  const layerOrderId = `${prefix}-layers`;
945
2018
  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)) {
2019
+ const { onInsert } = options;
2020
+ const insertLayerOrder = () => {
2021
+ if (hasLayers && !insertedIds.has(layerOrderId)) {
948
2022
  insertedIds.add(layerOrderId);
949
2023
  sheet.insert(layerOrder);
2024
+ onInsert?.(layerOrderId, layerOrder);
2025
+ }
2026
+ };
2027
+ /** Writes `layered` after the layer order statement, and reports them under `name`; with `indexes`, the place of each rule that the sheet took is added to it. */
2028
+ const insertLayered = (name, layered, indexes) => {
2029
+ if (layered.length === 0) return;
2030
+ insertLayerOrder();
2031
+ if (indexes) for (const rule of layered) {
2032
+ const index = sheet.rules.length;
2033
+ sheet.insert(rule);
2034
+ if (sheet.rules.length > index) indexes.push(index);
950
2035
  }
951
- for (const rule of layered) sheet.insert(rule);
952
- if (layered.length > 0) checkLater?.();
2036
+ else for (const rule of layered) sheet.insert(rule);
2037
+ onInsert?.(name, layered.join(""));
2038
+ checkLater?.(layered);
953
2039
  };
954
2040
  const themes = /* @__PURE__ */ new Map();
2041
+ const roots = /* @__PURE__ */ new Map();
2042
+ let root;
2043
+ let pageRoots = [];
2044
+ /** The rule of a root theme with the variables `names`, and its color-scheme; none when that is nothing. */
2045
+ const createRootRules = (theme, names) => {
2046
+ const body = toDeclarationText([...names].map((name) => [name, theme.declarations[name]])) + theme.schemeText;
2047
+ return body === "" ? [] : [createThemeRule(prefix, hasLayers, ROOT_SELECTOR, body)];
2048
+ };
2049
+ /** Writes the rule of the root theme anew with every variable written so far, after removing the one it had where the sheet can; a sheet that cannot keeps it, and the new rule, later, wins. */
2050
+ const writeRoot = (entry) => {
2051
+ const rules = createRootRules(roots.get(entry.id), entry.written);
2052
+ insertedRules.set(entry.id, rules);
2053
+ const { remove } = sheet;
2054
+ if (entry.index !== void 0 && remove) removeAt(remove, entry.index);
2055
+ entry.index = void 0;
2056
+ const before = sheet.rules.length;
2057
+ insertLayered(`${entry.id}-${hashString(rules.join(""))}`, rules);
2058
+ if (sheet.rules.length > before) entry.index = sheet.rules.length - 1;
2059
+ };
955
2060
  /** 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
2061
  const writeTheme = (className, entry, names) => {
957
2062
  const added = toDeclarationText(names.map((name) => [name, entry.declarations[name]]));
958
2063
  const ownScheme = entry.isSent ? "" : entry.schemeText;
959
2064
  const first = entry.isStarted ? "" : ownScheme;
960
2065
  if (added + first === "") return;
2066
+ const part = wrapInLayer([`.${className}{${added + first}}`], "theme");
2067
+ const reported = entry.isStarted ? `${className}-${hashString(added)}` : className;
961
2068
  entry.isStarted = true;
962
2069
  for (const name of names) entry.written.add(name);
963
2070
  entry.variables += added;
964
2071
  const { index } = entry;
965
- const body = index === void 0 ? added + first : entry.variables + ownScheme;
966
- const rules = wrapInLayer([`.${className}{${body}}`], "theme");
967
2072
  if (sheet.replace && index !== void 0) {
2073
+ const rules = wrapInLayer([`.${className}{${entry.variables + ownScheme}}`], "theme");
968
2074
  sheet.replace(index, rules[0]);
969
2075
  entry.rules = rules;
2076
+ onInsert?.(reported, part[0]);
970
2077
  } else {
971
2078
  const before = sheet.rules.length;
972
- insertLayered(rules);
2079
+ insertLayered(reported, part);
973
2080
  if (sheet.replace && sheet.rules.length > before) entry.index = sheet.rules.length - 1;
974
- entry.rules = [...entry.rules, ...rules];
2081
+ entry.rules = [...entry.rules, ...part];
975
2082
  }
976
2083
  insertedRules.set(className, entry.rules);
977
2084
  };
@@ -985,6 +2092,34 @@ function createCache(options = {}) {
985
2092
  propertyRules = rules;
986
2093
  for (const name of Object.keys(rules)) if (!hasPruning || used.has(name)) writeProperty(name);
987
2094
  };
2095
+ const animations = /* @__PURE__ */ new Map();
2096
+ let readKeyframesTheme = () => {
2097
+ throw new Error("keyframes(): these steps are a function of the theme, and this cache has no theme: make the cache through an engine.");
2098
+ };
2099
+ /** The `@keyframes` rule of `name`: the one written, else made now. */
2100
+ const readKeyframesRule = (name) => insertedRules.get(name)?.[0] ?? createKeyframesRule(name, readKeyframesTheme, hasColorFallbacks, hasValueRepair);
2101
+ /** Writes the `@keyframes` rule of the registered `name` once, outside every layer, unless the page has it. */
2102
+ const writeKeyframes = (name) => {
2103
+ const id = `@keyframes:${name}`;
2104
+ if (insertedIds.has(id)) return;
2105
+ const rule = readKeyframesRule(name);
2106
+ insertOnce(id, [rule]);
2107
+ insertedRules.set(name, [rule]);
2108
+ };
2109
+ /** Inserts the rules of a class once, after the `@keyframes` rules of the animations they use; with `indexes`, the places of its rules are added to it. */
2110
+ const insertClass = (className, rules, layer, indexes) => {
2111
+ if (insertedIds.has(className)) return;
2112
+ const names = findAnimationNames(rules);
2113
+ if (names.length > 0) {
2114
+ animations.set(className, names);
2115
+ names.forEach(writeKeyframes);
2116
+ }
2117
+ insertOnce(className, rules, layer, indexes);
2118
+ };
2119
+ const insertKeyframes = (name) => {
2120
+ if (!isKeyframesName(name)) throw new TypeError(`insertKeyframes(): "${name}" is not a name that keyframes() returned, so there is no rule to write.`);
2121
+ writeKeyframes(name);
2122
+ };
988
2123
  const markUsed = (names) => {
989
2124
  if (!hasPruning) return;
990
2125
  const queue = [...names];
@@ -993,7 +2128,7 @@ function createCache(options = {}) {
993
2128
  if (used.has(name)) continue;
994
2129
  used.add(name);
995
2130
  fresh.push(name);
996
- for (const { declarations } of themes.values()) {
2131
+ for (const { declarations } of [...themes.values(), ...roots.values()]) {
997
2132
  const value = declarations[name];
998
2133
  if (value !== void 0) queue.push(...scanVariables(value, VARIABLE_START));
999
2134
  }
@@ -1001,6 +2136,39 @@ function createCache(options = {}) {
1001
2136
  if (fresh.length === 0) return;
1002
2137
  fresh.forEach(writeProperty);
1003
2138
  for (const [className, entry] of themes) writeTheme(className, entry, fresh.filter((name) => entry.declarations[name] !== void 0 && !entry.written.has(name)));
2139
+ if (root === void 0) return;
2140
+ const { declarations } = roots.get(root.id);
2141
+ const added = fresh.filter((name) => declarations[name] !== void 0);
2142
+ if (added.length === 0) return;
2143
+ for (const name of added) root.written.add(name);
2144
+ writeRoot(root);
2145
+ };
2146
+ const insertRoot = (id, declarations, colorScheme) => {
2147
+ if (!roots.has(id)) {
2148
+ roots.set(id, {
2149
+ declarations,
2150
+ schemeText: colorScheme ? `color-scheme:${colorScheme};` : ""
2151
+ });
2152
+ themeNames.set(id, Object.keys(declarations));
2153
+ }
2154
+ if (root?.id === id) return;
2155
+ for (const rule of pageRoots) if (rule) deleteCssRule(rule);
2156
+ pageRoots = [];
2157
+ if (root) {
2158
+ insertedIds.delete(root.id);
2159
+ insertedRules.delete(root.id);
2160
+ }
2161
+ insertedIds.add(id);
2162
+ const names = Object.keys(declarations);
2163
+ const isUsed = (name) => !hasPruning || used.has(name);
2164
+ const entry = {
2165
+ id,
2166
+ written: new Set(names.filter(isUsed)),
2167
+ index: root?.index
2168
+ };
2169
+ root = entry;
2170
+ writeRoot(entry);
2171
+ markUsed([...entry.written].flatMap((name) => scanVariables(declarations[name], VARIABLE_START)));
1004
2172
  };
1005
2173
  const insertTheme = (className, declarations, colorScheme) => {
1006
2174
  const schemeText = colorScheme ? `color-scheme:${colorScheme};` : "";
@@ -1025,26 +2193,107 @@ function createCache(options = {}) {
1025
2193
  index: void 0,
1026
2194
  rules: []
1027
2195
  };
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)));
2196
+ themes.set(className, entry);
2197
+ insertedRules.set(className, []);
2198
+ markUsed(names.filter((name) => used.has(name)).flatMap((name) => scanVariables(declarations[name], VARIABLE_START)));
2199
+ writeTheme(className, entry, names.filter((name) => used.has(name) && !entry.written.has(name)));
2200
+ };
2201
+ function insertOnce(id, rules, layer, indexes) {
2202
+ if (insertedIds.has(id)) return false;
2203
+ insertedIds.add(id);
2204
+ const layered = wrapInLayer(rules, layer);
2205
+ insertedRules.set(id, layered);
2206
+ insertLayered(id, layered, indexes);
2207
+ if (hasPruning) markUsed(rules.flatMap((rule) => scanVariables(rule, VARIABLE_START)));
2208
+ return true;
2209
+ }
2210
+ const globals = /* @__PURE__ */ new Map();
2211
+ const pageGlobals = /* @__PURE__ */ new Map();
2212
+ let readArrived = () => void 0;
2213
+ const held = /* @__PURE__ */ new Map();
2214
+ const releasing = /* @__PURE__ */ new Set();
2215
+ const compileGlobal = (styles) => {
2216
+ const flat = compileGlobalRules(styles, hasColorFallbacks, scoping, hasValueRepair);
2217
+ const rules = wrapInLayer(flat, "global");
2218
+ return {
2219
+ id: `${prefix}-global-${hashString(rules.join(""))}`,
2220
+ rules,
2221
+ animations: findAnimationNames(flat)
2222
+ };
2223
+ };
2224
+ /** Whether the page has every one of `rules`, not taken by another set. */
2225
+ const hasPageRules = (rules) => rules.every((rule) => pageGlobals.get(rule)?.length);
2226
+ /** The rules of the page for `rules`, taken so that no other set takes them, when the page has every one of them; else undefined. */
2227
+ const takePageRules = (rules) => {
2228
+ if (!hasPageRules(rules)) return void 0;
2229
+ return rules.map((rule) => pageGlobals.get(rule).shift());
2230
+ };
2231
+ /** Writes the rules of `global`, or takes them over from the page, after the `@keyframes` rules they use. */
2232
+ const writeGlobal = ({ id, rules, animations: names }) => {
2233
+ names.forEach(writeKeyframes);
2234
+ if (!hasPageRules(rules)) readArrived();
2235
+ const pageRules = takePageRules(rules);
2236
+ const indexes = [];
2237
+ if (pageRules === void 0) {
2238
+ insertLayerOrder();
2239
+ for (const rule of rules) {
2240
+ const index = sheet.rules.length;
2241
+ sheet.insert(rule);
2242
+ if (sheet.rules.length > index) indexes.push(index);
2243
+ }
2244
+ onInsert?.(id, rules.join(""));
2245
+ checkLater?.(rules);
2246
+ }
2247
+ markUsed(rules.flatMap((rule) => scanVariables(rule, VARIABLE_START)));
2248
+ const entry = {
2249
+ count: 0,
2250
+ appCount: 0,
2251
+ rules,
2252
+ animations: names,
2253
+ indexes,
2254
+ pageRules
2255
+ };
2256
+ globals.set(id, entry);
2257
+ return entry;
2258
+ };
2259
+ /** Removes the rule at `index` of the sheet, and moves down every place the cache keeps that is after it. */
2260
+ const removeAt = (remove, index) => {
2261
+ remove(index);
2262
+ for (const entry of [...globals.values(), ...held.values()]) entry.indexes = entry.indexes.map((at) => at > index ? at - 1 : at);
2263
+ for (const entry of themes.values()) if (entry.index !== void 0 && entry.index > index) entry.index--;
2264
+ if (root?.index !== void 0 && root.index > index) root.index--;
2265
+ };
2266
+ /** Removes the rules of a set that nothing holds any more, unless they cannot be removed: then they stay, and count as written. */
2267
+ const removeGlobal = (id, entry) => {
2268
+ const { pageRules, indexes } = entry;
2269
+ const { remove } = sheet;
2270
+ if (pageRules ? pageRules.includes(void 0) : remove === void 0) return;
2271
+ globals.delete(id);
2272
+ pageRules?.forEach((rule) => deleteCssRule(rule));
2273
+ for (let at = indexes.length - 1; at >= 0; at--) removeAt(remove, indexes[at]);
2274
+ };
2275
+ const insertGlobal = (global, { isRendered = false } = {}) => {
2276
+ const entry = globals.get(global.id) ?? writeGlobal(global);
2277
+ const forApp = isRendered ? 0 : 1;
2278
+ entry.count++;
2279
+ entry.appCount += forApp;
2280
+ let isReleased = false;
2281
+ return () => {
2282
+ if (isReleased) return;
2283
+ isReleased = true;
2284
+ entry.count--;
2285
+ entry.appCount -= forApp;
2286
+ if (entry.count === 0) removeGlobal(global.id, entry);
2287
+ };
1032
2288
  };
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
2289
  const getFullRules = (id) => {
1043
2290
  const entry = themes.get(id);
1044
2291
  const properties = (themeNames.get(id) ?? []).flatMap((name) => propertyRules[name] ?? []);
2292
+ const rootTheme = roots.get(id);
2293
+ if (rootTheme) return [...properties, ...createRootRules(rootTheme, Object.keys(rootTheme.declarations))];
1045
2294
  if (entry === void 0) return [...properties, ...insertedRules.get(id) ?? []];
1046
2295
  const body = toDeclarationText(Object.entries(entry.declarations)) + entry.schemeText;
1047
- return [...properties, ...body ? wrapInLayer([`.${id}{${body}}`], "theme") : []];
2296
+ return [...properties, ...body ? [createThemeRule(prefix, hasLayers, `.${id}`, body)] : []];
1048
2297
  };
1049
2298
  /** 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
2299
  const nameClass = (layer, merged, rules, after) => {
@@ -1056,24 +2305,132 @@ function createCache(options = {}) {
1056
2305
  hash
1057
2306
  ].filter(Boolean).join("-") + suffix;
1058
2307
  };
2308
+ /** The merged style of `styles` (the label last) and the name of its class; undefined when it has no rule. */
2309
+ const prepareClass = (layer, label, after, styles) => {
2310
+ if (styles.length === 0) return void 0;
2311
+ const merged = mergeStyles(label ? [...styles, { label }] : styles);
2312
+ const rules = compileRules("&", merged, hasColorFallbacks, scoping, hasValueRepair);
2313
+ if (rules.length === 0) return void 0;
2314
+ return {
2315
+ merged,
2316
+ className: nameClass(layer, merged, rules, after)
2317
+ };
2318
+ };
2319
+ /** The rules of the class `className` with the style `merged`. */
2320
+ const compileClass = (className, merged) => compileRules(`.${className}`, merged, hasColorFallbacks, scoping, hasValueRepair);
1059
2321
  const cssWith = (options, ...values) => {
1060
2322
  const { layer = "components", label, after = "" } = options;
1061
- const { styles, rawClasses, sole } = sortClassValues(values, registered);
2323
+ const { styles, rawClasses, sole } = sortClassValues(values, registered, adoptEntry);
1062
2324
  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);
2325
+ const prepared = prepareClass(layer, label, after, styles);
2326
+ if (prepared === void 0) return rawClasses.join(" ");
2327
+ const { merged, className } = prepared;
2328
+ if (held.size > 0) held.delete(className);
1068
2329
  registered.set(className, merged);
1069
2330
  if (after !== "") afters.set(className, after);
1070
- insertOnce(className, compileRules(`.${className}`, merged, hasColorFallbacks, scoping), layer);
2331
+ insertClass(className, compileClass(className, merged), layer);
1071
2332
  return [...rawClasses, className].join(" ");
1072
2333
  };
2334
+ /**
2335
+ * Registers and writes the held class `className`, or takes it over from the page when the page has
2336
+ * it. A class written by this cache is removed after the delay unless it is held by then.
2337
+ */
2338
+ const writeHeld = (className, merged, layer) => {
2339
+ const rules = compileClass(className, merged);
2340
+ const isPage = insertedIds.has(className);
2341
+ const entry = {
2342
+ count: 0,
2343
+ indexes: [],
2344
+ pageRules: isPage ? rules.length : void 0,
2345
+ hold: () => {
2346
+ let holder = held.get(className);
2347
+ if (holder === void 0) {
2348
+ if (registered.has(className)) return () => void 0;
2349
+ holder = writeHeld(className, merged, layer);
2350
+ }
2351
+ const current = holder;
2352
+ current.count++;
2353
+ let isReleased = false;
2354
+ return () => {
2355
+ if (isReleased) return;
2356
+ isReleased = true;
2357
+ current.count--;
2358
+ if (current.count === 0) scheduleRelease(className);
2359
+ };
2360
+ }
2361
+ };
2362
+ held.set(className, entry);
2363
+ registered.set(className, merged);
2364
+ insertClass(className, rules, layer, entry.indexes);
2365
+ if (!isPage) scheduleRelease(className);
2366
+ return entry;
2367
+ };
2368
+ /** The rules of the page (the style elements of the engine) that name the class `className`, when there are `count` of them; else undefined. */
2369
+ const findPageRules = (className, count) => {
2370
+ const escaped = className.replaceAll(/[^\w-]/g, String.raw`\$&`);
2371
+ const pattern = new RegExp(String.raw`\.${escaped}(?![\w-])`);
2372
+ const found = [];
2373
+ for (const element of page.querySelectorAll(createStyleSelector(prefix))) for (const rule of element.sheet?.cssRules ?? []) if (pattern.test(rule.cssText)) found.push(rule);
2374
+ return found.length === count ? found : void 0;
2375
+ };
2376
+ /** Removes a held class that nothing holds: its rules from the sheet, or from the page when they are the page's and can all be found; then the class is forgotten. Rules that cannot be found stay, and the class is permanent. */
2377
+ const removeHeld = (className, entry) => {
2378
+ held.delete(className);
2379
+ if (entry.pageRules === void 0) for (let at = entry.indexes.length - 1; at >= 0; at--) removeAt(sheet.remove, entry.indexes[at]);
2380
+ else {
2381
+ const rules = findPageRules(className, entry.pageRules);
2382
+ if (rules === void 0) return;
2383
+ rules.forEach(deleteCssRule);
2384
+ }
2385
+ registered.delete(className);
2386
+ insertedIds.delete(className);
2387
+ insertedRules.delete(className);
2388
+ animations.delete(className);
2389
+ };
2390
+ /** Removes each held class that waits for its removal and that nothing holds any more. */
2391
+ const flushReleases = () => {
2392
+ for (const className of releasing) {
2393
+ const entry = held.get(className);
2394
+ if (entry?.count === 0) removeHeld(className, entry);
2395
+ }
2396
+ releasing.clear();
2397
+ };
2398
+ /** Marks `className` for removal after the delay: one macrotask, so that a class let go and held again in the same task (a commit, a value that comes straight back) stays. */
2399
+ const scheduleRelease = (className) => {
2400
+ releasing.add(className);
2401
+ if (releasing.size === 1) setTimeout(flushReleases, 0);
2402
+ };
2403
+ const cssHeld = (options, ...values) => {
2404
+ const { layer = "components", label } = options;
2405
+ const { styles, rawClasses, sole } = sortClassValues(values, registered, adoptEntry);
2406
+ if (sole || sheet.remove === void 0) return {
2407
+ className: cssWith(options, ...values),
2408
+ hold: void 0
2409
+ };
2410
+ const prepared = prepareClass(layer, label, "", styles);
2411
+ if (prepared === void 0) return {
2412
+ className: rawClasses.join(" "),
2413
+ hold: void 0
2414
+ };
2415
+ const { merged, className: name } = prepared;
2416
+ const className = [...rawClasses, name].join(" ");
2417
+ let entry = held.get(name);
2418
+ if (entry === void 0) {
2419
+ if (registered.has(name)) return {
2420
+ className,
2421
+ hold: void 0
2422
+ };
2423
+ entry = writeHeld(name, merged, layer);
2424
+ }
2425
+ return {
2426
+ className,
2427
+ hold: entry.hold
2428
+ };
2429
+ };
1073
2430
  const cssIn = (layer, ...values) => cssWith({ layer }, ...values);
1074
2431
  const createEntry = (style) => {
1075
2432
  const merged = mergeStyles([style]);
1076
- const rules = compileRules("&", merged, hasColorFallbacks, scoping);
2433
+ const rules = compileRules("&", merged, hasColorFallbacks, scoping, hasValueRepair);
1077
2434
  const names = {};
1078
2435
  const nameFor = (role) => {
1079
2436
  names[role] ??= rules.length === 0 ? "" : nameClass(role, merged, rules, "");
@@ -1081,11 +2438,13 @@ function createCache(options = {}) {
1081
2438
  };
1082
2439
  const source = {
1083
2440
  style: merged,
2441
+ cache: self,
1084
2442
  use(role) {
1085
2443
  const name = nameFor(role);
2444
+ if (held.size > 0) held.delete(name);
1086
2445
  if (name !== "" && !registered.has(name)) {
1087
2446
  registered.set(name, merged);
1088
- insertOnce(name, compileRules(`.${name}`, merged, hasColorFallbacks, scoping), role);
2447
+ insertClass(name, compileClass(name, merged), role);
1089
2448
  }
1090
2449
  return name;
1091
2450
  }
@@ -1094,10 +2453,22 @@ function createCache(options = {}) {
1094
2453
  entries.set(nameFor("components"), entry);
1095
2454
  return entry;
1096
2455
  };
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. */
2456
+ const adopted = /* @__PURE__ */ new WeakMap();
2457
+ const adoptEntry = (entry) => {
2458
+ const source = readEntrySource(entry);
2459
+ if (source === void 0 || source.cache === self) return entry;
2460
+ let own = adopted.get(source);
2461
+ if (own === void 0) {
2462
+ own = createEntry(source.style);
2463
+ adopted.set(source, own);
2464
+ }
2465
+ return own;
2466
+ };
2467
+ /** Takes in what rules on the page say: the classes, the layer order, the `@property` and `@keyframes` rules and the themes that are written, and the variables the rules use. */
1098
2468
  const absorb = (found) => {
1099
2469
  if (found.hasLayerOrder) insertedIds.add(layerOrderId);
1100
2470
  for (const name of found.classes) insertedIds.add(name);
2471
+ for (const name of found.keyframes) insertedIds.add(`@keyframes:${name}`);
1101
2472
  for (const [name, rule] of found.properties) insertedIds.add(`@property:${name}:${hashString(rule)}`);
1102
2473
  for (const [className, names] of found.themes) {
1103
2474
  insertedIds.add(className);
@@ -1111,19 +2482,35 @@ function createCache(options = {}) {
1111
2482
  }
1112
2483
  markUsed(found.variables);
1113
2484
  };
1114
- if (hasDocument) {
2485
+ if (page) {
1115
2486
  const selector = createStyleSelector(prefix);
1116
2487
  const scanned = /* @__PURE__ */ new WeakSet();
1117
2488
  const scan = (element) => {
1118
- if (scanned.has(element)) return;
2489
+ if (scanned.has(element) || element.getAttribute("media") === "not all") return;
1119
2490
  scanned.add(element);
1120
- absorb(scanStyleText(prefix, element.textContent));
2491
+ const found = scanStyleText(prefix, element.textContent);
2492
+ absorb(found);
2493
+ const list = element.sheet?.cssRules;
2494
+ const objects = list?.length === found.ruleCount ? list : void 0;
2495
+ for (const [index, text] of found.globals) {
2496
+ const known = pageGlobals.get(text) ?? [];
2497
+ known.push(objects?.[index]);
2498
+ pageGlobals.set(text, known);
2499
+ }
2500
+ for (const index of found.roots) pageRoots.push(objects?.[index]);
1121
2501
  };
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);
2502
+ for (const element of page.querySelectorAll(selector)) scan(element);
2503
+ const readRecords = (records) => {
2504
+ for (const { addedNodes } of records) for (const node of addedNodes) if (node === page.body) observer.observe(node, { childList: true });
2505
+ else if (node.nodeType === 1 && node.matches(selector)) scan(node);
2506
+ };
2507
+ const observer = new MutationObserver((records) => {
2508
+ readRecords(records);
1125
2509
  checkLater?.();
1126
- }).observe(document.head, { childList: true });
2510
+ });
2511
+ observer.observe(page.head, { childList: true });
2512
+ observer.observe(page.body ?? page.documentElement, { childList: true });
2513
+ readArrived = () => readRecords(observer.takeRecords());
1127
2514
  checkLater?.();
1128
2515
  }
1129
2516
  /** What orders the classes of a page: a props class is right after its base class (its `after`), the rest by name. */
@@ -1132,11 +2519,15 @@ function createCache(options = {}) {
1132
2519
  const readNames = (id) => themeNames.get(id);
1133
2520
  /** The rules that the cache wrote under `id`, a class or a theme class it made. */
1134
2521
  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) => {
2522
+ /** The variables a page needs declared: those its rules (of classes, and `@keyframes` and global rules) refer to, those marked from outside, and what the values of the themes in play refer to. */
2523
+ const collectPageVariables = (classIds, themeIds, otherRules) => {
1137
2524
  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);
2525
+ const addVariables = (rule) => {
2526
+ for (const name of scanVariables(rule, VARIABLE_START)) names.add(name);
2527
+ };
2528
+ for (const id of classIds) readRules(id).forEach(addVariables);
2529
+ otherRules.forEach(addVariables);
2530
+ addThemeReferences(names, themeIds, (id) => themes.get(id)?.declarations ?? roots.get(id)?.declarations);
1140
2531
  return names;
1141
2532
  };
1142
2533
  /** The rule of a theme class for a page: with pruning, only the variables in `names`, and its color-scheme. */
@@ -1146,31 +2537,62 @@ function createCache(options = {}) {
1146
2537
  const body = toDeclarationText(Object.keys(entry.declarations).filter((name) => names.has(name)).map((name) => [name, entry.declarations[name]])) + entry.schemeText;
1147
2538
  return body === "" ? [] : wrapInLayer([`.${id}{${body}}`], "theme");
1148
2539
  };
1149
- const extractPage = (classNames, pageOptions = {}) => {
1150
- const { themes: offered = [], carried = /* @__PURE__ */ new Set() } = pageOptions;
2540
+ const extractPageParts = (classNames, pageOptions = {}) => {
2541
+ const { themes: offered = [], animations: named = [], carried = /* @__PURE__ */ new Set(), rendered = /* @__PURE__ */ new Set() } = pageOptions;
1151
2542
  const wanted = /* @__PURE__ */ new Set([...classNames, ...offered]);
1152
2543
  const themeIds = [...wanted].filter((name) => themeNames.has(name)).sort(compareCodeUnits);
1153
2544
  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);
2545
+ const held = [...globals].filter(([id, entry]) => entry.appCount > 0 || rendered.has(id) || carried.has(id));
2546
+ const pageAnimations = [...classIds.flatMap((id) => animations.get(id) ?? []), ...held.flatMap(([, entry]) => entry.animations)];
2547
+ const keyframesRules = [.../* @__PURE__ */ new Set([...pageAnimations, ...named])].filter((name) => isKeyframesName(name) && !carried.has(name)).sort(compareCodeUnits).map(readKeyframesRule);
2548
+ const allGlobalRules = held.flatMap(([, entry]) => entry.rules);
2549
+ const rootIds = root === void 0 ? [] : [root.id];
2550
+ const allThemeIds = [...rootIds, ...themeIds];
2551
+ const names = hasPruning ? collectPageVariables(classIds, allThemeIds, [...keyframesRules, ...allGlobalRules]) : /* @__PURE__ */ new Set();
2552
+ const covered = new Set(allThemeIds.filter((id) => carried.has(id)).flatMap(readNames));
2553
+ const declared = hasPruning ? names : allThemeIds.flatMap(readNames);
1157
2554
  const properties = [...new Set(declared)].filter((name) => propertyRules[name] !== void 0 && !covered.has(name)).sort(compareCodeUnits);
2555
+ const newRoots = rootIds.filter((id) => !carried.has(id));
1158
2556
  const newThemes = themeIds.filter((id) => !carried.has(id));
2557
+ const newGlobals = held.filter(([id]) => !carried.has(id));
1159
2558
  const newClasses = classIds.filter((id) => !carried.has(id));
1160
- const themeRules = newThemes.flatMap((id) => createPageThemeRules(id, names));
2559
+ const themeRules = [...newRoots.flatMap((id) => {
2560
+ const theme = roots.get(id);
2561
+ const all = Object.keys(theme.declarations);
2562
+ return createRootRules(theme, hasPruning ? all.filter((name) => names.has(name)) : all);
2563
+ }), ...newThemes.flatMap((id) => createPageThemeRules(id, names))];
2564
+ const globalRules = newGlobals.flatMap(([, entry]) => entry.rules);
1161
2565
  const classRules = newClasses.flatMap(readRules);
1162
- const hasLayered = themeRules.length + classRules.length > 0;
2566
+ const hasLayered = themeRules.length + globalRules.length + classRules.length > 0;
1163
2567
  return {
1164
- css: [
1165
- hasLayers && hasLayered ? layerOrder : "",
1166
- ...properties.map((name) => propertyRules[name]),
1167
- ...themeRules,
1168
- ...classRules
1169
- ].join(""),
1170
- ids: [...newThemes, ...newClasses]
2568
+ global: {
2569
+ css: [
2570
+ hasLayers && hasLayered ? layerOrder : "",
2571
+ ...properties.map((name) => propertyRules[name]),
2572
+ ...keyframesRules,
2573
+ ...themeRules,
2574
+ ...globalRules
2575
+ ].join(""),
2576
+ ids: [
2577
+ ...newRoots,
2578
+ ...newThemes,
2579
+ ...newGlobals.map(([id]) => id)
2580
+ ]
2581
+ },
2582
+ classes: {
2583
+ css: classRules.join(""),
2584
+ ids: newClasses
2585
+ }
1171
2586
  };
1172
2587
  };
1173
- return {
2588
+ const extractPage = (classNames, pageOptions) => {
2589
+ const { global, classes } = extractPageParts(classNames, pageOptions);
2590
+ return {
2591
+ css: global.css + classes.css,
2592
+ ids: [...global.ids, ...classes.ids]
2593
+ };
2594
+ };
2595
+ const self = {
1174
2596
  prefix,
1175
2597
  hasLayers,
1176
2598
  layerOrder,
@@ -1178,8 +2600,10 @@ function createCache(options = {}) {
1178
2600
  css: (...values) => cssIn("components", ...values),
1179
2601
  cssIn,
1180
2602
  cssWith,
2603
+ cssHeld,
1181
2604
  createEntry,
1182
2605
  findEntry: (className) => entries.get(className),
2606
+ adoptEntry,
1183
2607
  hasBaseClass,
1184
2608
  hasScope,
1185
2609
  hasPruning,
@@ -1190,142 +2614,32 @@ function createCache(options = {}) {
1190
2614
  markUsed(list);
1191
2615
  },
1192
2616
  insertTheme,
2617
+ insertRoot,
1193
2618
  registerProperties,
2619
+ setKeyframesTheme: (read) => {
2620
+ readKeyframesTheme = read;
2621
+ },
2622
+ insertKeyframes,
2623
+ getAnimations: (className) => animations.get(className) ?? [],
2624
+ compileGlobal,
2625
+ insertGlobal,
1194
2626
  insertOnce,
1195
2627
  getRules: (id) => insertedRules.get(id) ?? [],
1196
2628
  getFullRules,
1197
2629
  extract: () => ({
1198
2630
  css: sheet.rules.join(""),
1199
- ids: [...insertedIds, ...used]
2631
+ ids: [
2632
+ ...insertedIds,
2633
+ ...globals.keys(),
2634
+ ...used
2635
+ ]
1200
2636
  }),
1201
2637
  extractPage,
2638
+ extractPageParts,
1202
2639
  fingerprint
1203
2640
  };
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, "*");
2641
+ if (sheet.document) registerCache(sheet.document, self);
2642
+ return self;
1329
2643
  }
1330
2644
  // src/lazyRecord.ts
1331
2645
  /**
@@ -1363,6 +2677,34 @@ function createDeferredRecord(source, build) {
1363
2677
  return built[key];
1364
2678
  });
1365
2679
  }
2680
+ /**
2681
+ * An object that stands for the one `make` returns, which is made the first time the object is used in
2682
+ * any way (a property read, `in`, a listing of its keys, a check of whether it is frozen): from then on it
2683
+ * has the same properties, and is frozen as that one is. When `make` throws, the next use tries again. For a value that a module makes before the
2684
+ * engine it needs may exist, such as a `css()` result of a default style before `configure` is called.
2685
+ */
2686
+ function createDeferredObject(make) {
2687
+ const target = {};
2688
+ let isMade = false;
2689
+ const ensure = () => {
2690
+ if (!isMade) {
2691
+ const made = make();
2692
+ isMade = true;
2693
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(made));
2694
+ Object.setPrototypeOf(target, Object.getPrototypeOf(made));
2695
+ if (Object.isFrozen(made)) Object.freeze(target);
2696
+ }
2697
+ return target;
2698
+ };
2699
+ return new Proxy(target, {
2700
+ get: (_target, key) => Reflect.get(ensure(), key),
2701
+ has: (_target, key) => Reflect.has(ensure(), key),
2702
+ ownKeys: () => Reflect.ownKeys(ensure()),
2703
+ getOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(ensure(), key),
2704
+ getPrototypeOf: () => Reflect.getPrototypeOf(ensure()),
2705
+ isExtensible: () => Reflect.isExtensible(ensure())
2706
+ });
2707
+ }
1366
2708
  // src/styleBase.ts
1367
2709
  /** Whether `style` is a function style. */
1368
2710
  function isStyleFunction(style) {
@@ -1435,6 +2777,35 @@ function splitLeading(list, props, view) {
1435
2777
  propsFrom
1436
2778
  };
1437
2779
  }
2780
+ // src/sameView.ts
2781
+ /** Whether `value` is an array, or an object made by a literal. */
2782
+ function isContainer(value) {
2783
+ if (typeof value !== "object" || value === null) return false;
2784
+ const prototype = Object.getPrototypeOf(value);
2785
+ return prototype === Object.prototype || prototype === null || Array.isArray(value);
2786
+ }
2787
+ /** Whether two descriptors hold the same: equal values, or the same accessors. */
2788
+ function isSameDescriptor(first, second) {
2789
+ if ("value" in first) return "value" in second && isSameView(first.value, second.value);
2790
+ return first.get === second.get && first.set === second.set;
2791
+ }
2792
+ /**
2793
+ * Whether two theme views hold the same thing: arrays and plain objects with the same own members
2794
+ * (enumerable or not), each the same, and anything else the same value (a function, a class instance,
2795
+ * by identity). Two views of themes that differ only in the values of their variables are the same.
2796
+ */
2797
+ function isSameView(first, second) {
2798
+ if (first === second) return true;
2799
+ if (!isContainer(first) || !isContainer(second)) return false;
2800
+ if (Object.getPrototypeOf(first) !== Object.getPrototypeOf(second)) return false;
2801
+ const keys = Reflect.ownKeys(first);
2802
+ if (keys.length !== Reflect.ownKeys(second).length) return false;
2803
+ return keys.every((key) => {
2804
+ const other = Object.getOwnPropertyDescriptor(second, key);
2805
+ const own = Object.getOwnPropertyDescriptor(first, key);
2806
+ return other !== void 0 && isSameDescriptor(own, other);
2807
+ });
2808
+ }
1438
2809
  // src/registered.ts
1439
2810
  const SYNTAXES = [
1440
2811
  "<color>",
@@ -1641,12 +3012,18 @@ function createTokens(theme, options = {}) {
1641
3012
  function isThemedSheet(sheet) {
1642
3013
  return typeof sheet.resolve === "function";
1643
3014
  }
3015
+ /** How many recent views a new view is compared with. */
3016
+ const RECENT_VIEWS = 8;
1644
3017
  /** What is thrown when something needs the shape of the theme before any theme is known. */
1645
3018
  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
3019
  /** `text` in kebab-case: ButtonBase gives button-base. */
1647
3020
  function toKebabCase(text) {
1648
3021
  return text.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
1649
3022
  }
3023
+ /** Whether `value`, given to a styled component from outside, is a plain style object: not a sheet entry, not a class name. */
3024
+ function isPlainStyle(value) {
3025
+ return typeof value === "object" && value !== null && !isSheetEntry(value);
3026
+ }
1650
3027
  /** The label of a styled component: `name-slot`, or '' without a name. */
1651
3028
  function createLabel({ name, slot = "root" }) {
1652
3029
  return name ? `${toKebabCase(name)}-${toKebabCase(slot)}` : "";
@@ -1657,8 +3034,15 @@ function createTokenSignature(values) {
1657
3034
  }
1658
3035
  /** Makes an engine that has no theme yet: it takes one from `setTheme`, or from the first `themeClass`. It needs no framework. */
1659
3036
  function createLazyEngine(options = {}) {
3037
+ return createFamilyEngine(options, {
3038
+ theme: void 0,
3039
+ engines: /* @__PURE__ */ new WeakMap()
3040
+ });
3041
+ }
3042
+ /** Makes an engine of `family`: its cache is the one in `options` or a new one; its base theme is the family's. */
3043
+ function createFamilyEngine(options, family) {
1660
3044
  const { cache: given, suffix, hasLabels, hasLayers, hasPruning, hasColorFallbacks } = options;
1661
- const { hasScope, hasBaseClass, hasDevChecks } = options;
3045
+ const { hasScope, hasBaseClass, hasDevChecks, hasValueRepair } = options;
1662
3046
  const { alwaysDeclare = [] } = options;
1663
3047
  const { rawKeys, lengthKeys, modes, registered } = options;
1664
3048
  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.`);
@@ -1670,6 +3054,7 @@ function createLazyEngine(options = {}) {
1670
3054
  hasLayers,
1671
3055
  hasPruning,
1672
3056
  hasColorFallbacks,
3057
+ hasValueRepair,
1673
3058
  hasScope,
1674
3059
  hasBaseClass,
1675
3060
  hasDevChecks,
@@ -1688,34 +3073,50 @@ function createLazyEngine(options = {}) {
1688
3073
  modes,
1689
3074
  registered
1690
3075
  };
1691
- let baseTheme;
3076
+ let tokensTheme;
1692
3077
  let tokens;
1693
3078
  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;
3079
+ /** Makes the tokens of the base theme of the family, when they were made from another one or not yet. */
3080
+ const sync = () => {
3081
+ const theme = family.theme;
3082
+ if (theme === tokensTheme) return;
3083
+ tokensTheme = theme;
1701
3084
  tokens = createTokens(theme, tokenOptions);
1702
3085
  views = /* @__PURE__ */ new WeakMap();
3086
+ recentViews = [];
1703
3087
  cache.registerProperties(tokens.registrations);
1704
3088
  cache.markUsed(tokens.findNames(alwaysDeclare));
1705
3089
  version++;
1706
3090
  };
3091
+ const readTokens = () => {
3092
+ sync();
3093
+ if (!tokens) throw new Error(NO_THEME_MESSAGE);
3094
+ return tokens;
3095
+ };
3096
+ cache.setKeyframesTheme(() => readTokens().refs);
3097
+ const setTheme = (theme) => {
3098
+ family.theme = theme;
3099
+ sync();
3100
+ };
1707
3101
  let views = /* @__PURE__ */ new WeakMap();
3102
+ let recentViews = [];
1708
3103
  const createThemeView = (realTheme) => {
3104
+ sync();
1709
3105
  let view = views.get(realTheme);
1710
3106
  if (view === void 0) {
1711
- view = (tokens ?? createTokens(realTheme, tokenOptions)).createView(realTheme);
3107
+ const made = (tokens ?? createTokens(realTheme, tokenOptions)).createView(realTheme);
3108
+ view = recentViews.find((recent) => isSameView(recent, made));
3109
+ if (view === void 0) {
3110
+ view = made;
3111
+ recentViews = [made, ...recentViews].slice(0, RECENT_VIEWS);
3112
+ }
1712
3113
  views.set(realTheme, view);
1713
3114
  }
1714
3115
  return view;
1715
3116
  };
1716
3117
  const themeClasses = /* @__PURE__ */ new WeakMap();
1717
3118
  const themeId = (partial, colorScheme) => {
1718
- if (!tokens) setTheme(partial);
3119
+ if (family.theme === void 0) setTheme(partial);
1719
3120
  const key = colorScheme ?? "";
1720
3121
  const known = themeClasses.get(partial) ?? /* @__PURE__ */ new Map();
1721
3122
  themeClasses.set(partial, known);
@@ -1726,6 +3127,39 @@ function createLazyEngine(options = {}) {
1726
3127
  }
1727
3128
  return className;
1728
3129
  };
3130
+ const roots = /* @__PURE__ */ new WeakMap();
3131
+ const declareRoot = (theme, colorScheme) => {
3132
+ if (family.theme === void 0) setTheme(theme);
3133
+ const key = colorScheme ?? "";
3134
+ const known = roots.get(theme) ?? /* @__PURE__ */ new Map();
3135
+ roots.set(theme, known);
3136
+ let made = known.get(key);
3137
+ if (made === void 0) {
3138
+ const declarations = readTokens().declare(theme);
3139
+ made = [declareRootTheme(cache, declarations, { colorScheme }), declarations];
3140
+ known.set(key, made);
3141
+ }
3142
+ const [id, declarations] = made;
3143
+ cache.insertRoot(id, declarations, colorScheme);
3144
+ return id;
3145
+ };
3146
+ const themeTexts = /* @__PURE__ */ new WeakMap();
3147
+ const readThemeText = (partial) => {
3148
+ sync();
3149
+ let text = themeTexts.get(partial);
3150
+ if (text === void 0) {
3151
+ const { declare, registrations } = tokens ?? createTokens(partial, tokenOptions);
3152
+ const declarations = declare(partial);
3153
+ const names = Object.keys(declarations);
3154
+ text = {
3155
+ declarations: toDeclarationText(Object.entries(declarations)),
3156
+ properties: names.map((name) => registrations[name] ?? "").join(""),
3157
+ names
3158
+ };
3159
+ if (tokens) themeTexts.set(partial, text);
3160
+ }
3161
+ return text;
3162
+ };
1729
3163
  const findThemeIds = (partial) => [...themeClasses.get(partial)?.values() ?? []];
1730
3164
  const themeClass = (partial, colorScheme) => createThemeClassName(cache.prefix, themeId(partial, colorScheme), colorScheme);
1731
3165
  const when = (partial, colorScheme) => createThemeKey(themeId(partial, colorScheme));
@@ -1749,8 +3183,9 @@ function createLazyEngine(options = {}) {
1749
3183
  }
1750
3184
  return entries;
1751
3185
  }
3186
+ const { refs } = readTokens();
1752
3187
  if (baseEntries === void 0 || madeAt !== version) {
1753
- baseEntries = createEntries(styles(readTokens().refs));
3188
+ baseEntries = createEntries(styles(refs));
1754
3189
  madeAt = version;
1755
3190
  }
1756
3191
  return baseEntries;
@@ -1809,45 +3244,97 @@ function createLazyEngine(options = {}) {
1809
3244
  };
1810
3245
  /** 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
3246
  const getMerged = (props, theme, extras) => cache.css(...resolveAll(list, props, theme), ...extras);
3247
+ const getClassName = (props, extra, theme) => {
3248
+ const extras = Array.isArray(extra) ? extra : [extra];
3249
+ const hasExtras = extras.some(Boolean);
3250
+ if (hasExtras && !cache.hasLayers) return getMerged(props, theme, extras);
3251
+ const own = getOwn(getPlan(props, theme), props, theme);
3252
+ if (!hasExtras) return own;
3253
+ return [own, cache.cssWith({
3254
+ layer: "overrides",
3255
+ label: label || void 0
3256
+ }, ...extras)].filter(Boolean).join(" ");
3257
+ };
1812
3258
  return {
1813
3259
  styles: list,
1814
3260
  isDynamic: hasFunction,
1815
- getClassName(props, extra, theme) {
3261
+ getClassName,
3262
+ getHeldClass(props, extra, theme) {
1816
3263
  const extras = Array.isArray(extra) ? extra : [extra];
1817
- const hasExtras = extras.some(Boolean);
1818
- if (hasExtras && !cache.hasLayers) return getMerged(props, theme, extras);
3264
+ if (!extras.some(isPlainStyle)) return {
3265
+ className: getClassName(props, extras, theme),
3266
+ hold: void 0
3267
+ };
3268
+ if (!cache.hasLayers) return cache.cssHeld({}, ...resolveAll(list, props, theme), ...extras);
1819
3269
  const own = getOwn(getPlan(props, theme), props, theme);
1820
- if (!hasExtras) return own;
1821
- return [own, cache.cssWith({
3270
+ const overrides = cache.cssHeld({
1822
3271
  layer: "overrides",
1823
3272
  label: label || void 0
1824
- }, ...extras)].filter(Boolean).join(" ");
3273
+ }, ...extras);
3274
+ return {
3275
+ className: [own, overrides.className].filter(Boolean).join(" "),
3276
+ hold: overrides.hold
3277
+ };
1825
3278
  }
1826
3279
  };
1827
3280
  };
1828
- return {
3281
+ const resolveGlobal = (input, theme) => {
3282
+ const readTheme = () => theme ?? readTokens().refs;
3283
+ return (Array.isArray(input) ? input : [input]).map((item) => cache.compileGlobal(readGlobalStyles(item, readTheme)));
3284
+ };
3285
+ const insertGlobal = (input, theme) => {
3286
+ const releases = resolveGlobal(input, theme).map((set) => cache.insertGlobal(set));
3287
+ return () => {
3288
+ for (const release of releases) release();
3289
+ };
3290
+ };
3291
+ const adoptedSheets = /* @__PURE__ */ new WeakMap();
3292
+ const adoptSheet = (entries) => {
3293
+ let adopted = adoptedSheets.get(entries);
3294
+ if (adopted === void 0) {
3295
+ adopted = createLazyRecord(Object.keys(entries), (key) => cache.adoptEntry(entries[key]));
3296
+ adoptedSheets.set(entries, adopted);
3297
+ }
3298
+ return adopted;
3299
+ };
3300
+ const engine = {
1829
3301
  cache,
1830
3302
  css: cache.css,
3303
+ resolveGlobal,
3304
+ insertGlobal,
1831
3305
  get hasTheme() {
1832
- return baseTheme !== void 0;
3306
+ return family.theme !== void 0;
1833
3307
  },
1834
3308
  get baseTheme() {
1835
- return baseTheme;
3309
+ return family.theme;
1836
3310
  },
1837
3311
  get refs() {
1838
3312
  return readTokens().refs;
1839
3313
  },
3314
+ tokenOptions,
1840
3315
  scopeClass,
3316
+ keyframes,
3317
+ insertKeyframes: cache.insertKeyframes,
1841
3318
  setTheme,
1842
3319
  createThemeView,
1843
3320
  themeClass,
1844
3321
  themeId,
1845
3322
  findThemeIds,
3323
+ declareRoot,
3324
+ readThemeText,
1846
3325
  when,
1847
3326
  whenScheme: createSchemeKey,
1848
3327
  createSheet,
1849
- createStyler
3328
+ createStyler,
3329
+ withCache: (other) => family.engines.get(other) ?? createFamilyEngine({
3330
+ ...options,
3331
+ prefix: void 0,
3332
+ cache: other
3333
+ }, family),
3334
+ adoptSheet
1850
3335
  };
3336
+ family.engines.set(cache, engine);
3337
+ return engine;
1851
3338
  }
1852
3339
  /** Makes the engine of one theme shape: a cache, the theme as variables, and what the bindings build on. It needs no framework. */
1853
3340
  function createEngine(theme, options = {}) {
@@ -1855,7 +3342,91 @@ function createEngine(theme, options = {}) {
1855
3342
  engine.setTheme(theme);
1856
3343
  return engine;
1857
3344
  }
3345
+ // src/css.ts
3346
+ /** Whether `value`, or an item of a list in it, is a function. */
3347
+ function hasFunction(value) {
3348
+ return typeof value === "function" || Array.isArray(value) && value.some(hasFunction);
3349
+ }
3350
+ /**
3351
+ * The style of `args` when they are a tagged template (`caller` was used as a tag), read as CSS text;
3352
+ * undefined when they are not. `caller` has no props, so a function among the interpolations is a
3353
+ * `TypeError` that names it.
3354
+ */
3355
+ function readStaticTemplate(args, caller) {
3356
+ const [first, ...values] = args;
3357
+ if (!isTemplateStrings(first)) return void 0;
3358
+ const parsed = parseStyleTemplate(first, values);
3359
+ if (typeof parsed === "function") throw new TypeError(`${caller}(): an interpolation of this template is a function, which needs props, and ${caller}() has none. Use the template with styled, or call the function yourself and interpolate what it returns.`);
3360
+ return parsed;
3361
+ }
3362
+ /**
3363
+ * Throws a `TypeError` that names `caller` when an argument, or an item of a list among them, is a
3364
+ * function: `caller` has no props to call it with.
3365
+ */
3366
+ function rejectFunctions(args, caller) {
3367
+ if (args.some(hasFunction)) throw new TypeError(`${caller}(): a function is not a style here, because ${caller}() has no props. Give it to styled, or call it yourself and pass what it returns.`);
3368
+ }
3369
+ /**
3370
+ * The style of the arguments of `css()`: a tagged template read as CSS text, or style objects, `css()`
3371
+ * results and sheet entries, with lists flattened and `false`, `null` and `undefined` dropped, merged in
3372
+ * order, the last winning. An entry that a framework merged into an object is found with `findEntry`.
3373
+ * Throws a `TypeError` for a function, for a string, and for an entry that is only a class name.
3374
+ */
3375
+ function readCssStyle(args, findEntry) {
3376
+ const template = readStaticTemplate(args, "css");
3377
+ if (template) return template;
3378
+ rejectFunctions(args, "css");
3379
+ return mergeStyles(flattenStyle(args, findEntry).map((item) => readEntryStyle(item, "css")));
3380
+ }
3381
+ /**
3382
+ * `css()` of a web binding over `cache`: one sheet entry of the merged style (see `readCssStyle`). Its
3383
+ * class name is worked out now and its rule is written when the entry is first used, as an entry of a
3384
+ * sheet; equal styles give the same class.
3385
+ */
3386
+ function createCssEntry(cache, args) {
3387
+ return cache.createEntry(readCssStyle(args, cache.findEntry));
3388
+ }
3389
+ /**
3390
+ * The styles of a call of the function that `styled(tag)` returns: as a tag, the template is one style
3391
+ * (an object, or a function of the props when an interpolation is a function); else the styles given,
3392
+ * with lists flattened.
3393
+ */
3394
+ function readStyleArguments(args) {
3395
+ const [first, ...values] = args;
3396
+ if (isTemplateStrings(first)) return [parseStyleTemplate(first, values)];
3397
+ return args.flat(1e400);
3398
+ }
3399
+ /**
3400
+ * The `toString` of a styled component, which makes it a selector in a template or a key
3401
+ * (`${Button}:hover &`): `.` and a class that every element of the component has. That is the
3402
+ * component's own `target` when it was given one (each class of it, when it holds several); else, when none of its styles is a function, its class
3403
+ * (the base class, the same for every element); else there is none, and it throws a `TypeError` that says
3404
+ * to give the component a `target`.
3405
+ */
3406
+ function createComponentSelector(target, styler) {
3407
+ return () => {
3408
+ if (target) return `.${target.trim().replaceAll(/\s+/g, ".")}`;
3409
+ const className = styler.isDynamic ? "" : styler.getClassName({});
3410
+ if (className === "") throw new TypeError("A styled component used as a selector needs a class that every element of it has: give it a `target` (styled(tag, { target: \"my-button\" })), or write its styles without functions.");
3411
+ return `.${className}`;
3412
+ };
3413
+ }
1858
3414
  // src/scanHtml.ts
3415
+ /** The end of the name of a marker of global rules: `<prefix>-global`. */
3416
+ const MARKER_END = "-global";
3417
+ /**
3418
+ * The marker by which a `Global` that renders no style element names its sets in the markup of a server
3419
+ * render, so that `extractPageStyles` puts them in that page only: the sets that have rules, by id. None
3420
+ * when no set has a rule. A binding renders it as `<meta name="<name>" content="<ids>">` (React) or as a
3421
+ * comment `<!--<name> <ids>-->` (Vue).
3422
+ */
3423
+ function createGlobalMarker(prefix, sets) {
3424
+ const ids = sets.filter(({ rules }) => rules.length > 0).map(({ id }) => id);
3425
+ return ids.length === 0 ? void 0 : {
3426
+ name: `${prefix}${MARKER_END}`,
3427
+ ids: ids.join(" ")
3428
+ };
3429
+ }
1859
3430
  /** The elements whose content is text, not markup: nothing in them is an attribute. */
1860
3431
  const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set([
1861
3432
  "script",
@@ -1903,62 +3474,89 @@ function readValue(html, index) {
1903
3474
  end
1904
3475
  };
1905
3476
  }
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) {
3477
+ /** Adds the ids that a marker names to `found`: the tokens of `content` when `name` is that of a marker. */
3478
+ function addMarked(found, name, content) {
3479
+ if (name.endsWith(MARKER_END)) addTokens(found.rendered, content);
3480
+ }
3481
+ /** Adds what the attribute `name` with `value` says to `found`, or keeps it in `meta`. */
3482
+ function addAttribute(found, meta, name, value) {
3483
+ if (name === "class" || name === "classname") addTokens(found.classes, value);
3484
+ else if (name === "data-href") addTokens(found.carried, value);
3485
+ else if (name === "name") meta.name = value;
3486
+ else if (name === "content") meta.content = value;
3487
+ }
3488
+ /** Reads the attribute that starts at `index`, adds what matters to `found` or `meta`, and returns the index after it. */
3489
+ function readAttribute(html, index, found, meta) {
3490
+ let position = readNameEnd(html, index);
3491
+ if (position === index) position++;
3492
+ const name = html.slice(index, position).toLowerCase();
3493
+ position = skipSpaces(html, position);
3494
+ if (html[position] !== "=") return position;
3495
+ const { value, end } = readValue(html, skipSpaces(html, position + 1));
3496
+ addAttribute(found, meta, name, value);
3497
+ return end;
3498
+ }
3499
+ /** Reads the attributes of the tag whose name ended at `index`, adds what matters to `found`, and returns the index after the `>`. A `<meta>` (`isMeta`) is read for the marker of global rules too. */
3500
+ function readAttributes(html, index, found, isMeta) {
3501
+ const meta = {
3502
+ name: "",
3503
+ content: ""
3504
+ };
1908
3505
  let position = index;
1909
3506
  while (position < html.length) {
1910
3507
  const code = codeAt(html, position);
1911
- if (code === 62) return position + 1;
1912
- if (isSpace(code) || code === 47) {
1913
- position++;
1914
- continue;
3508
+ if (code === 62) {
3509
+ if (isMeta) addMarked(found, meta.name, meta.content);
3510
+ return position + 1;
1915
3511
  }
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);
3512
+ position = isSpace(code) || code === 47 ? position + 1 : readAttribute(html, position, found, meta);
1926
3513
  }
1927
3514
  return html.length;
1928
3515
  }
3516
+ /** Reads the comment whose text starts at `start` and ends at `end`: a marker of global rules adds the ids it names to `found`. */
3517
+ function readComment(html, start, end, found) {
3518
+ if (!isLetter(codeAt(html, start))) return;
3519
+ const text = html.slice(start, end);
3520
+ const space = text.indexOf(" ");
3521
+ if (space !== -1) addMarked(found, text.slice(0, space), text.slice(space + 1));
3522
+ }
1929
3523
  /** The index of the `</name` that closes a raw text element, or the end of the document. */
1930
3524
  function findClosingTag(html, index, name) {
1931
3525
  let at = html.indexOf("</", index);
1932
3526
  while (at !== -1 && html.slice(at + 2, at + 2 + name.length).toLowerCase() !== name) at = html.indexOf("</", at + 2);
1933
3527
  return at === -1 ? html.length : at;
1934
3528
  }
1935
- /** The index of the end of the tag name that starts at `index`. */
1936
- function readTagNameEnd(html, index) {
3529
+ /** The index of the end of the name (of a tag or an attribute) that starts at `index`. */
3530
+ function readNameEnd(html, index) {
1937
3531
  let end = index;
1938
3532
  while (end < html.length && !isNameEnd(codeAt(html, end))) end++;
1939
3533
  return end;
1940
3534
  }
1941
3535
  /**
1942
3536
  * 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.
3537
+ * the markup, with the keys of the style elements it carries (`data-href`) and the ids that the markers
3538
+ * of `Global` name. Comments other than a marker and the content of `script`, `style`, `textarea` and
3539
+ * `title` are skipped, so a class name inside a script or a text is not taken for a class. Quoted and
3540
+ * bare values are read; a class name in any other attribute is not looked at. The pass moves forward
3541
+ * only: its time is linear in the length of the document, and there is no pattern to backtrack.
1947
3542
  */
1948
3543
  function scanHtml(html) {
1949
3544
  const found = {
1950
3545
  classes: /* @__PURE__ */ new Set(),
1951
- carried: /* @__PURE__ */ new Set()
3546
+ carried: /* @__PURE__ */ new Set(),
3547
+ rendered: /* @__PURE__ */ new Set()
1952
3548
  };
1953
3549
  let at = html.indexOf("<");
1954
3550
  while (at !== -1) {
1955
3551
  if (html.startsWith("<!--", at)) {
1956
3552
  const close = html.indexOf("-->", at + 4);
1957
- at = close === -1 ? html.length : close + 3;
3553
+ const end = close === -1 ? html.length : close;
3554
+ readComment(html, at + 4, end, found);
3555
+ at = end + 3;
1958
3556
  } else if (isLetter(codeAt(html, at + 1))) {
1959
- const nameEnd = readTagNameEnd(html, at + 1);
3557
+ const nameEnd = readNameEnd(html, at + 1);
1960
3558
  const name = html.slice(at + 1, nameEnd).toLowerCase();
1961
- at = readAttributes(html, nameEnd, found);
3559
+ at = readAttributes(html, nameEnd, found, name === "meta");
1962
3560
  if (RAW_TEXT_ELEMENTS.has(name)) at = findClosingTag(html, at, name);
1963
3561
  } else at++;
1964
3562
  at = html.indexOf("<", at);
@@ -1983,19 +3581,17 @@ function createStyleTag(cache) {
1983
3581
  /**
1984
3582
  * The CSS of one page, decided from the page: the finished `html` is scanned for the class names it
1985
3583
  * 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
3584
+ * attributes are not looked at), and only those classes are written, with the `@keyframes` rules they
3585
+ * use and the theme classes trimmed to the variables that the page uses. Nothing depends on what else the cache holds, on the
1988
3586
  * order pages were rendered in, or on pages being rendered at the same time, and the cache is not changed.
1989
3587
  * The `<style href precedence>` elements that `html` carries already (React's server render of the
1990
- * client build emits them) are not written again.
3588
+ * client build emits them) are not written again. The global rules are those inserted for the app
3589
+ * (`engine.insertGlobal`), which are in every page, and those of the `Global` components that `html`
3590
+ * rendered: a style element it carries, or a marker that names the set (a `<meta name="<prefix>-global">`
3591
+ * of React, a comment `<!--<prefix>-global ...-->` of Vue). A set that another page rendered is not.
1991
3592
  */
1992
3593
  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
- });
3594
+ const { css, ids } = cache.extractPage(...readPage(html, options));
1999
3595
  return {
2000
3596
  css,
2001
3597
  ids,
@@ -2003,6 +3599,24 @@ function extractPageStyles(cache, html, options = {}) {
2003
3599
  tag: createTag(cache, css)
2004
3600
  };
2005
3601
  }
3602
+ /** The class names of `html`, and what `extractPage` is told besides them. */
3603
+ function readPage(html, options) {
3604
+ const { classes, carried, rendered } = scanHtml(html);
3605
+ return [classes, {
3606
+ themes: (options.themes ?? []).flatMap((value) => value.split(/\s+/)),
3607
+ animations: options.animations,
3608
+ carried,
3609
+ rendered
3610
+ }];
3611
+ }
3612
+ /**
3613
+ * `extractPageStyles` in two parts, decided from `html` the same way: the rules that no class stands for
3614
+ * (the layer order, the `@property` and `@keyframes` rules, the theme classes, the global rules) and the
3615
+ * rules of the classes. The two CSS texts joined in this order are the CSS of `extractPageStyles`.
3616
+ */
3617
+ function extractPageStyleParts(cache, html, options = {}) {
3618
+ return cache.extractPageParts(...readPage(html, options));
3619
+ }
2006
3620
  // src/mergeDeep.ts
2007
3621
  /** Whether `value` is an object made by a literal, not a class instance. */
2008
3622
  function isPlainObject(value) {
@@ -2010,16 +3624,54 @@ function isPlainObject(value) {
2010
3624
  const prototype = Object.getPrototypeOf(value);
2011
3625
  return prototype === Object.prototype || prototype === null;
2012
3626
  }
2013
- /** `override` over `base`: plain objects merge key by key, everything else is replaced, undefined keeps `base`. */
3627
+ /**
3628
+ * `override` over `base`: plain objects merge key by key, everything else is replaced, undefined keeps
3629
+ * `base`. Every own member is taken with its descriptor, so a member that is not enumerable (a helper
3630
+ * function on `breakpoints`) is kept, from `override` when it has one, else from `base`.
3631
+ */
2014
3632
  function mergeDeep(base, override) {
2015
3633
  if (override === void 0) return base;
2016
3634
  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;
3635
+ const descriptors = Object.getOwnPropertyDescriptors(base);
3636
+ const given = Object.getOwnPropertyDescriptors(override);
3637
+ for (const key of Reflect.ownKeys(given)) {
3638
+ const descriptor = given[key];
3639
+ descriptors[key] = "value" in descriptor ? {
3640
+ ...descriptor,
3641
+ value: mergeDeep(base[key], descriptor.value)
3642
+ } : descriptor;
3643
+ }
3644
+ return Object.create(Object.getPrototypeOf(base), descriptors);
3645
+ }
3646
+ // src/tagShorthands.ts
3647
+ /** What a shorthand can be: a tag name, a lowercase letter then letters and digits (`div`, `h1`, `foreignObject`). */
3648
+ const TAG_PATTERN = /^[a-z][a-zA-Z0-9]*$/;
3649
+ /**
3650
+ * `styled` with a shorthand for every tag: `styled.div(...styles)` is `styled('div')(...styles)`. Nothing
3651
+ * is made up front: a member that the function does not have and that looks like a tag name is made when
3652
+ * it is read. `then` is not a tag, so that `styled` is never taken for a promise.
3653
+ */
3654
+ function withTagShorthands(styled) {
3655
+ return new Proxy(styled, { get(target, key, receiver) {
3656
+ if (typeof key !== "string" || key in target || key === "then" || !TAG_PATTERN.test(key)) return Reflect.get(target, key, receiver);
3657
+ return target(key);
3658
+ } });
3659
+ }
3660
+ // src/themeInput.ts
3661
+ /** The theme where there is no provider and no base theme: an object with nothing in it, never changed. */
3662
+ const EMPTY_THEME = Object.freeze({});
3663
+ /** The theme that a provider given `input` adds below `outer` (the theme above it, or `EMPTY_THEME`): the result of a function, or the object as it is. */
3664
+ function resolveThemeInput(input, outer) {
3665
+ return typeof input === "function" ? input(outer) : input;
3666
+ }
3667
+ /** The theme below a provider: `given` merged over the theme above it, or `given` as it is where there is none above and no base theme. */
3668
+ function mergeTheme(outer, given) {
3669
+ return outer === void 0 ? given : mergeDeep(outer, given);
2020
3670
  }
2021
3671
  exports.DEFAULT_SCOPING = DEFAULT_SCOPING;
3672
+ exports.EMPTY_THEME = EMPTY_THEME;
2022
3673
  exports.NO_THEME_MESSAGE = NO_THEME_MESSAGE;
3674
+ exports.ROOT_SELECTOR = ROOT_SELECTOR;
2023
3675
  exports.RULE_LAYERS = RULE_LAYERS;
2024
3676
  exports.add = add;
2025
3677
  exports.alpha = alpha;
@@ -2027,9 +3679,13 @@ exports.assertAlphaInput = assertAlphaInput;
2027
3679
  exports.at = at;
2028
3680
  exports.compileRules = compileRules;
2029
3681
  exports.createCache = createCache;
3682
+ exports.createComponentSelector = createComponentSelector;
3683
+ exports.createCssEntry = createCssEntry;
3684
+ exports.createDeferredObject = createDeferredObject;
2030
3685
  exports.createDeferredRecord = createDeferredRecord;
2031
3686
  exports.createDomSheet = createDomSheet;
2032
3687
  exports.createEngine = createEngine;
3688
+ exports.createGlobalMarker = createGlobalMarker;
2033
3689
  exports.createLazyEngine = createLazyEngine;
2034
3690
  exports.createLazyRecord = createLazyRecord;
2035
3691
  exports.createMemorySheet = createMemorySheet;
@@ -2037,28 +3693,49 @@ exports.createNoSchemeGuard = createNoSchemeGuard;
2037
3693
  exports.createSchemeKey = createSchemeKey;
2038
3694
  exports.createScopeRule = createScopeRule;
2039
3695
  exports.createSheetEntry = createSheetEntry;
3696
+ exports.createStyleSelector = createStyleSelector;
2040
3697
  exports.createStyleTag = createStyleTag;
2041
3698
  exports.createThemeClass = createThemeClass;
2042
3699
  exports.createThemeClassName = createThemeClassName;
3700
+ exports.createThemeId = createThemeId;
2043
3701
  exports.createThemeKey = createThemeKey;
3702
+ exports.createThemeRule = createThemeRule;
2044
3703
  exports.createTokens = createTokens;
3704
+ exports.declareRootTheme = declareRootTheme;
2045
3705
  exports.divide = divide;
3706
+ exports.extractPageStyleParts = extractPageStyleParts;
2046
3707
  exports.extractPageStyles = extractPageStyles;
3708
+ exports.findCache = findCache;
3709
+ exports.findEntryCache = findEntryCache;
2047
3710
  exports.findMissingStyles = findMissingStyles;
2048
3711
  exports.flattenStyle = flattenStyle;
2049
3712
  exports.getBoundaryClass = getBoundaryClass;
2050
3713
  exports.getSchemeClass = getSchemeClass;
3714
+ exports.globalStyles = globalStyles;
2051
3715
  exports.hashString = hashString;
2052
3716
  exports.isAlphaColor = isAlphaColor;
3717
+ exports.isDevelopment = isDevelopment;
2053
3718
  exports.isSheetEntry = isSheetEntry;
3719
+ exports.isTemplateStrings = isTemplateStrings;
2054
3720
  exports.isThemedSheet = isThemedSheet;
3721
+ exports.keyframes = keyframes;
2055
3722
  exports.mergeDeep = mergeDeep;
2056
3723
  exports.mergeStyles = mergeStyles;
3724
+ exports.mergeTheme = mergeTheme;
2057
3725
  exports.multiply = multiply;
2058
3726
  exports.negate = negate;
3727
+ exports.parseKeyframesTemplate = parseKeyframesTemplate;
3728
+ exports.parseStyleTemplate = parseStyleTemplate;
2059
3729
  exports.readCondition = readCondition;
3730
+ exports.readCssStyle = readCssStyle;
2060
3731
  exports.readEntrySource = readEntrySource;
3732
+ exports.readEntryStyle = readEntryStyle;
2061
3733
  exports.readLabel = readLabel;
3734
+ exports.readStaticTemplate = readStaticTemplate;
3735
+ exports.readStyleArguments = readStyleArguments;
3736
+ exports.rejectFunctions = rejectFunctions;
3737
+ exports.resolveThemeInput = resolveThemeInput;
2062
3738
  exports.subtract = subtract;
2063
3739
  exports.toDeclarationText = toDeclarationText;
2064
3740
  exports.toRgba = toRgba;
3741
+ exports.withTagShorthands = withTagShorthands;