@tarve/svelte 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/css.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { extendTailwind, viewport } from "@tarve/core";
1
2
  import { camelCase, parseDeclarations, styleDependencies, windowInstance, type TElement } from "./dom";
2
- import { parseSelectorList, ruleState, selectorMatches, usesHas, type Selector } from "./selectors";
3
+ import { ancestorState, parseSelectorList, ruleState, selectorMatches, usesHas, type PseudoElement, type Selector } from "./selectors";
3
4
 
4
5
  /**
5
6
  * Svelte's component CSS for Tarve. The compiler emits each rule's selector and
@@ -15,13 +16,23 @@ export interface CssRule {
15
16
  keyframes?: { name: string; frames: { offset: number; declarations: [string, string][] }[] };
16
17
  /** `@media` condition (width queries and `prefers-color-scheme`). */
17
18
  media?: string;
19
+ /** Tailwind v4 `@theme` (with `selector` empty): its custom properties (`--color-lead: …`). */
20
+ theme?: [string, string][];
21
+ /** The sheet imports Tailwind (`@import "tailwindcss"`): every utility class applies, as in the browser. */
22
+ tailwind?: true;
18
23
  }
19
24
 
25
+ /**
26
+ * Tailwind's build directives: Tarve compiles utility classes itself, so a style sheet
27
+ * written for Tailwind v4 (`@import "tailwindcss"`, `@source`, `@plugin`…) keeps them as no-ops.
28
+ */
29
+ const TAILWIND_DIRECTIVE = /^@(?:import\s+["']tailwindcss[^"']*["']|source|plugin|config|custom-variant|variant|reference|tailwind|charset)\b/;
30
+
20
31
  const UNITLESS = new Set(["opacity", "flex", "flexGrow", "flexShrink", "fontWeight", "zIndex", "lineHeight", "order", "aspectRatio", "grow", "shrink", "lineClamp", "columns"]);
21
- const ALIASES: Record<string, string> = { flexGrow: "grow", flexShrink: "shrink", flexBasis: "basis", borderRadius: "radius" };
32
+ const ALIASES: Record<string, string> = { flexGrow: "grow", flexShrink: "shrink", flexBasis: "basis", borderRadius: "radius", gridTemplateColumns: "columns", gridTemplateRows: "rows", gridAutoRows: "autoRows", gridAutoColumns: "autoColumns", scrollbarThumbColor: "scrollbarColor" };
22
33
  const BOXES = new Set(["padding", "margin", "borderWidth"]);
23
34
  const CORNERS = ["topLeft", "topRight", "bottomRight", "bottomLeft"] as const;
