@c9up/orbit 0.0.0-stage → 0.1.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.
Files changed (105) hide show
  1. package/Cargo.lock +139 -0
  2. package/Cargo.toml +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +320 -2
  5. package/android/orbit.cmake +31 -0
  6. package/android/src/main/cpp/NativeOrbit.cpp +309 -0
  7. package/android/src/main/cpp/NativeOrbit.h +35 -0
  8. package/android/src/main/cpp/orbit_host.h +34 -0
  9. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +286 -0
  10. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +258 -0
  11. package/android/src/main/java/com/c9up/orbit/OrbitImage.kt +346 -0
  12. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +161 -0
  13. package/android/src/main/java/com/c9up/orbit/OrbitPress.kt +110 -0
  14. package/android/src/main/java/com/c9up/orbit/OrbitVector.kt +115 -0
  15. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +362 -0
  16. package/crates/orbit-host/Cargo.toml +14 -0
  17. package/crates/orbit-host/src/gesture.rs +561 -0
  18. package/crates/orbit-host/src/lib.rs +2042 -0
  19. package/crates/orbit-host/src/motion.rs +328 -0
  20. package/crates/orbit-host/src/vector.rs +1173 -0
  21. package/dist/color.d.ts +10 -0
  22. package/dist/color.d.ts.map +1 -0
  23. package/dist/color.js +62 -0
  24. package/dist/color.js.map +1 -0
  25. package/dist/commit.d.ts +77 -0
  26. package/dist/commit.d.ts.map +1 -0
  27. package/dist/commit.js +302 -0
  28. package/dist/commit.js.map +1 -0
  29. package/dist/errors.d.ts +76 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +89 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/host.d.ts +49 -0
  34. package/dist/host.d.ts.map +1 -0
  35. package/dist/host.js +20 -0
  36. package/dist/host.js.map +1 -0
  37. package/dist/index.d.ts +31 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +31 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/motion.d.ts +18 -0
  42. package/dist/motion.d.ts.map +1 -0
  43. package/dist/motion.js +67 -0
  44. package/dist/motion.js.map +1 -0
  45. package/dist/node.d.ts +46 -0
  46. package/dist/node.d.ts.map +1 -0
  47. package/dist/node.js +110 -0
  48. package/dist/node.js.map +1 -0
  49. package/dist/pages.d.ts +56 -0
  50. package/dist/pages.d.ts.map +1 -0
  51. package/dist/pages.js +157 -0
  52. package/dist/pages.js.map +1 -0
  53. package/dist/react-native/index.d.ts +33 -0
  54. package/dist/react-native/index.d.ts.map +1 -0
  55. package/dist/react-native/index.js +71 -0
  56. package/dist/react-native/index.js.map +1 -0
  57. package/dist/report.d.ts +13 -0
  58. package/dist/report.d.ts.map +1 -0
  59. package/dist/report.js +22 -0
  60. package/dist/report.js.map +1 -0
  61. package/dist/server.d.ts +109 -0
  62. package/dist/server.d.ts.map +1 -0
  63. package/dist/server.js +290 -0
  64. package/dist/server.js.map +1 -0
  65. package/dist/stack.d.ts +117 -0
  66. package/dist/stack.d.ts.map +1 -0
  67. package/dist/stack.js +299 -0
  68. package/dist/stack.js.map +1 -0
  69. package/dist/styles.d.ts +138 -0
  70. package/dist/styles.d.ts.map +1 -0
  71. package/dist/styles.js +920 -0
  72. package/dist/styles.js.map +1 -0
  73. package/dist/template.d.ts +27 -0
  74. package/dist/template.d.ts.map +1 -0
  75. package/dist/template.js +1436 -0
  76. package/dist/template.js.map +1 -0
  77. package/dist/textDecoder.d.ts +29 -0
  78. package/dist/textDecoder.d.ts.map +1 -0
  79. package/dist/textDecoder.js +149 -0
  80. package/dist/textDecoder.js.map +1 -0
  81. package/dist/url.d.ts +45 -0
  82. package/dist/url.d.ts.map +1 -0
  83. package/dist/url.js +303 -0
  84. package/dist/url.js.map +1 -0
  85. package/package.json +96 -3
  86. package/scripts/build-android.sh +27 -0
  87. package/scripts/test-styles.mjs +31 -0
  88. package/specs/NativeOrbit.ts +34 -0
  89. package/src/color.ts +68 -0
  90. package/src/commit.ts +373 -0
  91. package/src/errors.ts +178 -0
  92. package/src/host.ts +91 -0
  93. package/src/index.ts +64 -0
  94. package/src/motion.ts +88 -0
  95. package/src/node.ts +133 -0
  96. package/src/pages.ts +207 -0
  97. package/src/react-native/index.ts +115 -0
  98. package/src/react-native/react-native.d.ts +39 -0
  99. package/src/report.ts +25 -0
  100. package/src/server.ts +395 -0
  101. package/src/stack.ts +428 -0
  102. package/src/styles.ts +1021 -0
  103. package/src/template.ts +1681 -0
  104. package/src/textDecoder.ts +162 -0
  105. package/src/url.ts +333 -0
