Debian Codegraph @

node/@patternfly/react-tokens/scripts/generateTokens.mjs

raw
1 import { glob } from 'glob';
2 import { createRequire } from 'node:module';
3 import { dirname, basename, sep } from 'node:path';
4 import { parse, stringify } from '@adobe/css-tools';
5 import { readFileSync } from 'node:fs';
6
7 const require = createRequire(import.meta.url);
8 const pfStylesDir = dirname(require.resolve('@patternfly/patternfly/patternfly.css'));
9 const version = 'v6';
10
11 // Helpers
12 const formatCustomPropertyName = (key) =>
13 key.replace(`--pf-${version}-`, '').replace('--pf-t--', 't_').replace(/-+/g, '_');
14
15 const getRegexMatches = (string, regex) => {
16 const res = {};
17 let matches;
18 while ((matches = regex.exec(string))) {
19 res[matches[1]] = matches[2].trim();
20 }
21 return res;
22 };
23
24 const getDeclarations = (cssAst) =>
25 cssAst.stylesheet.rules
26 .filter(
27 (node) =>
28 node.type === 'rule' &&
29 !node.selectors.includes(`.pf-${version}-t-dark`) &&
30 (!node.selectors || !node.selectors.some((item) => item.includes(`.pf-${version}-theme-dark`))) // exclude dark theme blocks since dark theme variable values override default token values
31 )
32 .map((node) => node.declarations.filter((decl) => decl.type === 'declaration'))
33 .reduce((acc, val) => acc.concat(val), []); // flatten
34
35 const formatFilePathToName = (filePath) => {
36 // const filePathArr = filePath.split('/');
37 let prefix = '';
38 if (filePath.includes('components/')) {
39 prefix = 'c_';
40 } else if (filePath.includes('layouts/')) {
41 prefix = 'l_';
42 }
43 return `${prefix}${basename(filePath, '.css').replace(/-+/g, '_')}`;
44 };
45
46 const getLocalVarsMap = (cssFiles) => {
47 const res = {};
48
49 cssFiles.forEach((filePath) => {
50 const cssAst = parse(readFileSync(filePath, 'utf8'));
51
52 getDeclarations(cssAst).forEach(({ property, value, parent }) => {
53 if (res[property]) {
54 // Accounts for multiple delcarations out of root scope.
55 // TODO: revamp CSS var mapping
56 return;
57 }
58 if (property.startsWith(`--pf-${version}`)) {
59 res[property] = {
60 ...res[property],
61 [parent.selectors[0]]: value
62 };
63 } else if (property.startsWith('--pf-t')) {
64 res[property] = {
65 ...res[property],
66 [parent.selectors[0]]: value
67 };
68 }
69 });
70 });
71
72 return res;
73 };
74
75 /**
76 * Generates tokens from CSS in node_modules/@patternfly/patternfly/**
77 *
78 * @returns {object} of form {
79 * c_about_modal_box: {
80 * ".pf-c-about-modal-box" : {
81 * "global_Color_100": {
82 * "name": "--pf-${version}-global--Color--100",
83 * "value": "#fff",
84 * "values": [
85 * "--pf-${version}-global--Color--light-100",
86 * "$pf-global--Color--light-100",
87 * "$pf-color-white",
88 * "#fff"
89 * ]
90 * },
91 * },
92 * ".pf-c-about-modal-box .pf-c-card": {}
93 * }
94 * }
95 */
96 export function generateTokens() {
97 const cssFiles = glob
98 .sync(['{**/{components,layouts}/**/*.css', '**/patternfly-charts.css', '**/patternfly-variables.css}'].join(','), {
99 cwd: pfStylesDir,
100 ignore: ['assets/**', '/**/_index.css'],
101 absolute: true
102 })
103 // Sort to put variables and charts at END of list so getLocalVarsMap returns correct values
104 .sort((a, b) => (a.split(sep).length < b.split(sep).length ? 1 : -1));
105
106 // various lookup tables to resolve variables
107 const scssVariables = readFileSync(
108 require.resolve('@patternfly/patternfly/sass-utilities/scss-variables.scss'),
109 'utf8'
110 );
111 const scssVarsMap = getRegexMatches(scssVariables, /(\$.*):\s*([^;^!]+)/g);
112
113 const cssGlobalVariablesAst = parse(
114 readFileSync(require.resolve('@patternfly/patternfly/base/patternfly-variables.css'), 'utf8')
115 );
116 cssGlobalVariablesAst.stylesheet.rules = cssGlobalVariablesAst.stylesheet.rules.filter(
117 (node) => !node.selectors || !node.selectors.some((item) => item.includes(`.pf-${version}-theme-dark`))
118 );
119
120 const cssGlobalVariablesMap = getRegexMatches(stringify(cssGlobalVariablesAst), /(--pf-[\w-]*):\s*([\w -_]+);/g);
121
122 const getComputedCSSVarValue = (value, selector, varMap) =>
123 value.replace(/var\(([\w-]*)(,.*)?\)/g, (full, m1, m2) => {
124 if (m1.startsWith(`--pf-${version}-global`)) {
125 if (varMap[m1]) {
126 return varMap[m1] + (m2 || '');
127 } else {
128 return full;
129 }
130 } else {
131 if (selector) {
132 return getFromLocalVarsMap(m1, selector) + (m2 || '');
133 }
134 }
135 });
136
137 const getComputedScssVarValue = (value) =>
138 value.replace(/\$pf[^,)\s*/]*/g, (match) => {
139 if (scssVarsMap[match]) {
140 return scssVarsMap[match];
141 } else {
142 return match;
143 }
144 });
145
146 const getVarsMap = (value, selector) => {
147 // evaluate the value and follow the variable chain
148 const varsMap = [value];
149
150 let computedValue = value;
151 let finalValue = value;
152 while (finalValue.includes('var(--pf') || computedValue.includes('var(--pf') || computedValue.includes('$pf-')) {
153 // keep following the variable chain until we get to a value
154 if (finalValue.includes('var(--pf')) {
155 finalValue = getComputedCSSVarValue(finalValue, selector, cssGlobalVariablesMap);
156 }
157 if (computedValue.includes('var(--pf')) {
158 computedValue = getComputedCSSVarValue(computedValue, selector);
159 } else {
160 computedValue = getComputedScssVarValue(computedValue);
161 }
162
163 // error out if variable doesn't exist to avoid infinite loop
164 if (finalValue === value && computedValue === value) {
165 // eslint-disable-next-line no-console
166 console.error(`Error: "${value}" variable not found`);
167 throw Error;
168 }
169
170 varsMap.push(computedValue);
171 }
172 const lastElement = varsMap[varsMap.length - 1];
173 if (lastElement.includes('pf-')) {
174 varsMap.push(finalValue);
175 }
176 // all values should not be boxed by var()
177 return varsMap.map((variable) => variable.replace(/var\(([\w-]*)\)/g, (_, match) => match));
178 };
179
180 // pre-populate the localVarsMap so we can lookup local variables within or across files, e.g. if we have the declaration:
181 // --pf-${version}-c-chip-group--MarginBottom: calc(var(--pf-${version}-c-chip-group--c-chip--MarginBottom) * -1);
182 // then we need to find:
183 // --pf-${version}-c-chip-group--c-chip--MarginBottom: var(--pf-${version}-global--spacer--xs);
184 const localVarsMap = getLocalVarsMap(cssFiles);
185
186 const getFromLocalVarsMap = (match, selector) => {
187 if (localVarsMap[match]) {
188 // have exact selectors match
189 if (localVarsMap[match][selector]) {
190 return localVarsMap[match][selector];
191 } else if (Object.keys(localVarsMap[match]).length === 1) {
192 // only one match, return its value
193 return Object.values(localVarsMap[match])[0];
194 } else {
195 // find the nearest parent selector and return its value
196 let bestMatch = '';
197 let bestValue = '';
198 for (const key in localVarsMap[match]) {
199 if (localVarsMap[match].hasOwnProperty(key)) {
200 // remove trailing * from key to compare
201 let sanitizedKey = key.replace(/\*$/, '').trim();
202 sanitizedKey = sanitizedKey.replace(/>$/, '').trim();
203 sanitizedKey = sanitizedKey.replace(/\[.*\]$/, '').trim();
204 // is key a parent of selector?
205 if (selector.indexOf(sanitizedKey) > -1) {
206 if (sanitizedKey.length > bestMatch.length) {
207 // longest matching key is the winner
208 bestMatch = key;
209 bestValue = localVarsMap[match][key];
210 }
211 }
212 }
213 }
214 if (!bestMatch) {
215 // eslint-disable-next-line no-console
216 console.error(`no matching selector found for ${match} in localVarsMap`);
217 }
218 return bestValue;
219 }
220 } else {
221 // eslint-disable-next-line no-console
222 console.error(`no matching property found for ${match} in localVarsMap`);
223 }
224 };
225
226 const fileTokens = {};
227 cssFiles.forEach((filePath) => {
228 const cssAst = parse(readFileSync(filePath, 'utf8'));
229 // key is the formatted file name, e.g. c_about_modal_box
230 const key = formatFilePathToName(filePath);
231
232 getDeclarations(cssAst)
233 .filter(({ property }) => property.startsWith('--pf'))
234 .forEach(({ property, value, parent }) => {
235 const selector = parent.selectors[0];
236
237 const varsMap = getVarsMap(value, selector);
238 const propertyObj = {
239 name: property,
240 value: varsMap[varsMap.length - 1]
241 };
242 if (varsMap.length > 1) {
243 propertyObj.values = varsMap;
244 }
245
246 fileTokens[key] = fileTokens[key] || {};
247 fileTokens[key][selector] = fileTokens[key][selector] || {};
248 fileTokens[key][selector][formatCustomPropertyName(property)] = propertyObj;
249 });
250 });
251
252 return fileTokens;
253 }