-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathbuildTokens.ts
More file actions
406 lines (379 loc) · 14.1 KB
/
buildTokens.ts
File metadata and controls
406 lines (379 loc) · 14.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
import type {Config} from 'style-dictionary/types'
import {PrimerStyleDictionary} from '../src/primerStyleDictionary.js'
import {copyFromDir} from '../src/utilities/index.js'
import {deprecatedJson, css, docJson, fallbacks, styleLint} from '../src/platforms/index.js'
import type {
ConfigGeneratorOptions,
StyleDictionaryConfigGenerator,
} from '../src/types/styleDictionaryConfigGenerator.js'
import type {TokenBuildInput} from '../src/types/tokenBuildInput.js'
import glob from 'fast-glob'
import {themes} from './themes.config.js'
import fs from 'fs'
import {getFallbackTheme} from './utilities/getFallbackTheme.js'
import {CSS_SPEC_HEADER} from './buildLlm.js'
import {isDimension, isSource} from '../src/filters/index.js'
/**
* getStyleDictionaryConfig
* @param filename output file name without extension
* @param source array of source token json files
* @param include array of included token json files (will not be present in output btu values are used when referenced)
* @param options options object
* @returns style dictionary config object
*/
const getStyleDictionaryConfig: StyleDictionaryConfigGenerator = (
filename,
source,
include,
options,
platforms = {},
): Config => ({
source, // build the special formats
include,
log: {
warnings: 'disabled', // 'warn' | 'error' | 'disabled'
verbosity: 'silent', // 'default' | 'silent' | 'verbose'
errors: {
brokenReferences: 'throw', // 'throw' | 'console'
},
},
platforms: Object.fromEntries(
Object.entries({
css: css(`css/${filename}.css`, options.prefix, options.buildPath, {
themed: options.themed,
theme: options.theme,
}),
docJson: docJson(`docs/${filename}.json`, options.prefix, options.buildPath, {
theme: options.theme,
}),
styleLint: styleLint(`styleLint/${filename}.json`, options.prefix, options.buildPath, {
theme: options.theme,
}),
fallbacks: fallbacks(`fallbacks/${filename}.json`, options.prefix, options.buildPath),
...platforms,
}).filter((entry: [string, unknown]) => entry[1] !== undefined),
),
})
export const buildDesignTokens = async (buildOptions: ConfigGeneratorOptions): Promise<void> => {
let debugCurrentFile: string | undefined = undefined
/** -----------------------------------
* Internal Colors
* ----------------------------------- */
try {
for (const {filename, source, include, theme} of themes) {
debugCurrentFile = `internalCss/${filename}.css`
// build functional scales
const extendedSD = await PrimerStyleDictionary.extend({
source: [...source, ...include], // build the special formats
include,
platforms: {
css: css(`internalCss/${filename}.css`, buildOptions.prefix, buildOptions.buildPath, {
themed: true,
theme: [theme, getFallbackTheme(theme)],
}),
},
})
await extendedSD.buildAllPlatforms()
}
} catch (e) {
console.error(
'🛑 Error trying to build internal css colors for code output:',
`${e} when building ${debugCurrentFile}`,
)
}
/** -----------------------------------
* Colors, shadows & borders
* ----------------------------------- */
try {
for (const {filename, source, include, theme} of themes) {
debugCurrentFile = `functional/themes/${filename}.css`
// Override docJson and styleLint filters to exclude dimension tokens from theme output
const themeDocJson = docJson(
`docs/functional/themes/${filename}.json`,
buildOptions.prefix,
buildOptions.buildPath,
{theme: [theme, getFallbackTheme(theme)]},
)
themeDocJson.files = themeDocJson.files.map(f => ({
...f,
filter: (token: {$type: string; isSource: boolean}) =>
isSource(token as Parameters<typeof isSource>[0]) && token.$type !== 'dimension',
}))
const themeStyleLint = styleLint(
`styleLint/functional/themes/${filename}.json`,
buildOptions.prefix,
buildOptions.buildPath,
{theme: [theme, getFallbackTheme(theme)]},
)
themeStyleLint.files = themeStyleLint.files.map(f => ({
...f,
filter: (token: {$type: string; isSource: boolean}) =>
isSource(token as Parameters<typeof isSource>[0]) && token.$type !== 'dimension',
}))
// build functional scales
const extendedSD = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(
`functional/themes/${filename}`,
source,
include,
{...buildOptions, themed: true, theme: [theme, getFallbackTheme(theme)]},
// disable fallbacks for themes, override docJson and styleLint with dimension filter
{fallbacks: undefined, docJson: themeDocJson, styleLint: themeStyleLint},
),
)
await extendedSD.buildAllPlatforms()
}
} catch (e) {
console.error(
'🛑 Error trying to build Colors, shadows & borders for code output:',
`${e} when building ${debugCurrentFile}`,
)
}
/** -----------------------------------
* Size tokens
* ----------------------------------- */
try {
const sizeFiles = glob.sync('src/tokens/functional/size/*')
//
for (const file of sizeFiles) {
const basename = file.replace('src/tokens/functional/size/', '').replace('.json5', '')
debugCurrentFile = `functional/size/${basename}`
// Border build: also include focus dimension tokens from component/focus.json5
if (basename === 'border') {
// Filter that only allows dimension + custom-string source tokens (excludes color/border from focus.json5)
const dimensionOnlyFilter = (token: {$type: string; isSource: boolean}) =>
isSource(token as Parameters<typeof isSource>[0]) &&
(isDimension(token as Parameters<typeof isDimension>[0]) || token.$type === 'custom-string')
// Override all platform filters to only emit dimension tokens
const borderCss = css(`css/functional/size/${basename}.css`, buildOptions.prefix, buildOptions.buildPath)
borderCss.files = [{...borderCss.files[1], filter: dimensionOnlyFilter}]
const borderDocJson = docJson(
`docs/functional/size/${basename}.json`,
buildOptions.prefix,
buildOptions.buildPath,
)
borderDocJson.files = borderDocJson.files.map(f => ({...f, filter: dimensionOnlyFilter}))
const borderStyleLint = styleLint(
`styleLint/functional/size/${basename}.json`,
buildOptions.prefix,
buildOptions.buildPath,
)
borderStyleLint.files = borderStyleLint.files.map(f => ({...f, filter: dimensionOnlyFilter}))
const borderFallbacks = fallbacks(
`fallbacks/functional/size/${basename}.json`,
buildOptions.prefix,
buildOptions.buildPath,
)
borderFallbacks.files = borderFallbacks.files.map(f => ({...f, filter: dimensionOnlyFilter}))
const borderSD = await PrimerStyleDictionary.extend({
source: [file, 'src/tokens/component/focus.json5'],
include: [
'src/tokens/base/size/*.json5',
...sizeFiles,
'src/tokens/functional/color/borderColor.json5',
'src/tokens/base/color/light/light.json5',
],
log: {
warnings: 'disabled',
verbosity: 'silent',
errors: {
brokenReferences: 'throw',
},
},
platforms: {
css: borderCss,
docJson: borderDocJson,
styleLint: borderStyleLint,
fallbacks: borderFallbacks,
},
})
await borderSD.buildAllPlatforms()
continue
}
const extendedSD = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(
`functional/size/${basename}`,
[file],
['src/tokens/base/size/*.json5', ...sizeFiles],
buildOptions,
),
)
await extendedSD.buildAllPlatforms()
}
// build base scales
debugCurrentFile = `base/size/size.css`
const SdBaseSize = await PrimerStyleDictionary.extend(
// using includes as source
getStyleDictionaryConfig(`base/size/size`, ['src/tokens/base/size/size.json5'], [], {
buildPath: buildOptions.buildPath,
prefix: undefined,
}),
)
await SdBaseSize.buildAllPlatforms()
debugCurrentFile = `base/size/z-index.css`
const SdBaseZIndex = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(`base/size/z-index`, ['src/tokens/base/size/z-index.json5'], [], {
buildPath: buildOptions.buildPath,
prefix: undefined,
}),
)
await SdBaseZIndex.buildAllPlatforms()
} catch (e) {
console.error('🛑 Error trying to build size tokens for code output:', `${e} when building ${debugCurrentFile}`)
}
/** -----------------------------------
* Typography tokens
* ----------------------------------- */
try {
debugCurrentFile = `functional/typography/typography.css`
const extendedSD = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(
`functional/typography/typography`,
[`src/tokens/functional/typography/*.json5`],
[`src/tokens/base/typography/*.json5`],
buildOptions,
{
css: css(`css/functional/typography/typography.css`, buildOptions.prefix, buildOptions.buildPath, {
options: {outputReferences: true},
}),
},
),
)
await extendedSD.buildAllPlatforms()
debugCurrentFile = `base/typography/typography.css`
const SdTypo = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(`base/typography/typography`, [`src/tokens/base/typography/*.json5`], [], buildOptions),
)
await SdTypo.buildAllPlatforms()
} catch (e) {
console.error(
'🛑 Error trying to build typography tokens for code output:',
`${e} when building ${debugCurrentFile}`,
)
}
/** -----------------------------------
* Motion tokens
* ----------------------------------- */
try {
debugCurrentFile = `functional/motion/motion.css`
const extendedSD = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(
`functional/motion/motion`,
[
`src/tokens/functional/motion/*.json5`,
// `src/tokens/base/motion/timing.json5`,
// `src/tokens/base/motion/easing.json5`,
],
[`src/tokens/base/motion/*.json5`],
buildOptions,
{
css: css(`css/functional/motion/motion.css`, buildOptions.prefix, buildOptions.buildPath, {
options: {outputReferences: true},
}),
},
),
)
await extendedSD.buildAllPlatforms()
debugCurrentFile = `base/motion/motion.css`
const SdMotion = await PrimerStyleDictionary.extend(
getStyleDictionaryConfig(`base/motion/motion`, [`src/tokens/base/motion/*.json5`], [], buildOptions),
)
await SdMotion.buildAllPlatforms()
} catch (e) {
console.error('🛑 Error trying to build motion tokens for code output:', `${e} when building ${debugCurrentFile}`)
}
/** -----------------------------------
* deprecated tokens
* ----------------------------------- */
const deprecatedBuilds: TokenBuildInput[] = [
// color, shadow & borders
{
filename: 'theme',
source: themes.find(theme => theme.filename === 'light')?.source || [],
include: themes.find(theme => theme.filename === 'light')?.include || [],
},
// typography
{
filename: 'typography',
source: [`src/tokens/base/typography/*.json5`, `src/tokens/functional/typography/*.json5`],
include: [`src/tokens/base/typography/*.json5`],
},
// size
{
filename: 'size',
source: [`src/tokens/base/size/*.json5`, `src/tokens/functional/size/*.json5`],
include: [`src/tokens/base/size/*.json5`],
},
// motion
{
filename: 'motion',
source: [`src/tokens/base/motion/*.json5`, `src/tokens/functional/motion/*.json5`],
include: [`src/tokens/base/motion/*.json5`],
},
]
//
try {
for (const {filename, source, include} of deprecatedBuilds) {
const extendedSD = await PrimerStyleDictionary.extend({
source,
include,
platforms: {
deprecated: deprecatedJson(`deprecated/${filename}.json`, buildOptions.prefix, buildOptions.buildPath),
},
log: {
warnings: 'disabled', // 'warn' | 'error' | 'disabled'
verbosity: 'silent', // 'default' | 'silent' | 'verbose'
errors: {
brokenReferences: 'throw', // 'throw' | 'console'
},
},
})
await extendedSD.buildAllPlatforms()
}
} catch (e) {
console.error('🛑 Error trying to build deprecated tokens output:', e)
}
/** -----------------------------------
* Copy `removed` files
* ----------------------------------- */
copyFromDir(`src/tokens/removed`, `${buildOptions.buildPath}removed`)
const excludePaths = [
(path: string) => {
return path === 'dist/css/functional/size/viewport.css'
},
(path: string) => {
return path.startsWith('dist/css/functional/themes/')
},
]
const all: string[] = []
for (const cssFile of glob.sync('dist/css/{base,functional}/**/*.css')) {
let skip = false
for (const matcher of excludePaths) {
if (matcher(cssFile)) {
skip = true
break
}
}
if (skip) continue
all.push(`@import '${cssFile.replace(/dist\/css/g, '.')}';`)
}
// Write primitives.css with spec header
fs.writeFileSync('dist/css/primitives.css', `${CSS_SPEC_HEADER}${all.join('\n')}\n`)
/** -----------------------------------
* Add spec header to theme CSS files
* ----------------------------------- */
for (const themeFile of glob.sync('dist/css/functional/themes/*.css')) {
const content = fs.readFileSync(themeFile, 'utf-8')
// Only add header if not already present
if (!content.startsWith('/**')) {
fs.writeFileSync(themeFile, `${CSS_SPEC_HEADER}${content}`)
}
}
}
/** -----------------------------------
* Run build script
* ----------------------------------- */
// build to dist
await buildDesignTokens({
buildPath: 'dist/',
})