@tarve/svelte 0.0.0-stage → 0.7.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/README.md +54 -3
- package/package.json +50 -4
- package/src/TitleBar.svelte +44 -0
- package/src/bun-preload.ts +4 -0
- package/src/bun.ts +13 -0
- package/src/compiler.ts +39 -0
- package/src/css.ts +606 -0
- package/src/dom.ts +1578 -0
- package/src/editable.ts +372 -0
- package/src/elements.d.ts +43 -0
- package/src/events.ts +87 -0
- package/src/index.ts +126 -0
- package/src/install.ts +4 -0
- package/src/plugin.ts +83 -0
- package/src/render.ts +460 -0
- package/src/resolve.ts +39 -0
- package/src/selectors.ts +316 -0
- package/src/svelte-client.ts +8 -0
package/src/css.ts
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
import { camelCase, parseDeclarations, styleDependencies, windowInstance, type TElement } from "./dom";
|
|
2
|
+
import { parseSelectorList, ruleState, selectorMatches, usesHas, type Selector } from "./selectors";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Svelte's component CSS for Tarve. The compiler emits each rule's selector and
|
|
6
|
+
* declarations (`parseCss`, at build time); the view matches them against the
|
|
7
|
+
* Svelte DOM: compound selectors by class/tag index, combinators and structural
|
|
8
|
+
* pseudo-classes against the element's ancestors and siblings, `@media` width
|
|
9
|
+
* queries against the window, and `var()`/`vw`/`vh` when the element renders.
|
|
10
|
+
*/
|
|
11
|
+
export interface CssRule {
|
|
12
|
+
selector: string;
|
|
13
|
+
declarations: [string, string][];
|
|
14
|
+
/** `@keyframes` (with `selector` empty): its frames by offset. */
|
|
15
|
+
keyframes?: { name: string; frames: { offset: number; declarations: [string, string][] }[] };
|
|
16
|
+
/** `@media` condition (width queries and `prefers-color-scheme`). */
|
|
17
|
+
media?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
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" };
|
|
22
|
+
const BOXES = new Set(["padding", "margin", "borderWidth"]);
|
|
23
|
+
const CORNERS = ["topLeft", "topRight", "bottomRight", "bottomLeft"] as const;
|
|
24
|
+
const DYNAMIC = /var\(|\d(vw|vh|vmin|vmax)\b/;
|
|
25
|
+
const kebab = (name: string) => name.startsWith("--") ? name : name.replace(/[A-Z]/g, letter => "-" + letter.toLowerCase());
|
|
26
|
+
|
|
27
|
+
/** What a value is resolved against: the viewport for `vw`/`vh`, the font size for `em`. */
|
|
28
|
+
export interface CssContext { width: number; height: number; fontSize: number; /** The element's size: `transform` turns about its centre, as CSS does. */ box?: { width: number; height: number } }
|
|
29
|
+
const DEFAULT_CONTEXT: CssContext = { width: 1120, height: 820, fontSize: 16 };
|
|
30
|
+
|
|
31
|
+
/** CSS 1–4 value box shorthand as Tarve's per-side object. */
|
|
32
|
+
function box(value: unknown): unknown {
|
|
33
|
+
if (!Array.isArray(value)) return value;
|
|
34
|
+
const [top, right = top, bottom = top, left = right] = value;
|
|
35
|
+
return { top, right, bottom, left };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
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);
|
|
40
|
+
if (!match) return undefined;
|
|
41
|
+
const value = Number(match[1]);
|
|
42
|
+
switch (match[2]) {
|
|
43
|
+
case "px": return value;
|
|
44
|
+
case "rem": return value * 16;
|
|
45
|
+
case "em": return value * context.fontSize;
|
|
46
|
+
case "vw": return value * context.width / 100;
|
|
47
|
+
case "vh": return value * context.height / 100;
|
|
48
|
+
case "vmin": return value * Math.min(context.width, context.height) / 100;
|
|
49
|
+
case "vmax": return value * Math.max(context.width, context.height) / 100;
|
|
50
|
+
case "pt": return value * 4 / 3;
|
|
51
|
+
default: return value === 0 || UNITLESS.has(property) ? value : undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function cssValue(property: string, raw: string, context: CssContext): unknown {
|
|
56
|
+
const value = raw.trim();
|
|
57
|
+
// `line-height: 20px` is a length; Tarve's lineHeight is a multiple of the font size.
|
|
58
|
+
if (property === "lineHeight") {
|
|
59
|
+
const px = /^(\d*\.?\d+)px$/.exec(value);
|
|
60
|
+
if (px) return Number(px[1]) / context.fontSize;
|
|
61
|
+
}
|
|
62
|
+
const parts = value.split(/\s+/);
|
|
63
|
+
const lengths = parts.map(part => length(part, property, context));
|
|
64
|
+
if (lengths.every(item => item !== undefined)) return lengths.length === 1 ? lengths[0] : lengths;
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
type Matrix = [number, number, number, number, number, number];
|
|
69
|
+
const multiply = (m: Matrix, n: Matrix): Matrix => [
|
|
70
|
+
m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1],
|
|
71
|
+
m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],
|
|
72
|
+
m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5],
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
/** A CSS `transform` list as one matrix about the box's centre (Tarve's origin is its top left). */
|
|
76
|
+
function transformMatrix(value: string, context: CssContext): Matrix | undefined {
|
|
77
|
+
if (value.trim() === "none") return [1, 0, 0, 1, 0, 0];
|
|
78
|
+
const { width = 0, height = 0 } = context.box ?? {};
|
|
79
|
+
const toPx = (text: string, axis: number) => {
|
|
80
|
+
const percent = /^(-?\d*\.?\d+)%$/.exec(text.trim());
|
|
81
|
+
return percent ? Number(percent[1]) * axis / 100 : length(text.trim(), "x", context) ?? 0;
|
|
82
|
+
};
|
|
83
|
+
const toRad = (text: string) => {
|
|
84
|
+
const match = /^(-?\d*\.?\d+)(deg|rad|turn)?$/.exec(text.trim());
|
|
85
|
+
if (!match) return 0;
|
|
86
|
+
const amount = Number(match[1]);
|
|
87
|
+
return match[2] === "rad" ? amount : match[2] === "turn" ? amount * 2 * Math.PI : amount * Math.PI / 180;
|
|
88
|
+
};
|
|
89
|
+
let matrix: Matrix = [1, 0, 0, 1, width / 2, height / 2];
|
|
90
|
+
for (const [, name, args] of value.matchAll(/([a-zA-Z0-9]+)\(([^)]*)\)/g)) {
|
|
91
|
+
const parts = args!.split(/\s*,\s*|\s+/).filter(Boolean);
|
|
92
|
+
let step: Matrix;
|
|
93
|
+
switch (name) {
|
|
94
|
+
case "translate": step = [1, 0, 0, 1, toPx(parts[0] ?? "0", width), toPx(parts[1] ?? "0", height)]; break;
|
|
95
|
+
case "translateX": step = [1, 0, 0, 1, toPx(parts[0] ?? "0", width), 0]; break;
|
|
96
|
+
case "translateY": step = [1, 0, 0, 1, 0, toPx(parts[0] ?? "0", height)]; break;
|
|
97
|
+
case "translate3d": step = [1, 0, 0, 1, toPx(parts[0] ?? "0", width), toPx(parts[1] ?? "0", height)]; break;
|
|
98
|
+
case "scale": { const x = Number(parts[0] ?? 1), y = Number(parts[1] ?? parts[0] ?? 1); step = [x, 0, 0, y, 0, 0]; break; }
|
|
99
|
+
case "scaleX": step = [Number(parts[0] ?? 1), 0, 0, 1, 0, 0]; break;
|
|
100
|
+
case "scaleY": step = [1, 0, 0, Number(parts[0] ?? 1), 0, 0]; break;
|
|
101
|
+
case "rotate": case "rotateZ": { const angle = toRad(parts[0] ?? "0"); step = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0]; break; }
|
|
102
|
+
case "skewX": step = [1, 0, Math.tan(toRad(parts[0] ?? "0")), 1, 0, 0]; break;
|
|
103
|
+
case "skewY": step = [1, Math.tan(toRad(parts[0] ?? "0")), 0, 1, 0, 0]; break;
|
|
104
|
+
case "matrix": step = parts.slice(0, 6).map(Number) as Matrix; break;
|
|
105
|
+
default: return undefined;
|
|
106
|
+
}
|
|
107
|
+
matrix = multiply(matrix, step);
|
|
108
|
+
}
|
|
109
|
+
return multiply(matrix, [1, 0, 0, 1, -width / 2, -height / 2]);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Substitutes `var(--name, fallback)` from `variables`. */
|
|
113
|
+
function substitute(value: string, variables: ReadonlyMap<string, string> | undefined): string {
|
|
114
|
+
let out = value;
|
|
115
|
+
for (let guard = 0; guard < 8 && out.includes("var("); guard++) {
|
|
116
|
+
out = out.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*((?:[^()]|\([^()]*\))*))?\)/g, (_, name: string, fallback: string | undefined) => variables?.get(name) ?? fallback?.trim() ?? "");
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** CSS declarations as a Tarve style object. Custom properties (`--x`) are skipped; `var()` reads `variables`. */
|
|
122
|
+
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;
|
|
124
|
+
const style: Record<string, unknown> = {};
|
|
125
|
+
for (const [name, rawValue] of entries) {
|
|
126
|
+
if (name.startsWith("--")) continue;
|
|
127
|
+
const raw = rawValue.includes("var(") ? substitute(rawValue, variables) : rawValue;
|
|
128
|
+
if (!raw) continue;
|
|
129
|
+
let property = camelCase(name);
|
|
130
|
+
if (property === "border" || property === "outline" || /^border(Top|Right|Bottom|Left)$/.test(property)) {
|
|
131
|
+
const side = /^border(Top|Right|Bottom|Left)$/.exec(property)?.[1]?.toLowerCase();
|
|
132
|
+
const target = property === "outline" ? "outline" : "border";
|
|
133
|
+
for (const part of raw.trim().split(/\s+/)) {
|
|
134
|
+
const width = length(part, "borderWidth", context);
|
|
135
|
+
if (width !== undefined) {
|
|
136
|
+
if (side) {
|
|
137
|
+
const current = style.borderWidth;
|
|
138
|
+
style.borderWidth = { ...(typeof current === "object" ? current : current === undefined ? {} : { top: current, right: current, bottom: current, left: current }), [side]: width };
|
|
139
|
+
} else style[`${target}Width`] = width;
|
|
140
|
+
} else if (part === "none" || part === "hidden") {
|
|
141
|
+
if (!side) style[`${target}Width`] = 0;
|
|
142
|
+
} else if (/^(solid|dashed|dotted|double)$/.test(part)) style[`${target}Style`] = part;
|
|
143
|
+
else style[`${target}Color`] = part;
|
|
144
|
+
}
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (property === "background" && !/url\(|gradient\(/.test(raw)) { style.background = raw.trim(); continue; }
|
|
148
|
+
if (property === "transform") {
|
|
149
|
+
const matrix = transformMatrix(raw, context);
|
|
150
|
+
if (matrix) style.transformMatrix = matrix;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (property === "font") {
|
|
154
|
+
// font: [style] [weight] size[/line-height] family
|
|
155
|
+
const match = /^(?:(italic|oblique|normal)\s+)?(?:(bold|bolder|lighter|normal|\d{3})\s+)?(\S+?)(?:\/(\S+))?\s+(.+)$/.exec(raw.trim());
|
|
156
|
+
if (match) {
|
|
157
|
+
if (match[1]) style.fontStyle = match[1];
|
|
158
|
+
if (match[2]) style.fontWeight = match[2] === "bold" ? 700 : match[2] === "normal" ? 400 : Number(match[2]) || match[2];
|
|
159
|
+
const size = length(match[3]!, "fontSize", context);
|
|
160
|
+
if (size !== undefined) style.fontSize = size;
|
|
161
|
+
if (match[4]) style.lineHeight = cssValue("lineHeight", match[4], { ...context, fontSize: size ?? context.fontSize });
|
|
162
|
+
style.fontFamily = match[5]!.trim();
|
|
163
|
+
}
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const edge = /^(padding|margin)(Top|Right|Bottom|Left)$/.exec(property);
|
|
167
|
+
if (edge) {
|
|
168
|
+
const key = edge[1]!;
|
|
169
|
+
const current = style[key];
|
|
170
|
+
const sides = typeof current === "object" && current ? { ...current } : current === undefined ? {} : { top: current, right: current, bottom: current, left: current };
|
|
171
|
+
style[key] = { ...sides, [edge[2]!.toLowerCase()]: cssValue(property, raw, context) };
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (property === "borderRadius" && raw.trim().includes(" ")) {
|
|
175
|
+
const corners = cssValue(property, raw, context) as unknown[];
|
|
176
|
+
const [a, b = a, c = a, d = b] = corners;
|
|
177
|
+
style.radius = Object.fromEntries(CORNERS.map((corner, index) => [corner, [a, b, c, d][index]]));
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (property === "flexDirection") { style.direction = raw.trim(); continue; }
|
|
181
|
+
if (property === "flexWrap") { style.wrap = raw.trim() !== "nowrap"; continue; }
|
|
182
|
+
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;
|
|
185
|
+
property = ALIASES[property] ?? property;
|
|
186
|
+
const value = cssValue(property, raw, context);
|
|
187
|
+
style[property] = BOXES.has(property) ? box(value) : value;
|
|
188
|
+
}
|
|
189
|
+
return style;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Top-level blocks of a style sheet: `[prelude, body]`. */
|
|
193
|
+
function blocks(text: string): [string, string][] {
|
|
194
|
+
const out: [string, string][] = [];
|
|
195
|
+
let index = 0;
|
|
196
|
+
while (index < text.length) {
|
|
197
|
+
const open = text.indexOf("{", index);
|
|
198
|
+
if (open < 0) break;
|
|
199
|
+
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--;
|
|
203
|
+
}
|
|
204
|
+
out.push([text.slice(index, open).trim(), text.slice(open + 1, close - 1)]);
|
|
205
|
+
index = close;
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Parses Svelte's emitted CSS into rules (at build time); `warn` hears about what Tarve cannot match. */
|
|
211
|
+
export function parseCss(code: string, warn?: (message: string) => void): CssRule[] {
|
|
212
|
+
const rules: CssRule[] = [];
|
|
213
|
+
const visit = (text: string, media?: string) => {
|
|
214
|
+
for (const [prelude, body] of blocks(text)) {
|
|
215
|
+
if (prelude.startsWith("@media")) {
|
|
216
|
+
const condition = prelude.slice(6).trim();
|
|
217
|
+
if (parseMedia(condition)) visit(body, media ? `${media} and ${condition}` : condition);
|
|
218
|
+
else warn?.(`@media ${condition} is not supported`);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const keyframes = /^@(?:-webkit-)?keyframes\s+(\S+)/.exec(prelude);
|
|
222
|
+
if (keyframes) {
|
|
223
|
+
const frames: { offset: number; declarations: [string, string][] }[] = [];
|
|
224
|
+
for (const [selectors, frame] of blocks(body)) {
|
|
225
|
+
for (const at of selectors.split(",")) {
|
|
226
|
+
const text = at.trim();
|
|
227
|
+
const offset = text === "from" ? 0 : text === "to" ? 1 : parseFloat(text) / 100;
|
|
228
|
+
if (Number.isFinite(offset)) frames.push({ offset, declarations: [...parseDeclarations(frame)] });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
rules.push({ selector: "", declarations: [], keyframes: { name: keyframes[1]!, frames: frames.sort((a, b) => a.offset - b.offset) } });
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if (prelude.startsWith("@")) {
|
|
235
|
+
if (!/^@font-face/.test(prelude)) warn?.(`${prelude} is not supported`);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const declarations = [...parseDeclarations(body)];
|
|
239
|
+
for (const selector of splitSelectors(prelude)) {
|
|
240
|
+
try {
|
|
241
|
+
parseSelectorList(selector);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
warn?.(`selector "${selector}": ${(error as Error).message}`);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
rules.push({ selector, declarations, ...(media ? { media } : {}) });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
visit(code.replace(/\/\*[\s\S]*?\*\//g, ""));
|
|
251
|
+
return rules;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function splitSelectors(prelude: string): string[] {
|
|
255
|
+
const out: string[] = [];
|
|
256
|
+
let depth = 0, start = 0;
|
|
257
|
+
for (let index = 0; index < prelude.length; index++) {
|
|
258
|
+
const char = prelude[index];
|
|
259
|
+
if (char === "(" || char === "[") depth++;
|
|
260
|
+
else if (char === ")" || char === "]") depth--;
|
|
261
|
+
else if (char === "," && depth === 0) { out.push(prelude.slice(start, index).trim()); start = index + 1; }
|
|
262
|
+
}
|
|
263
|
+
out.push(prelude.slice(start).trim());
|
|
264
|
+
return out.filter(Boolean);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
type MediaTest = { min?: number; max?: number; dark?: boolean; orientation?: "portrait" | "landscape"; minHeight?: number; maxHeight?: number };
|
|
268
|
+
|
|
269
|
+
/** Width/height/orientation/color-scheme media queries; undefined for anything else. */
|
|
270
|
+
function parseMedia(condition: string): MediaTest | undefined {
|
|
271
|
+
const test: MediaTest = {};
|
|
272
|
+
for (const part of condition.replace(/^(only\s+)?(screen|all)\s*(and\s*)?/i, "").split(/\s+and\s+/i)) {
|
|
273
|
+
const feature = /^\(\s*([\w-]+)\s*:\s*([^)]+?)\s*\)$/.exec(part.trim());
|
|
274
|
+
if (!feature) { if (part.trim()) return undefined; continue; }
|
|
275
|
+
const [, name, value] = feature;
|
|
276
|
+
const px = /^(\d*\.?\d+)(px|em|rem)?$/.exec(value!);
|
|
277
|
+
const size = px ? Number(px[1]) * (px[2] === "em" || px[2] === "rem" ? 16 : 1) : undefined;
|
|
278
|
+
if (name === "min-width" && size !== undefined) test.min = size;
|
|
279
|
+
else if (name === "max-width" && size !== undefined) test.max = size;
|
|
280
|
+
else if (name === "min-height" && size !== undefined) test.minHeight = size;
|
|
281
|
+
else if (name === "max-height" && size !== undefined) test.maxHeight = size;
|
|
282
|
+
else if (name === "prefers-color-scheme") test.dark = value === "dark";
|
|
283
|
+
else if (name === "orientation" && (value === "portrait" || value === "landscape")) test.orientation = value;
|
|
284
|
+
else return undefined;
|
|
285
|
+
}
|
|
286
|
+
return test;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function mediaMatches(test: MediaTest): boolean {
|
|
290
|
+
const width = windowInstance.innerWidth, height = windowInstance.innerHeight;
|
|
291
|
+
if (test.min !== undefined && width < test.min) return false;
|
|
292
|
+
if (test.max !== undefined && width > test.max) return false;
|
|
293
|
+
if (test.minHeight !== undefined && height < test.minHeight) return false;
|
|
294
|
+
if (test.maxHeight !== undefined && height > test.maxHeight) return false;
|
|
295
|
+
if (test.orientation && (test.orientation === "portrait") !== (height >= width)) return false;
|
|
296
|
+
if (test.dark !== undefined && test.dark !== windowInstance._dark) return false;
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
interface Entry {
|
|
301
|
+
selector: Selector;
|
|
302
|
+
state?: string;
|
|
303
|
+
order: number;
|
|
304
|
+
specificity: number;
|
|
305
|
+
declarations: [string, string][];
|
|
306
|
+
/** Resolved once when no value depends on the element (`var()`, viewport units). */
|
|
307
|
+
style?: Record<string, unknown>;
|
|
308
|
+
variables?: [string, string][];
|
|
309
|
+
media?: MediaTest;
|
|
310
|
+
/** Matches by the element's own tag and classes alone: cacheable per tag + class list. */
|
|
311
|
+
simple: boolean;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const byClass = new Map<string, Entry[]>();
|
|
315
|
+
const byTag = new Map<string, Entry[]>();
|
|
316
|
+
const byId = new Map<string, Entry[]>();
|
|
317
|
+
const universal: Entry[] = [];
|
|
318
|
+
/** `@keyframes` by name (Svelte scopes the names per component). */
|
|
319
|
+
const keyframeSets = new Map<string, { offset: number; declarations: [string, string][] }[]>();
|
|
320
|
+
/** `::before` / `::after` rules: they style generated content, not the element. */
|
|
321
|
+
const pseudoEntries: Entry[] = [];
|
|
322
|
+
/** Class names some component's CSS selects: they style through those rules, not as Tailwind utilities. */
|
|
323
|
+
const ruleClasses = new Set<string>();
|
|
324
|
+
let counter = 0;
|
|
325
|
+
let complex = 0;
|
|
326
|
+
let customProperties = false;
|
|
327
|
+
const simpleCache = new Map<string, Entry[]>();
|
|
328
|
+
/** Width/height thresholds of registered `@media` rules: crossing one restyles the app. */
|
|
329
|
+
const mediaThresholds = new Set<number>();
|
|
330
|
+
let viewportUnits = false;
|
|
331
|
+
|
|
332
|
+
export function isComponentClass(name: string): boolean {
|
|
333
|
+
return ruleClasses.has(name);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function bucket(map: Map<string, Entry[]>, key: string, entry: Entry): void {
|
|
337
|
+
let list = map.get(key);
|
|
338
|
+
if (!list) map.set(key, list = []);
|
|
339
|
+
list.push(entry);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Registers a component's rules (the compiled module calls this once). */
|
|
343
|
+
export function registerCss(rules: readonly CssRule[]): void {
|
|
344
|
+
for (const rule of rules) {
|
|
345
|
+
if (rule.keyframes) { keyframeSets.set(rule.keyframes.name, rule.keyframes.frames); continue; }
|
|
346
|
+
for (const selector of parseSelectorList(rule.selector)) {
|
|
347
|
+
const media = rule.media ? parseMedia(rule.media) : undefined;
|
|
348
|
+
if (rule.media && !media) continue;
|
|
349
|
+
const last = selector.compounds[selector.compounds.length - 1]!;
|
|
350
|
+
if (usesHas(selector)) styleDependencies.ancestors = true;
|
|
351
|
+
const dynamic = rule.declarations.some(([name, value]) => DYNAMIC.test(value) || name.startsWith("--"));
|
|
352
|
+
const variables = rule.declarations.filter(([name]) => name.startsWith("--"));
|
|
353
|
+
const simple = selector.compounds.length === 1 && !last.id && last.attributes.length === 0
|
|
354
|
+
&& last.pseudos.every(pseudo => pseudo.kind === "state") && !media && !dynamic;
|
|
355
|
+
const state = ruleState(selector);
|
|
356
|
+
const entry: Entry = {
|
|
357
|
+
selector, order: counter++, specificity: selector.specificity, declarations: rule.declarations,
|
|
358
|
+
...(state ? { state } : {}), ...(media ? { media } : {}), ...(variables.length ? { variables } : {}), simple,
|
|
359
|
+
...(dynamic ? {} : { style: cssStyle(rule.declarations) }),
|
|
360
|
+
};
|
|
361
|
+
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; }
|
|
363
|
+
if (last.id) bucket(byId, last.id, entry);
|
|
364
|
+
else if (last.classes[0]) bucket(byClass, last.classes[0], entry);
|
|
365
|
+
else if (last.tag) bucket(byTag, last.tag, entry);
|
|
366
|
+
else universal.push(entry);
|
|
367
|
+
if (!simple) complex++;
|
|
368
|
+
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;
|
|
370
|
+
if (media) for (const value of [media.min, media.max, media.minHeight, media.maxHeight]) if (value !== undefined) mediaThresholds.add(value);
|
|
371
|
+
if (media?.dark !== undefined) colorScheme = true;
|
|
372
|
+
// Restyle what a change can affect: descendants for ancestor selectors and
|
|
373
|
+
// inherited custom properties, siblings for `+`, `~` and :nth-child().
|
|
374
|
+
if (selector.combinators.some(combinator => combinator === " " || combinator === ">") || customProperties) styleDependencies.descendants = true;
|
|
375
|
+
if (selector.combinators.some(combinator => combinator === "+" || combinator === "~")
|
|
376
|
+
|| selector.compounds.some(compound => compound.pseudos.some(pseudo => /child|of-type|empty/.test(pseudo.kind)))) styleDependencies.siblings = true;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
simpleCache.clear();
|
|
380
|
+
}
|
|
381
|
+
let colorScheme = false;
|
|
382
|
+
|
|
383
|
+
/** Forgets every registered rule (tests). */
|
|
384
|
+
export function resetCss(): void {
|
|
385
|
+
byClass.clear(); byTag.clear(); byId.clear(); universal.length = 0; pseudoEntries.length = 0;
|
|
386
|
+
ruleClasses.clear(); simpleCache.clear(); mediaThresholds.clear();
|
|
387
|
+
counter = 0; complex = 0; customProperties = false; viewportUnits = false; colorScheme = false;
|
|
388
|
+
styleDependencies.descendants = false; styleDependencies.siblings = false; styleDependencies.ancestors = false;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Whether a window resize from `before` to `after` changes any rule's outcome. */
|
|
392
|
+
export function resizeRestyles(before: { width: number; height: number }, after: { width: number; height: number }): boolean {
|
|
393
|
+
if (viewportUnits && (before.width !== after.width || before.height !== after.height)) return true;
|
|
394
|
+
for (const threshold of mediaThresholds) {
|
|
395
|
+
const side = (value: number) => Math.sign(value - threshold);
|
|
396
|
+
if (side(before.width) !== side(after.width) || side(before.height) !== side(after.height)) return true;
|
|
397
|
+
}
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Whether a `prefers-color-scheme` rule exists (a theme change restyles the app). */
|
|
402
|
+
export function usesColorScheme(): boolean {
|
|
403
|
+
return colorScheme;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function compare(a: Entry, b: Entry): number {
|
|
407
|
+
return a.specificity - b.specificity || a.order - b.order;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function candidates(element: TElement, classes: readonly string[]): Entry[] {
|
|
411
|
+
const out = new Set<Entry>(universal);
|
|
412
|
+
for (const entry of byTag.get(element.localName) ?? []) out.add(entry);
|
|
413
|
+
for (const name of classes) for (const entry of byClass.get(name) ?? []) out.add(entry);
|
|
414
|
+
const id = element.getAttribute("id");
|
|
415
|
+
if (id) for (const entry of byId.get(id) ?? []) out.add(entry);
|
|
416
|
+
return [...out];
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** A stand-in element with only a tag and classes, for the cached simple matches. */
|
|
420
|
+
function asSelectorElement(tag: string, classes: readonly string[]) {
|
|
421
|
+
const className = classes.join(" ");
|
|
422
|
+
return {
|
|
423
|
+
localName: tag, parentElement: null, previousElementSibling: null, nextElementSibling: null,
|
|
424
|
+
getAttribute: (name: string) => name === "class" ? className : null,
|
|
425
|
+
hasAttribute: (name: string) => name === "class", _isChecked: false, _isDisabled: false,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** The rules matching an element of `tag` with `classes` that need nothing else; cached. */
|
|
430
|
+
function simpleMatches(tag: string, classes: readonly string[], all: Entry[]): Entry[] {
|
|
431
|
+
const key = tag + "\0" + classes.join(" ");
|
|
432
|
+
let matched = simpleCache.get(key);
|
|
433
|
+
if (!matched) {
|
|
434
|
+
const stand = asSelectorElement(tag, classes);
|
|
435
|
+
matched = all.filter(entry => entry.simple && selectorMatches(stand, entry.selector, "any")).sort(compare);
|
|
436
|
+
if (simpleCache.size > 4096) simpleCache.clear();
|
|
437
|
+
simpleCache.set(key, matched);
|
|
438
|
+
}
|
|
439
|
+
return matched;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function matching(element: TElement, classes: readonly string[]): Entry[] {
|
|
443
|
+
const all = candidates(element, classes);
|
|
444
|
+
const simple = simpleMatches(element.localName, classes, all);
|
|
445
|
+
if (!complex) return simple;
|
|
446
|
+
const rest = all.filter(entry => !entry.simple && (!entry.media || mediaMatches(entry.media)) && selectorMatches(element, entry.selector, "any"));
|
|
447
|
+
return rest.length ? [...simple, ...rest].sort(compare) : simple;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Custom properties an element sees: inherited from its ancestors, then its own rules and inline style. */
|
|
451
|
+
function variablesOf(element: TElement | null): Map<string, string> | undefined {
|
|
452
|
+
if (!element || !customProperties) return undefined;
|
|
453
|
+
const cached = element._cssVariables;
|
|
454
|
+
if (cached && cached.version === element._attrVersion) return cached.map;
|
|
455
|
+
const inherited = variablesOf(element.parentElement);
|
|
456
|
+
let map = inherited;
|
|
457
|
+
const classes = (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
|
|
458
|
+
const own = matching(element, classes).filter(entry => entry.variables && !entry.state);
|
|
459
|
+
const inline = element._style ? [...element._style._values].filter(([name]) => name.startsWith("--")) : [];
|
|
460
|
+
if (own.length || inline.length) {
|
|
461
|
+
map = new Map(inherited);
|
|
462
|
+
for (const entry of own) for (const [name, value] of entry.variables!) map.set(name, substitute(value, map));
|
|
463
|
+
for (const [name, value] of inline) map.set(name, substitute(value, map));
|
|
464
|
+
}
|
|
465
|
+
element._cssVariables = { version: element._attrVersion, map };
|
|
466
|
+
return map;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function fold(matched: Entry[], context: CssContext, variables: ReadonlyMap<string, string> | undefined): Record<string, unknown> | undefined {
|
|
470
|
+
let style: Record<string, unknown> | undefined;
|
|
471
|
+
for (const entry of matched) {
|
|
472
|
+
const values = entry.style ?? cssStyle(entry.declarations, context, variables);
|
|
473
|
+
style ??= {};
|
|
474
|
+
if (entry.state) style[entry.state] = { ...(style[entry.state] as object | undefined), ...values };
|
|
475
|
+
else Object.assign(style, values);
|
|
476
|
+
}
|
|
477
|
+
return style;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const foldCache = new WeakMap<Entry[], Record<string, unknown> | undefined>();
|
|
481
|
+
|
|
482
|
+
/** The style the registered rules give `element`, plus its inline `style` (which wins). */
|
|
483
|
+
export function elementStyle(element: TElement, classes: readonly string[]): Record<string, unknown> | undefined {
|
|
484
|
+
const hasRules = byClass.size || byTag.size || byId.size || universal.length;
|
|
485
|
+
const inlineValues = element._style?.length ? element._style._values : undefined;
|
|
486
|
+
if (!hasRules && !inlineValues && !element._animations?.size) return undefined;
|
|
487
|
+
const matched = hasRules ? matching(element, classes) : [];
|
|
488
|
+
const context = { width: windowInstance.innerWidth, height: windowInstance.innerHeight, fontSize: 16 };
|
|
489
|
+
const variables = customProperties ? variablesOf(element) : undefined;
|
|
490
|
+
let style: Record<string, unknown> | undefined;
|
|
491
|
+
if (matched.length && matched.every(entry => entry.style)) {
|
|
492
|
+
// Static rules only: one folded object per matched set, shared by every element with it.
|
|
493
|
+
if (!foldCache.has(matched)) foldCache.set(matched, fold(matched, context, variables));
|
|
494
|
+
style = foldCache.get(matched);
|
|
495
|
+
} else if (matched.length) style = fold(matched, context, variables);
|
|
496
|
+
if (inlineValues) style = { ...style, ...cssStyle(inlineValues, { ...context, ...(element._size ? { box: element._size } : {}) }, variables) };
|
|
497
|
+
if (style && (style.animation !== undefined || style.animationName !== undefined)) style = applyCssAnimation(element, style);
|
|
498
|
+
else if (element._cssAnimation) applyCssAnimation(element, {});
|
|
499
|
+
// A running animation's frame (Svelte transitions, CSS animations) overrides both.
|
|
500
|
+
const frame = element._animationStyle;
|
|
501
|
+
if (frame) style = { ...style, ...cssStyle(Object.entries(frame).map(([name, value]) => [kebab(name), value] as [string, string]), { ...context, ...(element._size ? { box: element._size } : {}) }, variables) };
|
|
502
|
+
return style;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** The tag-and-class style of an element (rules that need nothing else). */
|
|
506
|
+
export function matchCss(tag: string, classes: readonly string[]): Record<string, unknown> | undefined {
|
|
507
|
+
const all = new Set<Entry>(universal);
|
|
508
|
+
for (const entry of byTag.get(tag) ?? []) all.add(entry);
|
|
509
|
+
for (const name of classes) for (const entry of byClass.get(name) ?? []) all.add(entry);
|
|
510
|
+
const matched = simpleMatches(tag, classes, [...all]);
|
|
511
|
+
return matched.length ? fold(matched, DEFAULT_CONTEXT, undefined) : undefined;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export interface GeneratedContent { text: string; style: Record<string, unknown> }
|
|
515
|
+
|
|
516
|
+
/** The value of `content`: strings and `attr()` joined; undefined for none/normal. */
|
|
517
|
+
function contentText(value: string, element: TElement): string | undefined {
|
|
518
|
+
const text = value.trim();
|
|
519
|
+
if (text === "none" || text === "normal") return undefined;
|
|
520
|
+
let out = "";
|
|
521
|
+
for (const [, double, single, attribute] of text.matchAll(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|attr\(\s*([\w-]+)\s*\)/g)) {
|
|
522
|
+
if (attribute) out += element.getAttribute(attribute) ?? "";
|
|
523
|
+
else out += (double ?? single ?? "").replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_, hex: string) => String.fromCodePoint(parseInt(hex, 16))).replace(/\\(.)/g, "$1");
|
|
524
|
+
}
|
|
525
|
+
return out;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** `::before` and `::after` content generated for `element`. */
|
|
529
|
+
export function generatedContent(element: TElement): { before?: GeneratedContent; after?: GeneratedContent } | undefined {
|
|
530
|
+
if (!pseudoEntries.length) return undefined;
|
|
531
|
+
const matched = pseudoEntries.filter(entry => (!entry.media || mediaMatches(entry.media)) && !entry.state && selectorMatches(element, entry.selector, "any")).sort(compare);
|
|
532
|
+
if (!matched.length) return undefined;
|
|
533
|
+
const context = { width: windowInstance.innerWidth, height: windowInstance.innerHeight, fontSize: 16 };
|
|
534
|
+
const variables = customProperties ? variablesOf(element) : undefined;
|
|
535
|
+
const out: { before?: GeneratedContent; after?: GeneratedContent } = {};
|
|
536
|
+
for (const side of ["before", "after"] as const) {
|
|
537
|
+
let content: string | undefined;
|
|
538
|
+
let style: Record<string, unknown> = {};
|
|
539
|
+
for (const entry of matched) {
|
|
540
|
+
if (entry.selector.pseudoElement !== side) continue;
|
|
541
|
+
for (const [name, value] of entry.declarations) if (name === "content") content = contentText(substitute(value, variables), element);
|
|
542
|
+
style = { ...style, ...(entry.style ?? cssStyle(entry.declarations, context, variables)) };
|
|
543
|
+
}
|
|
544
|
+
delete style.content;
|
|
545
|
+
if (content !== undefined) out[side] = { text: content, style };
|
|
546
|
+
}
|
|
547
|
+
return out.before || out.after ? out : undefined;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const TIME = /^(-?\d*\.?\d+)(ms|s)$/;
|
|
551
|
+
const DIRECTIONS = new Set(["normal", "reverse", "alternate", "alternate-reverse"]);
|
|
552
|
+
const FILLS = new Set(["none", "forwards", "backwards", "both"]);
|
|
553
|
+
const EASINGS = /^(linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end|cubic-bezier\(.*\)|steps\(.*\))$/;
|
|
554
|
+
|
|
555
|
+
/** The `animation` shorthand (first animation of a list) as Web Animations timing. */
|
|
556
|
+
function parseAnimation(style: Record<string, unknown>): { name: string; duration: number; delay: number; iterations: number; direction: string; fill: string; easing: string } | undefined {
|
|
557
|
+
const shorthand = typeof style.animation === "string" ? style.animation : "";
|
|
558
|
+
const parts = shorthand ? (shorthand.split(/,(?![^(]*\))/)[0] ?? "").match(/[\w-]+\([^)]*\)|\S+/g) ?? [] : [];
|
|
559
|
+
let name = typeof style.animationName === "string" ? style.animationName : "";
|
|
560
|
+
const times: number[] = [];
|
|
561
|
+
let iterations = 1, direction = "normal", fill = "none", easing = "ease";
|
|
562
|
+
for (const part of parts) {
|
|
563
|
+
const time = TIME.exec(part);
|
|
564
|
+
if (time) times.push(Number(time[1]) * (time[2] === "s" ? 1000 : 1));
|
|
565
|
+
else if (part === "infinite") iterations = Infinity;
|
|
566
|
+
else if (/^\d*\.?\d+$/.test(part)) iterations = Number(part);
|
|
567
|
+
else if (DIRECTIONS.has(part)) direction = part;
|
|
568
|
+
else if (FILLS.has(part)) fill = part;
|
|
569
|
+
else if (EASINGS.test(part)) easing = part;
|
|
570
|
+
else if (part !== "running" && part !== "paused" && part !== "none") name = part;
|
|
571
|
+
}
|
|
572
|
+
const read = (key: string) => typeof style[key] === "string" ? style[key] as string : typeof style[key] === "number" ? String(style[key]) : undefined;
|
|
573
|
+
const duration = read("animationDuration"), delay = read("animationDelay");
|
|
574
|
+
const parseTime = (value: string | undefined) => { const time = value ? TIME.exec(value) : null; return time ? Number(time[1]) * (time[2] === "s" ? 1000 : 1) : undefined; };
|
|
575
|
+
const iterationCount = read("animationIterationCount");
|
|
576
|
+
if (iterationCount) iterations = iterationCount === "infinite" ? Infinity : Number(iterationCount);
|
|
577
|
+
if (read("animationDirection")) direction = read("animationDirection")!;
|
|
578
|
+
if (read("animationFillMode")) fill = read("animationFillMode")!;
|
|
579
|
+
if (read("animationTimingFunction")) easing = read("animationTimingFunction")!;
|
|
580
|
+
if (!name || name === "none") return undefined;
|
|
581
|
+
return { name, duration: parseTime(duration) ?? times[0] ?? 0, delay: parseTime(delay) ?? times[1] ?? 0, iterations, direction, fill, easing };
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** Starts (or keeps, or stops) the CSS animation `style` asks for; returns the style without animation keys. */
|
|
585
|
+
function applyCssAnimation(element: TElement, style: Record<string, unknown>): Record<string, unknown> {
|
|
586
|
+
const spec = parseAnimation(style);
|
|
587
|
+
const rest = { ...style };
|
|
588
|
+
for (const key of Object.keys(rest)) if (key === "animation" || key.startsWith("animation")) delete rest[key];
|
|
589
|
+
const key = spec ? JSON.stringify(spec) : undefined;
|
|
590
|
+
if (element._cssAnimation?.key === key) return rest;
|
|
591
|
+
(element._cssAnimation?.animation as { cancel(): void } | undefined)?.cancel();
|
|
592
|
+
element._cssAnimation = undefined;
|
|
593
|
+
const frames = spec ? keyframeSets.get(spec.name) : undefined;
|
|
594
|
+
if (!spec || !frames?.length) return rest;
|
|
595
|
+
const keyframes = frames.map(frame => {
|
|
596
|
+
const out: Record<string, string | number> = { offset: frame.offset };
|
|
597
|
+
for (const [name, value] of frame.declarations) out[camelCase(name)] = value;
|
|
598
|
+
return out;
|
|
599
|
+
});
|
|
600
|
+
// Started after this render: `animate` restyles the element, which must not re-enter the render.
|
|
601
|
+
const animation = { cancel() { started?.cancel(); cancelled = true; } } as { cancel(): void };
|
|
602
|
+
let started: { cancel(): void } | undefined, cancelled = false;
|
|
603
|
+
queueMicrotask(() => { if (!cancelled) started = element.animate(keyframes, { duration: spec.duration, delay: spec.delay, iterations: spec.iterations, direction: spec.direction, fill: spec.fill, easing: spec.easing }); });
|
|
604
|
+
element._cssAnimation = { key: key!, animation };
|
|
605
|
+
return rest;
|
|
606
|
+
}
|