package/src/styles.ts ADDED
@@ -0,0 +1,1021 @@
1
+ import { type Signal, signal } from "@c9up/aurora/core";
2
+ import { E_ORBIT_STYLE_TABLE } from "./errors.js";
3
+ import type { Style } from "./node.js";
4
+
5
+ /**
6
+ * Styles from the app's own Tailwind build.
7
+ *
8
+ * `ream android:build` runs Tailwind over the app as its web build does, and
9
+ * compiles the stylesheet into a table (`ream css:compile`): every utility
10
+ * rule with its declarations already resolved against the theme (lengths in
11
+ * px, colours as `#rrggbbaa`, light and dark), its variant as conditions, and
12
+ * the custom properties classes compose at run time (`--tw-shadow`,
13
+ * `--tw-leading`…) left as `var()`. This applies the table to orbit's tree
14
+ * the way a browser applies the stylesheet: rules matched by class and
15
+ * condition, cascaded by specificity then order, custom properties resolved,
16
+ * and the result read into the host's style keys.
17
+ */
18
+
19
+ type SchemeValue = string | { light: string; dark: string };
20
+
21
+ export type StyleCondition =
22
+ | { attribute: string; equals: string | null }
23
+ | { attribute: string; operator: "*" | "^" | "$" | "~" | "|"; value: string }
24
+ | { state: string }
25
+ | { scheme: "dark" }
26
+ | { class: string }
27
+ | { not: StyleCondition[] }
28
+ | { any: StyleCondition[] }
29
+ | { all: StyleCondition[] }
30
+ | { ancestor: Relative }
31
+ | { parent: Relative }
32
+ | { previous: Relative }
33
+ | { previousAdjacent: Relative }
34
+ | { has: string }
35
+ | { position: string; of?: string }
36
+ | { dir: string };
37
+
38
+ interface Relative {
39
+ classes: string[];
40
+ when: StyleCondition[];
41
+ }
42
+
43
+ type Target =
44
+ | "self"
45
+ | { pseudo: string }
46
+ | {
47
+ relation: "child" | "descendant";
48
+ tag: string | null;
49
+ when: StyleCondition[];
50
+ pseudo: string | null;
51
+ };
52
+
53
+ export interface StyleRule {
54
+ /** The utility class it belongs to; absent for an element rule. */
55
+ class?: string;
56
+ /** A rule of the base layer: a tag, or `*` for every element. */
57
+ element?: string;
58
+ when?: StyleCondition[];
59
+ target?: Target;
60
+ media?: { minWidth?: number; maxWidth?: number };
61
+ specificity: number;
62
+ declarations: Array<[string, SchemeValue]>;
63
+ }
64
+
65
+ export interface StyleTable {
66
+ version: 1;
67
+ properties: { [name: string]: { initial: string | null; inherits: boolean } };
68
+ rules: StyleRule[];
69
+ inert: string[];
70
+ }
71
+
72
+ /** What the resolver reads of an element: all reactive reads. */
73
+ export interface StyledElement {
74
+ /** The tag; the root answers to `html` and `body` as well (`root`). */
75
+ readonly tag: string;
76
+ readonly root?: boolean;
77
+ classes(): readonly string[];
78
+ /** The attribute's value, `""` when present without one, null when absent. */
79
+ attribute(name: string): string | null;
80
+ readonly parent: StyledElement | null;
81
+ /** The element sibling just before this one, if any. */
82
+ readonly previous: StyledElement | null;
83
+ /** Custom properties this element passes down (resolved), set once computed. */
84
+ vars?: ReadonlyMap<string, string>;
85
+ }
86
+
87
+ /** An element's computed style, read into the host's keys. */
88
+ export interface Computed {
89
+ box: Style;
90
+ text: Style;
91
+ /** `display: flex` / `inline-flex`: each child its own item, a row by default. */
92
+ flex: boolean;
93
+ /** `overflow(-y): auto | scroll`. */
94
+ scroll: boolean;
95
+ /** `::placeholder`'s colour, for a text field. */
96
+ placeholder?: string;
97
+ vars: ReadonlyMap<string, string>;
98
+ }
99
+
100
+ interface Indexed {
101
+ rule: StyleRule;
102
+ order: number;
103
+ }
104
+
105
+ let selfRules = new Map<string, Indexed[]>();
106
+ let elementRules = new Map<string, Indexed[]>();
107
+ let relatedRules = new Map<string, Indexed[]>();
108
+ let known = new Set<string>();
109
+ let properties: StyleTable["properties"] = {};
110
+
111
+ /** Classes an element asked for that the app's stylesheet does not have. */
112
+ export const unknownClasses = new Set<string>();
113
+
114
+ /** The scheme `dark:` and the theme's dark values follow. */
115
+ export const colorScheme: Signal<"light" | "dark"> = signal<"light" | "dark">(
116
+ "light",
117
+ );
118
+
119
+ /** The viewport, for `sm:` / `md:` and `vw` / `vh` (set by `mount`). */
120
+ export const viewportSize: Signal<{ width: number; height: number }> = signal({
121
+ width: 0,
122
+ height: 0,
123
+ });
124
+
125
+ const isObject = (v: unknown): v is { [key: string]: unknown } =>
126
+ typeof v === "object" && v !== null && !Array.isArray(v);
127
+
128
+ function isRule(v: unknown): v is StyleRule {
129
+ return (
130
+ isObject(v) &&
131
+ (typeof v.class === "string" || typeof v.element === "string") &&
132
+ typeof v.specificity === "number" &&
133
+ Array.isArray(v.declarations)
134
+ );
135
+ }
136
+
137
+ /** A table `ream css:compile` wrote, checked rather than trusted (it is a file read at run time). */
138
+ export function isStyleTable(v: unknown): v is StyleTable {
139
+ return (
140
+ isObject(v) &&
141
+ v.version === 1 &&
142
+ isObject(v.properties) &&
143
+ Array.isArray(v.rules) &&
144
+ v.rules.every(isRule) &&
145
+ Array.isArray(v.inert)
146
+ );
147
+ }
148
+
149
+ /** Give orbit the app's style table (`ream android:*` does it before the app runs). */
150
+ export function useStyles(table: unknown): void {
151
+ if (!isStyleTable(table)) {
152
+ throw new E_ORBIT_STYLE_TABLE();
153
+ }
154
+ selfRules = new Map();
155
+ relatedRules = new Map();
156
+ elementRules = new Map();
157
+ known = new Set(table.inert);
158
+ properties = table.properties;
159
+ table.rules.forEach((rule, order) => {
160
+ if (rule.class === undefined) {
161
+ const tag = rule.element ?? "*";
162
+ const list = elementRules.get(tag) ?? [];
163
+ list.push({ rule, order });
164
+ elementRules.set(tag, list);
165
+ return;
166
+ }
167
+ known.add(rule.class);
168
+ const into =
169
+ rule.target === undefined ||
170
+ rule.target === "self" ||
171
+ !("relation" in rule.target)
172
+ ? selfRules
173
+ : relatedRules;
174
+ const list = into.get(rule.class) ?? [];
175
+ list.push({ rule, order });
176
+ into.set(rule.class, list);
177
+ });
178
+ unknownClasses.clear();
179
+ }
180
+
181
+ // ─── Matching ────────────────────────────────────────────────────────
182
+
183
+ function matches(el: StyledElement, rel: Relative): boolean {
184
+ const classes = el.classes();
185
+ return (
186
+ rel.classes.every((c) => classes.includes(c)) &&
187
+ rel.when.every((cond) => holds(cond, el))
188
+ );
189
+ }
190
+
191
+ function holds(cond: StyleCondition, el: StyledElement): boolean {
192
+ if ("attribute" in cond) {
193
+ const value =
194
+ cond.attribute === "class"
195
+ ? el.classes().join(" ")
196
+ : el.attribute(cond.attribute);
197
+ if ("operator" in cond) {
198
+ if (value === null) return false;
199
+ switch (cond.operator) {
200
+ case "*":
201
+ return value.includes(cond.value);
202
+ case "^":
203
+ return value.startsWith(cond.value);
204
+ case "$":
205
+ return value.endsWith(cond.value);
206
+ case "~":
207
+ return value.split(/\s+/).includes(cond.value);
208
+ default:
209
+ return value === cond.value || value.startsWith(`${cond.value}-`);
210
+ }
211
+ }
212
+ return cond.equals === null ? value !== null : value === cond.equals;
213
+ }
214
+ if ("scheme" in cond) return colorScheme() === cond.scheme;
215
+ if ("class" in cond) return el.classes().includes(cond.class);
216
+ if ("not" in cond) return !cond.not.every((c) => holds(c, el));
217
+ if ("any" in cond) return cond.any.some((c) => holds(c, el));
218
+ if ("all" in cond) return cond.all.every((c) => holds(c, el));
219
+ if ("ancestor" in cond) {
220
+ for (let a = el.parent; a; a = a.parent)
221
+ if (matches(a, cond.ancestor)) return true;
222
+ return false;
223
+ }
224
+ if ("parent" in cond)
225
+ return el.parent !== null && matches(el.parent, cond.parent);
226
+ if ("previous" in cond) {
227
+ for (let p = el.previous; p; p = p.previous)
228
+ if (matches(p, cond.previous)) return true;
229
+ return false;
230
+ }
231
+ if ("previousAdjacent" in cond)
232
+ return el.previous !== null && matches(el.previous, cond.previousAdjacent);
233
+ if ("dir" in cond) return cond.dir === "ltr";
234
+ // A touch screen is never hovered; orbit does not see :has() or positions yet.
235
+ return false;
236
+ }
237
+
238
+ function mediaHolds(media: StyleRule["media"]): boolean {
239
+ if (!media) return true;
240
+ const { width } = viewportSize();
241
+ if (media.minWidth !== undefined && width < media.minWidth) return false;
242
+ if (media.maxWidth !== undefined && width > media.maxWidth) return false;
243
+ return true;
244
+ }
245
+
246
+ interface Hit {
247
+ specificity: number;
248
+ order: number;
249
+ declarations: StyleRule["declarations"];
250
+ pseudo: string | null;
251
+ }
252
+
253
+ /** The rules that apply to `el`, in cascade order. */
254
+ function hits(el: StyledElement): Hit[] {
255
+ const out: Hit[] = [];
256
+ // The base layer's element rules: `*`, the tag, and html / body at the root.
257
+ const tags = el.root ? ["*", el.tag, "html", "body"] : ["*", el.tag];
258
+ for (const tag of tags) {
259
+ for (const { rule, order } of elementRules.get(tag) ?? []) {
260
+ if (!(rule.when ?? []).every((c) => holds(c, el))) continue;
261
+ const pseudo =
262
+ typeof rule.target === "object" &&
263
+ "pseudo" in rule.target &&
264
+ !("relation" in rule.target)
265
+ ? rule.target.pseudo
266
+ : null;
267
+ out.push({
268
+ specificity: rule.specificity,
269
+ order,
270
+ declarations: rule.declarations,
271
+ pseudo,
272
+ });
273
+ }
274
+ }
275
+ for (const cls of el.classes()) {
276
+ const list = selfRules.get(cls);
277
+ if (!list) {
278
+ if (!known.has(cls)) unknownClasses.add(cls);
279
+ continue;
280
+ }
281
+ for (const { rule, order } of list) {
282
+ if (!mediaHolds(rule.media)) continue;
283
+ if (!(rule.when ?? []).every((c) => holds(c, el))) continue;
284
+ const pseudo =
285
+ typeof rule.target === "object" &&
286
+ "pseudo" in rule.target &&
287
+ !("relation" in rule.target)
288
+ ? rule.target.pseudo
289
+ : null;
290
+ out.push({
291
+ specificity: rule.specificity,
292
+ order,
293
+ declarations: rule.declarations,
294
+ pseudo,
295
+ });
296
+ }
297
+ }
298
+ // Rules an ancestor's class aims at its children or descendants (`[&_svg]:`, `*:`).
299
+ for (let a = el.parent, depth = 0; a; a = a.parent, depth++) {
300
+ for (const cls of a.classes()) {
301
+ for (const { rule, order } of relatedRules.get(cls) ?? []) {
302
+ const target = rule.target;
303
+ if (typeof target !== "object" || !("relation" in target)) continue;
304
+ if (target.relation === "child" && depth > 0) continue;
305
+ if (target.tag !== null && target.tag !== el.tag) continue;
306
+ if (!mediaHolds(rule.media)) continue;
307
+ if (!target.when.every((c) => holds(c, el))) continue;
308
+ if (!(rule.when ?? []).every((c) => holds(c, a))) continue;
309
+ out.push({
310
+ specificity: rule.specificity,
311
+ order,
312
+ declarations: rule.declarations,
313
+ pseudo: target.pseudo,
314
+ });
315
+ }
316
+ }
317
+ }
318
+ out.sort((x, y) => x.specificity - y.specificity || x.order - y.order);
319
+ return out;
320
+ }
321
+
322
+ // ─── Values ──────────────────────────────────────────────────────────
323
+
324
+ function pick(value: SchemeValue): string {
325
+ return typeof value === "string" ? value : value[colorScheme()];
326
+ }
327
+
328
+ /** `)` matching the `(` before `from`. */
329
+ function closing(s: string, from: number): number {
330
+ let depth = 1;
331
+ for (let i = from; i < s.length; i++) {
332
+ if (s[i] === "(") depth++;
333
+ else if (s[i] === ")" && --depth === 0) return i;
334
+ }
335
+ return -1;
336
+ }
337
+
338
+ /** Substitute `var()`; null when one resolves to nothing (invalid at computed time). */
339
+ function substitute(
340
+ value: string,
341
+ lookup: (name: string) => string | null,
342
+ depth = 0,
343
+ ): string | null {
344
+ if (depth > 16) return null;
345
+ let out = "";
346
+ let rest = value;
347
+ for (;;) {
348
+ const at = rest.indexOf("var(");
349
+ if (at < 0) return out + rest;
350
+ const end = closing(rest, at + 4);
351
+ if (end < 0) return null;
352
+ out += rest.slice(0, at);
353
+ const inner = rest.slice(at + 4, end);
354
+ const comma = inner.indexOf(",");
355
+ const name = (comma < 0 ? inner : inner.slice(0, comma)).trim();
356
+ const own = lookup(name);
357
+ const raw = own ?? (comma < 0 ? null : inner.slice(comma + 1));
358
+ if (raw === null) return null;
359
+ const resolved = substitute(raw, lookup, depth + 1);
360
+ if (resolved === null) return null;
361
+ out += resolved;
362
+ rest = rest.slice(end + 1);
363
+ }
364
+ }
365
+
366
+ /** `calc()` over px, % and numbers, once `var()`s are gone. */
367
+ function evaluateCalc(value: string): string {
368
+ let rest = value;
369
+ let at = rest.indexOf("calc(");
370
+ while (at >= 0) {
371
+ const end = closing(rest, at + 5);
372
+ if (end < 0) return rest;
373
+ const result = arithmetic(rest.slice(at + 5, end));
374
+ const text = result === null ? `calc(${rest.slice(at + 5, end)})` : result;
375
+ rest = rest.slice(0, at) + text + rest.slice(end + 1);
376
+ at = rest.indexOf("calc(", at + (result === null ? 5 : text.length));
377
+ }
378
+ return rest;
379
+ }
380
+
381
+ function arithmetic(expr: string): string | null {
382
+ const tokens = expr.match(/-?\d*\.?\d+(?:e-?\d+)?(?:px|%)?|[-+*/()]/g);
383
+ if (!tokens) return null;
384
+ let pos = 0;
385
+ type Q = { n: number; unit: string };
386
+ const atom = (): Q | null => {
387
+ const t = tokens[pos++];
388
+ if (t === undefined) return null;
389
+ if (t === "(") {
390
+ const q = sum();
391
+ pos++;
392
+ return q;
393
+ }
394
+ const m = /^(-?\d*\.?\d+(?:e-?\d+)?)(px|%)?$/.exec(t);
395
+ return m ? { n: Number(m[1]), unit: m[2] ?? "" } : null;
396
+ };
397
+ const product = (): Q | null => {
398
+ let q = atom();
399
+ while (q && (tokens[pos] === "*" || tokens[pos] === "/")) {
400
+ const op = tokens[pos++];
401
+ const r = atom();
402
+ if (!r) return null;
403
+ if (op === "*") q = { n: q.n * r.n, unit: q.unit || r.unit };
404
+ else if (r.unit === "" && r.n !== 0) q = { n: q.n / r.n, unit: q.unit };
405
+ else return null;
406
+ }
407
+ return q;
408
+ };
409
+ const sum = (): Q | null => {
410
+ let q = product();
411
+ while (q && (tokens[pos] === "+" || tokens[pos] === "-")) {
412
+ const op = tokens[pos++];
413
+ const r = product();
414
+ if (!r) return null;
415
+ const unit =
416
+ q.unit === r.unit || r.n === 0 ? q.unit : q.n === 0 ? r.unit : null;
417
+ if (unit === null) return null;
418
+ q = { n: op === "+" ? q.n + r.n : q.n - r.n, unit };
419
+ }
420
+ return q;
421
+ };
422
+ const q = sum();
423
+ if (!q || pos !== tokens.length) return null;
424
+ return `${Math.round(q.n * 10000) / 10000}${q.unit}`;
425
+ }
426
+
427
+ /** Split at top-level commas or spaces. */
428
+ function split(value: string, by: "," | " "): string[] {
429
+ const out: string[] = [];
430
+ let depth = 0;
431
+ let start = 0;
432
+ for (let i = 0; i < value.length; i++) {
433
+ const c = value[i];
434
+ if (c === "(") depth++;
435
+ else if (c === ")") depth--;
436
+ else if (depth === 0 && (by === "," ? c === "," : /\s/.test(c ?? ""))) {
437
+ const part = value.slice(start, i).trim();
438
+ if (part) out.push(part);
439
+ start = i + 1;
440
+ }
441
+ }
442
+ const last = value.slice(start).trim();
443
+ if (last) out.push(last);
444
+ return out;
445
+ }
446
+
447
+ const isColor = (v: string) =>
448
+ /^#[0-9a-f]{8}$/i.test(v) || v === "currentcolor";
449
+
450
+ /** `#rrggbbaa` to the `#rrggbb` / `rgba()` orbit's colour reader takes. */
451
+ function cssColor(v: string, current: string | undefined): string | undefined {
452
+ if (v === "currentcolor") return current;
453
+ // What the build could not mix: the text colour faded over transparent
454
+ // (`color-mix(in oklab, currentcolor 50%, transparent)`).
455
+ const mix =
456
+ /^color-mix\(in [a-z]+,\s*(currentcolor|#[0-9a-f]{8})\s+([\d.]+)%,\s*#00000000\)$/i.exec(
457
+ v,
458
+ );
459
+ if (mix) {
460
+ const base =
461
+ mix[1] === "currentcolor" ? current : cssColor(mix[1] ?? "", current);
462
+ if (base === undefined) return undefined;
463
+ return withAlpha(base, Number(mix[2]) / 100);
464
+ }
465
+ const m = /^#([0-9a-f]{6})([0-9a-f]{2})$/i.exec(v);
466
+ if (!m) return undefined;
467
+ const alpha = Number.parseInt(m[2] ?? "ff", 16) / 255;
468
+ if (alpha >= 1) return `#${m[1]}`;
469
+ const n = Number.parseInt(m[1] ?? "0", 16);
470
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${Math.round(alpha * 1000) / 1000})`;
471
+ }
472
+
473
+ /** A colour orbit writes (`#rrggbb` or `rgba()`) with its alpha scaled. */
474
+ function withAlpha(css: string, factor: number): string {
475
+ let r = 0;
476
+ let g = 0;
477
+ let b = 0;
478
+ let a = 1;
479
+ const hex = /^#([0-9a-f]{6})$/i.exec(css);
480
+ const rgba =
481
+ /^rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)$/.exec(css);
482
+ if (hex) {
483
+ const n = Number.parseInt(hex[1] ?? "0", 16);
484
+ [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
485
+ } else if (rgba) {
486
+ [r, g, b] = [Number(rgba[1]), Number(rgba[2]), Number(rgba[3])];
487
+ a = rgba[4] === undefined ? 1 : Number(rgba[4]);
488
+ }
489
+ return `rgba(${r}, ${g}, ${b}, ${Math.round(a * factor * 1000) / 1000})`;
490
+ }
491
+
492
+ function length(v: string, fontSize: number): number | string | undefined {
493
+ if (v === "auto") return "auto";
494
+ if (v.endsWith("%")) return v;
495
+ const m = /^(-?\d*\.?\d+(?:e-?\d+)?)(px|em|vw|vh|dvh|svh|lvh)?$/.exec(v);
496
+ if (!m) return undefined;
497
+ const n = Number(m[1]);
498
+ switch (m[2]) {
499
+ case undefined:
500
+ case "px":
501
+ return n;
502
+ case "em":
503
+ return n * fontSize;
504
+ case "vw":
505
+ return (n / 100) * viewportSize().width;
506
+ default:
507
+ return (n / 100) * viewportSize().height;
508
+ }
509
+ }
510
+
511
+ const ALIGN: { [v: string]: string } = {
512
+ start: "flex-start",
513
+ "flex-start": "flex-start",
514
+ end: "flex-end",
515
+ "flex-end": "flex-end",
516
+ center: "center",
517
+ stretch: "stretch",
518
+ baseline: "baseline",
519
+ normal: "stretch",
520
+ "space-between": "space-between",
521
+ "space-around": "space-around",
522
+ "space-evenly": "space-evenly",
523
+ };
524
+
525
+ const SIDES = ["Top", "Right", "Bottom", "Left"] as const;
526
+
527
+ /** `a`, `a b`, `a b c` or `a b c d` → top, right, bottom, left. */
528
+ function fourSides(values: string[]): [string, string, string, string] | null {
529
+ const [a, b = a, c = a, d = b] = values;
530
+ return a === undefined ||
531
+ b === undefined ||
532
+ c === undefined ||
533
+ d === undefined
534
+ ? null
535
+ : [a, b, c, d];
536
+ }
537
+
538
+ const TEXT_KEYS = new Set([
539
+ "color",
540
+ "fontSize",
541
+ "fontWeight",
542
+ "fontStyle",
543
+ "fontFamily",
544
+ "textAlign",
545
+ "lineHeight",
546
+ "letterSpacing",
547
+ ]);
548
+
549
+ /** One declaration into the host's keys (`out`); what orbit does not draw is skipped. */
550
+ function apply(
551
+ prop: string,
552
+ v: string,
553
+ out: Style,
554
+ state: {
555
+ flex: boolean;
556
+ scroll: boolean;
557
+ fontSize: number;
558
+ weight: number;
559
+ color?: string;
560
+ },
561
+ ): void {
562
+ const len = (x: string) => length(x, state.fontSize);
563
+ const set = (key: string, x: string | number | undefined) => {
564
+ if (x !== undefined) out[key] = x;
565
+ };
566
+ const sides = (prefix: string, suffix: string, value: string) => {
567
+ const four = fourSides(split(value, " "));
568
+ if (!four) return;
569
+ four.forEach((x, i) => {
570
+ set(`${prefix}${SIDES[i]}${suffix}`, len(x));
571
+ });
572
+ };
573
+ switch (prop) {
574
+ case "display":
575
+ // The host lays every box out as flex; only `none` is sent.
576
+ if (v === "none") out.display = "none";
577
+ else delete out.display;
578
+ state.flex = v === "flex" || v === "inline-flex";
579
+ return;
580
+ case "width":
581
+ case "height":
582
+ case "min-width":
583
+ case "min-height":
584
+ case "max-width":
585
+ case "max-height": {
586
+ if (v === "none" || /content$/.test(v)) return;
587
+ const key = prop.replace(/-(\w)/, (_, c: string) => c.toUpperCase());
588
+ set(key, len(v));
589
+ return;
590
+ }
591
+ case "padding":
592
+ case "margin":
593
+ sides(prop, "", v);
594
+ return;
595
+ case "padding-inline":
596
+ case "margin-inline":
597
+ case "padding-block":
598
+ case "margin-block": {
599
+ const [a, b = a] = split(v, " ");
600
+ const base = prop.startsWith("padding") ? "padding" : "margin";
601
+ const [x, y] = prop.endsWith("inline")
602
+ ? ["Left", "Right"]
603
+ : ["Top", "Bottom"];
604
+ if (a !== undefined && b !== undefined) {
605
+ set(`${base}${x}`, len(a));
606
+ set(`${base}${y}`, len(b));
607
+ }
608
+ return;
609
+ }
610
+ case "padding-block-start":
611
+ case "padding-block-end":
612
+ case "padding-inline-start":
613
+ case "padding-inline-end":
614
+ case "margin-block-start":
615
+ case "margin-block-end":
616
+ case "margin-inline-start":
617
+ case "margin-inline-end":
618
+ case "padding-top":
619
+ case "padding-right":
620
+ case "padding-bottom":
621
+ case "padding-left":
622
+ case "margin-top":
623
+ case "margin-right":
624
+ case "margin-bottom":
625
+ case "margin-left": {
626
+ const [base = "", ...rest] = prop.split("-");
627
+ const where = rest.join("-");
628
+ const side =
629
+ {
630
+ "block-start": "Top",
631
+ "block-end": "Bottom",
632
+ "inline-start": "Left",
633
+ "inline-end": "Right",
634
+ }[where] ?? `${where.charAt(0).toUpperCase()}${where.slice(1)}`;
635
+ set(`${base}${side}`, len(v));
636
+ return;
637
+ }
638
+ case "inset":
639
+ sides("", "", v);
640
+ for (const s of SIDES) {
641
+ const k = s;
642
+ if (out[k] !== undefined) {
643
+ out[k.toLowerCase()] = out[k];
644
+ delete out[k];
645
+ }
646
+ }
647
+ return;
648
+ case "inset-inline":
649
+ case "inset-block": {
650
+ const [a, b = a] = split(v, " ");
651
+ const [x, y] =
652
+ prop === "inset-inline" ? ["left", "right"] : ["top", "bottom"];
653
+ if (a !== undefined && b !== undefined) {
654
+ set(x, len(a));
655
+ set(y, len(b));
656
+ }
657
+ return;
658
+ }
659
+ case "top":
660
+ case "right":
661
+ case "bottom":
662
+ case "left":
663
+ set(prop, len(v));
664
+ return;
665
+ case "inset-inline-start":
666
+ set("left", len(v));
667
+ return;
668
+ case "inset-inline-end":
669
+ set("right", len(v));
670
+ return;
671
+ case "gap":
672
+ case "row-gap":
673
+ case "column-gap": {
674
+ const [a, b = a] = split(v, " ");
675
+ if (prop === "gap" && a !== undefined && b !== undefined) {
676
+ set("rowGap", len(a));
677
+ set("columnGap", len(b));
678
+ } else set(prop === "row-gap" ? "rowGap" : "columnGap", len(v));
679
+ return;
680
+ }
681
+ case "flex": {
682
+ const parts = split(v, " ");
683
+ if (v === "none")
684
+ Object.assign(out, { flexGrow: 0, flexShrink: 0, flexBasis: "auto" });
685
+ else if (v === "auto")
686
+ Object.assign(out, { flexGrow: 1, flexShrink: 1, flexBasis: "auto" });
687
+ else {
688
+ const [grow, shrink = "1", basis = "0%"] = parts;
689
+ set("flexGrow", Number(grow));
690
+ set("flexShrink", Number(shrink));
691
+ set("flexBasis", len(basis));
692
+ }
693
+ return;
694
+ }
695
+ case "flex-grow":
696
+ set("flexGrow", Number(v));
697
+ return;
698
+ case "flex-shrink":
699
+ set("flexShrink", Number(v));
700
+ return;
701
+ case "flex-basis":
702
+ set("flexBasis", len(v));
703
+ return;
704
+ case "flex-direction":
705
+ set("flexDirection", v);
706
+ return;
707
+ case "flex-wrap":
708
+ set("flexWrap", v);
709
+ return;
710
+ case "align-items":
711
+ case "align-self":
712
+ case "align-content":
713
+ case "justify-content": {
714
+ const key = prop.replace(/-(\w)/, (_, c: string) => c.toUpperCase());
715
+ set(key, ALIGN[v.replace(/^safe /, "")]);
716
+ return;
717
+ }
718
+ case "position":
719
+ set(
720
+ "position",
721
+ v === "absolute" || v === "fixed" ? "absolute" : "relative",
722
+ );
723
+ return;
724
+ case "overflow":
725
+ case "overflow-y":
726
+ case "overflow-x":
727
+ if (v === "auto" || v === "scroll") {
728
+ if (prop !== "overflow-x") state.scroll = true;
729
+ } else if (v === "hidden" || v === "clip") out.overflow = "hidden";
730
+ return;
731
+ case "aspect-ratio": {
732
+ const [a, b] = v.split("/").map((x) => Number(x.trim()));
733
+ if (a !== undefined && Number.isFinite(a))
734
+ set("aspectRatio", b !== undefined && b > 0 ? a / b : a);
735
+ return;
736
+ }
737
+ case "border-width":
738
+ sides("border", "Width", v);
739
+ if (new Set(SIDES.map((s) => out[`border${s}Width`])).size === 1)
740
+ for (const s of SIDES) {
741
+ out.borderWidth = out[`border${s}Width`] ?? 0;
742
+ delete out[`border${s}Width`];
743
+ }
744
+ return;
745
+ case "border-top-width":
746
+ case "border-right-width":
747
+ case "border-bottom-width":
748
+ case "border-left-width": {
749
+ const side = prop.split("-")[1] ?? "";
750
+ set(`border${side.charAt(0).toUpperCase()}${side.slice(1)}Width`, len(v));
751
+ return;
752
+ }
753
+ case "border-style":
754
+ if (v === "none" || v === "hidden") out.borderStyleNone = 1;
755
+ else delete out.borderStyleNone;
756
+ return;
757
+ case "border-color":
758
+ case "border-top-color":
759
+ case "border-bottom-color":
760
+ case "border-left-color":
761
+ case "border-right-color": {
762
+ const [first] = split(v, " ");
763
+ if (first !== undefined) set("borderColor", cssColor(first, state.color));
764
+ return;
765
+ }
766
+ case "border-radius": {
767
+ const [first] = split(v, " ");
768
+ if (first !== undefined) set("borderRadius", len(first));
769
+ return;
770
+ }
771
+ case "background-color":
772
+ set("backgroundColor", cssColor(v, state.color));
773
+ return;
774
+ case "color": {
775
+ const c = cssColor(v, state.color);
776
+ if (c) {
777
+ out.color = c;
778
+ state.color = c;
779
+ }
780
+ return;
781
+ }
782
+ case "opacity":
783
+ set(
784
+ "opacity",
785
+ v.endsWith("%") ? Number(v.slice(0, -1)) / 100 : Number(v),
786
+ );
787
+ return;
788
+ case "font-size": {
789
+ const n = len(v);
790
+ if (typeof n === "number") {
791
+ out.fontSize = n;
792
+ state.fontSize = n;
793
+ }
794
+ return;
795
+ }
796
+ case "font-weight": {
797
+ // bolder / lighter: CSS's relative weights, from the inherited one.
798
+ const w = state.weight;
799
+ const weight =
800
+ v === "bold"
801
+ ? 700
802
+ : v === "normal"
803
+ ? 400
804
+ : v === "bolder"
805
+ ? w < 350
806
+ ? 400
807
+ : w < 550
808
+ ? 700
809
+ : 900
810
+ : v === "lighter"
811
+ ? w < 550
812
+ ? 100
813
+ : w < 750
814
+ ? 400
815
+ : 700
816
+ : Number(v);
817
+ if (Number.isFinite(weight)) {
818
+ out.fontWeight = String(weight);
819
+ state.weight = weight;
820
+ }
821
+ return;
822
+ }
823
+ case "font-style":
824
+ set("fontStyle", v);
825
+ return;
826
+ case "font-family":
827
+ if (/mono/.test(v)) out.fontFamily = "monospace";
828
+ return;
829
+ case "line-height": {
830
+ // Unitless: a multiple of the font size, kept so it follows a size set later.
831
+ if (/^\d*\.?\d+$/.test(v)) set("lineHeight", `${v}x`);
832
+ else set("lineHeight", len(v));
833
+ return;
834
+ }
835
+ case "letter-spacing":
836
+ set("letterSpacing", len(v));
837
+ return;
838
+ case "text-align":
839
+ set("textAlign", v === "start" ? "left" : v === "end" ? "right" : v);
840
+ return;
841
+ case "object-fit":
842
+ set("objectFit", v);
843
+ return;
844
+ case "field-sizing":
845
+ set("fieldSizing", v);
846
+ return;
847
+ case "backdrop-filter": {
848
+ const m = /blur\(([\d.]+)px\)/.exec(v);
849
+ if (m) set("backdropBlur", Number(m[1]));
850
+ return;
851
+ }
852
+ case "box-shadow":
853
+ shadow(v, out, state.color);
854
+ return;
855
+ default:
856
+ return;
857
+ }
858
+ }
859
+
860
+ /** The first visible outer shadow of a `box-shadow` list (orbit draws one). */
861
+ function shadow(v: string, out: Style, current: string | undefined): void {
862
+ for (const layer of split(v, ",")) {
863
+ const parts = split(layer, " ");
864
+ if (parts.includes("inset")) continue;
865
+ const color = parts.find(isColor);
866
+ const numbers = parts.filter((p) => !isColor(p)).map((p) => length(p, 16));
867
+ if (!color || numbers.some((n) => typeof n !== "number")) continue;
868
+ const [x = 0, y = 0, blur = 0, spread = 0] = numbers.map(Number);
869
+ const css = cssColor(color, current);
870
+ if (!css || (/^#[0-9a-f]{8}$/i.test(color) && color.endsWith("00")))
871
+ continue;
872
+ if (x === 0 && y === 0 && blur === 0 && spread === 0) continue;
873
+ Object.assign(out, {
874
+ shadowX: x,
875
+ shadowY: y,
876
+ shadowBlur: blur,
877
+ shadowSpread: spread,
878
+ shadowColor: css,
879
+ });
880
+ return;
881
+ }
882
+ }
883
+
884
+ /**
885
+ * Equal sides back into one key (`padding`, `marginHorizontal`, `gap`), and
886
+ * nothing the host already assumes (a zero margin or padding, a border colour
887
+ * without a border): the base layer sets those on every element.
888
+ */
889
+ function compact(style: Style): void {
890
+ for (const [key, value] of Object.entries(style))
891
+ if (value === 0 && /^(margin|padding)/.test(key)) delete style[key];
892
+ const bordered = [
893
+ "borderWidth",
894
+ "borderTopWidth",
895
+ "borderRightWidth",
896
+ "borderBottomWidth",
897
+ "borderLeftWidth",
898
+ ].some((k) => typeof style[k] === "number" && style[k] !== 0);
899
+ if (!bordered) delete style.borderColor;
900
+ for (const base of ["padding", "margin"]) {
901
+ const [t, r, b, l] = SIDES.map((side) => style[`${base}${side}`]);
902
+ if (t !== undefined && t === r && r === b && b === l) {
903
+ for (const side of SIDES) delete style[`${base}${side}`];
904
+ style[base] = t;
905
+ continue;
906
+ }
907
+ if (l !== undefined && l === r) {
908
+ delete style[`${base}Left`];
909
+ delete style[`${base}Right`];
910
+ style[`${base}Horizontal`] = l;
911
+ }
912
+ if (t !== undefined && t === b) {
913
+ delete style[`${base}Top`];
914
+ delete style[`${base}Bottom`];
915
+ style[`${base}Vertical`] = t;
916
+ }
917
+ }
918
+ if (style.rowGap !== undefined && style.rowGap === style.columnGap) {
919
+ style.gap = style.rowGap;
920
+ delete style.rowGap;
921
+ delete style.columnGap;
922
+ }
923
+ }
924
+
925
+ /**
926
+ * `el`'s style: the table's rules cascaded, custom properties resolved, read
927
+ * into the host's keys. `inherited` is the text style it inherits (and its
928
+ * colour, for `currentcolor`).
929
+ */
930
+ export function computeStyle(el: StyledElement, inherited: Style): Computed {
931
+ const own = new Map<string, string>();
932
+ const declared: Array<[string, string]> = [];
933
+ const placeholder: Array<[string, string]> = [];
934
+ for (const hit of hits(el)) {
935
+ for (const [prop, value] of hit.declarations) {
936
+ const v = pick(value);
937
+ if (hit.pseudo === "placeholder") placeholder.push([prop, v]);
938
+ else if (hit.pseudo !== null) continue;
939
+ else if (prop.startsWith("--")) own.set(prop, v);
940
+ else declared.push([prop, v]);
941
+ }
942
+ }
943
+ const parentVars = el.parent?.vars;
944
+ const resolving = new Set<string>();
945
+ const lookup = (name: string): string | null => {
946
+ const mine = own.get(name);
947
+ if (mine !== undefined) {
948
+ if (resolving.has(name)) return null;
949
+ resolving.add(name);
950
+ const r = substitute(mine, lookup);
951
+ resolving.delete(name);
952
+ return r;
953
+ }
954
+ const registered = properties[name];
955
+ if (!registered || registered.inherits) {
956
+ const up = parentVars?.get(name);
957
+ if (up !== undefined) return up;
958
+ }
959
+ return registered?.initial ?? null;
960
+ };
961
+ const vars = new Map<string, string>();
962
+ for (const name of own.keys()) {
963
+ const r = lookup(name);
964
+ if (r !== null) vars.set(name, r);
965
+ }
966
+ if (parentVars) {
967
+ for (const [name, value] of parentVars) {
968
+ const registered = properties[name];
969
+ if (!vars.has(name) && (!registered || registered.inherits))
970
+ vars.set(name, value);
971
+ }
972
+ }
973
+ const inheritedSize = inherited.fontSize;
974
+ const inheritedColor = inherited.color;
975
+ const inheritedWeight = Number(inherited.fontWeight ?? 400);
976
+ const state = {
977
+ flex: false,
978
+ scroll: false,
979
+ fontSize: typeof inheritedSize === "number" ? inheritedSize : 16,
980
+ weight: Number.isFinite(inheritedWeight) ? inheritedWeight : 400,
981
+ color: typeof inheritedColor === "string" ? inheritedColor : undefined,
982
+ };
983
+ const style: Style = {};
984
+ // font-size, color and font-weight first: em lengths, currentcolor and
985
+ // bolder read them.
986
+ const first = (p: string) =>
987
+ p === "font-size" || p === "color" || p === "font-weight";
988
+ const ordered = [
989
+ ...declared.filter(([p]) => first(p)),
990
+ ...declared.filter(([p]) => !first(p)),
991
+ ];
992
+ for (const [prop, raw] of ordered) {
993
+ const v = substitute(raw, lookup);
994
+ if (v === null) continue;
995
+ apply(prop, evaluateCalc(v).trim(), style, state);
996
+ }
997
+ compact(style);
998
+ if (style.borderStyleNone !== undefined) {
999
+ delete style.borderStyleNone;
1000
+ style.borderWidth = 0;
1001
+ }
1002
+ const box: Style = {};
1003
+ const text: Style = {};
1004
+ for (const [key, value] of Object.entries(style)) {
1005
+ (TEXT_KEYS.has(key) ? text : box)[key] = value;
1006
+ }
1007
+ if (state.flex && box.flexDirection === undefined) box.flexDirection = "row";
1008
+ const computed: Computed = {
1009
+ box,
1010
+ text,
1011
+ flex: state.flex,
1012
+ scroll: state.scroll,
1013
+ vars,
1014
+ };
1015
+ for (const [prop, raw] of placeholder) {
1016
+ const v = substitute(raw, lookup);
1017
+ if (prop === "color" && v !== null)
1018
+ computed.placeholder = cssColor(v.trim(), state.color);
1019
+ }
1020
+ return computed;
1021
+ }