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.
@@ -0,0 +1,389 @@
1
+ import { hexOf, parseColor, shadowsOf, type RGB } from "./css";
2
+ import { textRole, titleCase } from "./naming";
3
+ import { walk, type El, type Run, type SvgEl } from "./snapshot";
4
+ import type { ImportSpec } from "./spec";
5
+
6
+ export type TextStyleSpec = {
7
+ /** The family, when a run sets one other than the page's main family, which takes the spec's `font`. */
8
+ family?: string;
9
+ size: number;
10
+ line: number;
11
+ style: string;
12
+ tracking?: number;
13
+ case?: "ORIGINAL" | "UPPER" | "LOWER" | "TITLE" | "SMALL_CAPS" | "SMALL_CAPS_FORCED";
14
+ };
15
+
16
+ export type ColorRef = { token: string } | RGB;
17
+
18
+ export type ShadowLayer = {
19
+ type: "DROP_SHADOW" | "INNER_SHADOW";
20
+ color: ColorRef;
21
+ alpha: number;
22
+ x: number;
23
+ y: number;
24
+ radius: number;
25
+ spread: number;
26
+ };
27
+
28
+ /** One effect style: every layer of a `box-shadow`, outer and inset, in CSS order. */
29
+ export type ElevationSpec = { name: string; shadows: ShadowLayer[] };
30
+
31
+ export type IconSpec = { svg: string; filled: boolean };
32
+
33
+ export type Theme = {
34
+ font: string;
35
+ colors: Record<string, string>;
36
+ colorAliases: Record<string, string>;
37
+ /** The `--name` each color variable came from, for its WEB code syntax. */
38
+ cssNames: Record<string, string>;
39
+ /** Color values by mode name, for the variables a mode changes, from the snapshot's `themes`. */
40
+ colorModes: Record<string, Record<string, string>>;
41
+ spacing: Record<string, number>;
42
+ radii: Record<string, number>;
43
+ textStyles: Record<string, TextStyleSpec>;
44
+ elevations: Record<string, ElevationSpec>;
45
+ icons: Record<string, IconSpec>;
46
+ iconColor: ColorRef;
47
+ iconLibrary: string;
48
+ svgs: Record<string, string>;
49
+ images: Record<string, string>;
50
+ };
51
+
52
+ const WEIGHTS = new Map([
53
+ [100, "Thin"],
54
+ [200, "Extra Light"],
55
+ [300, "Light"],
56
+ [400, "Regular"],
57
+ [500, "Medium"],
58
+ [600, "Semi Bold"],
59
+ [700, "Bold"],
60
+ [800, "Extra Bold"],
61
+ [900, "Black"],
62
+ ]);
63
+
64
+ export const fontStyle = (r: Run) =>
65
+ r.italic ? `${r.weight === 400 ? "" : `${WEIGHTS.get(r.weight)} `}Italic` : (WEIGHTS.get(r.weight) ?? "Regular");
66
+
67
+ export const typeKey = (r: Run) =>
68
+ [r.weight, r.size, r.lineHeight, r.letterSpacing, r.upper, r.italic, r.fontFamily ?? ""].join("|");
69
+
70
+ export const runKey = (r: Run) => `${typeKey(r)}|${r.color}|${r.underline}|${!!r.strike}|${r.href ?? ""}`;
71
+
72
+ export const svgInner = (svg: string) => svg.replace(/^<svg[^>]*>|<\/svg>$/g, "");
73
+
74
+ export const iconKey = (el: SvgEl) => svgInner(el.svg).replace(/ (stroke|fill|style|color)="[^"]*"/g, "");
75
+
76
+ const svgPaint = (svg: string, attr: "stroke" | "fill") => {
77
+ for (const [, value] of svg.matchAll(new RegExp(` ${attr}="([^"]*)"`, "g"))) {
78
+ if (value === "none" || value === "transparent") continue;
79
+ const c = parseColor(value);
80
+
81
+ if (c && c.a > 0) return value;
82
+ }
83
+ };
84
+
85
+ export const svgColor = (el: SvgEl) => svgPaint(el.svg, "stroke") ?? svgPaint(el.svg, "fill") ?? "rgb(0, 0, 0)";
86
+
87
+ export const viewBox = (el: SvgEl) => el.svg.match(/viewBox="([^"]+)"/)?.[1] ?? `0 0 ${el.box[2]} ${el.box[3]}`;
88
+
89
+ const PAINT = / (?:fill|stroke)="([^"]*)"/g;
90
+
91
+ /**
92
+ * A small one-color drawing, which becomes a recolorable icon component. Anything else, such as a logo, a chart or an illustration,
93
+ * keeps its own colors as a vector frame.
94
+ */
95
+ export function isSimpleIcon(el: SvgEl) {
96
+ if (el.box[2] > 64 || el.box[3] > 64 || /<(defs|linearGradient|radialGradient|text|image|filter)\b/.test(el.svg))
97
+ return false;
98
+ const paints = new Set<string>();
99
+
100
+ for (const [, value] of el.svg.matchAll(PAINT)) {
101
+ if (value === "none" || value === "transparent") continue;
102
+ const c = parseColor(value);
103
+
104
+ if (!c) return false;
105
+
106
+ if (c.a > 0) paints.add(`${hexOf(c)} ${c.a}`);
107
+ }
108
+
109
+ return paints.size <= 1;
110
+ }
111
+
112
+ export const filled = (el: SvgEl) => !svgPaint(el.svg, "stroke");
113
+ export const strokeWidth = (el: SvgEl) => parseFloat(el.svg.match(/stroke-width="([\d.]+)"/)?.[1] ?? "2");
114
+
115
+ export type PaintUse = "fill" | "text" | "stroke";
116
+
117
+ /** The token a `var(--name)` chain ends at, or `name` itself when it holds a value. A loop or a missing token ends the chain. */
118
+ function targetIn(tokens: Record<string, string>, name: string, seen = new Set<string>()): string {
119
+ const ref = tokens[name]?.match(/^var\(--([\w-]+)\)$/)?.[1];
120
+
121
+ return ref && ref in tokens && !seen.has(ref) ? targetIn(tokens, ref, seen.add(name)) : name;
122
+ }
123
+
124
+ const opaqueHex = (css: string | undefined) => {
125
+ const c = css === undefined ? undefined : parseColor(css);
126
+
127
+ return c && c.a === 1 ? hexOf(c) : undefined;
128
+ };
129
+
130
+ export function colorTokens(tokens: Record<string, string>) {
131
+ const targetOf = (name: string) => targetIn(tokens, name);
132
+
133
+ const aliased = new Set(
134
+ Object.keys(tokens)
135
+ .filter((n) => targetOf(n) !== n)
136
+ .map((n) => targetOf(n)),
137
+ );
138
+
139
+ const varName = (name: string) => (aliased.has(name) ? `palette/${name}` : name);
140
+ const colors: Record<string, string> = {};
141
+ const colorAliases: Record<string, string> = {};
142
+ const cssNames: Record<string, string> = {};
143
+
144
+ for (const name of Object.keys(tokens)) {
145
+ const hex = opaqueHex(tokens[targetOf(name)]);
146
+
147
+ if (!hex) continue;
148
+ colors[varName(name)] = hex;
149
+ cssNames[varName(name)] = name;
150
+
151
+ if (targetOf(name) !== name) colorAliases[name] = varName(targetOf(name));
152
+ }
153
+
154
+ const tokensByHex = new Map<string, string[]>();
155
+
156
+ for (const [name, hex] of Object.entries(colors)) tokensByHex.set(hex, [...(tokensByHex.get(hex) ?? []), name]);
157
+
158
+ const declaredFor = (hex: string, declared?: string) =>
159
+ declared && colors[varName(declared)] === hex ? varName(declared) : undefined;
160
+
161
+ const tokenFor = (hex: string, use: PaintUse = "fill", declared?: string) => {
162
+ const names = tokensByHex.get(hex);
163
+
164
+ if (!names) return;
165
+ const known = declaredFor(hex, declared);
166
+
167
+ if (known) return known;
168
+ const hint = { text: /foreground/, stroke: /border|ring/, fill: /^$/ }[use];
169
+ const fits = names.filter((n) => hint.test(n));
170
+ const pool = fits.length ? fits : use === "fill" ? names.filter((n) => !/foreground|border|ring/.test(n)) : names;
171
+ const candidates = pool.length ? pool : names;
172
+
173
+ return candidates.find((n) => n in colorAliases) ?? candidates[0];
174
+ };
175
+
176
+ const guessedAmong = (hex: string, declared?: string) => {
177
+ const names = tokensByHex.get(hex) ?? [];
178
+
179
+ return names.length > 1 && !declaredFor(hex, declared) ? names : [];
180
+ };
181
+
182
+ return { colors, colorAliases, cssNames, tokenFor, guessedAmong };
183
+ }
184
+
185
+ /**
186
+ * Each mode's color values, for the variables it changes. A mode that changes an alias's target the same way leaves the alias alone,
187
+ * since the alias follows its target into the mode.
188
+ */
189
+ export function colorModesOf(
190
+ tokens: Record<string, string>,
191
+ themes: Record<string, Record<string, string>>,
192
+ { colors, colorAliases, cssNames }: Pick<ReturnType<typeof colorTokens>, "colors" | "colorAliases" | "cssNames">,
193
+ ) {
194
+ const modes: Record<string, Record<string, string>> = {};
195
+
196
+ for (const [mode, overrides] of Object.entries(themes)) {
197
+ const merged = { ...tokens, ...overrides };
198
+ const hexIn = (name: string) => opaqueHex(merged[targetIn(merged, name)]);
199
+ const values: Record<string, string> = {};
200
+
201
+ for (const [v, css] of Object.entries(cssNames)) {
202
+ const hex = hexIn(css);
203
+ const target = colorAliases[v];
204
+
205
+ if (!hex || hex === colors[v] || (target && hexIn(cssNames[target]) === hex)) continue;
206
+ values[v] = hex;
207
+ }
208
+
209
+ if (Object.keys(values).length) modes[mode] = values;
210
+ }
211
+
212
+ return modes;
213
+ }
214
+
215
+ /** The family most of the page's text is set in, by characters. The spec's `font` takes its place. */
216
+ function mainFamily(root: El) {
217
+ const chars = new Map<string, number>();
218
+ walk(root, (el) => {
219
+ if (el.kind === "text")
220
+ for (const r of el.runs)
221
+ if (r.fontFamily) chars.set(r.fontFamily, (chars.get(r.fontFamily) ?? 0) + r.text.length);
222
+ });
223
+
224
+ return [...chars].sort((a, b) => b[1] - a[1])[0]?.[0];
225
+ }
226
+
227
+ const ROLE_ORDER = ["Heading", "Body", "Eyebrow", "Label", "Button", "Link", "Text"];
228
+
229
+ /**
230
+ * `styleOf` names a run's weight and slant in a family's own style names. `available` says whether Figma has a family; a run in one it
231
+ * lacks is set in `font`, and the family is listed in `missingFamilies`.
232
+ */
233
+ export function foundationsOf(
234
+ spec: ImportSpec,
235
+ root: El,
236
+ font: string,
237
+ styleOf: (r: Run, family: string) => string,
238
+ available: (family: string) => boolean = () => true,
239
+ ) {
240
+ const tokens = colorTokens(spec.snapshot.tokens);
241
+ const { colors, colorAliases, cssNames, tokenFor, guessedAmong } = tokens;
242
+ const main = mainFamily(root);
243
+ const missingFamilies = new Set<string>();
244
+
245
+ const familyOf = (r: Run) => {
246
+ if (!r.fontFamily || r.fontFamily === main || r.fontFamily === font) return font;
247
+
248
+ if (available(r.fontFamily)) return r.fontFamily;
249
+ missingFamilies.add(r.fontFamily);
250
+
251
+ return font;
252
+ };
253
+
254
+ const typeRuns = new Map<string, { run: Run; roles: Map<string, number> }>();
255
+ const shadows = new Map<string, ElevationSpec>();
256
+ const icons = new Map<string, { name: string; el: SvgEl }>();
257
+ const iconNames = new Set<string>();
258
+ walk(root, (el, parent, context) => {
259
+ if (el.kind === "text") {
260
+ for (const r of el.runs) {
261
+ const entry = typeRuns.get(typeKey(r)) ?? { run: r, roles: new Map() };
262
+ const role = textRole(el, parent, r);
263
+ entry.roles.set(role, (entry.roles.get(role) ?? 0) + 1);
264
+ typeRuns.set(typeKey(r), entry);
265
+ }
266
+ }
267
+
268
+ const layers = shadows.has(el.style.shadow) ? [] : shadowsOf(el.style.shadow);
269
+
270
+ if (layers.length) {
271
+ shadows.set(el.style.shadow, {
272
+ name: "",
273
+ shadows: layers.map(({ color: c, ...layer }) => {
274
+ const token = tokenFor(hexOf(c));
275
+
276
+ return { ...layer, color: token === undefined ? { r: c.r, g: c.g, b: c.b } : { token }, alpha: c.a };
277
+ }),
278
+ });
279
+ }
280
+
281
+ if (el.kind === "svg" && isSimpleIcon(el) && !icons.has(iconKey(el))) {
282
+ const key = iconKey(el);
283
+
284
+ const base =
285
+ Object.entries(spec.icons ?? {}).find(([fragment]) => key.includes(fragment))?.[1] ??
286
+ (titleCase(context.split("__").pop()!) || "Icon");
287
+
288
+ let name = base;
289
+
290
+ for (let i = 2; iconNames.has(name); i++) name = `${base} ${i}`;
291
+ iconNames.add(name);
292
+ icons.set(key, { name, el });
293
+ }
294
+ });
295
+
296
+ const typeEntries = [...typeRuns.values()]
297
+ .map(({ run, roles }) => ({
298
+ run,
299
+ role: [...roles].sort((a, b) => b[1] - a[1] || ROLE_ORDER.indexOf(a[0]) - ROLE_ORDER.indexOf(b[0]))[0][0],
300
+ }))
301
+ .sort(
302
+ (a, b) =>
303
+ ROLE_ORDER.indexOf(a.role) - ROLE_ORDER.indexOf(b.role) ||
304
+ b.run.size - a.run.size ||
305
+ a.run.weight - b.run.weight ||
306
+ a.run.lineHeight - b.run.lineHeight,
307
+ );
308
+
309
+ const textStyles: Record<string, TextStyleSpec> = {};
310
+ const textStyleNames = new Map<string, string>();
311
+
312
+ for (const { run, role } of typeEntries) {
313
+ const family = familyOf(run);
314
+ const style = styleOf(run, family);
315
+ const base = `${role}/${+run.size.toFixed(2)} ${family === font ? "" : `${family} `}${style}`;
316
+ let name = base;
317
+
318
+ for (let i = 2; name in textStyles; i++) name = `${base} ${i}`;
319
+ textStyles[name] = {
320
+ family: family === font ? undefined : family,
321
+ size: run.size,
322
+ line: run.lineHeight,
323
+ style,
324
+ tracking: (run.letterSpacing / run.size) * 100,
325
+ case: run.upper ? "UPPER" : undefined,
326
+ };
327
+ textStyleNames.set(typeKey(run), name);
328
+ }
329
+
330
+ const elevations: Record<string, ElevationSpec> = {};
331
+ const widest = (e: ElevationSpec) => Math.max(...e.shadows.map((s) => s.radius));
332
+ [...shadows.entries()]
333
+ .sort((a, b) => widest(a[1]) - widest(b[1]))
334
+ .forEach(([css, e], i) => {
335
+ e.name = `Elevation/${i + 1}`;
336
+ elevations[css] = e;
337
+ });
338
+
339
+ const iconColorCounts = new Map<string, number>();
340
+ const themeIcons: Record<string, IconSpec> = {};
341
+ const svgs: Record<string, string> = {};
342
+ let rawIconColor: RGB | undefined;
343
+
344
+ for (const { name, el } of icons.values()) {
345
+ const solid = filled(el);
346
+ themeIcons[name] = { svg: name, filled: solid };
347
+ // A filled shape keeps its own aspect ratio; a line icon is drawn on the usual 24px square.
348
+ const [w, h] = solid ? [el.box[2], el.box[3]] : [24, 24];
349
+ const paint = solid ? `fill="#000000" stroke="none"` : `fill="none" stroke="#000000"`;
350
+ svgs[name] =
351
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="${viewBox(el)}" ${paint}>${svgInner(el.svg).replace(/ (stroke|fill)="(?!none)[^"]*"/g, "")}</svg>`;
352
+ const { r, g, b } = parseColor(svgColor(el)) ?? { r: 0, g: 0, b: 0 };
353
+ rawIconColor ??= { r, g, b };
354
+ const token = tokenFor(hexOf({ r, g, b }), "text", el.vars?.[svgColor(el)]);
355
+
356
+ if (token) iconColorCounts.set(token, (iconColorCounts.get(token) ?? 0) + 1);
357
+ }
358
+
359
+ const iconToken = [...iconColorCounts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? Object.keys(colors)[0];
360
+ const iconColor = iconToken === undefined ? (rawIconColor ?? { r: 0, g: 0, b: 0 }) : { token: iconToken };
361
+
362
+ const theme: Theme = {
363
+ font,
364
+ colors,
365
+ colorAliases,
366
+ cssNames,
367
+ colorModes: colorModesOf(spec.snapshot.tokens, spec.snapshot.themes ?? {}, tokens),
368
+ spacing: spec.spacing ?? {},
369
+ radii: spec.radii ?? {},
370
+ textStyles,
371
+ elevations,
372
+ icons: themeIcons,
373
+ iconColor,
374
+ iconLibrary: spec.name,
375
+ svgs,
376
+ images: spec.images,
377
+ };
378
+
379
+ return {
380
+ theme,
381
+ tokenFor,
382
+ guessedAmong,
383
+ textStyleNames,
384
+ missingFamilies: [...missingFamilies],
385
+ iconNames: new Map([...icons].map(([key, { name }]) => [key, name])),
386
+ };
387
+ }
388
+
389
+ export type Foundations = ReturnType<typeof foundationsOf>;
@@ -0,0 +1,4 @@
1
+ declare module "*/snapshot.json" {
2
+ const snapshot: import("./snapshot").Snapshot;
3
+ export default snapshot;
4
+ }