-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathextract-theme-css.ts
269 lines (226 loc) · 8.27 KB
/
extract-theme-css.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
import { Theme } from 'qwik-themes/lib-types/lib/types';
import { calculate, compare } from 'specificity';
import { extractBetweenComments } from './extract-between-comments';
export const extractThemeCSS = (theme: Theme, globalCSS: string) => {
const cssClasses = extractRelevantCSS(globalCSS);
// Parse the CSS to get the variables
const classesMap = createClassesMap(cssClasses);
// console.log('classesMap', classesMap);
// Example usage with the cssThemeToObjectTheme function output
const objDarkClasses = applyDarkOverrides(classesMap);
// console.log('objDarkClasses', objDarkClasses);
const objRootClasses = removeDarkClasses(classesMap);
// Build the theme CSS
const objTheme = generateObjThemeOutput({ theme, objRootClasses, objDarkClasses });
const orderedObjTheme = reorderThemeObject(objTheme);
const output = objThemeToCSSThemeOutput(orderedObjTheme);
return output;
};
function extractRelevantCSS(cssContent: string) {
const startMarker = '/* CSS PARSER: START - DO NOT REMOVE */';
const endMarker = '/* CSS PARSER: END - DO NOT REMOVE */';
let extractedCSS = extractBetweenComments(cssContent, startMarker, endMarker);
// Remove all CSS comments
extractedCSS = extractedCSS.replace(/\/\*[\s\S]*?\*\//g, '').trim();
return extractedCSS;
}
function createClassesMap(css: string): Record<string, Record<string, string>> {
const classesMap: Record<string, Record<string, string>> = {};
// Split the CSS string by '}' to separate class blocks, filtering out empty strings.
const classBlocks = css.split('}').filter((block) => block.trim() !== '');
classBlocks.forEach((block) => {
// Find the index where the class definitions end and the CSS properties start.
const startOfProperties = block.indexOf('{');
if (startOfProperties === -1) return; // Skip if '{' not found to avoid errors.
// Extract class names and properties substrings.
const classKeys = block.substring(0, startOfProperties).trim();
const classValues = block.substring(startOfProperties + 1).trim();
// Split class names by ',' in case multiple classes are defined together.
const classKeysArray = classKeys.split(',').map((name) => name.trim()); // Remove leading '.' from class names.
// Process CSS properties into a key-value map.
const properties = classValues
.split(';')
.reduce((acc: Record<string, string>, current) => {
const [key, value] = current.split(':').map((part) => part.trim());
if (key && value) {
acc[key] = value;
}
return acc;
}, {});
// Assign properties to each class name found.
classKeysArray.forEach((className) => {
if (!classesMap[className]) {
classesMap[className] = {};
}
Object.assign(classesMap[className], properties);
});
});
return classesMap;
}
function removeDarkClasses(
classes: Record<string, Record<string, string>>,
): Record<string, Record<string, string>> {
const filteredClasses: Record<string, Record<string, string>> = {};
// Iterate over all class names in the input object
Object.keys(classes).forEach((className) => {
// Check if the class name does not start with 'dark'
if (!className.includes('.dark')) {
// If it doesn't, include it in the filtered classes
filteredClasses[className] = classes[className];
}
});
return filteredClasses;
}
function applyDarkOverrides(
classes: Record<string, Record<string, string>>,
): Record<string, Record<string, string>> {
const result: Record<string, Record<string, string>> = {};
Object.keys(classes).forEach((className) => {
// Check if this class is a dark theme override
if (className.includes('.dark')) {
// Extract the actual class name by removing the 'dark' prefix and any leading dots
const baseClassName = className.replace(/^\.dark/, '');
// If the base class exists, merge the dark properties into it
if (classes[baseClassName]) {
result[baseClassName] = {
...classes[baseClassName], // Original properties
...classes[className], // Override with dark properties
};
} else {
// If the base class does not exist, just add the dark class as is (without 'dark' prefix)
result[baseClassName] = classes[className];
}
} else if (!result[className]) {
// Ensure not to override already processed classes
// If it's not a dark override, copy the class as is
result[className] = classes[className];
}
});
return result;
}
type ThemeMap = {
root: Record<string, string>;
dark: Record<string, string>;
};
type GenerateThemeProps = {
theme: Theme;
objRootClasses: Record<string, Record<string, string>>;
objDarkClasses: Record<string, Record<string, string>>;
};
function generateObjThemeOutput({
theme,
objRootClasses,
objDarkClasses,
}: GenerateThemeProps): ThemeMap {
if (!theme) throw new Error('No theme provided');
// Sort classes by specificity
const sortedObjRootClasses = sortObjClassesBySpecificity(objRootClasses);
const sortedObjDarkClasses = sortObjClassesBySpecificity(objDarkClasses);
const themeClasses: string[] = Array.isArray(theme) ? theme : theme?.split(' ');
let rootOutput: Record<string, string> = {};
let darkOutput: Record<string, string> = {};
// For root classes
Object.entries(sortedObjRootClasses).forEach(([key, value]) => {
themeClasses.forEach((themeClass) => {
// Modify this to check if the key ends with the class name, accounting for specificity
if (key.includes(`.${themeClass}`)) {
rootOutput = { ...rootOutput, ...value };
}
});
});
// For dark classes
Object.entries(sortedObjDarkClasses).forEach(([key, value]) => {
themeClasses.forEach((themeClass) => {
// Similar logic for dark classes
if (key.includes(`.${themeClass}`)) {
darkOutput = { ...darkOutput, ...value };
}
});
});
return {
root: rootOutput,
dark: darkOutput,
};
}
// Sort objects props by specificity to automatically apply specificity to the output
function sortObjClassesBySpecificity(classes: Record<string, Record<string, string>>) {
// Convert the classes object to an array of [className, classStyles] pairs
const classNames = Object.keys(classes);
// Sort the array based on the specificity of className
const sortedClassNames = classNames.sort((a, b) => {
// using 'specificity' npm package
const specificityA = calculate(a);
const specificityB = calculate(b);
return compare(specificityA, specificityB);
});
// Convert the sorted array back to an object
const sortedObjClasses = sortedClassNames.reduce(
(obj: Record<string, Record<string, string>>, className) => {
obj[className] = classes[className];
return obj;
},
{},
);
return sortedObjClasses;
}
function reorderThemeObject(themeObject: ThemeMap) {
const order = [
'--background',
'--foreground',
'--muted',
'--muted-foreground',
'--popover',
'--popover-foreground',
'--card',
'--card-foreground',
'--border',
'--input',
'--primary',
'--primary-foreground',
'--secondary',
'--secondary-foreground',
'--accent',
'--accent-foreground',
'--alert',
'--alert-foreground',
'--ring',
'--border-width',
'--border-radius',
'--shadow-base',
'--shadow-sm',
'--shadow',
'--shadow-md',
'--shadow-lg',
'--shadow-xl',
'--shadow-2xl',
'--shadow-inner',
'--transform-press',
];
function reorderObject(obj: Record<string, string>) {
const ordered: Record<string, string> = {};
order.forEach((key) => {
if (key in obj) {
ordered[key] = obj[key];
}
});
return ordered;
}
return {
root: reorderObject(themeObject.root),
dark: reorderObject(themeObject.dark),
};
}
function objThemeToCSSThemeOutput(themeObject: ThemeMap) {
let cssOutput = `@layer base {\n`;
// Iterate over each theme (e.g., 'root', 'dark')
for (const [theme, values] of Object.entries(themeObject)) {
cssOutput += ` ${theme === 'root' ? ':root' : `.${theme}`} {\n`;
// Iterate over each variable in the theme
for (const [variable, value] of Object.entries(values)) {
cssOutput += ` ${variable}: ${value};\n`;
}
cssOutput += ` }\n`;
}
cssOutput += `}`;
return cssOutput;
}