-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
368 lines (284 loc) · 10.4 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
const fs = require('fs')
const jsincss = require('jsincss')
const puppeteer = require('puppeteer')
module.exports = function(
plugins = {},
inputCSS = '',
outputJS = '',
outputCSS = ''
) {
plugins = Object.assign(
{
stylesheet: {},
rule: {}
},
plugins
)
return (async () => {
// Exit if no CSS input specified
if (!inputCSS || !fs.existsSync(inputCSS)) {
if (!inputCSS) {
console.error('Error: No CSS stylesheet filename specified as input')
}
if (inputCSS && !fs.existsSync(inputCSS)) {
console.error(`Error: File named "${inputCSS}" cannot be found`)
}
process.exit(1)
}
// Launch Chrome on the command-line via Puppeteer
const browser = await puppeteer.launch()
const page = await browser.newPage()
// Load CSS in a blank page in Chrome
await page.goto(`data:text/html,`, {waitUntil: 'networkidle2'})
await page.addStyleTag({content: fs.readFileSync(inputCSS).toString()})
// Parse CSSOM and separate CSS from JS-powered styles
const result = await page.evaluate(plugins => {
const output = {
plugins: {
stylesheet: {},
rule: {}
},
generic: [],
custom: [],
css: [],
errors: []
}
// For each stylesheet in the CSSOM
Array.from(document.styleSheets).forEach(stylesheet => {
// For each rule in the stylesheet
Array.from(stylesheet.cssRules).forEach(rule => {
// If JS-powered style rule
if (rule.type === 1 && rule.selectorText.includes('--')) {
// selector[]
const selector = /(.*)\[--.+\]/.test(rule.selectorText)
&& rule.selectorText.match(/(.*)\[--.+\]/)[1]
.replace(/([>~+])\s*$/, '$1 *')
|| '*'
// [plugin]
const plugin = rule.selectorText
.replace(/.*\[--([^=]+).*\]/, '$1')
.replace(/-([a-z])/g, (string, match) => match.toUpperCase())
// If we have a rule plugin with the same name
if (plugins.rule.includes(plugin)) {
// [="(args)"]
const args = /.*\[--.+="(.*)"\]/.test(rule.selectorText)
&& rule.selectorText.match(/.*\[--.+="(.*)"\]/)[1]
.replace(/\\"/g, '"')
+ ', '
|| ''
// { declarations }
const declarations = rule.cssText
.substring(rule.selectorText.length)
.trim()
.slice(1, -1)
.trim()
// Remember that this plugin has been used
output.plugins.rule[plugin] = 'used'
// If rule defines custom --selector and --events properties
if (
Array.from(rule.style).includes('--selector')
&& Array.from(rule.style).includes('--events')
) {
// Push a rule with custom events to output
output.custom.push(
'jsincss(event =>\n'
+ ' customStyleRule.' + plugin + '(\n'
+ ' `' + selector + '`,\n'
+ (
args.length
? ' ' + args + '\n'
: ''
)
+ ' `' + declarations + '`\n'
+ ' ),\n'
+ ' ' + rule.style.getPropertyValue('--selector').trim() + ',\n'
+ ' ' + rule.style.getPropertyValue('--events').trim() + '\n'
+ ')'
)
} else {
// Otherwise push a generic rule to output
output.generic.push(
'customStyleRule.' + plugin + '(\n'
+ ' `' + selector + '`,\n'
+ (
args.length
? ' ' + args + '\n'
: ''
)
+ ' `' + declarations + '`\n'
+ ')'
)
}
} else {
output.errors.push(`No rule plugin named "${plugin}"`)
output.css.push(rule.cssText)
}
// If JS-powered @supports rule
} else if (rule.type === 12 && rule.conditionText.includes('--')) {
// plugin()
const plugin = rule.conditionText
.replace(/\(*--([^(]+)\(.+\)\)*/, '$1')
.replace(/-([a-z])/g, (string, match) => match.toUpperCase())
// If we have an at-rule plugin with the same name
if (plugins.stylesheet.includes(plugin)) {
// (args)
const args = /--[^(]+(.*)/.test(rule.conditionText)
&& rule.conditionText
.replace(/^\((.+)\)$/g, '$1')
.replace(/^[^(]*\((.*)\)$/, '$1')
.trim()
+ ', '
|| ''
// { body }
const body = rule.cssText
.substring(`@supports `.length + rule.conditionText.length)
.trim()
.slice(1, -1)
// Remember that this plugin has been used
output.plugins.stylesheet[plugin] = 'used'
// If group body rule contains a top-level rule for [--options]
// And that rule contains custom --selector and --events properties
if (
Array.from(rule.cssRules).find(rule =>
rule.selectorText === '[--options]'
)
&& ['--selector', '--events'].every(prop =>
Array.from(rule.cssRules)
.reverse()
.find(rule => rule.selectorText === '[--options]')
.style
.getPropertyValue(prop) !== null
)
) {
const props = Array.from(rule.cssRules)
.reverse()
.find(rule => rule.selectorText === '[--options]')
.style
// Push a stylesheet with custom events to output
output.custom.push(
'jsincss(event =>\n'
+ ' customAtRule.' + plugin + '(\n'
+ (
args.length
? ' ' + args + '\n'
: ''
)
+ ' `\n'
+ ' ' + body.trim().replace(/\n/g, '\n ') + '\n'
+ ' `\n'
+ ' ),\n'
+ ' ' + props.getPropertyValue('--selector').trim() + ',\n'
+ ' ' + props.getPropertyValue('--events').trim() + '\n'
+ ')'
)
} else {
// Otherwise push a generic stylesheet to output
output.generic.push(
'customAtRule.' + plugin + '(\n'
+ (
args.length
? ' ' + args + '\n'
: ''
)
+ ' `\n'
+ ' ' + body.trim().replace(/\n/g, '\n ') + '\n'
+ ' `\n'
+ ')'
)
}
} else {
output.errors.push(`No stylesheet plugin named "${plugin}"`)
output.css.push(rule.cssText)
}
// Otherwise pass all non-JS-powered CSS rules through untouched to output
} else {
output.css.push(rule.cssText)
}
})
})
// Return all JS-powered rules, names of plugins used, and CSS
return output
},
{
stylesheet: Object.keys(plugins.stylesheet),
rule: Object.keys(plugins.rule)
})
// Log errors
result.errors.forEach(error => console.error(`Error: ${error}`))
// Create JavaScript file to output
let file = ''
// If there were plugins used
if (
Object.keys(result.plugins.stylesheet).length
|| Object.keys(result.plugins.rule).length
) {
// Add jsincss to JS file
file += '// jsincss\n'
+ `const jsincss = ${jsincss.toString()}\n`
+ '\n// jsincss plugins\n'
// Add any rule plugins used to JS file
if (Object.keys(result.plugins.stylesheet).length) {
file += 'const customAtRule = {}\n\n'
+ Object.keys(result.plugins.stylesheet)
.map(plugin => `customAtRule.${plugin} = ${plugins.stylesheet[plugin].toString()}`)
.join('\n')
+ '\n\n'
}
// Add any at-rule plugins used to JS file
if (Object.keys(result.plugins.rule).length) {
file += 'const customStyleRule = {}\n\n'
+ Object.keys(result.plugins.rule)
.map(plugin => `customStyleRule.${plugin} = ${plugins.rule[plugin].toString()}`)
.join('\n')
+ '\n\n'
}
}
// Add any generic rules to JS file
if (result.generic.length) {
file += '// JS-powered rules with default event listeners\n'
+ 'jsincss(event =>\n'
+' [\n'
+ ' ' + result.generic.join(',\n').replace(/\n/gm, '\n ') + '\n'
+ ' ].join(\'\')\n'
+ ')\n\n'
}
// Add rules with custom events to JS file
if (result.custom.length) {
file += '// JS-powered rules with custom event listeners\n'
+ result.custom.join('\n')
}
// Output CSS stylesheet
let renderedCSS = result.css.join('\n')
// If CSS output filename specified
if (outputCSS) {
// Write CSS file
fs.writeFileSync(outputCSS, renderedCSS)
} else {
// Otherwise add CSS styles to JS file
file += '\n\n// Original CSS\n'
+ 'const style = document.createElement(`style`)\n\n'
+ 'style.textContent = \`\n'
+ renderedCSS.replace(/`/g, '\`') + '\n`\n\n'
+ 'document.head.appendChild(style)'
}
// If JS output filename specified
if (outputJS) {
// Write JS file
fs.writeFileSync(outputJS, file)
} else {
// Otherwise output JS file to console
console.log(file)
}
// Close Chome
await browser.close()
})()
}
// If run from CLI with arguments
if (process.argv[2] && process.argv[3]) {
module.exports(
(require(process.argv[2]) || {}), // plugins filename
(process.argv[3] || ''), // input CSS filename
(process.argv[4] || ''), // output JS filename
(process.argv[5] || '') // output CSS filename
)
}