-
Notifications
You must be signed in to change notification settings - Fork 4
/
extractRules.js
89 lines (75 loc) · 2.59 KB
/
extractRules.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
// @flow
/* eslint-disable no-param-reassign */
const selectorParser = require("postcss-selector-parser");
const transformAnimationNames = require("postcss-transform-animations/dist/transformAnimationNames");
const getRoot = require("../util/getRoot");
const { isDirectChildOfKeyframes } = require("../util/cssAst");
/*:: import type { Args } from './types' */
/*::
type Generators = {
generateClassName: (?string, ?string) => string,
generateAnimationName: (string) => string,
}
*/
module.exports = (
inputCss /*: string */,
{ generateClassName, generateAnimationName } /*: Generators */
) /*: { css: string, propTypes: Object, args: Args } */ => {
const classNameMap = {}; // { propName: { propValue: className } }
const animationNameMap = {};
let defaultClassName = null;
const getDefaultClassName = () => {
if (defaultClassName === null) defaultClassName = generateClassName();
return defaultClassName;
};
const getClassNameFor = (prop, value) => {
if (!classNameMap[prop]) {
classNameMap[prop] = {};
}
if (!classNameMap[prop][value]) {
classNameMap[prop][value] = generateClassName(
prop,
value !== "true" ? value : null
);
}
return classNameMap[prop][value];
};
const transformSelectors = selectorParser(container => {
container.each(selector => {
container.walkNesting(node => {
const className = getDefaultClassName();
const replacementNode = selectorParser.className({ value: className });
node.replaceWith(replacementNode);
});
selector.walkAttributes(node => {
const attribute = node.attribute.trim();
if (attribute[0] !== "*") return;
const prop = attribute.slice(1);
const value = node.value ? node.raws.unquoted : "true";
const className = getClassNameFor(prop, value);
const replacementNode = selectorParser.className({ value: className });
node.replaceWith(replacementNode);
});
});
});
const { root, propTypes } = getRoot(inputCss, true);
root.walkRules(node => {
if (!isDirectChildOfKeyframes(node)) {
node.selector = transformSelectors.process(node.selector).result;
}
});
transformAnimationNames(
{
transform: value => {
if (value in animationNameMap) return animationNameMap[value];
const transformValue = generateAnimationName(value);
animationNameMap[value] = transformValue;
return transformValue;
}
},
root
);
const css = root.toString();
const args = { defaultClassName, classNameMap };
return { css, propTypes, args };
};