figdriver 0.0.0-stage → 0.4.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/CHANGELOG.md +86 -0
- package/LICENSE +21 -0
- package/README.md +87 -2
- package/cli/result.ts +231 -0
- package/dist/cli.js +4125 -0
- package/index.d.ts +12 -0
- package/index.js +8 -0
- package/package.json +78 -4
- package/src/core/color.ts +435 -0
- package/src/core/css.ts +668 -0
- package/src/core/foundations.ts +389 -0
- package/src/core/json.d.ts +4 -0
- package/src/core/layout.ts +684 -0
- package/src/core/naming.ts +129 -0
- package/src/core/protocol.ts +328 -0
- package/src/core/rerun.ts +130 -0
- package/src/core/reuse.ts +149 -0
- package/src/core/snapshot.ts +88 -0
- package/src/core/spec.ts +167 -0
- package/src/core/text.ts +37 -0
- package/src/core/tokens.ts +77 -0
- package/src/core/types.ts +181 -0
- package/src/core/users.ts +17 -0
- package/src/figma/helpers.ts +238 -0
- package/src/figma/import.ts +962 -0
- package/src/figma/inspect.ts +254 -0
- package/src/figma/kit.ts +562 -0
- package/src/figma/migrate.ts +301 -0
- package/src/figma/owned.ts +56 -0
- package/src/figma/read.ts +618 -0
- package/src/figma/rerun.ts +387 -0
- package/src/figma/review.ts +481 -0
- package/src/figma/tokens.ts +97 -0
- package/src/page/capture.ts +999 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { isSimpleIcon } from "./foundations";
|
|
2
|
+
import { layoutOf, type Layout, type Parent, type Sizing } from "./layout";
|
|
3
|
+
import { selectorOf, truncateList, type El, type FrameEl } from "./snapshot";
|
|
4
|
+
import type { Assigned, ComponentRule } from "./spec";
|
|
5
|
+
|
|
6
|
+
type Rules = { assignments: Map<El, Assigned>; mains: Map<ComponentRule, Map<string, El>> };
|
|
7
|
+
|
|
8
|
+
type Keyed = Layout[keyof Layout] | Sizing;
|
|
9
|
+
|
|
10
|
+
/** Whole pixels: layout inference leaves sub-pixel noise, such as a 0.01px padding, that no one can see. */
|
|
11
|
+
const key = (v: Keyed | Keyed[]) => JSON.stringify(v, (_, x) => (Number.isFinite(x) ? Math.round(x) : x));
|
|
12
|
+
|
|
13
|
+
function placeKey(el: El, l: Layout) {
|
|
14
|
+
const { w, h } = l.place;
|
|
15
|
+
|
|
16
|
+
return key([
|
|
17
|
+
l.place,
|
|
18
|
+
l.maxWidth,
|
|
19
|
+
l.minHeight,
|
|
20
|
+
l.rotation,
|
|
21
|
+
w === "FIXED" ? el.box[2] : w,
|
|
22
|
+
h === "FIXED" ? el.box[3] : h,
|
|
23
|
+
]);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Whether a rule's BOOLEAN properties can hide `el`, a layer of its main. */
|
|
27
|
+
export const optionalIn = (rule: ComponentRule | undefined) => (el: El, parent: El) =>
|
|
28
|
+
Object.values(rule?.booleans ?? {}).some((match) => match(el, parent));
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Which child of `w` stands for each child of `s`, or undefined for an optional child `w` leaves out, which its instance hides. Gives
|
|
32
|
+
* nothing when the children differ in any other way.
|
|
33
|
+
*/
|
|
34
|
+
export function childPairs(s: FrameEl, w: FrameEl, optional: (el: El, parent: El) => boolean) {
|
|
35
|
+
if (s.children.length === w.children.length) return s.children.map((_, i) => i);
|
|
36
|
+
const out: (number | undefined)[] = [];
|
|
37
|
+
let j = 0;
|
|
38
|
+
|
|
39
|
+
for (const c of s.children) {
|
|
40
|
+
const n = w.children[j];
|
|
41
|
+
|
|
42
|
+
if (n && n.kind === c.kind && n.tag === c.tag && (!optional(c, s) || optional(n, w))) out.push(j++);
|
|
43
|
+
else if (optional(c, s)) out.push(undefined);
|
|
44
|
+
else return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return j === w.children.length ? out : undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The layer of `want` at `path` in `shown`, or nothing when an optional layer on the way is left out. */
|
|
51
|
+
export function counterpart(shown: El, want: El, path: number[], optional: (el: El, parent: El) => boolean) {
|
|
52
|
+
let s = shown,
|
|
53
|
+
w = want;
|
|
54
|
+
|
|
55
|
+
for (const i of path) {
|
|
56
|
+
if (s.kind !== "frame" || w.kind !== "frame") return;
|
|
57
|
+
const j = childPairs(s, w, optional)?.[i];
|
|
58
|
+
|
|
59
|
+
if (j === undefined) return;
|
|
60
|
+
s = s.children[i];
|
|
61
|
+
w = w.children[j];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return w;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The names a reuse gap gives the auto layout fields: `main` and `cross` are both alignment, `cols` and `rows` both tracks. */
|
|
68
|
+
const LAYOUT_NAMES = new Map([
|
|
69
|
+
["main", "align"],
|
|
70
|
+
["cross", "align"],
|
|
71
|
+
["rowGap", "gap"],
|
|
72
|
+
["pad", "padding"],
|
|
73
|
+
["cols", "tracks"],
|
|
74
|
+
["rows", "tracks"],
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
/** The auto layout properties `s` and `w` set apart, such as `gap, padding`, or nothing when they match. */
|
|
78
|
+
function layoutChanges(s: Layout["container"], w: Layout["container"]) {
|
|
79
|
+
if (s?.mode !== w?.mode) return "mode";
|
|
80
|
+
const sf = new Map(Object.entries(s ?? {}).map(([k, v]) => [k, key(v)]));
|
|
81
|
+
const wf = new Map(Object.entries(w ?? {}).map(([k, v]) => [k, key(v)]));
|
|
82
|
+
const changed = [...new Set([...sf.keys(), ...wf.keys()])].filter((k) => sf.get(k) !== wf.get(k));
|
|
83
|
+
|
|
84
|
+
return [...new Set(changed.map((k) => LAYOUT_NAMES.get(k) ?? k))].join(", ");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const listed = (els: El[]) => `${els.length} (${truncateList(els.map(selectorOf), 6)})`;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The first difference between `want` and an instance of the main built from `shown` that import.ts cannot override. Overrides carry
|
|
91
|
+
* text, icons, paints, strokes, corners, opacity, effects, clipping and nested swaps; structure, layout, sizing and placement stay the main's.
|
|
92
|
+
*/
|
|
93
|
+
export function reuseGap(shown: El, want: El, rules: Rules): string | undefined {
|
|
94
|
+
const mainOf = (a: Assigned) => rules.mains.get(a.rule)!.get(a.value)!;
|
|
95
|
+
const optional = optionalIn(rules.assignments.get(want)?.rule);
|
|
96
|
+
|
|
97
|
+
const compare = (s: El, w: El, sp?: Parent, wp?: Parent): string | undefined => {
|
|
98
|
+
if (s === w) return;
|
|
99
|
+
const at = (what: string) => `${selectorOf(w)} ${what}`;
|
|
100
|
+
|
|
101
|
+
if (s.kind !== w.kind || s.tag !== w.tag)
|
|
102
|
+
return at(`is ${w.kind} <${w.tag}> where the main has ${s.kind} <${s.tag}>`);
|
|
103
|
+
|
|
104
|
+
let pairs: (number | undefined)[] = [];
|
|
105
|
+
|
|
106
|
+
if (s.kind === "frame" && w.kind === "frame") {
|
|
107
|
+
const found = childPairs(s, w, optional);
|
|
108
|
+
|
|
109
|
+
if (!found) return at(`has other children: the main has ${listed(s.children)}, this has ${listed(w.children)}`);
|
|
110
|
+
pairs = found;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (s.kind === "svg" && w.kind === "svg" && s.svg !== w.svg && !(isSimpleIcon(s) && isSimpleIcon(w)))
|
|
114
|
+
return at("draws another SVG, and an instance can swap only icons");
|
|
115
|
+
|
|
116
|
+
const sl = layoutOf(s, sp),
|
|
117
|
+
wl = layoutOf(w, wp);
|
|
118
|
+
|
|
119
|
+
if ((sp || s.kind !== "frame") && placeKey(s, sl) !== placeKey(w, wl)) return at("has another size or position");
|
|
120
|
+
|
|
121
|
+
// With an optional child hidden, a lone child leaves no gap to measure, and the gap the main has still holds.
|
|
122
|
+
const lone = pairs.includes(undefined) && w.kind === "frame" && w.children.length < 2;
|
|
123
|
+
const flat = (c: Layout["container"]) => (lone && c && c.mode !== "GRID" ? { ...c, gap: 0 } : c);
|
|
124
|
+
const changed = layoutChanges(flat(sl.container), flat(wl.container));
|
|
125
|
+
|
|
126
|
+
if (changed) return at(`has another auto layout (${changed})`);
|
|
127
|
+
|
|
128
|
+
if (sp) {
|
|
129
|
+
const sa = rules.assignments.get(s),
|
|
130
|
+
wa = rules.assignments.get(w);
|
|
131
|
+
|
|
132
|
+
if (sa?.rule !== wa?.rule) return at("is an instance of another component");
|
|
133
|
+
|
|
134
|
+
if (sa && wa && sa.value !== wa.value && !reuseGap(mainOf(sa), s, rules)) return reuseGap(mainOf(wa), w, rules);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (s.kind !== "frame" || w.kind !== "frame") return;
|
|
138
|
+
const parentOf = (el: typeof s, l: Layout): Parent => ({ el, container: l.container!, w: l.place.w, h: l.place.h });
|
|
139
|
+
|
|
140
|
+
for (const [i, c] of s.children.entries()) {
|
|
141
|
+
const j = pairs[i];
|
|
142
|
+
const gap = j === undefined ? undefined : compare(c, w.children[j], parentOf(s, sl), parentOf(w, wl));
|
|
143
|
+
|
|
144
|
+
if (gap) return gap;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
return compare(shown, want);
|
|
149
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { splitTop } from "./css";
|
|
2
|
+
import type { El, FrameEl, TextEl } from "./types";
|
|
3
|
+
|
|
4
|
+
export type {
|
|
5
|
+
Asset,
|
|
6
|
+
Box,
|
|
7
|
+
Capture,
|
|
8
|
+
Clips,
|
|
9
|
+
El,
|
|
10
|
+
FrameEl,
|
|
11
|
+
ImageEl,
|
|
12
|
+
Pseudo,
|
|
13
|
+
Run,
|
|
14
|
+
Snapshot,
|
|
15
|
+
Style,
|
|
16
|
+
SvgEl,
|
|
17
|
+
TextEl,
|
|
18
|
+
Vars,
|
|
19
|
+
} from "./types";
|
|
20
|
+
|
|
21
|
+
export const round = (v: number) => Math.round(v * 100) / 100;
|
|
22
|
+
export const BLOCK_LEVEL = /^(block|flex|grid|table|list-item|flow-root)$/;
|
|
23
|
+
export const selectorOf = (el: Pick<El, "tag" | "cls">) => el.tag + el.cls.map((c) => `.${c}`).join("");
|
|
24
|
+
export const textOf = (el: TextEl) => el.runs.map((r) => r.text).join("");
|
|
25
|
+
|
|
26
|
+
/** A thrown value's message, for a sentence of ours. */
|
|
27
|
+
export const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));
|
|
28
|
+
|
|
29
|
+
export const truncateList = (items: readonly string[], max: number, sep = ", ") =>
|
|
30
|
+
`${items.slice(0, max).join(sep)}${items.length > max ? `${sep}and ${items.length - max} more` : ""}`;
|
|
31
|
+
|
|
32
|
+
export function walk(
|
|
33
|
+
el: El,
|
|
34
|
+
visit: (el: El, parent: El | undefined, context: string) => void,
|
|
35
|
+
parent?: El,
|
|
36
|
+
context = "",
|
|
37
|
+
) {
|
|
38
|
+
visit(el, parent, context);
|
|
39
|
+
|
|
40
|
+
if (el.kind !== "frame") return;
|
|
41
|
+
const own = el.cls.find((c) => c.includes("__")) ?? el.cls[0];
|
|
42
|
+
|
|
43
|
+
for (const c of el.children) walk(c, visit, el, own ?? context);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Drop images and background-image URL layers whose assets could not be fetched. */
|
|
47
|
+
export function withoutImages(e: FrameEl, missing: (name: string) => boolean): FrameEl;
|
|
48
|
+
export function withoutImages(e: El, missing: (name: string) => boolean): El;
|
|
49
|
+
export function withoutImages(e: El, missing: (name: string) => boolean): El {
|
|
50
|
+
if (e.kind === "image") {
|
|
51
|
+
if (!missing(e.image)) return e.video && missing(e.video) ? { ...e, video: undefined } : e;
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
tag: e.tag,
|
|
55
|
+
cls: e.cls,
|
|
56
|
+
box: e.box,
|
|
57
|
+
style: e.style,
|
|
58
|
+
label: e.label,
|
|
59
|
+
vars: e.vars,
|
|
60
|
+
kind: "frame",
|
|
61
|
+
children: [],
|
|
62
|
+
pseudos: [],
|
|
63
|
+
bgImages: [],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (e.kind !== "frame") return e;
|
|
68
|
+
const children = e.children.map((c) => withoutImages(c, missing));
|
|
69
|
+
|
|
70
|
+
if (!e.bgImages.some(missing)) return { ...e, children };
|
|
71
|
+
let url = 0;
|
|
72
|
+
const keep = splitTop(e.style.bgImage).map((layer) => !layer.startsWith("url(") || !missing(e.bgImages[url++]));
|
|
73
|
+
|
|
74
|
+
const pick = (list: string, fallback: string) => {
|
|
75
|
+
const items = splitTop(list);
|
|
76
|
+
|
|
77
|
+
return keep.flatMap((ok, i) => (ok ? [items[i % items.length]] : [])).join(", ") || fallback;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const style = {
|
|
81
|
+
...e.style,
|
|
82
|
+
bgImage: pick(e.style.bgImage, "none"),
|
|
83
|
+
bgSize: pick(e.style.bgSize, "auto"),
|
|
84
|
+
bgPos: pick(e.style.bgPos, "0% 0%"),
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return { ...e, children, style, bgImages: e.bgImages.filter((n) => !missing(n)) };
|
|
88
|
+
}
|
package/src/core/spec.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { SYNTHETIC_TAGS } from "./layout";
|
|
2
|
+
import { selectorOf, textOf, walk } from "./snapshot";
|
|
3
|
+
import type { ComponentRule, El, ImportSpec } from "./types";
|
|
4
|
+
|
|
5
|
+
export type { ComponentRule, ImportSpec, Match } from "./types";
|
|
6
|
+
|
|
7
|
+
export type Assigned = { rule: ComponentRule; value: string };
|
|
8
|
+
|
|
9
|
+
const mainsOf = (occ: (Assigned & { el: El })[]) => {
|
|
10
|
+
const mains = new Map<string, El>();
|
|
11
|
+
|
|
12
|
+
for (const { el, value } of occ) if (!mains.has(value)) mains.set(value, el);
|
|
13
|
+
|
|
14
|
+
return mains;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function assignRules(spec: ImportSpec, root: El) {
|
|
18
|
+
if (!spec.name.trim())
|
|
19
|
+
throw new Error(
|
|
20
|
+
"The spec's name is blank. The name owns what a run builds, so give it one, such as the product's name.",
|
|
21
|
+
);
|
|
22
|
+
const sectionRules: ComponentRule[] = spec.sections.map((s) => ({ name: `Section/${s.name}`, match: s.match }));
|
|
23
|
+
const rules = [...spec.components, ...sectionRules];
|
|
24
|
+
// A rerun moves what a person built from the old output to the new part of the same name, so two parts must never share one.
|
|
25
|
+
const names = rules.map((r) => r.name);
|
|
26
|
+
const twice = names.filter((name, i) => names.indexOf(name) !== i);
|
|
27
|
+
|
|
28
|
+
if (twice.length)
|
|
29
|
+
throw new Error(
|
|
30
|
+
`Two rules are named ${[...new Set(twice)].map((n) => `"${n}"`).join(", ")}. Give each component and section a name of its own.`,
|
|
31
|
+
);
|
|
32
|
+
const assignments = new Map<El, Assigned>();
|
|
33
|
+
const occurrences = new Map<ComponentRule, (Assigned & { el: El })[]>();
|
|
34
|
+
walk(root, (el, parent) => {
|
|
35
|
+
const rule = rules.find((r) => r.match(el, parent));
|
|
36
|
+
|
|
37
|
+
if (!rule) return;
|
|
38
|
+
const a = { rule, value: rule.variant?.value(el) ?? "" };
|
|
39
|
+
assignments.set(el, a);
|
|
40
|
+
occurrences.set(rule, [...(occurrences.get(rule) ?? []), { ...a, el }]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const warnings = rules.flatMap((r) =>
|
|
44
|
+
occurrences.has(r)
|
|
45
|
+
? []
|
|
46
|
+
: [`Rule "${r.name}" matches no element, or only elements an earlier rule claims. It was skipped.`],
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
if (!sectionRules.some((r) => occurrences.has(r)))
|
|
50
|
+
throw new Error(
|
|
51
|
+
`No section rule matches an element of the page. Sections: ${sectionRules.map((r) => r.name).join(", ") || "none"}.`,
|
|
52
|
+
);
|
|
53
|
+
const repeated = spec.screens ? sectionRules.filter((r) => (occurrences.get(r)?.length ?? 0) > 1) : [];
|
|
54
|
+
|
|
55
|
+
if (repeated.length) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`With screens, each section becomes a screen named after it, and ${repeated.map((r) => `"${r.name.slice("Section/".length)}" matches ${occurrences.get(r)!.length} elements`).join(", ")}. Give each screen a section rule of its own.`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A main is built before the instances inside it, so a rule whose main holds itself, directly or through another rule, never finishes.
|
|
62
|
+
const inside = new Map<ComponentRule, Map<ComponentRule, string>>();
|
|
63
|
+
|
|
64
|
+
for (const [rule, occ] of occurrences) {
|
|
65
|
+
const held = new Map<ComponentRule, string>();
|
|
66
|
+
|
|
67
|
+
for (const el of mainsOf(occ).values()) {
|
|
68
|
+
walk(el, (d) => {
|
|
69
|
+
const a = assignments.get(d);
|
|
70
|
+
|
|
71
|
+
if (d !== el && a && !held.has(a.rule)) held.set(a.rule, `${selectorOf(el)} contains ${selectorOf(d)}`);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
inside.set(rule, held);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const loopFree = new Set<ComponentRule>();
|
|
79
|
+
|
|
80
|
+
const loopFrom = (rule: ComponentRule, path: ComponentRule[]): ComponentRule[] | undefined => {
|
|
81
|
+
if (path.includes(rule)) return [...path.slice(path.indexOf(rule)), rule];
|
|
82
|
+
|
|
83
|
+
if (loopFree.has(rule)) return;
|
|
84
|
+
|
|
85
|
+
for (const next of inside.get(rule)!.keys()) {
|
|
86
|
+
const loop = loopFrom(next, [...path, rule]);
|
|
87
|
+
|
|
88
|
+
if (loop) return loop;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
loopFree.add(rule);
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
for (const rule of occurrences.keys()) {
|
|
95
|
+
const loop = loopFrom(rule, []);
|
|
96
|
+
|
|
97
|
+
if (!loop) continue;
|
|
98
|
+
const steps = loop.slice(1).map((r, i) => `"${loop[i].name}" holds "${r.name}" (${inside.get(loop[i])!.get(r)})`);
|
|
99
|
+
throw new Error(
|
|
100
|
+
`Component rules contain each other: ${steps.join(", ")}. A main cannot hold an instance of itself. Narrow one rule's match.`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
libraryRules: spec.components.filter((r) => occurrences.has(r)),
|
|
106
|
+
sectionRules: sectionRules.filter((r) => occurrences.has(r)),
|
|
107
|
+
assignments,
|
|
108
|
+
occurrences,
|
|
109
|
+
warnings,
|
|
110
|
+
mains: new Map([...occurrences].map(([rule, occ]) => [rule, mainsOf(occ)])),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function droppedContent(root: El, reached: ReadonlySet<El>) {
|
|
115
|
+
const parentOf = new Map<El, El>();
|
|
116
|
+
walk(root, (el, parent) => parent && parentOf.set(el, parent));
|
|
117
|
+
|
|
118
|
+
const ancestors = (el: El) => {
|
|
119
|
+
const out: El[] = [];
|
|
120
|
+
|
|
121
|
+
for (let p = parentOf.get(el); p; p = parentOf.get(p)) out.push(p);
|
|
122
|
+
|
|
123
|
+
return out;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const live = new Set([...reached].flatMap((el) => [el, ...ancestors(el)]));
|
|
127
|
+
const synthetic = (el: El) => el.tag in SYNTHETIC_TAGS || el.tag.startsWith("::");
|
|
128
|
+
const lost = new Map<El, { runs: number; images: number; sample?: string }>();
|
|
129
|
+
walk(root, (el) => {
|
|
130
|
+
const [x, y, w, h] = el.box;
|
|
131
|
+
const runs = el.kind === "text" ? el.runs.filter((r) => r.text.trim()).length : 0;
|
|
132
|
+
const images = el.kind === "image" || el.kind === "svg" ? 1 : el.kind === "frame" ? el.bgImages.length : 0;
|
|
133
|
+
|
|
134
|
+
if ((!runs && !images) || reached.has(el) || x + w <= 0 || y + h <= 0 || w <= 1 || h <= 1) return;
|
|
135
|
+
let top = el;
|
|
136
|
+
|
|
137
|
+
for (let p = parentOf.get(top); p && !live.has(p) && !synthetic(p); p = parentOf.get(top)) top = p;
|
|
138
|
+
const entry = lost.get(top) ?? { runs: 0, images: 0 };
|
|
139
|
+
entry.runs += runs;
|
|
140
|
+
entry.images += images;
|
|
141
|
+
|
|
142
|
+
if (el.kind === "text") entry.sample ??= textOf(el).replace(/\s+/g, " ").slice(0, 40);
|
|
143
|
+
lost.set(top, entry);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const pathOf = (el: El) =>
|
|
147
|
+
[...ancestors(el).reverse(), el].flatMap((a) => (synthetic(a) ? [] : [selectorOf(a)])).join(" > ");
|
|
148
|
+
|
|
149
|
+
const sections: string[] = [];
|
|
150
|
+
const elements: string[] = [];
|
|
151
|
+
|
|
152
|
+
for (const [top, { runs, images, sample }] of lost) {
|
|
153
|
+
const what =
|
|
154
|
+
[runs && `${runs} text run${runs > 1 ? "s" : ""}`, images && `${images} image${images > 1 ? "s" : ""}`]
|
|
155
|
+
.filter(Boolean)
|
|
156
|
+
.join(" and ") + (sample ? ` ("${sample}")` : "");
|
|
157
|
+
|
|
158
|
+
if (live.has(top) || ancestors(top).some((a) => reached.has(a)))
|
|
159
|
+
elements.push(`${pathOf(top)}: ${what} reached no Figma layer.`);
|
|
160
|
+
else
|
|
161
|
+
sections.push(
|
|
162
|
+
`${pathOf(top)} was dropped: no section rule matches it, so its ${what} reached no Figma layer. Add it to the spec's sections.`,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return { sections, elements };
|
|
167
|
+
}
|
package/src/core/text.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Which part of a text node's characters `fd.replaceText` replaces: a `[start, end)` range, the first match of `replace`, or all. */
|
|
2
|
+
export type TextTarget = { replace?: string | RegExp; range?: [number, number] };
|
|
3
|
+
|
|
4
|
+
/** The `[start, end)` span of `text` that `target` names. Throws when the range is out of bounds or the pattern does not occur. */
|
|
5
|
+
export function textSpan(text: string, target: TextTarget = {}): [number, number] {
|
|
6
|
+
const { replace, range } = target;
|
|
7
|
+
|
|
8
|
+
if (replace !== undefined && range !== undefined) throw new Error("Pass either replace or range, not both.");
|
|
9
|
+
|
|
10
|
+
if (range) {
|
|
11
|
+
const [start, end] = range;
|
|
12
|
+
|
|
13
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > text.length)
|
|
14
|
+
throw new Error(`range [${start}, ${end}] is outside the text, which has ${text.length} characters.`);
|
|
15
|
+
|
|
16
|
+
return [start, end];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (replace instanceof RegExp) {
|
|
20
|
+
// A global or sticky pattern starts at its lastIndex, so search a copy without those flags from the start.
|
|
21
|
+
const match = new RegExp(replace.source, replace.flags.replace(/[gy]/g, "")).exec(text);
|
|
22
|
+
|
|
23
|
+
if (!match) throw new Error(`${replace} does not match the text.`);
|
|
24
|
+
|
|
25
|
+
return [match.index, match.index + match[0].length];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (replace !== undefined) {
|
|
29
|
+
const at = text.indexOf(replace);
|
|
30
|
+
|
|
31
|
+
if (at < 0) throw new Error(`"${replace}" does not occur in the text.`);
|
|
32
|
+
|
|
33
|
+
return [at, at + replace.length];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return [0, text.length];
|
|
37
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { rgb } from "./css";
|
|
2
|
+
import type { TokenImportPlan, TokenImportVariable } from "./protocol";
|
|
3
|
+
|
|
4
|
+
/** A variable name as a CSS custom property name: lowercase, with every run of other characters than letters, digits, `-` and `_` as `-`. */
|
|
5
|
+
export const cssSlug = (name: string) =>
|
|
6
|
+
name
|
|
7
|
+
.toLowerCase()
|
|
8
|
+
.replace(/[^a-z0-9_-]+/g, "-")
|
|
9
|
+
.replace(/^-+|-+$/g, "");
|
|
10
|
+
|
|
11
|
+
const CSS_NAME = /^(?:var\(\s*(--[\w-]+)\s*\)|(--[\w-]+))$/;
|
|
12
|
+
|
|
13
|
+
/** The custom property a variable exports as: the one its WEB code syntax names, else its slugged name. */
|
|
14
|
+
export function cssProperty(name: string, web?: string) {
|
|
15
|
+
const named = web?.trim().match(CSS_NAME);
|
|
16
|
+
|
|
17
|
+
return named ? (named[1] ?? named[2]) : `--${cssSlug(name)}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Mode names match whatever their case and punctuation, so `dark` from `[data-theme="dark"]` finds a `Dark` mode. */
|
|
21
|
+
export const modeKey = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, "");
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The existing variable an imported one updates: the one of its name, else, when the import names a CSS property, the one that exports
|
|
25
|
+
* as that property, so a CSS export imports back onto the variables it came from.
|
|
26
|
+
*/
|
|
27
|
+
export function matchVariable<T extends { name: string; web?: string }>(planned: TokenImportVariable, existing: T[]) {
|
|
28
|
+
const byName = existing.find((v) => v.name === planned.name);
|
|
29
|
+
|
|
30
|
+
if (byName || planned.codeSyntaxWeb === undefined) return byName;
|
|
31
|
+
const property = cssProperty(planned.name, planned.codeSyntaxWeb);
|
|
32
|
+
|
|
33
|
+
return existing.find((v) => cssProperty(v.name, v.web) === property);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type Existing = { name: string; type: string; web?: string };
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The planned variables a token import upserts, each with the variable of its collection (`own`) it updates, and a warning for each it
|
|
40
|
+
* leaves out because its match has another type. The live import and `--dry-run` share it, so the preview matches what Figma does.
|
|
41
|
+
*/
|
|
42
|
+
export function upsertsOf<T extends Existing>(plan: TokenImportPlan, own: T[]) {
|
|
43
|
+
const upserts: { planned: TokenImportVariable; match?: T }[] = [];
|
|
44
|
+
const warnings: string[] = [];
|
|
45
|
+
|
|
46
|
+
for (const planned of plan.variables) {
|
|
47
|
+
const match = matchVariable(planned, own);
|
|
48
|
+
|
|
49
|
+
if (match && match.type !== planned.type)
|
|
50
|
+
warnings.push(`${planned.name} is left out: ${plan.collection}/${match.name} is a ${match.type} variable.`);
|
|
51
|
+
else upserts.push({ planned, match });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return { upserts, warnings };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The variable an alias of `type` binds to: the upserted one of its name, else one the file already holds. Nothing when neither holds
|
|
59
|
+
* one, as when its target was left out for a type clash.
|
|
60
|
+
*/
|
|
61
|
+
export function aliasTarget<U extends Existing, L extends Existing>(
|
|
62
|
+
alias: string,
|
|
63
|
+
type: string,
|
|
64
|
+
upserted: Map<string, U>,
|
|
65
|
+
local: L[],
|
|
66
|
+
) {
|
|
67
|
+
const own = upserted.get(alias);
|
|
68
|
+
|
|
69
|
+
return own?.type === type ? own : local.find((v) => v.name === alias && v.type === type);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The warning for an alias `aliasTarget` finds no variable for. */
|
|
73
|
+
export const unboundAlias = (name: string, mode: string, alias: string) =>
|
|
74
|
+
`${name} keeps its ${mode} value: it aliases ${alias}, which neither the tokens file nor this Figma file holds.`;
|
|
75
|
+
|
|
76
|
+
/** #rrggbb or #rrggbbaa as Figma's 0–1 channels. */
|
|
77
|
+
export const rgbaOf = (hex: string) => ({ ...rgb(hex), a: hex.length === 9 ? parseInt(hex.slice(7, 9), 16) / 255 : 1 });
|