-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
760 lines (760 loc) · 35.1 KB
/
Copy pathcode.js
File metadata and controls
760 lines (760 loc) · 35.1 KB
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
"use strict";
/**
* @fileoverview Figma plugin code to export transformed design tokens in W3C format.
*
* Collects data from the current Figma file using the plugin API, transforms it into
* W3C Design Token format, and sends it to a hidden UI for download as JSON files.
*
* @since 2.0.0
*/
/// <reference types="@figma/plugin-typings" />
// --- Helper Functions ---
/**
* Recursively simplifies a Figma object or value for safe JSON serialization.
* @param obj - The object or value to simplify.
* @returns A simplified version suitable for JSON stringification.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function simplifyObject(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(simplifyObject);
}
const simplified = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && key !== 'parent' && key !== 'children') {
const value = obj[key];
if (typeof value !== 'function') {
simplified[key] = simplifyObject(value);
}
}
}
return simplified;
}
/**
* Converts RGBA values (0-1 range) to a 6-digit hex string.
* @param r Red component (0-1).
* @param g Green component (0-1).
* @param b Blue component (0-1).
* @returns The 6-digit hex color string (e.g., #ffffff).
*/
function rgbaToHex(r, g, b) {
const toHex = (c) => {
const hex = Math.round(c * 255).toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
/**
* Sets a value in a nested object based on an array of path parts.
* @param obj The target object.
* @param pathParts An array of strings representing the path.
* @param value The value to set at the nested path.
*/
function setNestedValue(obj, pathParts, value) {
let current = obj;
for (let i = 0; i < pathParts.length - 1; i++) {
const part = pathParts[i];
if (!current[part]) {
current[part] = {};
}
current = current[part];
}
current[pathParts[pathParts.length - 1]] = value;
}
/**
* Helper to safely round potentially imprecise floating point numbers from Figma.
* @param num The number to round.
* @param precision The number of decimal places (default is 0 for integers).
* @returns The rounded number.
*/
function roundNear(num, precision = 0) {
const factor = Math.pow(10, precision);
return Math.round(num * factor) / factor;
}
/**
* Checks if a variable name contains any of the specified terms in different naming conventions.
* Supports camelCase, kebab-case, and space-separated formats.
* @param name The variable name to check (should be lowercase).
* @param terms Array of terms to check for (e.g., ['font', 'size'] for fontSize, font-size, font size).
* @returns True if the name contains the terms in any supported format.
*/
function nameContainsTerms(name, terms) {
if (terms.length === 0)
return false;
const lowerName = name.toLowerCase();
// First, check for compound variations if multiple terms are provided, as they are more specific.
if (terms.length > 1) {
const joinedTerms = terms.join('').toLowerCase(); // camelCase: fontsize
const kebabTerms = terms.join('-').toLowerCase(); // kebab-case: font-size
const spaceTerms = terms.join(' ').toLowerCase(); // space: font size
if (lowerName.indexOf(joinedTerms) !== -1 ||
lowerName.indexOf(kebabTerms) !== -1 ||
lowerName.indexOf(spaceTerms) !== -1) {
return true;
}
}
// As a fallback, or for single terms, check if ALL individual terms are present as substrings.
for (const term of terms) {
if (lowerName.indexOf(term.toLowerCase()) === -1) {
return false; // If any term is missing, it's not a match.
}
}
return true; // All terms were found.
}
/**
* Infers the W3C token type and formats the value based on Figma variable details.
* @param variableDetail The variable detail object from Figma raw data.
* @param modeId The mode ID to extract the value for.
* @returns An object containing the inferred type, value, and resolution flags.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getTokenTypeAndValue(variableDetail, modeId) {
const rawValue = variableDetail.valuesByMode[modeId];
const resolvedType = variableDetail.resolvedType;
const name = variableDetail.name.toLowerCase();
const scopes = variableDetail.scopes || [];
// Handle Aliases
if (typeof rawValue === 'object' && rawValue && rawValue.type === 'VARIABLE_ALIAS') {
return { type: 'alias', value: rawValue.id, needsResolution: true, originalValue: null };
}
switch (resolvedType) {
case 'COLOR': {
const { r, g, b, a } = rawValue;
return {
type: 'color',
value: {
colorSpace: 'srgb',
components: [r, g, b],
alpha: a,
hex: rgbaToHex(r, g, b),
},
originalValue: rawValue
};
}
case 'FLOAT': {
if (nameContainsTerms(name, ['font', 'size']) || scopes.indexOf('FONT_SIZE') !== -1) {
return { type: 'dimension', value: { value: rawValue, unit: 'px' }, originalValue: rawValue };
}
if (nameContainsTerms(name, ['font', 'weight']) || scopes.indexOf('FONT_WEIGHT') !== -1) {
return { type: 'fontWeight', value: rawValue, originalValue: rawValue };
}
if (nameContainsTerms(name, ['line', 'height']) || scopes.indexOf('LINE_HEIGHT') !== -1) {
return { type: 'number', value: roundNear(rawValue) / 100, originalValue: rawValue };
}
if (nameContainsTerms(name, ['letter', 'spacing']) || scopes.indexOf('LETTER_SPACING') !== -1) {
return { type: 'dimension', value: { value: rawValue, unit: '%' }, originalValue: rawValue };
}
if (nameContainsTerms(name, ['space']) || nameContainsTerms(name, ['gap']) || scopes.indexOf('GAP') !== -1) {
return { type: 'dimension', value: { value: rawValue, unit: 'px' }, originalValue: rawValue };
}
if (nameContainsTerms(name, ['border', 'radius']) || nameContainsTerms(name, ['radius']) || scopes.indexOf('CORNER_RADIUS') !== -1) {
return { type: 'dimension', value: { value: rawValue, unit: 'px' }, originalValue: rawValue };
}
if (nameContainsTerms(name, ['border', 'width']) || nameContainsTerms(name, ['stroke', 'width']) || scopes.indexOf('STROKE_WIDTH') !== -1) {
return { type: 'dimension', value: { value: rawValue, unit: 'px' }, originalValue: rawValue };
}
return { type: 'number', value: rawValue, originalValue: rawValue };
}
case 'STRING': {
if (nameContainsTerms(name, ['font', 'family']) || scopes.indexOf('FONT_FAMILY') !== -1) {
return { type: 'fontFamily', value: rawValue, originalValue: rawValue };
}
if (nameContainsTerms(name, ['border', 'style'])) {
const validBorderStyles = [
'solid',
'dashed',
'dotted',
'double',
'groove',
'ridge',
'outset',
'inset',
];
if (typeof rawValue === 'string' && validBorderStyles.indexOf(rawValue.toLowerCase()) !== -1) {
return { type: 'strokeStyle', value: rawValue, originalValue: rawValue };
}
console.warn(`WARNING: Invalid border-style value "${rawValue}" for variable "${variableDetail.name}". Treating as a generic string.`);
}
return { type: 'string', value: rawValue, originalValue: rawValue };
}
default: {
console.warn(`Unknown resolvedType: ${resolvedType} for variable ${variableDetail.name}`);
return { type: 'unknown', value: rawValue, originalValue: rawValue };
}
}
}
/**
* Recursively follows a chain of aliases to find the final, non-alias token.
* Detects cycles to prevent infinite loops.
* @param startVariableId The ID of the variable to start resolution from.
* @param idToPathMap A map of Figma Variable IDs to TokenInfo.
* @param visited A set to track visited variable IDs in the current resolution chain.
* @returns The TokenInfo of the final resolved token, or null if a cycle is detected or the chain is invalid.
*/
function resolveAliasChain(startVariableId, idToPathMap, visited = new Set()) {
if (visited.has(startVariableId)) {
console.error(`Cycle detected in alias chain involving variable ID: ${startVariableId}`);
return null; // Cycle detected
}
visited.add(startVariableId);
const tokenInfo = idToPathMap[startVariableId];
if (!tokenInfo) {
return null; // Invalid ID
}
if (tokenInfo.aliasTargetId) {
return resolveAliasChain(tokenInfo.aliasTargetId, idToPathMap, visited);
}
return tokenInfo; // Found the end of the chain
}
/**
* Recursively traverses the token object and resolves alias values.
* @param obj The token object structure to traverse.
* @param idToPathMap A map where keys are Figma Variable IDs and values are TokenInfo objects.
* @param errorsList Array to push error/warning messages into.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function resolveAliases(obj, idToPathMap, errorsList) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const node = obj[key];
if (typeof node === 'object' && node !== null) {
if (node.$type === 'alias' && typeof node.$value === 'string' && node.$value.indexOf('ALIAS:') === 0) {
const directTargetId = node.$value.substring(6);
const directTargetInfo = idToPathMap[directTargetId];
if (!directTargetInfo) {
errorsList.push(`WARNING: Could not find alias target with ID: ${directTargetId} for token ${key}`);
node.$value = `UNRESOLVED_ALIAS:${directTargetId}`;
node.$type = 'error';
continue;
}
// Deeply resolve to find the final type, but don't use its path for the value.
const finalTokenInfo = resolveAliasChain(directTargetId, idToPathMap);
if (finalTokenInfo) {
node.$type = finalTokenInfo.type;
// Shallowly resolve the value to point to the immediate next alias.
node.$value = `{${directTargetInfo.path}}`;
}
else {
errorsList.push(`WARNING: Could not resolve alias chain starting from ID: ${directTargetId} for token ${key}. It might be part of a cycle or an invalid reference.`);
node.$value = `UNRESOLVED_ALIAS_CHAIN:${directTargetId}`;
node.$type = 'error';
}
}
else {
resolveAliases(node, idToPathMap, errorsList);
}
}
}
}
}
/**
* Processes Figma Text Styles into W3C Typography Tokens.
* @param textStyles Array of simplified Figma Text Style objects.
* @param idToPathMap Map of Figma Variable IDs to TokenInfo.
* @param errorsList Array to push error/warning messages into.
* @returns Object containing the generated typography tokens.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function processTextStyles(textStyles, idToPathMap, errorsList) {
const typographyTokens = {};
const fontWeightMap = {
'Thin': 100,
'ExtraLight': 200,
'Light': 300,
'Regular': 400,
'Medium': 500,
'SemiBold': 600,
'Bold': 700,
'ExtraBold': 800,
'Black': 900,
};
console.log(' Processing Text Styles into Typography Tokens...');
for (const style of textStyles) {
if (!style || !style.name)
continue;
const pathParts = style.name.split('/');
const compositeValue = {};
// fontFamily
const fontFamilyVarId = style.boundVariables && style.boundVariables.fontFamily && style.boundVariables.fontFamily.id;
if (fontFamilyVarId && idToPathMap[fontFamilyVarId]) {
compositeValue.fontFamily = `{${idToPathMap[fontFamilyVarId].path}}`;
}
else if (style.fontFamily) {
compositeValue.fontFamily = style.fontFamily;
}
// fontWeight
const fontWeightVarId = style.boundVariables && style.boundVariables.fontWeight && style.boundVariables.fontWeight.id;
if (fontWeightVarId && idToPathMap[fontWeightVarId]) {
compositeValue.fontWeight = `{${idToPathMap[fontWeightVarId].path}}`;
}
else if (style.fontName && style.fontName.style) {
const styleWeightString = style.fontName.style;
const numericWeight = fontWeightMap[styleWeightString];
compositeValue.fontWeight = numericWeight !== undefined ? numericWeight : styleWeightString;
}
// textCase
const textCaseVarId = style.boundVariables && style.boundVariables.textCase && style.boundVariables.textCase.id;
if (textCaseVarId && idToPathMap[textCaseVarId]) {
compositeValue.textCase = `{${idToPathMap[textCaseVarId].path}}`;
}
else if (style.textCase) {
const textCaseMap = {
'ORIGINAL': 'none',
'UPPER': 'uppercase',
'LOWER': 'lowercase',
'TITLE': 'capitalize',
};
if (textCaseMap[style.textCase]) {
compositeValue.textCase = textCaseMap[style.textCase];
}
else {
errorsList.push(`WARNING: Unknown textCase value '${style.textCase}' in style '${style.name}'.`);
}
}
// textDecoration
const textDecorationVarId = style.boundVariables && style.boundVariables.textDecoration && style.boundVariables.textDecoration.id;
if (textDecorationVarId && idToPathMap[textDecorationVarId]) {
compositeValue.textDecoration = `{${idToPathMap[textDecorationVarId].path}}`;
}
else if (style.textDecoration) {
const textDecorationMap = {
'NONE': 'none',
'UNDERLINE': 'underline',
'STRIKETHROUGH': 'line-through',
};
if (textDecorationMap[style.textDecoration]) {
compositeValue.textDecoration = textDecorationMap[style.textDecoration];
}
else {
errorsList.push(`WARNING: Unknown textDecoration value '${style.textDecoration}' in style '${style.name}'.`);
}
}
// fontSize
const fontSizeVarId = style.boundVariables && style.boundVariables.fontSize && style.boundVariables.fontSize.id;
if (fontSizeVarId && idToPathMap[fontSizeVarId]) {
compositeValue.fontSize = `{${idToPathMap[fontSizeVarId].path}}`;
}
else if (style.fontSize !== undefined) {
if (fontSizeVarId) {
errorsList.push(`WARNING: Unresolved bound variable ID '${fontSizeVarId}' for fontSize in style '${style.name}'. Using raw value.`);
}
compositeValue.fontSize = { value: style.fontSize, unit: 'px' };
}
// lineHeight
const lineHeightVarId = style.boundVariables && style.boundVariables.lineHeight && style.boundVariables.lineHeight.id;
if (lineHeightVarId && idToPathMap[lineHeightVarId]) {
compositeValue.lineHeight = `{${idToPathMap[lineHeightVarId].path}}`;
}
else if (style.lineHeight && style.lineHeight.unit) {
if (lineHeightVarId) {
errorsList.push(`WARNING: Unresolved bound variable ID '${lineHeightVarId}' for lineHeight in style '${style.name}'. Falling back to manual matching.`);
}
if (style.lineHeight.unit === 'PERCENT') {
let aliasFound = false;
const targetPercent = roundNear(style.lineHeight.value);
for (const [, tokenInfo] of Object.entries(idToPathMap)) {
if (tokenInfo.type === 'number' && tokenInfo.path.indexOf('lineHeight.') === 0 && roundNear(tokenInfo.originalValue) === targetPercent) {
compositeValue.lineHeight = `{${tokenInfo.path}}`;
aliasFound = true;
break;
}
}
if (!aliasFound) {
errorsList.push(`WARNING: Could not find alias for lineHeight value '${targetPercent}%' in style '${style.name}'. Using raw calculated value.`);
compositeValue.lineHeight = targetPercent / 100;
}
}
else {
errorsList.push(`ERROR: Unexpected lineHeight unit '${style.lineHeight.unit}' for style '${style.name}'. Outputting raw value.`);
compositeValue.lineHeight = { value: style.lineHeight.value, unit: style.lineHeight.unit.toLowerCase() };
}
}
// letterSpacing
const letterSpacingVarId = style.boundVariables && style.boundVariables.letterSpacing && style.boundVariables.letterSpacing.id;
if (letterSpacingVarId && idToPathMap[letterSpacingVarId]) {
compositeValue.letterSpacing = `{${idToPathMap[letterSpacingVarId].path}}`;
}
else if (style.letterSpacing && style.letterSpacing.unit) {
if (letterSpacingVarId) {
errorsList.push(`WARNING: Unresolved bound variable ID '${letterSpacingVarId}' for letterSpacing in style '${style.name}'. Falling back to manual matching.`);
}
let aliasFound = false;
const tolerance = 0.01;
if (style.letterSpacing.unit === 'PERCENT') {
const targetPercent = style.letterSpacing.value;
for (const [, tokenInfo] of Object.entries(idToPathMap)) {
if (tokenInfo.type === 'dimension' && tokenInfo.path.indexOf('letterSpacing.') === 0 &&
tokenInfo.originalValue !== null && Math.abs(tokenInfo.originalValue - targetPercent) < tolerance) {
compositeValue.letterSpacing = `{${tokenInfo.path}}`;
aliasFound = true;
break;
}
}
if (!aliasFound) {
errorsList.push(`WARNING: Could not find alias for letterSpacing value '${targetPercent}%' in style '${style.name}'. Using raw value.`);
compositeValue.letterSpacing = { value: targetPercent, unit: '%' };
}
}
else if (style.letterSpacing.unit === 'PIXELS') {
const targetPixels = style.letterSpacing.value;
for (const [, tokenInfo] of Object.entries(idToPathMap)) {
if (tokenInfo.type === 'dimension' && tokenInfo.path.indexOf('letterSpacing.') === 0 && tokenInfo.originalValue === targetPixels) {
compositeValue.letterSpacing = `{${tokenInfo.path}}`;
aliasFound = true;
break;
}
}
if (!aliasFound) {
errorsList.push(`WARNING: letterSpacing for style '${style.name}' is in PIXELS, not PERCENT. Could not find alias. Outputting raw px value.`);
compositeValue.letterSpacing = { value: targetPixels, unit: 'px' };
}
}
else {
errorsList.push(`ERROR: Unexpected letterSpacing unit '${style.letterSpacing.unit}' for style '${style.name}'. Outputting raw value.`);
compositeValue.letterSpacing = { value: style.letterSpacing.value, unit: style.letterSpacing.unit.toLowerCase() };
}
}
if (Object.keys(compositeValue).length > 0) {
const tokenData = {
$type: 'typography',
$value: compositeValue,
$description: style.description || "",
$extensions: {
'figma.ID': style.id,
'figma.key': style.key,
},
};
setNestedValue(typographyTokens, ['typography', ...pathParts], tokenData);
}
else {
errorsList.push(`WARNING: Style '${style.name}' resulted in empty typography token.`);
}
}
console.log(' Text style processing complete.');
return typographyTokens;
}
/**
* Processes Figma Effect Styles into W3C Shadow Tokens.
* @param effectStyles Array of simplified Figma Effect Style objects.
* @param idToPathMap Map of Figma Variable IDs to TokenInfo.
* @param errorsList Array to push error/warning messages into.
* @returns Object containing the generated shadow tokens.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function processEffectStyles(effectStyles, idToPathMap, errorsList) {
const shadowTokens = {};
console.log(' Processing Effect Styles into Shadow Tokens...');
for (const style of effectStyles) {
if (!style || !style.name || !style.effects || style.effects.length === 0) {
continue;
}
const pathParts = style.name.split('/');
const w3cShadowValue = [];
for (const effect of style.effects) {
if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
if (!effect.color || !effect.offset || effect.radius === undefined) {
errorsList.push(`WARNING: Incomplete shadow data for effect in style '${style.name}'. Skipping this effect layer.`);
continue;
}
const shadowLayer = { inset: effect.type === 'INNER_SHADOW' };
// Color
const colorVarId = effect.boundVariables && effect.boundVariables.color && effect.boundVariables.color.id;
if (colorVarId && idToPathMap[colorVarId]) {
shadowLayer.color = `{${idToPathMap[colorVarId].path}}`;
}
else {
if (colorVarId) {
errorsList.push(`WARNING: Unresolved bound variable ID '${colorVarId}' for shadow color in style '${style.name}'. Using raw value.`);
}
shadowLayer.color = {
$type: 'color',
$value: {
colorSpace: 'srgb',
components: [effect.color.r, effect.color.g, effect.color.b],
alpha: effect.color.a,
hex: rgbaToHex(effect.color.r, effect.color.g, effect.color.b)
}
};
}
// Offset X/Y
shadowLayer.offsetX = { value: effect.offset.x, unit: 'px' };
shadowLayer.offsetY = { value: effect.offset.y, unit: 'px' };
// Blur
const blurVarId = effect.boundVariables && effect.boundVariables.radius && effect.boundVariables.radius.id;
if (blurVarId && idToPathMap[blurVarId]) {
shadowLayer.blur = `{${idToPathMap[blurVarId].path}}`;
}
else {
if (blurVarId) {
errorsList.push(`WARNING: Unresolved bound variable ID '${blurVarId}' for shadow blur (radius) in style '${style.name}'. Using raw value.`);
}
shadowLayer.blur = { value: effect.radius, unit: 'px' };
}
// Spread
const spreadVarId = effect.boundVariables && effect.boundVariables.spread && effect.boundVariables.spread.id;
if (spreadVarId && idToPathMap[spreadVarId]) {
shadowLayer.spread = `{${idToPathMap[spreadVarId].path}}`;
}
else {
if (spreadVarId) {
errorsList.push(`WARNING: Unresolved bound variable ID '${spreadVarId}' for shadow spread in style '${style.name}'. Using raw value.`);
}
shadowLayer.spread = { value: (effect.spread || 0), unit: 'px' };
}
w3cShadowValue.push(shadowLayer);
}
else {
errorsList.push(`WARNING: Skipping non-shadow effect type '${effect.type}' in style '${style.name}'.`);
}
}
if (w3cShadowValue.length > 0) {
const tokenData = {
$type: 'shadow',
$value: w3cShadowValue,
$description: style.description || "",
$extensions: {
'figma.ID': style.id,
'figma.key': style.key,
},
};
setNestedValue(shadowTokens, ['shadow', ...pathParts], tokenData);
}
else {
let hasProcessableEffect = false;
for (let i = 0; i < style.effects.length; i++) {
const eff = style.effects[i];
if (eff.type === 'DROP_SHADOW' || eff.type === 'INNER_SHADOW') {
hasProcessableEffect = true;
break;
}
}
if (!hasProcessableEffect) {
errorsList.push(`WARNING: Style '${style.name}' did not contain any processable shadow effects.`);
}
}
}
console.log(' Effect style processing complete.');
return shadowTokens;
}
/**
* Collects raw data for all local variable collections, variables, text styles, and effect styles.
* @returns A Promise resolving to an object containing the structured raw data.
*/
async function collectRawFigmaData() {
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const textStyles = await figma.getLocalTextStylesAsync();
const effectStyles = await figma.getLocalEffectStylesAsync();
const rawData = {
variables: {
collections: collections.map(collection => ({
id: collection.id,
name: collection.name,
key: collection.key,
remote: collection.remote,
modes: collection.modes.map(mode => ({
modeId: mode.modeId,
name: mode.name,
})),
defaultModeId: collection.defaultModeId,
variableIds: collection.variableIds,
})),
},
variableDetails: {},
textStyles: textStyles.map(style => simplifyObject({
id: style.id,
key: style.key,
name: style.name,
description: style.description,
remote: style.remote,
type: style.type,
fontSize: style.fontSize,
fontName: style.fontName,
fontFamily: style.fontName && style.fontName.family,
letterSpacing: style.letterSpacing,
lineHeight: style.lineHeight,
listSpacing: style.listSpacing,
hangingList: style.hangingList,
hangingPunctuation: style.hangingPunctuation,
paragraphIndent: style.paragraphIndent,
paragraphSpacing: style.paragraphSpacing,
textCase: style.textCase,
textDecoration: style.textDecoration,
boundVariables: style.boundVariables ? simplifyObject(style.boundVariables) : undefined,
})),
effectStyles: effectStyles.map(style => simplifyObject({
id: style.id,
key: style.key,
name: style.name,
description: style.description,
remote: style.remote,
type: style.type,
effects: style.effects ? simplifyObject(style.effects) : undefined,
boundVariables: style.boundVariables ? simplifyObject(style.boundVariables) : undefined,
})),
};
// Expand variable details
const variableDetails = {};
for (const collection of collections) {
for (const varId of collection.variableIds) {
try {
const variable = await figma.variables.getVariableByIdAsync(varId);
if (variable) {
variableDetails[varId] = simplifyObject({
id: variable.id,
key: variable.key,
name: variable.name,
description: variable.description,
remote: variable.remote,
variableCollectionId: variable.variableCollectionId,
resolvedType: variable.resolvedType,
scopes: variable.scopes,
codeSyntax: variable.codeSyntax,
valuesByMode: simplifyObject(variable.valuesByMode)
});
}
}
catch (e) {
console.error(`Error fetching variable details for ID ${varId}:`, e);
variableDetails[varId] = { error: `Failed to fetch details for ${varId}` };
}
}
}
rawData.variableDetails = variableDetails;
return rawData;
}
/**
* Transforms raw Figma data into W3C Design Token format.
* @param rawData The raw data collected from the Figma API.
* @returns An object containing the transformed token files and any processing errors.
*/
function transformTokens(rawData) {
const processingErrors = [];
const idToPathMap = {};
const outputs = {};
const collections = rawData && rawData.variables && rawData.variables.collections;
const variableDetails = rawData && rawData.variableDetails;
if (!collections || !variableDetails) {
processingErrors.push('Invalid raw data structure: Missing collections or variableDetails.');
return { outputs, errors: processingErrors };
}
console.log('Starting Pass 1: Building token structure and ID map...');
for (const collection of collections) {
const collectionName = collection.name.replace(/^\./, '').replace(/ /g, '-');
const outputFilename = `${collectionName}.json`;
if (!outputs[outputFilename]) {
outputs[outputFilename] = {};
}
// Standard handling for all collections
for (const mode of collection.modes) {
const modeName = mode.name;
const outputTokens = {};
outputs[outputFilename][modeName] = outputTokens;
console.log(` Processing collection '${collectionName}', mode '${modeName}'...`);
for (const variableId of collection.variableIds) {
const detail = variableDetails[variableId];
if (!detail) {
processingErrors.push(`WARNING: Variable details not found for ID: ${variableId} in collection ${collectionName}`);
continue;
}
const pathParts = detail.name.split('/');
const tokenNamePath = pathParts.join('.');
const { type, value, needsResolution, originalValue } = getTokenTypeAndValue(detail, mode.modeId);
if (type === 'unknown') {
processingErrors.push(`WARNING: Unknown resolvedType encountered for variable ${detail.name} (${variableId})`);
continue;
}
idToPathMap[variableId] = {
path: `${modeName}.${tokenNamePath}`,
type: type,
originalValue: originalValue,
aliasTargetId: needsResolution ? value : undefined
};
const tokenData = {
$type: needsResolution ? 'alias' : type,
$value: needsResolution ? `ALIAS:${value}` : value,
$description: detail.description || "",
$extensions: {
'figma.ID': detail.id,
'figma.key': detail.key,
'figma.collectionID': detail.variableCollectionId,
'figma.scopes': detail.scopes,
'figma.codeSyntax': detail.codeSyntax,
},
};
setNestedValue(outputTokens, pathParts, tokenData);
}
}
}
console.log('Pass 1 complete.');
// Process Text Styles
const typographyOutput = processTextStyles(rawData.textStyles || [], idToPathMap, processingErrors);
// Process Effect Styles
const shadowOutput = processEffectStyles(rawData.effectStyles || [], idToPathMap, processingErrors);
// Merge Styles into Outputs
console.log('Merging style tokens into outputs...');
for (const filename in outputs) {
if (Object.prototype.hasOwnProperty.call(outputs, filename)) {
// Merge into each mode for all files
const fileOutput = outputs[filename];
for (const modeName in fileOutput) {
if (Object.prototype.hasOwnProperty.call(fileOutput, modeName)) {
const modeObj = fileOutput[modeName];
Object.assign(modeObj, JSON.parse(JSON.stringify(typographyOutput)), JSON.parse(JSON.stringify(shadowOutput)));
}
}
}
}
// Pass 2: Resolve Aliases
console.log('Starting Pass 2: Resolving aliases...');
for (const filename in outputs) {
if (Object.prototype.hasOwnProperty.call(outputs, filename)) {
console.log(` Resolving aliases in ${filename}...`);
resolveAliases(outputs[filename], idToPathMap, processingErrors);
}
}
console.log('Pass 2 complete.');
return { outputs, errors: processingErrors };
}
/**
* Main plugin execution function.
* Collects data, transforms it to W3C Design Token format,
* and sends each file to the UI for download.
*/
async function main() {
// Show the UI with download buttons
figma.showUI(__html__, { width: 320, height: 400 });
try {
// Collect the raw data
console.log('Collecting raw data from Figma...');
const rawData = await collectRawFigmaData();
console.log('Raw data collected successfully.');
// Transform the data
console.log('Transforming tokens to W3C format...');
const { outputs, errors } = transformTokens(rawData);
// Log errors if any
if (errors.length > 0) {
console.log('\n--- Processing Errors/Warnings ---');
errors.forEach(err => console.error(`- ${err}`));
console.log(`\n(${errors.length} errors/warnings found)`);
}
// Send each transformed file to the UI
const files = Object.entries(outputs).map(([filename, data]) => ({
filename,
content: JSON.stringify(data, null, 2)
}));
figma.ui.postMessage({
type: 'download-tokens',
files: files
});
}
catch (error) {
console.error('Error during token export:', error);
const message = error instanceof Error ? error.message : String(error);
figma.closePlugin('Error: ' + message);
}
}
// Run the main function
main();