-
Notifications
You must be signed in to change notification settings - Fork 24
/
app.mjs
576 lines (552 loc) · 17.6 KB
/
app.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import fs from "fs";
import {
getFileStyles,
getFileVariables,
KEY_PREFIX_COLLECTION,
} from "./fromFigma.mjs";
const FILE_KEY = process.env.FIGMA_FILE_KEY;
const SKIP_REST_API = process.argv.includes("--skip-rest-api");
const WRITE_DIR = "../../src";
const CONVERT_TO_REM = true;
// Extension namespace for the w3c token file
const NAMESPACE = "com.figma.sds";
// Prefix for CSS custom properties
const TOKEN_PREFIX = "sds-";
// The data object. Each item in here represents a collection.
// `[collection].definitions` will contain all the token data
// You should ensure these names match those in your Figma variables data.
// Collection names are lowercased and underscored and stripped of non alphanumeric characters.
const COLLECTION_DATA = {
color_primitives: {
settings: { prefix: "color" },
},
color: {
settings: {
prefix: "color",
// Light mode names from Figma in lower underscore case. First is default light mode.
colorSchemes: ["sds_light"],
// Dark mode names from Figma in lower underscore case. First is default dark mode.
colorSchemesDark: ["sds_dark"],
// Strings to strip from mode names above when transforming to theme class names. (Only applicable when more than one per mode)
colorSchemeLightRemove: "_light",
colorSchemeDarkRemove: "_dark",
// Strings to find and replace in CSS values
replacements: {
color_primitives: "color",
},
},
},
size: {
settings: {
prefix: "size",
convertPixelToRem: true,
replacements: {
[`${KEY_PREFIX_COLLECTION}responsive`]: "responsive",
},
},
},
typography_primitives: {
settings: {
prefix: "typography",
convertPixelToRem: true,
replacements: {
[`${KEY_PREFIX_COLLECTION}responsive`]: "responsive",
"Extra Bold Italic": "800 italic",
"Semi Bold Italic": "600 italic",
"Medium Italic": "500 italic",
"Regular Italic": "400 italic",
"Extra Light Italic": "200 italic",
"Light Italic": "300 italic",
"Black Italic": "900 italic",
"Bold Italic": "700 italic",
"Thin Italic": "100 italic",
},
},
},
typography: {
settings: {
prefix: "typography",
convertPixelToRem: true,
replacements: {
typography_primitives: "typography",
},
},
},
};
initialize();
async function initialize() {
// We write data to disk before processing.
// This allows us to process independent of REST API.
// You can use Plugins to author these files manually without Variables REST API access.
if (!SKIP_REST_API) {
const stylesJSON = await getFileStyles(FILE_KEY);
fs.writeFileSync("./styles.json", JSON.stringify(stylesJSON, null, 2));
const tokensJSON = await getFileVariables(FILE_KEY, NAMESPACE);
fs.writeFileSync("./tokens.json", JSON.stringify(tokensJSON, null, 2));
}
// Process token JSON into CSS
const { processed, themeCSS } = processTokenJSON(
JSON.parse(fs.readFileSync("./tokens.json")),
);
// An object to lookup variables in when processing styles.
console.log(processed.color.definitions.sds_light);
const variableLookups = Object.keys(processed)
.flatMap((key) => Object.values(processed[key].definitions)[0])
.reduce((into, item) => {
into[item.figmaId] = item;
return into;
}, {});
// Process styles JSON into CSS
const stylesCSS = await processStyleJSON(
JSON.parse(fs.readFileSync("./styles.json")),
variableLookups,
);
// Write our processed CSS
fs.writeFileSync(
`${WRITE_DIR}/theme.css`,
[...themeCSS, ...stylesCSS].join("\n"),
);
console.log("Done!");
}
/**
* Massive operation to process Token JSON as parseable object for CSS conversion
* @param {Object<any>} data - W3C Token Spec JSON with collections at the root.
* @returns {{ processed: {[collection_key: string]: { definitions: { [mode_name: string]: Array<{ property: string, propertyName: string, figmaId: string, description: string, value: string, type: string }> } } } } }}
*/
function processTokenJSON(data) {
const processed = { ...COLLECTION_DATA };
for (let key in processed) {
processCollection(
data,
COLLECTION_DATA[key],
`${KEY_PREFIX_COLLECTION}${key}`,
);
}
// Our theme.css file string.
const fileStringCSSLines = [
"/*",
" * This file is automatically generated by scripts/tokens/app.mjs!",
" */",
];
for (let key in processed) {
fileStringCSSLines.push(
...fileStringCSSFromProcessedObject(processed[key], key),
);
}
// Turn variable collection data into a CSS file string
function fileStringCSSFromProcessedObject({ definitions, settings }, key) {
// Lines of CSS
const lines = [];
// This is how we know to do prefers-color scheme rather than plain :root
if (settings.colorSchemes) {
settings.colorSchemes.forEach((scheme, i) => {
if (i === 0) {
lines.push(...[`/* ${key}: ${scheme} (default) */`, ":root {"]);
} else {
lines.push(
...[
`/* ${key}: ${scheme} */`,
`.${TOKEN_PREFIX}scheme-${key}-${scheme.replace(settings.colorSchemeLightRemove, "")} {`,
],
);
}
lines.push(drawCSSPropLines(definitions[scheme], " "), "}");
});
if (settings.colorSchemesDark) {
lines.push("@media (prefers-color-scheme: dark) {");
settings.colorSchemesDark.forEach((scheme, i) => {
if (i === 0) {
lines.push(...[` /* ${key}: ${scheme} (default) */`, " :root {"]);
} else {
lines.push(
...[
` /* ${key}: ${scheme} */`,
` .${TOKEN_PREFIX}scheme-${key}-${scheme.replace(settings.colorSchemeDarkRemove, "")} {`,
],
);
}
lines.push(drawCSSPropLines(definitions[scheme], " "), " }");
});
lines.push("}");
}
} else {
let first;
// For each mode in definitions
for (let k in definitions) {
if (!first) {
first = true;
lines.push(...[`/* ${key}: ${k} (default) */`, ":root {"]);
} else {
lines.push(
...[`/* ${key}: ${k} */`, `.${TOKEN_PREFIX}theme-${key}-${k} {`],
);
}
lines.push(...[drawCSSPropLines(definitions[k], " "), "}"]);
}
}
return lines;
}
// Code syntax array string is something we can paste in Figma console
// to bulk update variable code syntax and descriptions to match our CSS property names.
const variableSyntaxAndDescriptionString = `Promise.all([
${Object.keys(processed)
.map((key) => drawVariableSyntaxAndDescription(processed[key].definitions))
.sort()
.join(",\n")},
].map(async ([variableId, webSyntax, description]) => {
const variable = await figma.variables.getVariableByIdAsync(variableId);
if (variable) {
variable.setVariableCodeSyntax("WEB", webSyntax);
variable.description = description;
}
return;
})).then(() => console.log("DONE!")).catch(console.error)`;
// Write the code syntax snippet
fs.writeFileSync(
"./tokenVariableSyntaxAndDescriptionSnippet.js",
variableSyntaxAndDescriptionString,
);
// Return our data
return { processed, themeCSS: fileStringCSSLines };
/**
* Transform an array of lines of CSS custom property definitions into indented CSS output.
* @param {string[]} lines
* @param {string} indent
* @returns {string}
*/
function drawCSSPropLines(lines = [], indent = " ") {
return (
lines
.sort((a, b) => (a.property > b.property ? 1 : -1))
.map((l) => `${indent}${l.property}: ${l.value}`)
.join(";\n") + ";"
);
}
/**
* Given an object of modes, return the Code Syntax snippet string
* @param {{ [mode: string]: string[]}} linesObject
* @returns {string}
*/
function drawVariableSyntaxAndDescription(linesObject = { default: [] }) {
const lines = linesObject[Object.keys(linesObject)[0]];
return lines
.map(
(l) =>
` ["${l.figmaId}", "var(${l.property})", "${l.description || ""}"]`,
)
.sort()
.join(",\n");
}
/**
*
* @param {Object<any>} data - All variable collection data (W3C token spec JSON)
* @param {Object<any>} processed - The object to write collection data to
* @param {string} definitionsKey - The key for the definitions
*/
function processCollection(data, processed, definitionsKey) {
const {
replacements = {},
convertPixelToRem = CONVERT_TO_REM,
prefix,
} = processed.settings;
const fullPrefix = `${TOKEN_PREFIX}${prefix}`;
processed.definitions = {};
traverse(
processed.definitions,
data[definitionsKey],
replacements,
definitionsKey,
fullPrefix,
convertPixelToRem,
"",
fullPrefix ? [fullPrefix] : undefined,
);
}
/**
* Traverse W3C token file to build out tokens.
* @param {Object<any>} definitions
* @param {Object<any>} object - collection from W3C token JSON
* @param {{[find: string]: string}} replacements - string replacement object, keyed by find.
* @param {string} definitionsKey
* @param {string} prefix - collection token prefix
* @param {boolean} convertPixelToRem - whether or not to turn numbers into n/16 rem values.
* @param {string} currentType - as we traverse token scope, we may need to track type from parent
* @param {string[]} keys - history of token scopes to prefix name
* @returns
*/
function traverse(
definitions,
object,
replacements,
definitionsKey,
prefix,
convertPixelToRem = CONVERT_TO_REM,
currentType = "",
keys = [],
) {
const property = `--${keys.join("-")}`;
const propertyNameFull = keys
.map((key) =>
key
.split(/[^\dA-Za-z]/)
.map((k) => `${k.charAt(0).toUpperCase()}${k.slice(1)}`)
.join(""),
)
.join("");
// .replace(/^color/i, "");
const valueWithReplacements = (value) => {
if (typeof value !== "string") return value;
for (let replacement in replacements) {
value = value.replace(replacement, replacements[replacement]);
}
return value.toLowerCase();
};
const propertyName =
propertyNameFull.charAt(0).toLowerCase() + propertyNameFull.slice(1);
const type = object.$type || currentType;
if ("$value" in object) {
if ("$extensions" in object && NAMESPACE in object.$extensions) {
const description = object.$description || "";
const figmaId = object.$extensions[NAMESPACE].figmaId;
for (let mode in object.$extensions[NAMESPACE].modes) {
definitions[mode] = definitions[mode] || [];
definitions[mode].push({
property,
propertyName,
figmaId,
description,
value: valueWithReplacements(
valueToCSS(
property,
object.$extensions[NAMESPACE].modes[mode],
definitionsKey,
convertPixelToRem,
prefix,
),
),
type,
});
}
} else {
const description = object.$description || "";
const figmaId =
"$extensions" in object && NAMESPACE in object.$extensions
? object.$extensions[NAMESPACE].figmaId
: "UNDEFINED";
const mode = "default";
definitions[mode] = definitions[mode] || [];
definitions[mode].push({
property,
propertyName,
description,
figmaId,
value: valueWithReplacements(
valueToCSS(
property,
object.$value,
definitionsKey,
convertPixelToRem,
"",
),
),
type,
});
}
} else {
Object.entries(object).forEach(([key, value]) => {
if (key.charAt(0) !== "$") {
traverse(
definitions,
value,
replacements,
definitionsKey,
prefix,
convertPixelToRem,
type,
[...keys, key],
);
}
});
}
}
/**
* Converting W3C token JSON value to CSS value.
* @param {string} property
* @param {string} value
* @param {string} definitionsKey
* @param {boolean} convertPixelToRem
* @param {string} prefix
* @returns {string}
*/
function valueToCSS(
property,
value,
definitionsKey,
convertPixelToRem,
prefix = "",
) {
if (value.toString().charAt(0) === "{")
return `var(--${value
.replace(`${definitionsKey}`, prefix)
.replace(/[\. ]/g, "-")
.replace(/^\{/, "")
.replace(/\}$/, "")})`;
const valueIsDigits = value.toString().match(/^-?\d+(\.\d+)?$/);
const isRatio = property.match(/(ratio-)/);
const isNumeric =
valueIsDigits && !property.match(/(weight|ratio-)/) && !isRatio;
if (isNumeric) {
return convertPixelToRem ? `${parseInt(value) / 16}rem` : `${value}px`;
} else if (isRatio) {
return Math.round(value * 10000) / 10000;
}
if (property.match("family-mono")) {
return `"${value}", monospace`;
} else if (property.match("family-sans")) {
return `"${value}", sans-serif`;
} else if (property.match("family-serif")) {
return `"${value}", serif`;
}
return value;
}
}
/**
* Turning style JSON into a box shadow, filter, or font property value
* @param {Object<any>} data - Style JSON data from Figma
* @param {Object<any>} variablesLookup - Object to find variable names
* @returns
*/
async function processStyleJSON(data, variablesLookup) {
const effectDefs = [];
const text = [];
data.forEach(({ type, ...style }) => {
if (type === "TEXT") {
const {
name,
fontSize,
fontFamily,
fontWeight,
fontStyle = "normal",
} = style;
const css = [
valueFromPossibleVariable(fontStyle),
valueFromPossibleVariable(fontWeight),
valueFromPossibleVariable(fontSize),
valueFromPossibleVariable(fontFamily),
].join(" ");
text.push(
`--${TOKEN_PREFIX}font-${name
.replace(/^[^a-zA-Z0-9]+/, "")
.replace(/[^a-zA-Z0-9]+/g, "-")
.toLowerCase()}: ${css};`,
);
} else if (type === "EFFECT") {
const { name, effects } = style;
const safeName = sanitizeName(name);
const shadows = [];
const filters = [];
const backdropFilters = [];
effects.forEach((effect) => {
if (effect.visible) {
if (effect.type.match("SHADOW")) {
shadows.push(formatEffect(effect));
}
if (effect.type.match("LAYER_BLUR")) {
filters.push(formatEffect(effect));
}
if (effect.type.match("BACKGROUND_BLUR")) {
backdropFilters.push(formatEffect(effect));
}
}
});
if (shadows.length) {
effectDefs.push(
`--${TOKEN_PREFIX}effects-shadows-${safeName}: ${shadows.join(", ")};`,
);
}
if (filters.length) {
effectDefs.push(
`--${TOKEN_PREFIX}effects-filter-${safeName}: ${filters[0]};`,
);
}
if (backdropFilters.length) {
effectDefs.push(
`--${TOKEN_PREFIX}effects-backdrop-filter-${safeName}: ${backdropFilters[0]};`,
);
}
}
});
return [
"/* styles */",
":root {",
" " + [...text, ...effectDefs].join("\n "),
"}",
];
/**
* Takes possible variable reference or value and returns an appropriate value
* @param {string} item
* @returns {string}
*/
function valueFromPossibleVariable(item = "") {
if (typeof item === "object") {
// attempting to find bound variables
const variable = variablesLookup[item.id];
return variable ? `var(${variable.property})` : JSON.stringify(item);
} else if (item.match(/^[1-9]00$/)) {
// attempting to find variable for weights
// the scenario where style is used so weight is int
const variable = variablesLookup.find(({ value }) => value === item);
return variable ? `var(${variable.property})` : item;
}
return item;
}
/**
* Lowercase hyphenate string
* @param {string} name
* @returns {string}
*/
function sanitizeName(name) {
return name
.replace(/[^a-zA-Z0-9 ]/g, " ")
.trim()
.replace(/ +/g, "-")
.toLowerCase();
}
/**
* Transforms Figma effect data into CSS string
* @param {{type: EffectType, ...effect}} args[0] Figma effect
* @returns {string}
*/
function formatEffect({ type, ...effect }) {
if (type === "DROP_SHADOW" || type === "INNER_SHADOW") {
const {
radius,
offset: { x, y },
spread,
hex,
boundVariables,
} = effect;
const numbers = [
boundVariables.offsetX
? valueFromPossibleVariable(boundVariables.offsetX)
: `${x}px`,
boundVariables.offsetY
? valueFromPossibleVariable(boundVariables.offsetY)
: `${y}px`,
boundVariables.radius
? valueFromPossibleVariable(boundVariables.radius)
: `${radius}px`,
boundVariables.spread
? valueFromPossibleVariable(boundVariables.spread)
: `${spread}px`,
boundVariables.color
? valueFromPossibleVariable(boundVariables.color)
: `${hex}px`,
];
return `${type === "INNER_SHADOW" ? "inset " : ""}${numbers.join(" ")}`;
} else if (type === "LAYER_BLUR" || type === "BACKGROUND_BLUR") {
const { radius, boundVariables } = effect;
return `blur(${boundVariables.radius ? valueFromPossibleVariable(boundVariables.radius) : `${radius}px`})`;
}
}
}