-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.ts
More file actions
535 lines (441 loc) · 17.4 KB
/
code.ts
File metadata and controls
535 lines (441 loc) · 17.4 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
/* eslint-disable @typescript-eslint/no-explicit-any */
async function exportVariablesToCss() {
const kebab = (str: string) =>
str.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase();
const pxToRem = (value: number, base = 16): string => {
const rem = value / base;
return rem === Math.floor(rem)
? `${rem}rem`
: `${rem.toFixed(4).replace(/\.?0+$/, '')}rem`;
};
const includesAny = (source: string, arr: string[]) =>
arr.some(k => source.includes(k));
const NAME_NUMBER_KEYWORDS = ['weight','opacity','z-index','flex','ratio','scale'];
const COLL_TYPO_KEYWORDS = ['font','typography','text'];
const NAME_TYPO_KEYWORDS = ['font-size','line-height','letter-spacing'];
const COLL_DIM_KEYWORDS = ['dimension','container','layout','grid','spacing'];
const NAME_DIM_KEYWORDS = ['space','padding','margin','gap','radius','border','size','height','width','offset','inset'];
type ModeBucket = 'desktop' | 'tablet' | 'mobile';
const MEDIA_QUERIES: Record<ModeBucket, string | null> = {
desktop: null,
tablet: '(width < 62rem)',
mobile: '(width < 48rem)',
};
const modeToBucket = (modeName: string): ModeBucket | null => {
const n = modeName.toLowerCase();
if (n.includes('mobile')) return 'mobile';
if (n.includes('tablet')) return 'tablet';
if (n.includes('desktop')) return 'desktop';
return null;
};
type ColorScheme = 'light' | 'dark';
const modeToScheme = (modeName: string): ColorScheme | null => {
const n = modeName.toLowerCase();
if (n.includes('dark')) return 'dark';
if (n.includes('light')) return 'light';
return null;
};
const isBaseMode = (modeName: string) => {
const n = modeName.toLowerCase();
if (n.includes('mode 1') || n.includes('default')) return true;
return modeToScheme(modeName) === null && modeToBucket(modeName) === null;
};
function isVariableAlias(value: VariableValue): value is VariableAlias {
return typeof value === 'object' && value !== null && 'type' in value;
}
async function resolveValue(
raw: VariableValue | null,
modeId: string,
preserveAlias = false,
collectionName = '',
varName = '',
depth = 0
): Promise<string | null> {
if (!raw || depth > 10) return null;
if (isVariableAlias(raw)) {
const target = await figma.variables.getVariableByIdAsync(raw.id);
if (!target) return null;
if (preserveAlias) return `var(--${kebab(target.name)})`;
return resolveValue(
target.valuesByMode[modeId] ?? null,
modeId,
preserveAlias,
collectionName,
target.name,
depth + 1
);
}
if (typeof raw === 'object' && 'r' in raw) {
const { r, g, b, a = 1 } = raw as RGBA;
const [rr, gg, bb] = [r, g, b].map(c => Math.round(c * 255));
return a === 1
? `#${[rr, gg, bb].map(x => x.toString(16).padStart(2, '0')).join('')}`
: `rgba(${rr},${gg},${bb},${a})`;
}
if (typeof raw === 'number') {
const lowerName = varName.toLowerCase();
const lowerColl = collectionName.toLowerCase();
if (includesAny(lowerName, NAME_NUMBER_KEYWORDS)) return raw.toString();
if (
includesAny(lowerColl, COLL_TYPO_KEYWORDS) ||
includesAny(lowerName, NAME_TYPO_KEYWORDS)
) return pxToRem(raw);
if (
includesAny(lowerColl, COLL_DIM_KEYWORDS) ||
includesAny(lowerName, NAME_DIM_KEYWORDS)
) return `${Math.round(raw * 100) / 100}px`;
return pxToRem(raw);
}
if (typeof raw === 'boolean') return raw ? 'true' : 'false';
if (typeof raw === 'string') return raw;
return null;
}
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const TEDI_SOURCE_NAMES = [
'TEDI colors base',
'TEDI colors semantic',
'TEDI dimensions base',
'TEDI dimensions semantic',
'TEDI fonts base',
'TEDI fonts semantic',
];
const normCollName = (s: string) =>
s.trim().toLowerCase().replace(/[\s\-_/]+/g, ' ').replace(/\s+/g, ' ');
const TEDI_SOURCE_NAMES_NORM = TEDI_SOURCE_NAMES.map(normCollName);
const isTediSource = (name: string) =>
TEDI_SOURCE_NAMES_NORM.includes(normCollName(name));
const isTediBaseLayer = (name: string) =>
/\bbase$/.test(normCollName(name));
const isTediSemanticLayer = (name: string) =>
/\bsemantic$/.test(normCollName(name));
const isTediDimensionsSource = (name: string) =>
normCollName(name).includes('dimensions');
const libraryVarSources = new Map<string, string>();
try {
const libCollections =
(await (figma as any).teamLibrary?.getAvailableLibraryVariableCollectionsAsync?.()) ?? [];
for (const lib of libCollections) {
if (!isTediSource(lib.name)) continue;
const libVars =
(await (figma as any).teamLibrary?.getVariablesInLibraryCollectionAsync?.(lib.key)) ?? [];
for (const lv of libVars) {
libraryVarSources.set(lv.name.toLowerCase(), lib.name.trim());
}
}
} catch (_e) {
// teamLibrary unavailable (e.g., permission missing) — fall through to alias-voting.
}
async function getSourceCollectionName(coll: VariableCollection): Promise<string | null> {
if (!('variableOverrides' in coll)) return null;
const localNorm = normCollName(coll.name);
const directMatch = TEDI_SOURCE_NAMES.find(s => normCollName(s) === localNorm);
if (directMatch) return directMatch;
const containsMatch = TEDI_SOURCE_NAMES.find(s => localNorm.includes(normCollName(s)));
if (containsMatch) return containsMatch;
if (libraryVarSources.size) {
const counts = new Map<string, number>();
for (const varId of coll.variableIds) {
const v = await figma.variables.getVariableByIdAsync(varId);
if (!v) continue;
const src = libraryVarSources.get(v.name.toLowerCase());
if (!src) continue;
counts.set(src, (counts.get(src) ?? 0) + 1);
}
if (counts.size) {
return Array.from(counts.entries()).sort((a, b) => b[1] - a[1])[0][0];
}
}
const overrides = (coll as any).variableOverrides ?? {};
const sameNameCounts = new Map<string, number>();
const anyCounts = new Map<string, number>();
for (const varId of coll.variableIds) {
const v = await figma.variables.getVariableByIdAsync(varId);
if (!v) continue;
for (const modeId of Object.keys(v.valuesByMode)) {
if (overrides[varId]?.[modeId] !== undefined) continue;
const raw = v.valuesByMode[modeId];
if (!isVariableAlias(raw)) continue;
const target = await figma.variables.getVariableByIdAsync(raw.id);
if (!target) continue;
const targetColl = await figma.variables.getVariableCollectionByIdAsync(
target.variableCollectionId
);
if (!targetColl || !targetColl.remote) continue;
const name = targetColl.name.trim();
anyCounts.set(name, (anyCounts.get(name) ?? 0) + 1);
if (target.name === v.name) {
sameNameCounts.set(name, (sameNameCounts.get(name) ?? 0) + 1);
}
}
}
const pickFromCounts = (m: Map<string, number>): string | null => {
if (!m.size) return null;
const entries = Array.from(m.entries());
const semantic = entries.find(([n]) => isTediSemanticLayer(n));
if (semantic) return semantic[0];
return entries.sort((a, b) => b[1] - a[1])[0][0];
};
return pickFromCounts(sameNameCounts) ?? pickFromCounts(anyCounts);
}
const sourceNameByCollName: Record<string, string | null> = {};
for (const coll of collections) {
sourceNameByCollName[coll.name.trim()] = await getSourceCollectionName(coll);
}
async function getFreshSourceValue(
variable: Variable,
localMode: { modeId: string; name: string }
): Promise<VariableValue | null> {
const localRaw = variable.valuesByMode[localMode.modeId] ?? null;
if (!localRaw || !isVariableAlias(localRaw)) return null;
const sourceVar = await figma.variables.getVariableByIdAsync(localRaw.id);
if (!sourceVar) return null;
const sourceColl = await figma.variables.getVariableCollectionByIdAsync(
sourceVar.variableCollectionId
);
if (!sourceColl) return null;
const localModeKey = localMode.name.trim().toLowerCase();
const matchedMode =
sourceColl.modes.find(m => m.name.trim().toLowerCase() === localModeKey) ??
sourceColl.modes.find(m => isBaseMode(m.name)) ??
sourceColl.modes[0];
if (!matchedMode) return null;
return sourceVar.valuesByMode[matchedMode.modeId] ?? null;
}
const dataByMode: Record<
string,
Record<string, { primitives: Record<string,string>; overrides: Record<string,string> }>
> = {};
for (const coll of collections) {
const collName = coll.name.trim();
const isExtended = 'variableOverrides' in coll;
const sourceName = sourceNameByCollName[collName];
if (!isExtended || !sourceName || !isTediSource(sourceName)) continue;
for (const mode of coll.modes) {
const modeName = mode.name.trim();
dataByMode[modeName] ??= {};
dataByMode[modeName][collName] ??= { primitives: {}, overrides: {} };
for (const varId of coll.variableIds) {
const variable = await figma.variables.getVariableByIdAsync(varId);
if (!variable) continue;
const isOverride =
(coll as any).variableOverrides?.[varId]?.[mode.modeId] !== undefined;
let rawValue: VariableValue | null = null;
if (!isOverride) {
rawValue = await getFreshSourceValue(variable, mode);
}
if (!rawValue) {
const valuesByMode = await variable.valuesByModeForCollectionAsync(coll);
rawValue = valuesByMode[mode.modeId] ?? null;
}
if (!rawValue) continue;
const resolved = await resolveValue(
rawValue,
mode.modeId,
true,
collName,
variable.name
);
if (!resolved) continue;
const target = isOverride
? dataByMode[modeName][collName].overrides
: dataByMode[modeName][collName].primitives;
target[variable.name] = resolved;
}
}
}
const isDimensionCollection = (collName: string) => {
const src = sourceNameByCollName[collName];
return src ? isTediDimensionsSource(src) : false;
};
const isSemanticCollection = (collName: string) => {
const src = sourceNameByCollName[collName];
return src ? isTediSemanticLayer(src) : false;
};
const buildSchemeLines = (scheme: ColorScheme) => {
const vars = new Map<string,string>();
for (const [modeName, collections] of Object.entries(dataByMode)) {
if (!isBaseMode(modeName)) continue;
for (const [collName, group] of Object.entries(collections)) {
if (!isSemanticCollection(collName)) continue;
if (isDimensionCollection(collName)) continue;
Object.entries(group.primitives).forEach(([k,v]) => vars.set(k,v));
Object.entries(group.overrides).forEach(([k,v]) => vars.set(k,v));
}
}
for (const [modeName, collections] of Object.entries(dataByMode)) {
if (modeToScheme(modeName) !== scheme) continue;
for (const [collName, group] of Object.entries(collections)) {
if (!isSemanticCollection(collName)) continue;
if (isDimensionCollection(collName)) continue;
Object.entries(group.primitives).forEach(([k,v]) => vars.set(k,v));
Object.entries(group.overrides).forEach(([k,v]) => vars.set(k,v));
}
}
return Array.from(vars.entries()).map(
([name,val]) => ` --${kebab(name)}: ${val};`
);
};
const buildColorSchemeFile = (theme: string, scheme: ColorScheme, lines: string[]) => ({
name: `_color-variables__${kebab(theme)}-${scheme}.css`,
content:
`.tedi-theme--${kebab(theme)}${scheme === 'dark' ? '-dark' : ''} {
${lines.join('\n')}
}
`
});
const buildBaseOverridesFile = (theme: string) => {
const colorLight = new Map<string,string>();
const colorDark = new Map<string,string>();
const dimDesktop = new Map<string,string>();
const dimTablet = new Map<string,string>();
const dimMobile = new Map<string,string>();
const mergeInto = (target: Map<string,string>, group: { primitives: Record<string,string>; overrides: Record<string,string> }) => {
Object.entries(group.primitives).forEach(([k,v]) => target.set(k,v));
Object.entries(group.overrides).forEach(([k,v]) => target.set(k,v));
};
for (const [modeName, collections] of Object.entries(dataByMode)) {
if (!isBaseMode(modeName)) continue;
for (const [collName, group] of Object.entries(collections)) {
const src = sourceNameByCollName[collName];
if (!src || !isTediBaseLayer(src)) continue;
if (isTediDimensionsSource(src)) {
mergeInto(dimDesktop, group);
} else {
mergeInto(colorLight, group);
mergeInto(colorDark, group);
}
}
}
for (const [modeName, collections] of Object.entries(dataByMode)) {
const scheme = modeToScheme(modeName);
const bucket = modeToBucket(modeName);
for (const [collName, group] of Object.entries(collections)) {
const src = sourceNameByCollName[collName];
if (!src || !isTediBaseLayer(src)) continue;
if (isTediDimensionsSource(src)) {
if (bucket === 'desktop') mergeInto(dimDesktop, group);
else if (bucket === 'tablet') mergeInto(dimTablet, group);
else if (bucket === 'mobile') mergeInto(dimMobile, group);
} else {
if (scheme === 'light') mergeInto(colorLight, group);
else if (scheme === 'dark') mergeInto(colorDark, group);
}
}
}
const toLines = (m: Map<string,string>) =>
Array.from(m.entries()).map(([k,v]) => ` --${kebab(k)}: ${v};`);
const colorLightLines = toLines(colorLight);
const colorDarkLines = toLines(colorDark);
const dimDesktopLines = toLines(dimDesktop);
const dimTabletLines = toLines(dimTablet);
const dimMobileLines = toLines(dimMobile);
const total =
colorLightLines.length + colorDarkLines.length +
dimDesktopLines.length + dimTabletLines.length + dimMobileLines.length;
if (!total) return null;
const themeKebab = kebab(theme);
let css = '';
if (colorLightLines.length || dimDesktopLines.length) {
css += `.tedi-theme--${themeKebab} {
${[...colorLightLines, ...dimDesktopLines].join('\n')}
}
`;
}
if (colorDarkLines.length) {
css += `.tedi-theme--${themeKebab}-dark {
${colorDarkLines.join('\n')}
}
`;
}
(['tablet','mobile'] as ModeBucket[]).forEach(b => {
const media = MEDIA_QUERIES[b];
const lines = b === 'tablet' ? dimTabletLines : dimMobileLines;
if (!media || !lines.length) return;
css += `
@media ${media} {
.tedi-theme--${themeKebab} {
${lines.join('\n')}
}
}
`;
});
return {
name: `_base-variables__${themeKebab}.css`,
content: css,
};
};
const buildResponsiveDimensionsFile = (theme: string) => {
const buckets: Record<ModeBucket, string[]> = {
desktop: [],
tablet: [],
mobile: [],
};
for (const [modeName, collections] of Object.entries(dataByMode)) {
const bucket = modeToBucket(modeName);
if (!bucket) continue;
for (const [collName, group] of Object.entries(collections)) {
if (!isSemanticCollection(collName)) continue;
if (!isDimensionCollection(collName)) continue;
Object.entries(group.primitives).forEach(([k,v]) => {
buckets[bucket].push(` --${kebab(k)}: ${v};`);
});
}
for (const [collName, group] of Object.entries(collections)) {
if (!isSemanticCollection(collName)) continue;
if (!isDimensionCollection(collName)) continue;
Object.entries(group.overrides).forEach(([k,v]) => {
buckets[bucket].push(` --${kebab(k)}: ${v};`);
});
}
}
if (!buckets.desktop.length) return null;
let css =
`.tedi-theme--${kebab(theme)} {
${buckets.desktop.map(l => l.replace(' ', ' ')).join('\n')}
}
`;
(['tablet','mobile'] as ModeBucket[]).forEach(bucket => {
const media = MEDIA_QUERIES[bucket];
if (!media || !buckets[bucket].length) return;
css += `
@media ${media} {
.tedi-theme--${kebab(theme)} {
${buckets[bucket].join('\n')}
}
}`;
});
return {
name: `_dimensional-variables__${kebab(theme)}.css`,
content: css,
};
};
figma.showUI(__html__, { width: 480, height: 720 });
figma.ui.onmessage = async msg => {
const themeName = msg.themeName?.trim();
if (!themeName) return figma.notify('Please enter a theme name', { error: true });
if (msg.type === 'export-all') {
const files: { name:string; content:string }[] = [];
const baseFile = buildBaseOverridesFile(themeName);
if (baseFile) files.push(baseFile);
(['light','dark'] as ColorScheme[]).forEach(scheme => {
const lines = buildSchemeLines(scheme);
if (lines.length) files.push(buildColorSchemeFile(themeName, scheme, lines));
});
const dimFile = buildResponsiveDimensionsFile(themeName);
if (dimFile) files.push(dimFile);
files.push({
name: 'index.css',
content: Array.from(
new Set(files.map(f => `@import "${f.name}";`))
).join('\n'),
});
figma.ui.postMessage({
type: 'zip-download',
files,
themeName,
});
}
if (msg.type === 'cancel') figma.closePlugin();
};
}
exportVariablesToCss();