-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.ts
401 lines (344 loc) · 10.6 KB
/
code.ts
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
// API reference: https://www.figma.com/plugin-docs/api/api-reference/
type Token = {
$type: string
$value: VariableValue
}
const TEXT_CASES = {
ORIGINAL: '{font.case.original}',
UPPER: '{font.case.uppercase}',
LOWER: '{font.case.lowercase}',
TITLE: '{font.case.capitalize}',
SMALL_CAPS: '{font.case.none}',
SMALL_CAPS_FORCED: '{font.case.none}',
}
figma.showUI(__uiFiles__['export'], {
width: 500,
height: 500,
themeColors: true,
})
const COLLECTION_MAPPING = {
Sizes: 'size',
'Color Tokens': 'color',
Typography: 'font',
Border: 'border',
Opacity: 'opacity',
'Base Colors': 'base-color',
} as {
[key: string]: string
}
const MODE_MAPPING = {
Default: 'default',
Dark: 'dark',
'Light – High Contrast': 'light-high-contrast',
'Dark – High Contrast': 'dark-high-contrast',
desktop: 'default',
'Mode 1': 'default', // Typography
} as {
[key: string]: string
}
type TokenData = {
[key: string]: {
[key: string]: Token
}
} | {
[key: string]: {
[key: string]: {
[key: string]: Token
}
}
}
const variablesDb = {} as {
[key in keyof typeof COLLECTION_MAPPING]: TokenData
}
const textStylesJSON = {} as {
[key: string]: TokenData
}
const effectStylesJSON = {} as {
[key: string]: TokenData
}
function set(obj: unknown, path: string[], value: unknown): unknown {
path.reduce((acc, key, index) => {
if (index === path.length - 1) {
acc[key] = value
} else {
if (!acc[key]) {
acc[key] = {}
}
}
return acc[key]
}, obj)
return obj
}
const rgbToHex = (data: VariableValue) => {
const { r, g, b, a } = data as RGBA
if (a !== 1) {
return `rgba(${[r, g, b]
.map((n) => Math.round(n * 255))
.join(', ')}, ${a.toFixed(4)})`;
}
const toHex = (value: number) => {
const hex = Math.round(value * 255).toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
const hex = [toHex(r), toHex(g), toHex(b)].join('');
return `#${hex}`;
}
const sanitizeCollectionName = (name: string) => name.split('.')[1].trim()
const getCollectionName = (collection: VariableCollection | null) => {
if (!collection) {
return ''
}
return COLLECTION_MAPPING[sanitizeCollectionName(collection.name)]
}
const isVariableAlias = (value: VariableValue) => {
return typeof value === 'object' && 'type' in value && 'id' in value
}
const getTokenType = (resolvedType: VariableResolvedDataType) => {
if (resolvedType === 'COLOR') return 'color'
// assuming that the only string data in tokens are font family values
if (resolvedType === 'STRING') return 'fontFamily'
return 'number'
}
const getVariableValue = (variable: Variable, modeId: string) => {
const value = variable.valuesByMode[modeId]
if (variable.name.includes('line_height/') && variable.resolvedType === 'FLOAT' && typeof value === 'number') {
return Number(value.toFixed(2))
}
const valuesToPx = ['unit/', 'view_port/', 'width/']
if (valuesToPx.some(value => variable.name.includes(value)) && variable.resolvedType === 'FLOAT' && typeof value === 'number') {
return `${value}px`
}
const valuesToRem = ['size/']
if (valuesToRem.some(value => variable.name.includes(value)) && variable.resolvedType === 'FLOAT' && typeof value === 'number') {
return `${value / 10}rem`
}
if (variable.name.includes('level/') && variable.resolvedType === 'FLOAT' && typeof value === 'number') {
return `${value}%`
}
if (variable.name.includes('radius/') && variable.resolvedType === 'FLOAT' && typeof value === 'number') {
return variable.name.includes('radius/full') ? '100%' : `${value}px`
}
return value
}
const getTokenValue = async (variable: Variable, modeId: string): Promise<Token> => {
const { resolvedType } = variable
const value = getVariableValue(variable, modeId)
const token = {
$type: getTokenType(resolvedType),
$value: value,
}
if (isVariableAlias(value) && value.type === 'VARIABLE_ALIAS') {
const currentVar = await figma.variables.getVariableByIdAsync(
value.id
);
const aliasCollection = await figma.variables.getVariableCollectionByIdAsync(currentVar?.variableCollectionId || '')
const aliasCollectionName = getCollectionName(aliasCollection)
token.$value = `{${aliasCollectionName}.${currentVar?.name.replace(/\//g, '.')}}`;
} else {
// token.id = variable.id;
token.$value = resolvedType === 'COLOR' ? rgbToHex(value) : value;
}
return token
}
const getVariableAlias = async (variableAlias: VariableAlias | undefined) => {
if (!variableAlias) return undefined
const currentVar = await figma.variables.getVariableByIdAsync(
variableAlias.id
)
const aliasCollection = await figma.variables.getVariableCollectionByIdAsync(currentVar?.variableCollectionId || '')
const aliasCollectionName = getCollectionName(aliasCollection)
return `{${aliasCollectionName}.${currentVar?.name.replace(/\//g, '.')}}`
}
const getLineHeightVariable = (value: number) => {
const variables = variablesDb.font.line_height
const valueToCheck = Number((value / 100).toFixed(2))
const keyFound = Object.keys(variables).reduce((acc: string, key: string) => {
if (acc) return acc
if (variables[key].$value === valueToCheck) return key
return ''
}, '')
return `{font.line_height.${keyFound}}`
}
const buildTokenData = async (modeId: string, variable: Variable, variables: TokenData = {}) => {
set(variables, variable.name.split('/'), await getTokenValue(variable, modeId))
return variables
}
const getVariablesFromCollection = async (modeId: string, variableIds: string[]) => {
const variables = {} as TokenData
for (const variableId of variableIds) {
const variable = await figma.variables.getVariableByIdAsync(variableId)
if (!variable) {
continue;
}
const { resolvedType } = variable
const value = variable.valuesByMode[modeId]
if (value !== undefined && ['COLOR', 'FLOAT', 'STRING'].includes(resolvedType)) {
await buildTokenData(modeId, variable, variables)
}
}
return variables
}
async function processCollection(variableColection: VariableCollection) {
const { variableIds } = variableColection
const collectionName = getCollectionName(variableColection)
if (variablesDb[collectionName] === undefined) {
variablesDb[collectionName] = variablesDb[collectionName] || {}
}
for (const mode of variableColection.modes) {
const modeName = MODE_MAPPING[mode.name]
const result = await getVariablesFromCollection(mode.modeId, variableIds)
if (!['base-color', 'size', 'font', 'border', 'opacity'].includes(collectionName)) {
variablesDb[collectionName][modeName] = variablesDb[collectionName][modeName] || {}
variablesDb[collectionName][modeName] = result
continue
}
variablesDb[collectionName] = result
}
}
const createJsonFiles = () => {
console.log('variablesDb', variablesDb)
const finalJSON = {} as {
[key: string]: {
file: string
content: TokenData
}
}
const sizeJson = variablesDb['size']
finalJSON['sizes.json'] = {
file: 'sizes.json',
content: {
size: sizeJson
}
}
const fontJson = variablesDb['font']
finalJSON['font.json'] = {
file: 'font.json',
content: {
font: fontJson
}
}
finalJSON['typography.json'] = {
file: 'typography.json',
content: {
typography: textStylesJSON
}
}
const borderJson = variablesDb['border']
finalJSON['borders.json'] = {
file: 'borders.json',
content: {
border: borderJson
}
}
const opacityJson = variablesDb['opacity']
finalJSON['opacity.json'] = {
file: 'base.json',
content: {
opacity: {
level: opacityJson.level
}
}
}
const baseColor = variablesDb['base-color']
finalJSON['colors/primitives.json'] = {
file: 'primitives.json',
content: {
'base-color': baseColor
}
}
const colorJson = variablesDb['color']
finalJSON['colors/default.json'] = {
file: 'default.json',
content: {
color: {
default: colorJson.default
}
}
}
finalJSON['colors/dark.json'] = {
file: 'dark.json',
content: {
color: {
dark: colorJson.dark
}
}
}
finalJSON['colors/dark-high-contrast.json'] = {
file: 'dark-high-contrast.json',
content: {
color: {
'dark-high-contrast': colorJson['dark-high-contrast']
}
}
}
finalJSON['colors/light-high-contrast.json'] = {
file: 'light-high-contrast.json',
content: {
color: {
'light-high-contrast': colorJson['light-high-contrast']
}
}
}
finalJSON['shadow.json'] = {
file: 'shadow.json',
content: effectStylesJSON
}
return JSON.parse(JSON.stringify(finalJSON).replaceAll('base-color', 'color'))
}
const processTextStyle = async (style: TextStyle) => {
const boundVariables = style.boundVariables
const tokenData = {
$type: 'typography',
$value: {
fontFamily: await getVariableAlias(boundVariables?.fontFamily),
fontSize: await getVariableAlias(boundVariables?.fontSize),
fontWeight: await getVariableAlias(boundVariables?.fontWeight),
letterSpacing: await getVariableAlias(boundVariables?.letterSpacing),
lineHeight: getLineHeightVariable(style?.lineHeight.value),
textCase: TEXT_CASES[style.textCase],
}
}
set(textStylesJSON, style.name.split('/'), tokenData)
}
const processEffectStyle = async (style: EffectStyle) => {
const effects = style.effects[0]
const token = {
$type: 'shadow',
$value: {
color: rgbToHex(effects.color),
offsetX: `${effects.offset.x}px`,
offsetY: `${effects.offset.y}px`,
blur: `${effects.radius}px`,
spread: `${effects.spread}px`,
},
}
set(effectStylesJSON, style.name.split('/'), token)
}
async function exportToJSON() {
// VariableCollection
// https://www.figma.com/plugin-docs/api/VariableCollection/
const collections = await figma.variables.getLocalVariableCollectionsAsync()
for (const collection of collections) {
await processCollection(collection)
}
const textStyles = await figma.getLocalTextStylesAsync()
for (const style of textStyles) {
await processTextStyle(style)
}
const effectStyles = await figma.getLocalEffectStylesAsync()
for (const style of effectStyles) {
// this Effect Style does not have any bound variables
if (style.name === 'Shadow') {
continue
}
await processEffectStyle(style)
}
const result = createJsonFiles()
console.log('result', result)
figma.ui.postMessage({ type: 'EXPORT_RESULT', tokens: result })
}
figma.ui.onmessage = (message) => {
if (message.type === 'EXPORT') {
exportToJSON()
}
}