-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
470 lines (395 loc) · 11.9 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// @ts-expect-error Typing of css-tree is incomplete
import parse from 'css-tree/parser'
const SPACE = ' '
const EMPTY_STRING = ''
const COLON = ':'
const SEMICOLON = ';'
const QUOTE = '"'
const OPEN_PARENTHESES = '('
const CLOSE_PARENTHESES = ')'
const OPEN_BRACKET = '['
const CLOSE_BRACKET = ']'
const TYPE_ATRULE = 'Atrule'
const TYPE_RULE = 'Rule'
const TYPE_BLOCK = 'Block'
const TYPE_SELECTORLIST = 'SelectorList'
const TYPE_SELECTOR = 'Selector'
const TYPE_DECLARATION = 'Declaration'
const TYPE_OPERATOR = 'Operator'
/** @param {string} str */
function lowercase(str) {
// Only create new strings in memory if we need to
if (/[A-Z]/.test(str)) {
return str.toLowerCase()
}
return str
}
/**
* @typedef {Object} Options
* @property {boolean} [minify] Whether to minify the CSS or keep it formatted
*
* Format a string of CSS using some simple rules
* @param {string} css The original CSS
* @param {Options} options
* @returns {string} The formatted CSS
*/
export function format(css, { minify = false } = {}) {
/** @type {import('css-tree').CssNode} */
let ast = parse(css, {
positions: true,
parseAtrulePrelude: false,
parseCustomProperty: true,
parseValue: true,
})
const NEWLINE = minify ? EMPTY_STRING : '\n'
const OPTIONAL_SPACE = minify ? EMPTY_STRING : SPACE
const LAST_SEMICOLON = minify ? EMPTY_STRING : SEMICOLON
let indent_level = 0
/**
* Indent a string
* @param {number} size
* @returns {string} A string with {size} tabs
*/
function indent(size) {
return minify ? EMPTY_STRING : '\t'.repeat(size)
}
/** @param {import('css-tree').CssNode} node */
function substr(node) {
let loc = node.loc
if (!loc) return EMPTY_STRING
return css.slice(loc.start.offset, loc.end.offset)
}
/** @param {import('css-tree').Rule} node */
function print_rule(node) {
let buffer
let prelude = node.prelude
let block = node.block
if (prelude.type === TYPE_SELECTORLIST) {
buffer = print_selectorlist(prelude)
}
if (block.type === TYPE_BLOCK) {
buffer += print_block(block)
}
return buffer
}
/** @param {import('css-tree').SelectorList} node */
function print_selectorlist(node) {
let buffer = EMPTY_STRING
node.children.forEach((selector, item) => {
if (selector.type === TYPE_SELECTOR) {
buffer += indent(indent_level) + print_simple_selector(selector)
}
if (item.next !== null) {
buffer += `,` + NEWLINE
}
})
return buffer
}
/** @param {import('css-tree').Selector|import('css-tree').PseudoClassSelector} node */
function print_simple_selector(node) {
let buffer = EMPTY_STRING
let children = node.children || []
children.forEach((child) => {
switch (child.type) {
case 'TypeSelector': {
buffer += lowercase(child.name)
break
}
case 'Combinator': {
// putting spaces around `child.name` (+ > ~ or ' '), unless the combinator is ' '
buffer += SPACE
if (child.name !== ' ') {
buffer += child.name + SPACE
}
break
}
case 'PseudoElementSelector': {
buffer += COLON + COLON
buffer += lowercase(child.name)
break
}
case 'PseudoClassSelector': {
buffer += COLON
// Special case for `:before` and `:after` which were used in CSS2 and are usually minified
// as `:before` and `:after`, but we want to print them as `::before` and `::after`
let pseudo = lowercase(child.name)
if (pseudo === 'before' || pseudo === 'after') {
buffer += COLON
}
buffer += pseudo
if (child.children) {
buffer += OPEN_PARENTHESES + print_simple_selector(child) + CLOSE_PARENTHESES
}
break
}
case TYPE_SELECTORLIST: {
child.children.forEach((grandchild, item) => {
if (grandchild.type === TYPE_SELECTOR) {
buffer += print_simple_selector(grandchild)
}
if (item.next) {
buffer += ',' + SPACE
}
})
break
}
case 'Nth': {
let nth = child.nth
if (nth) {
if (nth.type === 'AnPlusB') {
let a = nth.a
let b = nth.b
if (a !== null) {
buffer += a + 'n'
}
if (a !== null && b !== null) {
buffer += SPACE
}
if (b !== null) {
// When (1n + x) but not (1n - x)
if (a !== null && !b.startsWith('-')) {
buffer += '+' + SPACE
}
buffer += b
}
} else {
// For odd/even or maybe other identifiers later on
buffer += substr(nth)
}
}
if (child.selector !== null) {
// `of .selector`
// @ts-expect-error Typing of child.selector is SelectorList, which doesn't seem to be correct
buffer += SPACE + 'of' + SPACE + print_simple_selector(child.selector)
}
break
}
case 'AttributeSelector': {
buffer += OPEN_BRACKET
buffer += child.name.name
if (child.matcher && child.value) {
buffer += child.matcher
buffer += QUOTE
if (child.value.type === 'String') {
buffer += child.value.value
} else if (child.value.type === 'Identifier') {
buffer += child.value.name
}
buffer += QUOTE
}
if (child.flags) {
buffer += SPACE + child.flags
}
buffer += CLOSE_BRACKET
break
}
default: {
buffer += substr(child)
break
}
}
})
return buffer
}
/** @param {import('css-tree').Block} node */
function print_block(node) {
let children = node.children
let buffer = OPTIONAL_SPACE
if (children.isEmpty) {
return buffer + '{}'
}
buffer += '{' + NEWLINE
indent_level++
children.forEach((child, item) => {
if (child.type === TYPE_DECLARATION) {
buffer += print_declaration(child)
if (item.next === null) {
buffer += LAST_SEMICOLON
} else {
buffer += SEMICOLON
}
} else {
if (item.prev !== null && item.prev.data.type === TYPE_DECLARATION) {
buffer += NEWLINE
}
if (child.type === TYPE_RULE) {
buffer += print_rule(child)
} else if (child.type === TYPE_ATRULE) {
buffer += print_atrule(child)
} else {
buffer += print_unknown(child, indent_level)
}
}
if (item.next !== null) {
buffer += NEWLINE
if (child.type !== TYPE_DECLARATION) {
buffer += NEWLINE
}
}
})
indent_level--
buffer += NEWLINE
buffer += indent(indent_level) + '}'
return buffer
}
/** @param {import('css-tree').Atrule} node */
function print_atrule(node) {
let buffer = indent(indent_level) + '@'
let prelude = node.prelude
let block = node.block
buffer += lowercase(node.name)
// @font-face and anonymous @layer have no prelude
if (prelude !== null) {
buffer += SPACE + print_prelude(prelude)
}
if (block === null) {
// `@import url(style.css);` has no block, neither does `@layer layer1;`
buffer += SEMICOLON
} else if (block.type === TYPE_BLOCK) {
buffer += print_block(block)
}
return buffer
}
/**
* Pretty-printing atrule preludes takes an insane amount of rules,
* so we're opting for a couple of 'good-enough' string replacements
* here to force some nice formatting.
* Should be OK perf-wise, since the amount of atrules in most
* stylesheets are limited, so this won't be called too often.
* @param {import('css-tree').AtrulePrelude | import('css-tree').Raw} node
*/
function print_prelude(node) {
let buffer = substr(node)
return buffer
.replace(/\s*([:,])/g, buffer.toLowerCase().includes('selector(') ? '$1' : '$1 ') // force whitespace after colon or comma, except inside `selector()`
.replace(/\s*(=>|<=)\s*/g, ' $1 ') // force whitespace around => and <=
.replace(/\)([a-zA-Z])/g, ') $1') // force whitespace between closing parenthesis and following text (usually and|or)
.replace(/(?<!<=)(?<!=>)(?<!<= )([<>])(?![<= ])(?![=> ])(?![ =>])/g, ' $1 ')
.replace(/calc\(([^*]*)\*([^*])/g, 'calc($1 * $2') // force correct whitespace around * in calc()
.replace(/\s+/g, SPACE) // collapse multiple whitespaces into one
.replace(/selector|url|supports|layer\(/ig, (match) => lowercase(match)) // lowercase function names
}
/** @param {import('css-tree').Declaration} node */
function print_declaration(node) {
let property = node.property
// Lowercase the property, unless it's a custom property (starts with --)
if (!(property.charCodeAt(0) === 45 && property.charCodeAt(1) === 45)) {
// 45 == '-'
property = lowercase(property)
}
let value = print_value(node.value)
// Special case for `font` shorthand: remove whitespace around /
if (property === 'font') {
value = value.replace(/\s*\/\s*/, '/')
}
// Hacky: add a space in case of a `space toggle` during minification
if (value === EMPTY_STRING && minify) {
value += SPACE
}
return indent(indent_level) + property + COLON + OPTIONAL_SPACE + value
}
/** @param {import('css-tree').List<import('css-tree').CssNode>} children */
function print_list(children) {
let buffer = EMPTY_STRING
children.forEach((node, item) => {
if (node.type === 'Identifier') {
buffer += node.name
} else if (node.type === 'Function') {
buffer += lowercase(node.name) + OPEN_PARENTHESES + print_list(node.children) + CLOSE_PARENTHESES
} else if (node.type === 'Dimension') {
buffer += node.value + lowercase(node.unit)
} else if (node.type === 'Value') {
// Values can be inside var() as fallback
// var(--prop, VALUE)
buffer += print_value(node)
} else if (node.type === TYPE_OPERATOR) {
buffer += print_operator(node)
} else if (node.type === 'Parentheses') {
buffer += OPEN_PARENTHESES + print_list(node.children) + CLOSE_PARENTHESES
} else if (node.type === 'Url') {
buffer += 'url(' + QUOTE + node.value + QUOTE + CLOSE_PARENTHESES
} else {
buffer += substr(node)
}
// Add space after the item coming after an operator
if (node.type !== TYPE_OPERATOR) {
if (item.next !== null) {
if (item.next.data.type !== TYPE_OPERATOR) {
buffer += SPACE
}
}
}
})
return buffer
}
/** @param {import('css-tree').Operator} node */
function print_operator(node) {
let buffer = EMPTY_STRING
// https://developer.mozilla.org/en-US/docs/Web/CSS/calc#notes
// The + and - operators must be surrounded by whitespace
// Whitespace around other operators is optional
// Trim the operator because CSSTree adds whitespace around it
let operator = node.value.trim()
let code = operator.charCodeAt(0)
if (code === 43 || code === 45) {
// + or -
// Add required space before + and - operators
buffer += SPACE
} else if (code !== 44) {
// ,
// Add optional space before operator
buffer += OPTIONAL_SPACE
}
// FINALLY, render the operator
buffer += operator
if (code === 43 || code === 45) {
// + or -
// Add required space after + and - operators
buffer += SPACE
} else {
// Add optional space after other operators (like *, /, and ,)
buffer += OPTIONAL_SPACE
}
return buffer
}
/** @param {import('css-tree').Value | import('css-tree').Raw} node */
function print_value(node) {
if (node.type === 'Raw') {
return print_unknown(node, 0)
}
return print_list(node.children)
}
/**
* @param {import('css-tree').CssNode} node
* @param {number} indent_level
* @returns {string} A formatted unknown CSS string
*/
function print_unknown(node, indent_level) {
return indent(indent_level) + substr(node).trim()
}
/** @type {import('css-tree').List<import('css-tree').CssNode>} */
// @ts-expect-error Property 'children' does not exist on type 'AnPlusB', but we're never using that
let children = ast.children
let buffer = EMPTY_STRING
children.forEach((child, item) => {
if (child.type === TYPE_RULE) {
buffer += print_rule(child)
} else if (child.type === TYPE_ATRULE) {
buffer += print_atrule(child)
} else {
buffer += print_unknown(child, indent_level)
}
if (item.next !== null) {
buffer += NEWLINE + NEWLINE
}
})
return buffer
}
/**
* Minify a string of CSS
* @param {string} css The original CSS
* @returns {string} The minified CSS
*/
export function minify(css) {
return format(css, { minify: true })
}