-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcss.js
61 lines (44 loc) · 1.39 KB
/
css.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
const system = require("./system");
const kebabCase = require("lodash.kebabcase");
function css(styles, theme) {
const stylesArray = flattenNestedStyles(styles);
styleSheet = ``;
stylesArray.forEach(function({ selector, styles }) {
const interpolated = system.css(styles)(theme);
const css = objectToCss(interpolated);
styleSheet += `${selector} { \n ${css} \n } \n`;
});
return styleSheet;
}
function flattenNestedStyles(styles, className) {
const stylesArray = [];
const keys = Object.keys(styles);
keys.forEach(function(key) {
if (typeof styles[key] === "object") {
const nestedClassName = getFlatClassName(key);
stylesArray.push({
selector: "." + kebabCase(nestedClassName).replace("-", "--"),
styles: styles[key]
});
delete styles[key];
}
});
return stylesArray;
}
function getFlatClassName(selector) {
// there are more unhandled cases for sure
selector = selector.replace("&", "");
if (selector.startsWith(":")) return selector;
else return "." + selector;
}
function objectToCss(styles) {
const propertyNames = Object.keys(styles);
const cssArray = propertyNames.map(function(key) {
const property = kebabCase(key);
let value = styles[key];
if (value && typeof value === "number") value += "px";
return `${property}: ${value};`;
});
return cssArray.join("\n ");
}
module.exports = css;