|
| 1 | +const _ = require('lodash') |
| 2 | +const gonzales = require('gonzales-pe') |
| 3 | + |
| 4 | +const IGNORE_COMMENT_REGEX = /\bprunedcss:ignore\b/ |
| 5 | + |
| 6 | +class CssParser { |
| 7 | + constructor(content, corpra) { |
| 8 | + this._content = content |
| 9 | + this._corpra = corpra |
| 10 | + this._parsed = gonzales.parse(content) |
| 11 | + this._usedTokens = new Set() |
| 12 | + } |
| 13 | + |
| 14 | + pruned() { |
| 15 | + let ignoreRules = false |
| 16 | + this._parsed.traverse((rule, index, parent) => { |
| 17 | + Object.defineProperty(rule, 'parent', {get: _.constant(parent)}) |
| 18 | + |
| 19 | + if (rule.type === 'multilineComment' && IGNORE_COMMENT_REGEX.test(rule.content)) { |
| 20 | + ignoreRules = !ignoreRules; |
| 21 | + } else if (rule.type === 'ruleset') { |
| 22 | + const selectors = [] |
| 23 | + rule.traverseByType('selector', node => selectors.push(this.getSelectorTokens(node))) |
| 24 | + const usedSelectors = selectors.filter(s => this.findUsedSelector(s)) |
| 25 | + if (usedSelectors.length === 0) { |
| 26 | + parent.removeChild(index) |
| 27 | + } |
| 28 | + } |
| 29 | + }) |
| 30 | + |
| 31 | + return this._parsed.toString() |
| 32 | + } |
| 33 | + |
| 34 | + getSelectorTokens(parsed) { |
| 35 | + const tokens = [] |
| 36 | + parsed.traverseByTypes(['id', 'class', 'typeSelector'], node => { |
| 37 | + const content = _.get(node, 'content.0.content', '') |
| 38 | + if (node.type === 'typeSelector' && ['html', 'body'].includes(content)) { |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + tokens.push(content) |
| 43 | + }) |
| 44 | + |
| 45 | + return tokens; |
| 46 | + } |
| 47 | + |
| 48 | + findUsedSelector(tokens) { |
| 49 | + return _.every(tokens, token => { |
| 50 | + if (this._usedTokens.has(token)) { |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + const found = _.find(this._corpra, corpus => corpus.contains(token)) |
| 55 | + if (found) { |
| 56 | + this._usedTokens.add(token) |
| 57 | + } |
| 58 | + |
| 59 | + return found |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +module.exports = CssParser |
0 commit comments