24
- const DYNAMIC = /var\(|\d(vw|vh|vmin|vmax)\b/;
35
+ const DYNAMIC = /var\(|\d[dsl]?(vw|vh|vmin|vmax)\b/;
25
36
  const kebab = (name: string) => name.startsWith("--") ? name : name.replace(/[A-Z]/g, letter => "-" + letter.toLowerCase());
26
37
 
27
38
  /** What a value is resolved against: the viewport for `vw`/`vh`, the font size for `em`. */
@@ -35,11 +46,82 @@ function box(value: unknown): unknown {
35
46
  return { top, right, bottom, left };
36
47
  }
37
48
 
49
+ /**
50
+ * `calc()`, `min()`, `max()` and `clamp()` of lengths, in px (`clamp(2rem, 4vw, 3.5rem)`).
51
+ * Percentages have no basis here: such a value is not resolved.
52
+ */
53
+ function mathLength(text: string, property: string, context: CssContext): number | undefined {
54
+ let index = 0;
55
+ const source = text.trim();
56
+ const space = () => { while (source[index] === " " || source[index] === "\t" || source[index] === "\n") index++; };
57
+ const fail = () => { throw new SyntaxError(text); };
58
+ const list = (): number[] => {
59
+ const values = [sum()];
60
+ space();
61
+ while (source[index] === ",") { index++; values.push(sum()); space(); }
62
+ if (source[index] !== ")") fail();
63
+ index++;
64
+ return values;
65
+ };
66
+ const atom = (): number => {
67
+ space();
68
+ const call = /^(calc|min|max|clamp)\(/i.exec(source.slice(index));
69
+ if (call) {
70
+ index += call[0].length;
71
+ const values = list();
72
+ switch (call[1]!.toLowerCase()) {
73
+ case "calc": if (values.length !== 1) fail(); return values[0]!;
74
+ case "min": return Math.min(...values);
75
+ case "max": return Math.max(...values);
76
+ default: if (values.length !== 3) fail(); return Math.max(values[0]!, Math.min(values[1]!, values[2]!));
77
+ }
78
+ }
79
+ if (source[index] === "(") { index++; const value = sum(); space(); if (source[index] !== ")") fail(); index++; return value; }
80
+ const token = /^-?\d*\.?\d+[a-z%]*/i.exec(source.slice(index));
81
+ if (!token) fail();
82
+ index += token![0].length;
83
+ const unitless = /^-?\d*\.?\d+$/.test(token![0]);
84
+ const value = unitless ? Number(token![0]) : length(token![0], property, context);
85
+ if (value === undefined) fail();
86
+ return value!;
87
+ };
88
+ const product = (): number => {
89
+ let value = atom();
90
+ for (;;) {
91
+ space();
92
+ const operator = source[index];
93
+ if (operator !== "*" && operator !== "/") return value;
94
+ index++;
95
+ const next = atom();
96
+ value = operator === "*" ? value * next : value / next;
97
+ }
98
+ };
99
+ const sum = (): number => {
100
+ let value = product();
101
+ for (;;) {
102
+ space();
103
+ const operator = source[index];
104
+ if (operator !== "+" && operator !== "-") return value;
105
+ index++;
106
+ value = operator === "+" ? value + product() : value - product();
107
+ }
108
+ };
109
+ try {
110
+ const value = atom();
111
+ space();
112
+ return index === source.length && Number.isFinite(value) ? value : undefined;
113
+ } catch {
114
+ return undefined;
115
+ }
116
+ }
117
+
38
118
  function length(part: string, property: string, context: CssContext): number | undefined {
39
- const match = /^(-?\d*\.?\d+)(px|rem|em|vw|vh|vmin|vmax|pt)?$/.exec(part);
119
+ if (/^(calc|min|max|clamp)\(/i.test(part)) return mathLength(part, property, context);
120
+ // `dvh`/`svh`/`lvh` (and `*vw`): a desktop window has no collapsing browser toolbars, so all are `vh`.
121
+ const match = /^(-?\d*\.?\d+)(px|rem|em|[dsl]?vw|[dsl]?vh|[dsl]?vmin|[dsl]?vmax|pt)?$/.exec(part);
40
122
  if (!match) return undefined;
41
123
  const value = Number(match[1]);
42
- switch (match[2]) {
124
+ switch (match[2]?.replace(/^[dsl](?=v)/, "")) {
43
125
  case "px": return value;
44
126
  case "rem": return value * 16;
45
127
  case "em": return value * context.fontSize;
@@ -59,12 +141,64 @@ function cssValue(property: string, raw: string, context: CssContext): unknown {
59
141
  const px = /^(\d*\.?\d+)px$/.exec(value);
60
142
  if (px) return Number(px[1]) / context.fontSize;
61
143
  }
62
- const parts = value.split(/\s+/);
63
- const lengths = parts.map(part => length(part, property, context));
144
+ const parts = words(value);
145
+ // Percentages stay CSS text per side (`padding: 5% 10%`): native resolves them against the box.
146
+ const lengths = parts.map(part => length(part, property, context) ?? (/^-?\d*\.?\d+%$/.test(part) || (part === "auto" && property === "margin") ? part : undefined));
64
147
  if (lengths.every(item => item !== undefined)) return lengths.length === 1 ? lengths[0] : lengths;
65
148
  return value;
66
149
  }
67
150
 
151
+ /**
152
+ * `calc()`, `min()`, `max()`, `clamp()` and `env()` of lengths known now (px, rem, em,
153
+ * viewport units) become px, innermost first; `env()` takes its fallback, else 0 (no notch,
154
+ * no safe-area insets on a desktop window). Math with a percentage stays for the box to resolve.
155
+ */
156
+ function resolveMath(value: string, context: CssContext): string {
157
+ if (!/\b(calc|min|max|clamp|env)\(/.test(value)) return value;
158
+ let out = value;
159
+ for (let guard = 0; guard < 16; guard++) {
160
+ let changed = false;
161
+ out = out.replace(/\b(calc|min|max|clamp|env)\(([^()]*)\)/g, (whole, name: string, args: string) => {
162
+ if (name === "env") { changed = true; const fallback = args.split(",").slice(1).join(",").trim(); return fallback || "0px"; }
163
+ const parts = name === "calc" ? [args] : args.split(",");
164
+ const numbers = parts.map(part => evaluate(part.trim(), context));
165
+ if (numbers.some(number => number === undefined)) return whole;
166
+ const values = numbers as number[];
167
+ const result = name === "calc" ? values[0]! : name === "min" ? Math.min(...values) : name === "max" ? Math.max(...values)
168
+ : Math.min(Math.max(values[1]!, values[0]!), values[2] ?? Infinity);
169
+ changed = true;
170
+ return `${Math.round(result * 1000) / 1000}px`;
171
+ });
172
+ if (!changed) break;
173
+ }
174
+ return out;
175
+ }
176
+
177
+ /** A `calc()` expression of lengths and numbers in px, or undefined (a percentage, a bad token). */
178
+ function evaluate(expression: string, context: CssContext): number | undefined {
179
+ const tokens = expression.match(/-?\d*\.?\d+[a-z%]*|[-+*/]/gi);
180
+ if (!tokens || tokens.join("").replace(/\s/g, "") !== expression.replace(/\s/g, "")) return undefined;
181
+ const values: number[] = [], operators: string[] = [];
182
+ for (const token of tokens) {
183
+ if (/^[-+*/]$/.test(token) && values.length > operators.length) { operators.push(token); continue; }
184
+ if (token.endsWith("%")) return undefined;
185
+ const number = /^-?\d*\.?\d+$/.test(token) ? Number(token) : length(token, "x", context);
186
+ if (number === undefined) return undefined;
187
+ values.push(number);
188
+ }
189
+ if (values.length !== operators.length + 1) return undefined;
190
+ // * and / first, then + and -.
191
+ const sums: number[] = [values[0]!], signs: string[] = [];
192
+ operators.forEach((operator, index) => {
193
+ const next = values[index + 1]!;
194
+ if (operator === "*") sums[sums.length - 1]! *= next;
195
+ else if (operator === "/") sums[sums.length - 1]! /= next;
196
+ else { signs.push(operator); sums.push(next); }
197
+ });
198
+ const total = sums.slice(1).reduce((sum, value, index) => signs[index] === "-" ? sum - value : sum + value, sums[0]!);
199
+ return Number.isFinite(total) ? total : undefined;
200
+ }
201
+
68
202
  type Matrix = [number, number, number, number, number, number];
69
203
  const multiply = (m: Matrix, n: Matrix): Matrix => [
70
204
  m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],
@@ -72,6 +206,58 @@ const multiply = (m: Matrix, n: Matrix): Matrix => [
72
206
  m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5],
73
207
  ];
74
208
 
209
+ /**
210
+ * A CSS `transform` list in the order Tarve's `transform` composes (translate, rotate, skew,
211
+ * scale, about the box's centre), so it needs no box size: percents stay percents of the box.
212
+ * Undefined for another order or `matrix()`, which take the matrix form.
213
+ */
214
+ function transformObject(value: string, context: CssContext): Record<string, number> | undefined {
215
+ if (value.trim() === "none") return {};
216
+ const out = { x: 0, y: 0, xPercent: 0, yPercent: 0, rotate: 0, skewX: 0, skewY: 0, scaleX: 1, scaleY: 1 };
217
+ const toDeg = (text: string) => {
218
+ const match = /^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/.exec(text.trim());
219
+ if (!match) return undefined;
220
+ const amount = Number(match[1]);
221
+ return match[2] === "rad" ? amount * 180 / Math.PI : match[2] === "turn" ? amount * 360 : match[2] === "grad" ? amount * 0.9 : amount;
222
+ };
223
+ const shift = (text: string, axis: "x" | "y") => {
224
+ const percent = /^(-?\d*\.?\d+)%$/.exec(text.trim());
225
+ if (percent) { out[axis === "x" ? "xPercent" : "yPercent"] += Number(percent[1]); return true; }
226
+ const px = length(text.trim(), "x", context);
227
+ if (px === undefined) return false;
228
+ out[axis] += px;
229
+ return true;
230
+ };
231
+ let phase = 0;
232
+ const functions = [...value.matchAll(/([a-zA-Z0-9]+)\(([^)]*)\)/g)];
233
+ if (!functions.length || value.replace(/([a-zA-Z0-9]+)\(([^)]*)\)/g, "").trim()) return undefined;
234
+ for (const [, name, args] of functions) {
235
+ const parts = args!.split(/\s*,\s*|\s+/).filter(Boolean);
236
+ const order = /^translate/.test(name!) ? 0 : /^rotate/.test(name!) ? 1 : /^skew/.test(name!) ? 2 : /^scale/.test(name!) ? 3 : -1;
237
+ if (order < phase) return undefined;
238
+ phase = order;
239
+ switch (name) {
240
+ case "translate": case "translate3d": if (!shift(parts[0] ?? "0", "x") || !shift(parts[1] ?? "0", "y")) return undefined; break;
241
+ case "translateX": if (!shift(parts[0] ?? "0", "x")) return undefined; break;
242
+ case "translateY": if (!shift(parts[0] ?? "0", "y")) return undefined; break;
243
+ case "rotate": case "rotateZ": { const angle = toDeg(parts[0] ?? "0"); if (angle === undefined) return undefined; out.rotate += angle; break; }
244
+ case "skew": { const x = toDeg(parts[0] ?? "0"), y = toDeg(parts[1] ?? "0"); if (x === undefined || y === undefined) return undefined; out.skewX += x; out.skewY += y; break; }
245
+ case "skewX": { const x = toDeg(parts[0] ?? "0"); if (x === undefined) return undefined; out.skewX += x; break; }
246
+ case "skewY": { const y = toDeg(parts[0] ?? "0"); if (y === undefined) return undefined; out.skewY += y; break; }
247
+ case "scale": { const x = Number(parts[0] ?? 1), y = Number(parts[1] ?? parts[0] ?? 1); out.scaleX *= x; out.scaleY *= y; break; }
248
+ case "scaleX": out.scaleX *= Number(parts[0] ?? 1); break;
249
+ case "scaleY": out.scaleY *= Number(parts[0] ?? 1); break;
250
+ default: return undefined;
251
+ }
252
+ }
253
+ if (![out.scaleX, out.scaleY].every(Number.isFinite)) return undefined;
254
+ const result: Record<string, number> = {};
255
+ for (const key of ["x", "y", "xPercent", "yPercent", "rotate", "skewX", "skewY"] as const) if (out[key] !== 0) result[key] = out[key];
256
+ if (out.scaleX === out.scaleY) { if (out.scaleX !== 1) result.scale = out.scaleX; }
257
+ else { result.scaleX = out.scaleX; result.scaleY = out.scaleY; }
258
+ return result;
259
+ }
260
+
75
261
  /** A CSS `transform` list as one matrix about the box's centre (Tarve's origin is its top left). */
76
262
  function transformMatrix(value: string, context: CssContext): Matrix | undefined {
77
263
  if (value.trim() === "none") return [1, 0, 0, 1, 0, 0];
@@ -118,19 +304,90 @@ function substitute(value: string, variables: ReadonlyMap<string, string> | unde
118
304
  return out;
119
305
  }
120
306
 
307
+ /** CSS property names as the Tarve style keys a transition animates. */
308
+ const TRANSITION_PROPERTIES: Record<string, string> = {
309
+ "background-color": "background", background: "background", color: "foreground", "border-color": "borderColor",
310
+ "border-radius": "radius", "box-shadow": "boxShadow", "text-shadow": "textShadow", "max-height": "maxHeight", "min-height": "minHeight",
311
+ "max-width": "maxWidth", "min-width": "minWidth", fill: "foreground", stroke: "foreground",
312
+ };
313
+ const MOTION_PROPERTIES = new Set(["all", "width", "height", "top", "right", "bottom", "left", "opacity", "radius", "background", "foreground", "borderColor", "boxShadow", "textShadow", "transform"]);
314
+ const TRANSITION_EASINGS: Record<string, string> = { ease: "ease", linear: "linear", "ease-in": "easeIn", "ease-out": "easeOut", "ease-in-out": "easeInOut" };
315
+
316
+ function seconds(text: string): number | undefined {
317
+ const match = /^(-?\d*\.?\d+)(ms|s)$/.exec(text);
318
+ return match ? Number(match[1]) * (match[2] === "s" ? 1000 : 1) : undefined;
319
+ }
320
+
321
+ /** CSS `transition` (`opacity 0.2s ease, transform 300ms`) as Tarve's per-property transitions. */
322
+ export function cssTransition(value: string): Record<string, { duration: number; delay?: number; easing?: string }> | undefined {
323
+ if (value.trim() === "none") return undefined;
324
+ const out: Record<string, { duration: number; delay?: number; easing?: string }> = {};
325
+ for (const layer of value.split(/,(?![^(]*\))/)) {
326
+ let property = "all", easing: string | undefined;
327
+ const times: number[] = [];
328
+ for (const part of words(layer)) {
329
+ const time = seconds(part);
330
+ if (time !== undefined) times.push(time);
331
+ else if (TRANSITION_EASINGS[part]) easing = TRANSITION_EASINGS[part];
332
+ // cubic-bezier() and steps() have no Tarve counterpart: the closest named curve.
333
+ else if (/^(cubic-bezier|steps)\(/.test(part)) easing = "ease";
334
+ else property = part;
335
+ }
336
+ const [duration = 0, delay] = times;
337
+ if (duration <= 0) continue;
338
+ const key = property === "all" ? "all" : TRANSITION_PROPERTIES[property] ?? camelCase(property);
339
+ // Properties Tarve does not animate (`filter`, `visibility`) just change.
340
+ if (!MOTION_PROPERTIES.has(key)) continue;
341
+ out[key] = { duration, ...(delay ? { delay } : {}), ...(easing ? { easing } : {}) };
342
+ }
343
+ return Object.keys(out).length ? out : undefined;
344
+ }
345
+
346
+ /** A value's space-separated parts, keeping functions whole (`1px solid rgba(0, 0, 0, 0.1)`). */
347
+ function words(value: string): string[] {
348
+ const out: string[] = [];
349
+ let depth = 0, current = "";
350
+ for (const char of value.trim()) {
351
+ if (char === "(") depth++;
352
+ else if (char === ")") depth--;
353
+ if (/\s/.test(char) && depth === 0) { if (current) out.push(current); current = ""; continue; }
354
+ current += char;
355
+ }
356
+ if (current) out.push(current);
357
+ return out;
358
+ }
359
+
121
360
  /** CSS declarations as a Tarve style object. Custom properties (`--x`) are skipped; `var()` reads `variables`. */
361
+ /** One side's border colour; the other sides keep the colour the box had. */
362
+ function sideColor(style: Record<string, unknown>, side: string, value: string): void {
363
+ if (!style.borderColors) {
364
+ const previous = style.borderColor;
365
+ style.borderColors = typeof previous === "string" ? { top: previous, right: previous, bottom: previous, left: previous } : {};
366
+ }
367
+ (style.borderColors as Record<string, string>)[side] = value;
368
+ if (style.borderColor === undefined) style.borderColor = value;
369
+ }
370
+
122
371
  export function cssStyle(declarations: Map<string, string> | Iterable<[string, string]> | string, context: CssContext = DEFAULT_CONTEXT, variables?: ReadonlyMap<string, string>): Record<string, unknown> {
123
- const entries = typeof declarations === "string" ? parseDeclarations(declarations) : declarations;
372
+ const entries = [...(typeof declarations === "string" ? parseDeclarations(declarations) : declarations)];
373
+ // `em` lengths and a px `line-height` are of the element's own font size when the rule sets one.
374
+ const ownSize = entries.findLast(([name]) => name === "font-size");
375
+ if (ownSize && !/em$|%$/.test(ownSize[1].trim())) {
376
+ const size = length(ownSize[1].trim(), "fontSize", context);
377
+ if (typeof size === "number") context = { ...context, fontSize: size };
378
+ }
124
379
  const style: Record<string, unknown> = {};
125
380
  for (const [name, rawValue] of entries) {
126
381
  if (name.startsWith("--")) continue;
127
- const raw = rawValue.includes("var(") ? substitute(rawValue, variables) : rawValue;
382
+ const raw = resolveMath(rawValue.includes("var(") ? substitute(rawValue, variables) : rawValue, context);
128
383
  if (!raw) continue;
129
384
  let property = camelCase(name);
385
+ // `em` and a px `line-height` are of the element's own font size once the rule sets it.
386
+ if (typeof style.fontSize === "number" && context.fontSize !== style.fontSize) context = { ...context, fontSize: style.fontSize };
130
387
  if (property === "border" || property === "outline" || /^border(Top|Right|Bottom|Left)$/.test(property)) {
131
388
  const side = /^border(Top|Right|Bottom|Left)$/.exec(property)?.[1]?.toLowerCase();
132
389
  const target = property === "outline" ? "outline" : "border";
133
- for (const part of raw.trim().split(/\s+/)) {
390
+ for (const part of words(raw)) {
134
391
  const width = length(part, "borderWidth", context);
135
392
  if (width !== undefined) {
136
393
  if (side) {
@@ -140,12 +397,107 @@ export function cssStyle(declarations: Map<string, string> | Iterable<[string, s
140
397
  } else if (part === "none" || part === "hidden") {
141
398
  if (!side) style[`${target}Width`] = 0;
142
399
  } else if (/^(solid|dashed|dotted|double)$/.test(part)) style[`${target}Style`] = part;
143
- else style[`${target}Color`] = part;
400
+ else if (side) sideColor(style, side, part);
401
+ else {
402
+ style[`${target}Color`] = part;
403
+ if (target === "border") delete style.borderColors;
404
+ }
144
405
  }
145
406
  continue;
146
407
  }
408
+ // `border-top-color` and a 2–4 value `border-color`: colours per side (`borderColors`).
409
+ const sideColorProperty = /^border(Top|Right|Bottom|Left)Color$/.exec(property)?.[1]?.toLowerCase();
410
+ if (sideColorProperty) { sideColor(style, sideColorProperty, raw.trim()); continue; }
411
+ if (property === "borderColor") {
412
+ const parts = words(raw);
413
+ if (parts.length > 1) {
414
+ const [top, right = top, bottom = top, left = right] = parts;
415
+ delete style.borderColors;
416
+ style.borderColor = top;
417
+ for (const [side, part] of Object.entries({ top, right, bottom, left })) sideColor(style, side, part!);
418
+ } else { style.borderColor = raw.trim(); delete style.borderColors; }
419
+ continue;
420
+ }
147
421
  if (property === "background" && !/url\(|gradient\(/.test(raw)) { style.background = raw.trim(); continue; }
422
+ // `background: url(…) center / cover no-repeat, #000`: the image, its size and the colour.
423
+ if (property === "background" && /url\(/.test(raw)) {
424
+ const layers = raw.split(/,(?![^(]*\))/).map(layer => layer.trim());
425
+ style.backgroundImage = layers.filter(layer => /url\(|gradient\(/.test(layer)).map(layer => /url\([^)]*\)|[\w-]*gradient\((?:[^()]|\([^()]*\))*\)/.exec(layer)?.[0]).filter(Boolean).join(", ");
426
+ const size = /\/\s*(cover|contain|[\d.]+%?(?:\s+[\d.]+%?)?)/.exec(raw)?.[1];
427
+ if (size) style.backgroundSize = size;
428
+ const colour = words(layers.at(-1)!).find(part => /^(#|rgb|hsl)/.test(part) || /^[a-z]+$/.test(part) && !/^(center|top|bottom|left|right|no-repeat|repeat|cover|contain|fixed|scroll)$/.test(part));
429
+ if (colour) style.backgroundColor = colour;
430
+ continue;
431
+ }
432
+ // `place-items: center` (and -content, -self): the align-* value, then the justify-* one (the same when one).
433
+ const place = /^place(Items|Content|Self)$/.exec(property)?.[1];
434
+ if (place) {
435
+ const parts = words(raw);
436
+ const align = parts[0] === "first" || parts[0] === "last" || parts[0] === "safe" || parts[0] === "unsafe" ? parts.slice(0, 2).join(" ") : parts[0];
437
+ const rest = parts.slice(align?.includes(" ") ? 2 : 1).join(" ");
438
+ if (align) {
439
+ style[`align${place}`] = align;
440
+ style[`justify${place}`] = rest || align;
441
+ }
442
+ continue;
443
+ }
444
+ // `inset: 0` (1–4 values, as margin) is top/right/bottom/left.
445
+ if (property === "inset") {
446
+ const parts = words(raw);
447
+ const [top, right = top, bottom = top, left = right] = parts;
448
+ for (const [side, part] of Object.entries({ top, right, bottom, left })) {
449
+ if (part === undefined || part === "auto") continue;
450
+ const value = cssValue(side, part, context);
451
+ if (value !== undefined) style[side] = value;
452
+ }
453
+ continue;
454
+ }
455
+ if (property === "transition") { const transition = cssTransition(raw); if (transition) style.transition = transition; continue; }
456
+ // `top: calc(100% + 0.5rem)` (a dropdown under its trigger): the percentage places the box and
457
+ // the length moves it by its margin on that side, which offsets an absolute box the same way.
458
+ const offset = /^(top|right|bottom|left)$/.exec(property) && /^calc\(\s*(-?\d*\.?\d+%)\s*([+-])\s*([^()]+?)\s*\)$/.exec(raw.trim());
459
+ if (offset) {
460
+ const shift = length(offset[3]!, property, context);
461
+ if (shift !== undefined) {
462
+ style[property] = offset[1];
463
+ const margin = typeof style.margin === "object" && style.margin ? style.margin as Record<string, unknown> : {};
464
+ style.margin = { ...margin, [property]: offset[2] === "-" ? -shift : shift };
465
+ continue;
466
+ }
467
+ }
468
+ // `min(20rem, 60vh)` of lengths that resolve now is just the smaller (or larger) one.
469
+ const extreme = /^(min|max|clamp)\((.*)\)$/.exec(raw.trim());
470
+ if (extreme && !extreme[2]!.includes("%") && !extreme[2]!.includes("(")) {
471
+ const values = extreme[2]!.split(",").map(part => length(part.trim(), property, context));
472
+ if (values.length > 1 && values.every(value => typeof value === "number")) {
473
+ const numbers = values as number[];
474
+ style[ALIASES[property] ?? property] = extreme[1] === "min" ? Math.min(...numbers) : extreme[1] === "max" ? Math.max(...numbers)
475
+ : Math.min(Math.max(numbers[1]!, numbers[0]!), numbers[2] ?? Infinity);
476
+ continue;
477
+ }
478
+ }
479
+ // `width: min(92%, 34rem)` is a percentage with a cap; `max(…)` one with a floor.
480
+ const bounded = /^(width|height)$/.exec(property) && /^(min|max)\(\s*(-?\d*\.?\d+%)\s*,\s*([^,()]+)\)$/.exec(raw.trim());
481
+ if (bounded) {
482
+ const limit = length(bounded[3]!.trim(), property, context);
483
+ if (limit !== undefined) {
484
+ style[property] = bounded[2];
485
+ style[(bounded[1] === "min" ? "max" : "min") + property[0]!.toUpperCase() + property.slice(1)] = limit;
486
+ continue;
487
+ }
488
+ }
489
+ // Tarve positions boxes relative or absolute only: `fixed` is absolute to its positioned
490
+ // ancestor (the viewport while the page is not scrolled), `sticky` stays in the flow.
491
+ if (property === "position") {
492
+ const position = raw.trim();
493
+ style.position = position === "fixed" ? "absolute" : position === "sticky" ? "relative" : position;
494
+ continue;
495
+ }
496
+ // `scrollbar-color: <thumb> <track>`: Tarve paints the thumb over a clear track.
497
+ if (property === "scrollbarColor") { const thumb = words(raw)[0]; if (thumb && thumb !== "auto") style.scrollbarColor = thumb; continue; }
148
498
  if (property === "transform") {
499
+ const object = transformObject(raw, context);
500
+ if (object) { style.transform = object; continue; }
149
501
  const matrix = transformMatrix(raw, context);
150
502
  if (matrix) style.transformMatrix = matrix;
151
503
  continue;
@@ -178,10 +530,32 @@ export function cssStyle(declarations: Map<string, string> | Iterable<[string, s
178
530
  continue;
179
531
  }
180
532
  if (property === "flexDirection") { style.direction = raw.trim(); continue; }
533
+ // The legacy line-clamp box: `display: -webkit-box; -webkit-line-clamp: 2` clamps lines.
534
+ if (property === "WebkitLineClamp" || property === "lineClamp") { const lines = Number(raw); if (Number.isFinite(lines) && lines > 0) style.lineClamp = lines; continue; }
535
+ if (property === "WebkitBoxOrient") continue;
536
+ if (property === "display" && /^-webkit-(inline-)?box$/.test(raw.trim())) continue;
537
+ // CSS `direction` is the text direction, not Tarve's flex `direction`.
538
+ if (property === "direction") { style.textDirection = raw.trim(); continue; }
539
+ if (property === "writingMode" || property === "WebkitAppearance") { style[property === "WebkitAppearance" ? "appearance" : property] = raw.trim(); continue; }
540
+ // Track lists stay CSS text (`100px 100px`, `repeat(4, 1fr)`): a lone length is a track, not a count.
541
+ if (/^grid(Template|Auto)(Columns|Rows)$/.test(property)) { style[ALIASES[property]!] = raw.trim(); continue; }
542
+ // `aspect-ratio: 2 / 3` (or `16/9`, `1.5`); `auto` leaves the box to its content.
543
+ if (property === "aspectRatio") {
544
+ const ratio = /^(\d*\.?\d+)\s*(?:\/\s*(\d*\.?\d+))?$/.exec(raw.trim());
545
+ if (ratio && Number(ratio[2] ?? 1) > 0) style.aspectRatio = Number(ratio[1]) / Number(ratio[2] ?? 1);
546
+ continue;
547
+ }
181
548
  if (property === "flexWrap") { style.wrap = raw.trim() !== "nowrap"; continue; }
182
549
  if (property === "flex" && /^\d*\.?\d+$/.test(raw.trim())) { style.flex = Number(raw); continue; }
183
- if (property === "display" && raw.trim() === "inline-flex") { style.display = "flex"; continue; }
184
- if (property === "display" && /^(inline|inline-block)$/.test(raw.trim())) continue;
550
+ // The shorthand's other forms (`0 0 200px`, `1 1 auto`, `none`) pass as CSS text.
551
+ if (property === "flex") { style.flex = raw.trim(); continue; }
552
+ // Inline-level boxes (`inline-block`, `inline-flex`) are as wide as their content: `inline` marks
553
+ // them for the renderer, which knows whether their parent lays them out as a line or as flex items.
554
+ if (property === "display" && /^inline-(flex|grid)$/.test(raw.trim())) { style.display = raw.trim().slice(7); style.inline = true; continue; }
555
+ if (property === "display" && raw.trim() === "inline") { style.display = undefined; style.inline = true; continue; }
556
+ // `inline-block` is a box of its own on the line: `inline: "block"` keeps it out of text runs.
557
+ if (property === "display" && raw.trim() === "inline-block") { style.display = undefined; style.inline = "block"; continue; }
558
+ if (property === "display") style.inline = undefined;
185
559
  property = ALIASES[property] ?? property;
186
560
  const value = cssValue(property, raw, context);
187
561
  style[property] = BOXES.has(property) ? box(value) : value;
@@ -192,14 +566,27 @@ export function cssStyle(declarations: Map<string, string> | Iterable<[string, s
192
566
  /** Top-level blocks of a style sheet: `[prelude, body]`. */
193
567
  function blocks(text: string): [string, string][] {
194
568
  const out: [string, string][] = [];
569
+ // Braces inside strings (`@source "./**/*.{svelte,ts}"`, `content: "{"`) are text.
570
+ const next = (from: number): number => {
571
+ let quote = "";
572
+ for (let at = from; at < text.length; at++) {
573
+ const char = text[at]!;
574
+ if (quote) { if (char === "\\") at++; else if (char === quote) quote = ""; continue; }
575
+ if (char === '"' || char === "'") quote = char;
576
+ else if (char === "{" || char === "}") return at;
577
+ }
578
+ return -1;
579
+ };
195
580
  let index = 0;
196
581
  while (index < text.length) {
197
- const open = text.indexOf("{", index);
198
- if (open < 0) break;
582
+ const open = next(index);
583
+ if (open < 0 || text[open] !== "{") break;
199
584
  let depth = 1, close = open + 1;
200
- for (; close < text.length && depth > 0; close++) {
201
- if (text[close] === "{") depth++;
202
- else if (text[close] === "}") depth--;
585
+ while (depth > 0) {
586
+ const brace = next(close);
587
+ if (brace < 0) { close = text.length + 1; break; }
588
+ depth += text[brace] === "{" ? 1 : -1;
589
+ close = brace + 1;
203
590
  }
204
591
  out.push([text.slice(index, open).trim(), text.slice(open + 1, close - 1)]);
205
592
  index = close;
@@ -211,7 +598,18 @@ function blocks(text: string): [string, string][] {
211
598
  export function parseCss(code: string, warn?: (message: string) => void): CssRule[] {
212
599
  const rules: CssRule[] = [];
213
600
  const visit = (text: string, media?: string) => {
214
- for (const [prelude, body] of blocks(text)) {
601
+ for (let [prelude, body] of blocks(text)) {
602
+ // Statement at-rules (`@import …;`) end before the block's own prelude.
603
+ const statements = splitStatements(prelude);
604
+ prelude = statements.pop()!;
605
+ for (const statement of statements) {
606
+ if (!TAILWIND_DIRECTIVE.test(statement) && !/^@import\b/.test(statement)) warn?.(`${statement} is not supported`);
607
+ }
608
+ if (prelude.startsWith("@layer")) { visit(body, media); continue; }
609
+ if (prelude === "@theme" || prelude.startsWith("@theme ")) {
610
+ rules.push({ selector: "", declarations: [], theme: [...parseDeclarations(body)] });
611
+ continue;
612
+ }
215
613
  if (prelude.startsWith("@media")) {
216
614
  const condition = prelude.slice(6).trim();
217
615
  if (parseMedia(condition)) visit(body, media ? `${media} and ${condition}` : condition);
@@ -247,10 +645,37 @@ export function parseCss(code: string, warn?: (message: string) => void): CssRul
247
645
  }
248
646
  }
249
647
  };
250
- visit(code.replace(/\/\*[\s\S]*?\*\//g, ""));
648
+ const text = code.replace(/\/\*[\s\S]*?\*\//g, "");
649
+ if (/@import\s+(?:url\()?["']tailwindcss["'/]/.test(text)) rules.push({ selector: "", declarations: [], tailwind: true });
650
+ visit(text);
251
651
  return rules;
252
652
  }
253
653
 
654
+ /** `a; b; c`: the statements a prelude carries before its own (outside quotes and parentheses). */
655
+ function splitStatements(prelude: string): string[] {
656
+ const out: string[] = [];
657
+ let depth = 0, quote = "", start = 0;
658
+ for (let index = 0; index < prelude.length; index++) {
659
+ const char = prelude[index]!;
660
+ if (quote) { if (char === quote) quote = ""; continue; }
661
+ if (char === '"' || char === "'") quote = char;
662
+ else if (char === "(") depth++;
663
+ else if (char === ")") depth--;
664
+ else if (char === ";" && depth === 0) { out.push(prelude.slice(start, index).trim()); start = index + 1; }
665
+ }
666
+ out.push(prelude.slice(start).trim());
667
+ return out.filter((statement, index) => statement || index === out.length - 1);
668
+ }
669
+
670
+ /** `@import` targets of a style sheet that are files (not Tailwind's own `@import "tailwindcss"`). */
671
+ export function cssImports(code: string): string[] {
672
+ const out: string[] = [];
673
+ for (const [, url] of code.replace(/\/\*[\s\S]*?\*\//g, "").matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)) {
674
+ if (!/^tailwindcss(\/|$)/.test(url!)) out.push(url!);
675
+ }
676
+ return out;
677
+ }
678
+
254
679
  function splitSelectors(prelude: string): string[] {
255
680
  const out: string[] = [];
256
681
  let depth = 0, start = 0;
@@ -264,7 +689,7 @@ function splitSelectors(prelude: string): string[] {
264
689
  return out.filter(Boolean);
265
690
  }
266
691
 
267
- type MediaTest = { min?: number; max?: number; dark?: boolean; orientation?: "portrait" | "landscape"; minHeight?: number; maxHeight?: number };
692
+ type MediaTest = { min?: number; max?: number; dark?: boolean; orientation?: "portrait" | "landscape"; minHeight?: number; maxHeight?: number; reducedMotion?: boolean; displayMode?: "fullscreen" | "standalone" | "minimal-ui" | "browser" };
268
693
 
269
694
  /** Width/height/orientation/color-scheme media queries; undefined for anything else. */
270
695
  function parseMedia(condition: string): MediaTest | undefined {
@@ -281,6 +706,9 @@ function parseMedia(condition: string): MediaTest | undefined {
281
706
  else if (name === "max-height" && size !== undefined) test.maxHeight = size;
282
707
  else if (name === "prefers-color-scheme") test.dark = value === "dark";
283
708
  else if (name === "orientation" && (value === "portrait" || value === "landscape")) test.orientation = value;
709
+ else if (name === "prefers-reduced-motion" && (value === "reduce" || value === "no-preference")) test.reducedMotion = value === "reduce";
710
+ // A Tarve window is an installed app: `standalone`, or `fullscreen` while it fills the screen.
711
+ else if (name === "display-mode" && /^(fullscreen|standalone|minimal-ui|browser)$/.test(value!)) test.displayMode = value as MediaTest["displayMode"];
284
712
  else return undefined;
285
713
  }
286
714
  return test;
@@ -294,6 +722,8 @@ function mediaMatches(test: MediaTest): boolean {
294
722
  if (test.maxHeight !== undefined && height > test.maxHeight) return false;
295
723
  if (test.orientation && (test.orientation === "portrait") !== (height >= width)) return false;
296
724
  if (test.dark !== undefined && test.dark !== windowInstance._dark) return false;
725
+ if (test.reducedMotion !== undefined && test.reducedMotion !== viewport().reducedMotion) return false;
726
+ if (test.displayMode !== undefined && test.displayMode !== (windowInstance._fullscreen ? "fullscreen" : "standalone")) return false;
297
727
  return true;
298
728
  }
299
729
 
@@ -319,8 +749,11 @@ const universal: Entry[] = [];
319
749
  const keyframeSets = new Map<string, { offset: number; declarations: [string, string][] }[]>();
320
750
  /** `::before` / `::after` rules: they style generated content, not the element. */
321
751
  const pseudoEntries: Entry[] = [];
752
+ /** Ancestors an `X:hover Y` rule watches: elements matching one are a native hover `group`. */
753
+ const groupAnchors: Selector[] = [];
322
754
  /** Class names some component's CSS selects: they style through those rules, not as Tailwind utilities. */
323
755
  const ruleClasses = new Set<string>();
756
+ let tailwindSheets = false;
324
757
  let counter = 0;
325
758
  let complex = 0;
326
759
  let customProperties = false;
@@ -329,8 +762,14 @@ const simpleCache = new Map<string, Entry[]>();
329
762
  const mediaThresholds = new Set<number>();
330
763
  let viewportUnits = false;
331
764
 
765
+ /** The page imports Tailwind, whose preflight resets the browser's defaults (heading sizes, margins). */
766
+ export function usesPreflight(): boolean {
767
+ return tailwindSheets;
768
+ }
769
+
770
+ /** Whether a class styles only through the component CSS. In a Tailwind app every class may be a utility too. */
332
771
  export function isComponentClass(name: string): boolean {
333
- return ruleClasses.has(name);
772
+ return !tailwindSheets && ruleClasses.has(name);
334
773
  }
335
774
 
336
775
  function bucket(map: Map<string, Entry[]>, key: string, entry: Entry): void {
@@ -343,6 +782,11 @@ function bucket(map: Map<string, Entry[]>, key: string, entry: Entry): void {
343
782
  export function registerCss(rules: readonly CssRule[]): void {
344
783
  for (const rule of rules) {
345
784
  if (rule.keyframes) { keyframeSets.set(rule.keyframes.name, rule.keyframes.frames); continue; }
785
+ if (rule.theme) { for (const [name, value] of rule.theme) themeTokens.set(name, value); continue; }
786
+ if (rule.tailwind) { tailwindSheets = true; continue; }
787
+ if (rule.selector === ":root" || rule.selector === "html") {
788
+ for (const [name, value] of rule.declarations) if (name.startsWith("--")) rootVariables.set(name, value);
789
+ }
346
790
  for (const selector of parseSelectorList(rule.selector)) {
347
791
  const media = rule.media ? parseMedia(rule.media) : undefined;
348
792
  if (rule.media && !media) continue;
@@ -352,23 +796,41 @@ export function registerCss(rules: readonly CssRule[]): void {
352
796
  const variables = rule.declarations.filter(([name]) => name.startsWith("--"));
353
797
  const simple = selector.compounds.length === 1 && !last.id && last.attributes.length === 0
354
798
  && last.pseudos.every(pseudo => pseudo.kind === "state") && !media && !dynamic;
355
- const state = ruleState(selector);
799
+ // `.card:hover .title`: the title's `groupHover` style, shown while the card (a native
800
+ // `group`) is hovered. Other states of an ancestor (focus, active) have no native form.
801
+ const ancestor = ancestorState(selector);
802
+ if (ancestor && ancestor.state !== "hover") continue;
803
+ if (ancestor) {
804
+ const anchor = selector.compounds[ancestor.index]!;
805
+ groupAnchors.push({ compounds: [{ ...anchor, pseudos: anchor.pseudos.filter(pseudo => pseudo.kind !== "state") }], combinators: [], specificity: 0 });
806
+ }
807
+ const state = ruleState(selector) ?? (ancestor ? "groupHover" : undefined);
356
808
  const entry: Entry = {
357
809
  selector, order: counter++, specificity: selector.specificity, declarations: rule.declarations,
358
810
  ...(state ? { state } : {}), ...(media ? { media } : {}), ...(variables.length ? { variables } : {}), simple,
359
811
  ...(dynamic ? {} : { style: cssStyle(rule.declarations) }),
360
812
  };
361
813
  for (const compound of selector.compounds) for (const name of compound.classes) ruleClasses.add(name);
362
- if (selector.pseudoElement) { pseudoEntries.push(entry); entry.simple = false; complex++; continue; }
814
+ if (selector.pseudoElement === "before" || selector.pseudoElement === "after") { pseudoEntries.push(entry); entry.simple = false; complex++; continue; }
815
+ if (selector.pseudoElement) {
816
+ // `::placeholder` and the scrollbar parts style the element itself (its placeholder and
817
+ // scrollbar colours, the bar's thickness): the rule becomes one on the element.
818
+ const declarations = partDeclarations(selector.pseudoElement, rule.declarations);
819
+ if (!declarations.length || state) continue;
820
+ entry.declarations = declarations;
821
+ entry.selector = { ...selector, pseudoElement: undefined };
822
+ if (!dynamic) entry.style = cssStyle(declarations);
823
+ }
363
824
  if (last.id) bucket(byId, last.id, entry);
364
825
  else if (last.classes[0]) bucket(byClass, last.classes[0], entry);
365
826
  else if (last.tag) bucket(byTag, last.tag, entry);
366
827
  else universal.push(entry);
367
828
  if (!simple) complex++;
368
829
  if (variables.length || rule.declarations.some(([, value]) => value.includes("var("))) customProperties = true;
369
- if (rule.declarations.some(([, value]) => /\d(vw|vh|vmin|vmax)\b/.test(value))) viewportUnits = true;
830
+ if (rule.declarations.some(([, value]) => /\d[dsl]?(vw|vh|vmin|vmax)\b/.test(value))) viewportUnits = true;
370
831
  if (media) for (const value of [media.min, media.max, media.minHeight, media.maxHeight]) if (value !== undefined) mediaThresholds.add(value);
371
832
  if (media?.dark !== undefined) colorScheme = true;
833
+ if (media?.displayMode !== undefined) displayModeRules = true;
372
834
  // Restyle what a change can affect: descendants for ancestor selectors and
373
835
  // inherited custom properties, siblings for `+`, `~` and :nth-child().
374
836
  if (selector.combinators.some(combinator => combinator === " " || combinator === ">") || customProperties) styleDependencies.descendants = true;
@@ -377,14 +839,60 @@ export function registerCss(rules: readonly CssRule[]): void {
377
839
  }
378
840
  }
379
841
  simpleCache.clear();
842
+ applyTheme();
380
843
  }
381
844
  let colorScheme = false;
845
+ let displayModeRules = false;
846
+ /** Whether a `display-mode` rule exists (entering or leaving full screen restyles the app). */
847
+ export function usesDisplayMode(): boolean {
848
+ return displayModeRules;
849
+ }
850
+
851
+ /** `@theme` tokens, and the `:root` custom properties their values may read. */
852
+ const themeTokens = new Map<string, string>();
853
+ const rootVariables = new Map<string, string>();
854
+
855
+ /** `--color-<name>` tokens become Tailwind colours (`bg-<name>`), as Tailwind v4 builds them. */
856
+ function applyTheme(): void {
857
+ const colors: Record<string, string> = {};
858
+ for (const [name, value] of themeTokens) {
859
+ if (!name.startsWith("--color-")) continue;
860
+ const resolved = substitute(value, rootVariables).trim();
861
+ if (resolved && !resolved.includes("var(")) colors[name.slice("--color-".length)] = resolved;
862
+ }
863
+ if (Object.keys(colors).length) extendTailwind({ colors });
864
+ }
865
+
866
+ /**
867
+ * A pseudo-element rule as declarations on its element: `::placeholder { color }` is the
868
+ * placeholder colour, `::-webkit-scrollbar-thumb { background }` the scrollbar's, and
869
+ * `::-webkit-scrollbar { width }` (or `height`) its thickness (`thin` up to 8 px, `none` at 0).
870
+ * The track draws clear, as Tarve's always does.
871
+ */
872
+ function partDeclarations(part: PseudoElement, declarations: [string, string][]): [string, string][] {
873
+ const out: [string, string][] = [];
874
+ for (const [name, value] of declarations) {
875
+ if (part === "placeholder" && name === "color") out.push(["placeholder-color", value]);
876
+ else if (part === "-webkit-scrollbar-thumb" && (name === "background" || name === "background-color")) out.push(["scrollbar-thumb-color", value]);
877
+ // A range input's parts: the thumb, the track and (Firefox) the filled part.
878
+ else if ((part === "-webkit-slider-thumb" || part === "-moz-range-thumb") && (name === "background" || name === "background-color")) out.push(["thumb-color", value]);
879
+ else if ((part === "-webkit-slider-runnable-track" || part === "-moz-range-track") && (name === "background" || name === "background-color")) out.push(["track-color", value]);
880
+ else if (part === "-moz-range-progress" && (name === "background" || name === "background-color")) out.push(["accent-color", value]);
881
+ else if (part === "-webkit-scrollbar" && (name === "width" || name === "height")) {
882
+ const px = /^(\d*\.?\d+)(px)?$/.exec(value.trim());
883
+ if (px) out.push(["scrollbar-width", Number(px[1]) === 0 ? "none" : Number(px[1]) <= 8 ? "thin" : "auto"]);
884
+ if (value.trim() === "0") out.push(["scrollbar-width", "none"]);
885
+ } else if (part === "-webkit-scrollbar" && name === "display" && value.trim() === "none") out.push(["scrollbar-width", "none"]);
886
+ }
887
+ return out;
888
+ }
382
889
 
383
890
  /** Forgets every registered rule (tests). */
384
891
  export function resetCss(): void {
385
- byClass.clear(); byTag.clear(); byId.clear(); universal.length = 0; pseudoEntries.length = 0;
892
+ byClass.clear(); byTag.clear(); byId.clear(); universal.length = 0; pseudoEntries.length = 0; groupAnchors.length = 0;
386
893
  ruleClasses.clear(); simpleCache.clear(); mediaThresholds.clear();
387
- counter = 0; complex = 0; customProperties = false; viewportUnits = false; colorScheme = false;
894
+ counter = 0; complex = 0; tailwindSheets = false; customProperties = false; viewportUnits = false; colorScheme = false; displayModeRules = false;
895
+ themeTokens.clear(); rootVariables.clear();
388
896
  styleDependencies.descendants = false; styleDependencies.siblings = false; styleDependencies.ancestors = false;
389
897
  }
390
898
 
@@ -478,6 +986,22 @@ function fold(matched: Entry[], context: CssContext, variables: ReadonlyMap<stri
478
986
  }
479
987
 
480
988
  const foldCache = new WeakMap<Entry[], Record<string, unknown> | undefined>();
989
+ /**
990
+ * Rules with `var()` fold per custom-property set: elements that see the same variables (one shared
991
+ * map, inherited unchanged) share the result, at the viewport size it was folded for.
992
+ */
993
+ const NO_VARIABLES = new Map<string, string>();
994
+ const dynamicFoldCache = new WeakMap<Entry[], WeakMap<ReadonlyMap<string, string>, { width: number; height: number; style: Record<string, unknown> | undefined }>>();
995
+ function foldDynamic(matched: Entry[], context: CssContext, variables: ReadonlyMap<string, string> | undefined): Record<string, unknown> | undefined {
996
+ let byVariables = dynamicFoldCache.get(matched);
997
+ if (!byVariables) dynamicFoldCache.set(matched, byVariables = new WeakMap());
998
+ const key = variables ?? NO_VARIABLES;
999
+ const cached = byVariables.get(key);
1000
+ if (cached && cached.width === context.width && cached.height === context.height) return cached.style;
1001
+ const style = fold(matched, context, variables);
1002
+ byVariables.set(key, { width: context.width, height: context.height, style });
1003
+ return style;
1004
+ }
481
1005
 
482
1006
  /** The style the registered rules give `element`, plus its inline `style` (which wins). */
483
1007
  export function elementStyle(element: TElement, classes: readonly string[]): Record<string, unknown> | undefined {
@@ -492,8 +1016,11 @@ export function elementStyle(element: TElement, classes: readonly string[]): Rec
492
1016
  // Static rules only: one folded object per matched set, shared by every element with it.
493
1017
  if (!foldCache.has(matched)) foldCache.set(matched, fold(matched, context, variables));
494
1018
  style = foldCache.get(matched);
495
- } else if (matched.length) style = fold(matched, context, variables);
1019
+ } else if (matched.length) style = foldDynamic(matched, context, variables);
1020
+ if (groupAnchors.length && groupAnchors.some(anchor => selectorMatches(element, anchor, "any"))) style = { ...style, group: true };
496
1021
  if (inlineValues) style = { ...style, ...cssStyle(inlineValues, { ...context, ...(element._size ? { box: element._size } : {}) }, variables) };
1022
+ // CSS `display: grid` without `grid-template-columns` has one implicit column; Tarve's own default is two.
1023
+ if (style?.display === "grid" && style.columns === undefined) style = { ...style, columns: "none" };
497
1024
  if (style && (style.animation !== undefined || style.animationName !== undefined)) style = applyCssAnimation(element, style);
498
1025
  else if (element._cssAnimation) applyCssAnimation(element, {});
499
1026
  // A running animation's frame (Svelte transitions, CSS animations) overrides both.
@@ -581,6 +1108,19 @@ function parseAnimation(style: Record<string, unknown>): { name: string; duratio
581
1108
  return { name, duration: parseTime(duration) ?? times[0] ?? 0, delay: parseTime(delay) ?? times[1] ?? 0, iterations, direction, fill, easing };
582
1109
  }
583
1110
 
1111
+ /** The value `element`'s own rules and inline style declare for `property` (kebab-case), last one winning. */
1112
+ function declaredValue(element: TElement, property: string): string | undefined {
1113
+ const inline = element._style?._values.get(property);
1114
+ if (inline !== undefined) return inline;
1115
+ const classes = (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
1116
+ let value: string | undefined;
1117
+ for (const entry of matching(element, classes)) {
1118
+ if (entry.state) continue;
1119
+ for (const [name, declared] of entry.declarations) if (name === property) value = declared;
1120
+ }
1121
+ return value === undefined || value.includes("var(") ? value === undefined ? undefined : substitute(value, variablesOf(element)) : value;
1122
+ }
1123
+
584
1124
  /** Starts (or keeps, or stops) the CSS animation `style` asks for; returns the style without animation keys. */
585
1125
  function applyCssAnimation(element: TElement, style: Record<string, unknown>): Record<string, unknown> {
586
1126
  const spec = parseAnimation(style);
@@ -597,6 +1137,19 @@ function applyCssAnimation(element: TElement, style: Record<string, unknown>): R
597
1137
  for (const [name, value] of frame.declarations) out[camelCase(name)] = value;
598
1138
  return out;
599
1139
  });
1140
+ // A missing 0% or 100% keyframe is implicit and takes the element's own value (`.shimmer {
1141
+ // transform: translateX(-100%) }` with only `100% { transform: translateX(100%) }`).
1142
+ const offsets = keyframes.map(frame => frame.offset as number);
1143
+ for (const offset of [0, 1]) {
1144
+ if (offsets.includes(offset)) continue;
1145
+ const implicit: Record<string, string | number> = { offset };
1146
+ for (const frame of frames) for (const [name] of frame.declarations) {
1147
+ const own = declaredValue(element, name);
1148
+ if (own !== undefined) implicit[camelCase(name)] = own;
1149
+ }
1150
+ if (Object.keys(implicit).length > 1) keyframes.push(implicit);
1151
+ }
1152
+ keyframes.sort((x, y) => (x.offset as number) - (y.offset as number));
600
1153
  // Started after this render: `animate` restyles the element, which must not re-enter the render.
601
1154
  const animation = { cancel() { started?.cancel(); cancelled = true; } } as { cancel(): void };
602
1155
  let started: { cancel(): void } | undefined, cancelled = false;