-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
215 lines (195 loc) · 5.59 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
'use strict'
const cheerio = require('cheerio')
const postcss = require('postcss')
const fs = require('fs')
const path = require('path')
const globby = require('globby')
const mkdirp = require('mkdirp')
require('es6-promise').polyfill()
require('isomorphic-fetch')
const defaultOptions = require('./defaultOptions')
const DELIMITER = ' || '
function cssRazor (options, callback) {
let ignoreList = []
if (typeof options.ignore === 'undefined') {
ignoreList = defaultOptions.ignore.concat(options.ignore)
}
options = Object.assign({}, defaultOptions, options)
options.ignore = ignoreList
if (!((options.htmlRaw || options.html.length || options.webpages.length) && (options.cssRaw || options.css.length))) {
throw new Error('You must include HTML and CSS for input.')
}
const p = new Promise(function (resolve, reject) {
let htmlRaw = options.htmlRaw
let cssRaw = options.cssRaw
Promise.all([
globby(options.html),
globby(options.css)
]).then((pathsArray) => {
const htmlFiles = pathsArray[0]
const cssFiles = pathsArray[1]
getTextFromUrls(options.webpages, (webHtml) =>
getTextFromFiles(htmlFiles, (html) =>
getTextFromFiles(cssFiles, (css) => {
// TODO: Is there a better way to do this. I'd rather not nest it
// but I don't want to pass more args either.
function processInput (html, css) {
const outputFile = options.overwriteCss
? cssFiles[0]
: options.outputFile
postcss([
postcssRazor({
html: html,
ignore: options.ignore,
report: options.report
})
])
.process(css, {
from: options.inputCss,
to: outputFile
})
.then((result) => {
if (outputFile) {
// Make sure the directory exists first.
mkdirp(path.dirname(outputFile), (err, d1) => {
if (err) {
return reject(err)
}
fs.writeFile(outputFile, result.css, (err, d2) => {
if (err) {
return reject(err)
}
resolve(result)
})
})
} else {
resolve(result)
}
})
.catch((e) => {
reject(e)
})
}
return processInput(html + htmlRaw + webHtml, css + cssRaw)
})
)
)
})
})
// Enable callback support too.
if (callback) {
p.then((result) => {
callback(null, result)
}).catch(err => callback(err))
}
return p
}
const postcssRazor = postcss.plugin('postcss-razor', (opt) => {
const html = opt.html
let keepCount = 0
let keepSelectors = ''
let removeCount = 0
let removeSelectors = ''
return (root) => {
const $ = cheerio.load(html)
root.walk((node) => {
if (node.type === 'rule') {
const exists = checkExists(node, $)
const ignore = opt.ignore.some((ignore) => {
return node.selector.indexOf(ignore) !== -1
})
if (!exists && !ignore) {
node.remove()
removeSelectors += node.selector + DELIMITER
removeCount++
} else {
keepSelectors += node.selector + DELIMITER
keepCount++
}
}
})
// Remove empty media queries.
root.walkAtRules((rule) => {
if (typeof rule.nodes === 'undefined' || rule.nodes.length === 0) {
rule.remove()
}
})
if (opt.report) {
const percent = ((removeCount / (keepCount + removeCount)) * 100).toFixed()
console.log(' Selectors kept: ' + keepCount)
console.log('Selectors removed: ' + removeCount)
console.log(' Percent removed: ' + percent + '%')
console.log(' ')
if (opt.reportDetails) {
console.log('Removed selectors: ' + removeSelectors)
console.log(' ')
console.log(' Kept selectors: ' + keepSelectors)
}
}
}
})
function getTextFromFiles (files, cb) {
let text = ''
if (files.length) {
files.forEach((file, i) => {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err)
}
text += data.toString()
if (i === files.length - 1) {
cb(text)
}
})
})
} else {
cb(text)
}
}
function getTextFromUrls (urls, cb) {
let text = ''
if (urls.length) {
urls.forEach((file, i) => {
fetch(file).then(function (response) {
if (response.status >= 400) {
throw new Error('Bad response from server')
}
return response.text()
}).then(function (responseText) {
text += responseText
if (i === urls.length - 1) {
cb(text)
}
})
})
} else {
cb(text)
}
}
function checkExists (node, $) {
// Right now this try is needed because cheerio doesn't handle `pseudo-element` well.
// See: https://github.com/cheeriojs/cheerio/issues/979
try {
return $(removePseudoClasses(node.selector)).length > 0
} catch (e) {
return true
}
}
function removePseudoClasses (selector) {
return [
':active',
':focus',
':hover',
':visited',
'::before',
':before',
'::after',
':after'
].reduce((p, c) => {
return p.split(c).join('')
}, selector)
}
module.exports = {
default: cssRazor,
postcss: postcssRazor
}