forked from Ju99ernaut/grapesjs-tailwind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCssTreeWalker.js
68 lines (57 loc) · 1.63 KB
/
CssTreeWalker.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
import { EventEmitter } from "events"
import rework from "./rework"
const RULE_TYPE = "rule"
const MEDIA_TYPE = "media"
class CssTreeWalker extends EventEmitter {
constructor(code, plugins) {
super()
this.startingSource = code
this.ast = null
plugins.forEach(plugin => {
plugin.initialize(this)
})
}
beginReading() {
this.ast = rework(this.startingSource).use(this.readPlugin.bind(this))
}
readPlugin(tree) {
this.readRules(tree.rules)
this.removeEmptyRules(tree.rules)
}
readRules(rules) {
for (let rule of rules) {
if (rule.type === RULE_TYPE) {
this.emit("readRule", rule.selectors, rule)
}
if (rule.type === MEDIA_TYPE) {
this.readRules(rule.rules)
}
}
}
removeEmptyRules(rules) {
let emptyRules = []
for (let rule of rules) {
const ruleType = rule.type
if (ruleType === RULE_TYPE && rule.selectors.length === 0) {
emptyRules.push(rule)
}
if (ruleType === MEDIA_TYPE) {
this.removeEmptyRules(rule.rules)
if (rule.rules.length === 0) {
emptyRules.push(rule)
}
}
}
emptyRules.forEach(emptyRule => {
const index = rules.indexOf(emptyRule)
rules.splice(index, 1)
})
}
toString() {
if (this.ast) {
return this.ast.toString().replace(/,\n/g, ",")
}
return ""
}
}
export default CssTreeWalker