forked from mzohaibqc/antd-theme-generator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
609 lines (564 loc) · 16.1 KB
/
index.js
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
const fs = require("fs");
const path = require("path");
const glob = require("glob");
const postcss = require("postcss");
const less = require("less");
const hash = require("hash.js");
const NpmImportPlugin = require("less-plugin-npm-import");
let hashCache = "";
let cssCache = "";
const COLOR_FUNCTIONS = [
"color",
"lighten",
"darken",
"saturate",
"desaturate",
"fadein",
"fadeout",
"fade",
"spin",
"mix",
"hsv",
"tint",
"shade",
"greyscale",
"multiply",
"contrast",
"screen",
"overlay",
];
const defaultColorRegexArray = COLOR_FUNCTIONS.map(
(name) => new RegExp(`${name}\(.*\)`)
);
defaultColorRegexArray.matches = (color) => {
return defaultColorRegexArray.reduce((prev, regex) => {
return prev || regex.test(color);
}, false);
};
/*
Generated random hex color code
e.g. #fe12ee
*/
function randomColor() {
return "#" + (0x1000000 + Math.random() * 0xffffff).toString(16).substr(1, 6);
}
/*
Recursively get the color code assigned to a variable e.g.
@primary-color: #1890ff;
@link-color: @primary-color;
@link-color -> @primary-color -> #1890ff
Which means
@link-color: #1890ff
*/
function getColor(varName, mappings) {
const color = mappings[varName];
if (color in mappings) {
return getColor(color, mappings);
} else {
return color;
}
}
/*
Read following files and generate color variables and color codes mapping
- Ant design color.less, themes/default.less
- Your own variables.less
It will generate map like this
{
'@primary-color': '#00375B',
'@info-color': '#1890ff',
'@success-color': '#52c41a',
'@error-color': '#f5222d',
'@normal-color': '#d9d9d9',
'@primary-6': '#1890ff',
'@heading-color': '#fa8c16',
'@text-color': '#cccccc',
....
}
*/
function generateColorMap(content, customColorRegexArray = []) {
return content
.split("\n")
.filter((line) => line.startsWith("@") && line.indexOf(":") > -1)
.reduce((prev, next) => {
try {
const matches = next.match(
/(?=\S*['-])([@a-zA-Z0-9'-]+).*:[ ]{1,}(.*);/
);
if (!matches) {
return prev;
}
let [, varName, color] = matches;
if (color && color.startsWith("@")) {
color = getColor(color, prev);
if (!isValidColor(color, customColorRegexArray)) return prev;
// if (defaultColorRegexArray.matches(color) && !color.includes('~')) {
// color = `~'${color}'`;
// }
prev[varName] = color;
} else if (isValidColor(color, customColorRegexArray)) {
// if (defaultColorRegexArray.matches(color) && !color.includes('~')) {
// color = `~'${color}'`;
// }
prev[varName] = color;
}
return prev;
} catch (e) {
console.log("e", e);
return prev;
}
}, {});
}
/*
This plugin will remove all css rules except those are related to colors
e.g.
Input:
.body {
font-family: 'Lato';
background: #cccccc;
color: #000;
padding: 0;
pargin: 0
}
Output:
.body {
background: #cccccc;
color: #000;
}
*/
const reducePlugin = postcss.plugin("reducePlugin", () => {
const cleanRule = (rule) => {
if (rule.selector.startsWith(".main-color .palatte-")) {
rule.remove();
return;
}
let removeRule = true;
rule.walkDecls((decl) => {
let matched = false;
if (String(decl.value).match(/url\(.*\)/g)) {
decl.remove();
matched = true;
}
// Removing transparent adds Link Button border color
// https://github.com/mzohaibqc/antd-theme-generator/issues/64
// if (!matched && decl.value === 'transparent') {
// decl.remove();
// matched = true;
// }
/*
this block causing https://github.com/ant-design/ant-design/issues/24777
if (decl.prop !== 'background' && decl.prop.includes('background') && !decl.prop.match(/^background-(.*)color$/ig)) {
decl.remove();
matched = true;
}
if (decl.prop !== 'border' && decl.prop.includes('border') && !decl.prop.match(/^border-(.*)color$/ig)) {
decl.remove();
matched = true;
}
if (['transparent', 'inherit', 'none', '0'].includes(decl.value)) {
decl.remove();
matched = true;
}
*/
if (
!decl.prop.includes("color") &&
!decl.prop.includes("background") &&
!decl.prop.includes("border") &&
!decl.prop.includes("box-shadow") &&
!Number.isNaN(decl.value)
) {
// if (!matched) decl.remove();
decl.remove();
} else {
removeRule = matched ? removeRule : false;
}
});
if (removeRule) {
rule.remove();
}
};
return (css) => {
css.walkAtRules((atRule) => {
atRule.remove();
});
css.walkRules(cleanRule);
css.walkComments((c) => c.remove());
};
});
function getMatches(string, regex) {
const matches = {};
let match;
while ((match = regex.exec(string))) {
if (match[2].startsWith("rgba") || match[2].startsWith("#")) {
matches[`@${match[1]}`] = match[2];
}
}
return matches;
}
/*
This function takes less input as string and compiles into css.
*/
function render(text, paths) {
return less.render(text, {
paths: paths,
javascriptEnabled: true,
plugins: [new NpmImportPlugin({ prefix: "~" })],
});
}
/*
This funtion reads a less file and create an object with keys as variable names
and values as variables respective values. e.g.
//variabables.less
@primary-color : #1890ff;
@heading-color : #fa8c16;
@text-color : #cccccc;
to
{
'@primary-color' : '#1890ff',
'@heading-color' : '#fa8c16',
'@text-color' : '#cccccc'
}
*/
function getLessVars(filtPath) {
const sheet = fs.readFileSync(filtPath).toString();
const lessVars = {};
const matches = sheet.match(/@(.*:[^;]*)/g) || [];
matches.forEach((variable) => {
const definition = variable.split(/:\s*/);
const varName = definition[0].replace(/['"]+/g, "").trim();
lessVars[varName] = definition.splice(1).join(":");
});
return lessVars;
}
/*
This function take primary color palette name and returns @primary-color dependent value
.e.g
Input: @primary-1
Output: color(~`colorPalette("@{primary-color}", ' 1 ')`)
*/
function getShade(varName) {
let [, className, number] = varName.match(/(.*)-(\d)/);
if (/primary-\d/.test(varName)) className = "@primary-color";
if (/brand-primary-\d/.test(varName)) className = "@brand-primary";
return (
'color(~`colorPalette("@{' +
className.replace("@", "") +
'}", ' +
number +
")`)"
);
}
/*
This function takes color string as input and return true if string is a valid color otherwise returns false.
e.g.
isValidColor('#ffffff'); //true
isValidColor('#fff'); //true
isValidColor('rgba(0, 0, 0, 0.5)'); //true
isValidColor('20px'); //false
*/
function isValidColor(color, customColorRegexArray = []) {
if (color && color.includes("rgb")) return true;
if (!color || color.match(/px/g)) return false;
if (color.match(/colorPalette|fade/g)) return true;
if (color.charAt(0) === "#") {
color = color.substring(1);
return (
[3, 4, 6, 8].indexOf(color.length) > -1 && !isNaN(parseInt(color, 16))
);
}
// eslint-disable-next-line
const isColor = /^(rgb|hsl|hsv)a?\((\d+%?(deg|rad|grad|turn)?[,\s]+){2,3}[\s\/]*[\d\.]+%?\)$/i.test(
color
);
if (isColor) return true;
if (customColorRegexArray.length > 0) {
return customColorRegexArray.reduce((prev, regex) => {
return prev || regex.test(color);
}, false);
}
return false;
}
/*
This is main function which call all other functions to generate color.less file which contins all color
related css rules based on Ant Design styles and your own custom styles
By default color.less will be generated in /public directory
*/
async function generateTheme({
antDir,
antdStylesDir,
stylesDir,
varFile,
themeVariables = [],
customColorRegexArray = [],
customCss = "",
type = 'antd-mobile'
}) {
try {
const isAntd = type === 'antd';
const antdPath = antdStylesDir || path.join(antDir, "lib");
const nodeModulesPath = path.join(
antDir.slice(0, antDir.indexOf("node_modules")),
"./node_modules"
);
/*
stylesDir can be array or string
*/
const stylesDirs = [].concat(stylesDir);
let styles = [];
stylesDirs.forEach((s) => {
styles = styles.concat(glob.sync(path.join(s, "./**/*.less")));
});
const antdStylesFile = path.join(antDir, `./dist/${isAntd ? 'antd' : 'antd-mobile'}.less`); // path.join(antdPath, './style/index.less');
/*
You own custom styles (Change according to your project structure)
- stylesDir - styles directory containing all less files
- varFile - variable file containing ant design specific and your own custom variables
*/
varFile = varFile || path.join(antdPath, "./style/themes/default.less");
let content = "";
styles.forEach((filePath) => {
content += fs.readFileSync(filePath).toString();
});
const hashCode = hash.sha256().update(content).digest("hex");
if (hashCode === hashCache) {
return cssCache;
}
hashCache = hashCode;
let themeCompiledVars = {};
let themeVars = themeVariables || [];
const lessPaths = [path.join(antdPath, "./style")].concat(stylesDir);
const randomColors = {};
const randomColorsVars = {};
/*
Ant Design Specific Files (Change according to your project structure)
You can even use different less based css framework and create color.less for that
- antDir - ant design instalation path
- entry - Ant Design less main file / entry file
- styles - Ant Design less styles for each component
1. Bundle all variables into one file
2. process vars and create a color name, color value key value map
3. Get variables which are part of theme
4.
*/
const varFileContent = combineLess(varFile, nodeModulesPath);
customColorRegexArray = [
...customColorRegexArray,
...defaultColorRegexArray,
];
const mappings = Object.assign(
generateColorMap(varFileContent, customColorRegexArray),
getLessVars(varFile)
);
let css = "";
themeVars = themeVars.filter(
(name) => name in mappings && !name.match(/(.*)-(\d)/)
);
themeVars.forEach((varName) => {
let color = mappings[varName];
randomColors[varName] = color;
randomColorsVars[color] = varName;
css = `.${varName.replace("@", "")} { color: ${color}; }\n ${css}`;
});
const colorFuncMap = {};
let varsContent = "";
themeVars.forEach((varName) => {
[1, 2, 3, 4, 5, 7, 8, 9, 10].forEach((key) => {
const name =
varName === "@primary-color"
? `@primary-${key}`
: `${varName}-${key}`;
css = `.${name.replace("@", "")} { color: ${getShade(
name
)}; }\n ${css}`;
});
varsContent += `${varName}: ${randomColors[varName]};\n`;
});
// This is to compile colors
// Put colors.less content first,
// then add random color variables to override the variables values for given theme variables with random colors
// Then add css containinf color variable classes
if (isAntd) {
const colorFileContent = combineLess(
path.join(antdPath, "./style/color/colors.less"),
nodeModulesPath
);
css = `${colorFileContent}\n${varsContent}\n${css}`;
} else {
css = `${varsContent}\n${css}`;
}
let results = await render(css, lessPaths);
css = results.css;
css = css.replace(/(\/.*\/)/g, "");
const regex = /.(?=\S*['-])([.a-zA-Z0-9'-]+)\ {\n {2}color: (.*);/g;
themeCompiledVars = getMatches(css, regex);
let varsCombined = "";
themeVars.forEach((varName) => {
let color;
if (/(.*)-(\d)/.test(varName)) {
color = getShade(varName);
return;
} else {
color = themeCompiledVars[varName];
}
varsCombined = `${varsCombined}\n${varName}: ${color};`;
});
const allCss = `${customCss}`;
results = await postcss([reducePlugin]).process(allCss, {
from: antdStylesFile,
});
css = results.css;
Object.keys(themeCompiledVars).forEach((varName) => {
let color;
if (/(.*)-(\d)/.test(varName)) {
color = themeCompiledVars[varName];
varName = getShade(varName);
} else {
color = themeCompiledVars[varName];
}
color = color.replace("(", "\\(").replace(")", "\\)");
if (varName === "@slider-handle-color-focus") {
console.log("color", color, varName);
}
css = css.replace(new RegExp(color, "g"), varName);
});
Object.keys(colorFuncMap).forEach((varName) => {
const color = colorFuncMap[varName];
css = css.replace(new RegExp(color, "g"), varName);
});
COLOR_FUNCTIONS.forEach((name) => {
css = css.replace(new RegExp(`~'(${name}\(.*\))'`), (a, b) => {
return b;
});
});
// Handle special cases
// https://github.com/mzohaibqc/antd-theme-webpack-plugin/issues/69
// 1. Replace fade(@primary-color, 20%) value i.e. rgba(18, 52, 86, 0.2)
css = css.replace(
new RegExp("rgba\\(18, 52, 86, 0.2\\)", "g"),
"fade(@primary-color, 20%)"
);
css = css.replace(/@[\w-_]+:\s*.*;[\/.]*/gm, "");
// This is to replace \9 in Ant Design styles
css = css.replace(/\\9/g, "");
if (isAntd) {
css = `${css.trim()}\n${combineLess(
path.join(antdPath, "./style/themes/default.less"),
nodeModulesPath
)}`;
}
themeVars.reverse().forEach((varName) => {
css = css.replace(new RegExp(`${varName}( *):(.*);`, "g"), "");
css = `${varName}: ${mappings[varName]};\n${css}\n`;
});
css = minifyCss(css);
console.log("Theme generated successfully");
cssCache = css;
return cssCache;
} catch (error) {
console.log("error", error);
return "";
}
}
module.exports = {
generateTheme,
isValidColor,
getLessVars,
randomColor,
minifyCss,
renderLessContent: render,
};
function minifyCss(css) {
// Removed all comments and empty lines
css = css
.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "")
.replace(/^\s*$(?:\r\n?|\n)/gm, "");
/*
Converts from
.abc,
.def {
color: red;
background: blue;
border: grey;
}
to
.abc,
.def {color: red;
background: blue;
border: grey;
}
*/
css = css.replace(/\{(\r\n?|\n)\s+/g, "{");
/*
Converts from
.abc,
.def {color: red;
}
to
.abc,
.def {color: red;
background: blue;
border: grey;}
*/
css = css.replace(/;(\r\n?|\n)\}/g, ";}");
/*
Converts from
.abc,
.def {color: red;
background: blue;
border: grey;}
to
.abc,
.def {color: red;background: blue;border: grey;}
*/
css = css.replace(/;(\r\n?|\n)\s+/g, ";");
/*
Converts from
.abc,
.def {color: red;background: blue;border: grey;}
to
.abc, .def {color: red;background: blue;border: grey;}
*/
css = css.replace(/,(\r\n?|\n)[.]/g, ", .");
return css;
}
// const removeColorCodesPlugin = postcss.plugin('removeColorCodesPlugin', () => {
// const cleanRule = rule => {
// let removeRule = true;
// rule.walkDecls(decl => {
// if (
// !decl.value.includes('@')
// ) {
// decl.remove();
// } else {
// removeRule = false;
// }
// });
// if (removeRule) {
// rule.remove();
// }
// };
// return css => {
// css.walkRules(cleanRule);
// };
// });
function combineLess(filePath, nodeModulesPath) {
const fileContent = fs.readFileSync(filePath).toString();
const directory = path.dirname(filePath);
return fileContent
.split("\n")
.map((line) => {
if (line.startsWith("@import")) {
let importPath = line.match(/@import\ ["'](.*)["'];/)[1];
if (!importPath.endsWith(".less")) {
importPath += ".less";
}
let newPath = path.join(directory, importPath);
if (importPath.startsWith("~")) {
importPath = importPath.replace("~", "");
newPath = path.join(nodeModulesPath, `./${importPath}`);
}
return combineLess(newPath, nodeModulesPath);
}
return line;
})
.join("\n");
}