-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathstyle-dictionary.js
More file actions
497 lines (447 loc) · 17 KB
/
style-dictionary.js
File metadata and controls
497 lines (447 loc) · 17 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
/**
* This module creates and exports custom StyleDictionary instance for Paragon.
*/
const toml = require('js-toml');
const chalk = require('chalk');
const chroma = require('chroma-js');
const { colorYiq, darken, lighten } = require('./sass-helpers');
const cssUtilities = require('./css-utilities');
const { composeBreakpointName, processAndUpdateTokens, generateButtonVariantProperties } = require('./utils');
/* eslint-disable import/no-unresolved */
const getStyleDictionary = async () => (await import('style-dictionary')).default;
const getStyleDictionaryUtils = async () => import('style-dictionary/utils');
const getTokensStudioTransforms = async () => import('@tokens-studio/sd-transforms');
/* eslint-enable import/no-unresolved */
/**
* @typedef {import('style-dictionary/types').DesignToken} DesignToken
*/
/**
* @typedef ModifyColorYiq
* @property {'color-yiq'} type - The type of modification.
* @property {number} [amount] - The amount of modification to apply.
* @property {string} [otherColor] - The other color to mix with.
* @property {number} [light] - The light color to use for color-yiq.
* @property {number} [dark] - The dark color to use for color-yiq.
* @property {number} [threshold] - The threshold to use for color-yiq.
*/
/**
* @typedef ModifyColorDarken
* @property {'darken'} type - The type of modification.
* @property {number} amount - The amount of modification to apply.
*/
/**
* @typedef ModifyColorLighten
* @property {'lighten'} type - The type of modification.
* @property {number} amount - The amount of modification to apply.
*/
/**
* @typedef ModifyColorMix
* @property {'mix'} type - The type of modification.
* @property {number} amount - The amount of modification to apply.
* @property {string} otherColor - The other color to mix with.
*/
/**
* @typedef ModifyColorAlpha
* @property {'alpha'} type - The type of modification.
* @property {number} amount - The amount of modification to apply.
*/
/**
* @typedef DesignTokenModify
* @type {ModifyColorYiq | ModifyColorDarken | ModifyColorLighten | ModifyColorMix | ModifyColorAlpha}
*/
/**
* @typedef {DesignToken & {
* outputReferences?: boolean;
* modify?: DesignTokenModify[];
* }} ParagonDesignToken
*/
/**
* Transforms a color token based on various modifications.
*
* @param {ParagonDesignToken} token - The token object containing color information and modifications.
* @param {string} themeVariant - The themeVariant object containing additional information for color transformations.
* @returns {string} - The transformed color value in hexadecimal format, including alpha if applicable.
*/
const colorTransform = (token, themeVariant) => {
const {
name: tokenName,
$value,
original,
modify,
} = token;
const reservedColorValues = ['inherit', 'initial', 'revert', 'unset', 'currentColor', 'none'];
if (reservedColorValues.includes(original.$value)) {
return original.$value;
}
let color = chroma($value);
if (modify?.length > 0) {
modify.forEach((modifier) => {
const { type, amount, otherColor } = modifier;
switch (type) {
case 'mix':
color = color.mix(otherColor, amount, 'rgb');
break;
case 'color-yiq': {
const { light, dark, threshold } = modifier;
color = colorYiq({
tokenName,
backgroundColor: color,
light,
dark,
threshold,
themeVariant,
});
break;
}
case 'darken':
color = darken(color, amount);
break;
case 'lighten':
color = lighten(color, amount);
break;
default: {
if (!color[type]) {
// eslint-disable-next-line no-console
console.warn(
chalk.keyword('orange').bold(`[Paragon] Warning: Invalid color modification type "${type}" for ${tokenName}.`),
);
return;
}
color = color[type](amount);
}
}
});
}
return color.hex('rgba').toUpperCase();
};
/**
* Custom formatter that extends default css/variables format to allow specifying
* 1. 'outputReferences' per token (by default you are only able to specify it globally for all tokens)
* 2. 'theme' to output only theme's variables (e.g, 'light' or 'dark'), if theme is not provided - only
* core tokens are built.
*/
const createCustomCSSVariables = async ({ formatterArgs }) => {
const { fileHeader, formattedVariables } = await getStyleDictionaryUtils();
const { dictionary, options, file } = formatterArgs;
const { outputReferences, formatting } = options;
const variables = formattedVariables({
format: 'css',
dictionary,
outputReferences: (token) => {
// Formatter options configured to never output references
if (!outputReferences) {
return false;
}
// Token has modifications (e.g., mix, darken, lighten); the computed
// value should be output instead of the reference.
if (token.modify) {
return false;
}
// Formatter options configured to show output references, but handle when individual tokens might opt-out.
return token.outputReferences ?? true;
},
usesDtcg: true,
});
const header = await fileHeader({ file, formatting });
return `${header}:root {\n${variables}\n}\n`;
};
/**
* @typedef {type import("style-dictionary/types").StyleDictionary} StyleDictionary
*/
/**
* Initializes and configures Style Dictionary with custom transforms, formatters, filters, and parsers.
*
* @returns {Promise<StyleDictionary>} - A promise that resolves to the configured Style Dictionary instance.
*/
const initializeStyleDictionary = async ({ themes }) => {
const StyleDictionary = await getStyleDictionary();
const sdUtils = await getStyleDictionaryUtils();
const {
register: registerTokensStudioTransforms,
getTransforms: tokensStudioTransforms,
} = await getTokensStudioTransforms();
StyleDictionary.registerPreprocessor({
name: 'pgn-annotate-token-extensions-with-references',
preprocessor: (dictionary) => {
// Define the extension properties to add to the tokens $extensions object
const extensionProperties = [
{
name: 'isReferencedBySourceToken',
filter: tkn => tkn.isSource,
referenceTokenFilter: tkn => !tkn.isSource,
},
{
name: 'isReferencedByThemeVariant',
filter: tkn => themes.some(theme => tkn.filePath.includes(theme)),
referenceTokenFilter: tkn => !themes.some(theme => tkn.filePath.includes(theme)),
},
];
// Pass the dictionary to the recursive function to process and update tokens in place
const dictionaryCopy = { ...dictionary };
processAndUpdateTokens(dictionary, extensionProperties, sdUtils, dictionaryCopy);
// Return the updated dictionary
return dictionary;
},
});
/**
* Registers transforms from @tokens-studio/sd-transforms.
*/
registerTokensStudioTransforms(StyleDictionary);
/**
* Transforms tokens by applying SASS color functions to tokens.
*/
StyleDictionary.registerTransform({
name: 'color/sass-color-functions',
transitive: true,
type: 'value',
filter: (token) => token.attributes?.category === 'color' || token.$value.toString().startsWith('#'),
transform: (token) => colorTransform(token),
});
/**
* Transforms that implements str-replace from SASS.
*/
StyleDictionary.registerTransform({
name: 'str-replace',
transitive: true,
type: 'value',
filter: (token) => token.modify && token.modify[0].type === 'str-replace',
transform: (token) => {
const { $value, modify } = token;
const { toReplace, replaceWith } = modify[0];
return $value.replaceAll(toReplace, replaceWith);
},
});
/**
* Registers a custom transform group for Paragon CSS.
*/
const customTransforms = [
'color/sass-color-functions',
'str-replace',
];
StyleDictionary.registerTransformGroup({
name: 'paragon-css',
transforms: [
...tokensStudioTransforms({ platform: 'css' }),
...StyleDictionary.hooks.transformGroups.css,
...customTransforms,
],
});
/**
* The custom formatter to create CSS variables for core tokens.
*/
StyleDictionary.registerFormat({
name: 'css/custom-variables',
format: formatterArgs => createCustomCSSVariables({ formatterArgs }),
});
/**
* Formatter to generate CSS utility classes.
* Looks in ./src/utilities/ to get utility classes configuration, filters tokens by 'filters' object attributes
* (see https://amzn.github.io/style-dictionary/#/tokens?id=category-type-item for possible keys in the object,
* each key should have a list of valid values) and generates CSS classes with using functions defined in
* 'utilityFunctionsToApply' list, those functions must be located in css-utilities.js module and return string.
*/
StyleDictionary.registerFormat({
name: 'css/utility-classes',
format: async ({ dictionary, file, options = {} }) => {
const { formatting } = options;
const { fileHeader } = await getStyleDictionaryUtils();
const { utilities } = dictionary.tokens;
if (!utilities) {
return '';
}
let utilityClasses = '';
utilities.forEach(({ filters, utilityFunctionsToApply }) => {
let tokens = dictionary.allTokens;
Object.entries(filters).forEach(([attributeName, allowedValues]) => {
tokens = tokens.filter((token) => allowedValues.includes(token.attributes[attributeName]));
});
// eslint-disable-next-line no-restricted-syntax
for (const token of tokens) {
// Get action token by reference
const ref = sdUtils.getReferences(token.original.actions.default, dictionary.tokens)[0];
token.actions = { default: `var(--${ref.name})` };
// eslint-disable-next-line no-restricted-syntax
for (const funcName of utilityFunctionsToApply) {
utilityClasses += cssUtilities[funcName](token);
}
}
});
const header = await fileHeader({ file, formatting });
return `${header}${utilityClasses}`;
},
});
/**
* Formatter to generate CSS custom media queries for responsive breakpoints.
* Gets input about existing tokens of the 'size' category,
* 'breakpoints' subcategory, and generates a CSS custom media queries.
*/
StyleDictionary.registerFormat({
name: 'css/custom-media-breakpoints',
format: async ({ dictionary, file, options = {} }) => {
const { fileHeader } = await getStyleDictionaryUtils();
const { formatting } = options;
const { breakpoint } = dictionary.tokens.size;
let customMediaVariables = '';
const breakpoints = Object.values(breakpoint || {});
for (let i = 0; i < breakpoints.length; i++) {
const [currentBreakpoint, nextBreakpoint] = [breakpoints[i], breakpoints[i + 1]];
customMediaVariables
+= `${composeBreakpointName(currentBreakpoint.name, 'min')} (min-width: ${currentBreakpoint.$value});\n`;
if (nextBreakpoint) {
customMediaVariables
+= `${composeBreakpointName(currentBreakpoint.name, 'max')} (max-width: ${nextBreakpoint.$value});\n`;
}
}
const header = await fileHeader({ file, formatting });
return `${header}${customMediaVariables}`;
},
});
/**
* Configuration for button variant overrides by component type.
* Each entry defines:
* - getTokens: Function that receives the dictionary tokens and returns the button variant overrides
* - selectors: Array of CSS selectors where the button variants should be overridden
*/
const BUTTON_VARIANT_OVERRIDES_CONFIG = [
{
name: 'Alert actions',
getTokens: (tokens) => tokens?.color?.alert?.actions?.overrides?.button?.variants,
selectors: [
'.pgn__alert-message-wrapper .pgn__alert-actions',
'.pgn__alert-message-wrapper-stacked .pgn__alert-actions',
],
},
{
name: 'Modal footer',
getTokens: (tokens) => tokens?.color?.modal?.footer?.overrides?.button?.variants,
selectors: [
'.pgn__modal .pgn__modal-footer',
],
},
// Add new component configurations here!
];
/**
* Registers a custom format for generating CSS style overrides for button variants in different components.
* All overrides are combined into a single CSS file.
*/
StyleDictionary.registerFormat({
name: 'css/component-button-variant-overrides',
format: async ({ dictionary }) => {
const { fileHeader } = await getStyleDictionaryUtils();
const header = await fileHeader({
file: 'overrides/component-button-variants.css',
formatting: 'css',
});
let hasOutputHeader = false;
let output = '';
// Process each component configuration
BUTTON_VARIANT_OVERRIDES_CONFIG.forEach((config) => {
const buttonVariantOverrides = config.getTokens(dictionary.tokens);
if (!buttonVariantOverrides || typeof buttonVariantOverrides !== 'object' || Object.keys(buttonVariantOverrides).length === 0) {
return; // No overrides tokens found, skip.
}
if (!hasOutputHeader) {
output += header;
hasOutputHeader = true;
}
output += `/* ${config.name} */\n\n`;
Object.entries(buttonVariantOverrides).forEach(([originalVariant, overrideVariant]) => {
const selectorOutput = config.selectors
.map(selector => `${selector} .btn-${originalVariant}`)
.join(',\n');
output += `${selectorOutput} {\n`;
output += ` ${generateButtonVariantProperties(overrideVariant)}\n`;
output += '}\n\n';
});
});
return output;
},
});
/**
* @typedef {function} StyleDictionaryFilterFunction
* @param {import('style-dictionary/types').TransformedToken} token - The token object to filter.
* @param {object} [opts] - The options object passed to the filter.
*/
/**
* @typedef {object} StyleDictionaryFilterOptions
* @property {boolean} hasThemeVariants - Indicates whether the filter should also be registered with theme variants.
*/
/**
* Registers a custom filter with Style Dictionary.
* @param {string} name Name for the filter.
* @param {StyleDictionaryFilterFunction} filter Filter value or function.
* @param {StyleDictionaryFilterOptions} [filterOptions] Custom options for the filter.
*/
function registerStyleDictionaryFilter(name, filter, filterOptions = {}) {
StyleDictionary.registerFilter({ name, filter });
if (filterOptions.hasThemeVariants) {
themes.forEach((themeVariant) => {
StyleDictionary.registerFilter({
name: `${name}.${themeVariant}`,
filter: (token, opts) => {
const paragonExtensions = token.$extensions?.['org.openedx.paragon'];
const isReferencedByThemeVariant = !!paragonExtensions?.isReferencedByThemeVariant;
const baseFilterResult = typeof filter === 'function' ? filter(token, opts) || isReferencedByThemeVariant : filter;
if (!baseFilterResult) {
return false;
}
return token.filePath.includes(themeVariant) || isReferencedByThemeVariant;
},
});
});
}
}
const paragonFilters = [
/**
* Registers a filter `isSource` that filters output to only include source tokens.
*/
{
name: 'isSource',
filter: (token) => {
const paragonExtensions = token.$extensions?.['org.openedx.paragon'];
const isReferencedBySourceToken = !!paragonExtensions?.isReferencedBySourceToken;
return token.isSource || isReferencedBySourceToken;
},
opts: { hasThemeVariants: true },
},
/**
* Registers filter(s) `isThemeVariant.{variant}` that only include the requested theme variant tokens.
*/
...themes.map((themeVariant) => ({
name: `isThemeVariant.${themeVariant}`,
filter: (token) => {
const isThemeVariantToken = token.filePath.includes(themeVariant);
const paragonExtensions = token.$extensions?.['org.openedx.paragon'];
const isReferencedByThemeVariant = !!paragonExtensions?.isReferencedByThemeVariant;
return isThemeVariantToken || isReferencedByThemeVariant;
},
})),
];
paragonFilters.forEach(({ name, filter, opts }) => registerStyleDictionaryFilter(name, filter, opts));
/**
* Registers a custom TOML parser with Style Dictionary.
*/
StyleDictionary.registerParser({
name: 'toml-parser',
pattern: /\.toml$/,
parser: ({ contents }) => toml.load(contents),
});
/**
* Registers a custom fileHeader.
*/
StyleDictionary.registerFileHeader({
name: 'customFileHeader',
fileHeader: (defaultMessage) => [
`${defaultMessage}`,
'See <PARAGON_ROOT>/tokens/README.md for more details.',
],
});
return StyleDictionary;
};
module.exports = {
initializeStyleDictionary,
getTokensStudioTransforms,
createCustomCSSVariables,
colorTransform,
getStyleDictionaryUtils,
};