-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
75 lines (60 loc) · 1.75 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
function sortAtRules(queries, sort, sortCSSmq) {
if (typeof sort !== 'function') {
sort = sort === 'desktop-first' ? sortCSSmq.desktopFirst : sortCSSmq
}
return queries.sort(sort)
}
module.exports = (opts = {}) => {
opts = Object.assign(
{
sort: 'mobile-first',
configuration: false,
onlyTopLevel: false,
},
opts
)
const createSort = require('sort-css-media-queries/lib/create-sort');
const sortCSSmq = opts.configuration ? createSort(opts.configuration) : require('sort-css-media-queries');
return {
postcssPlugin: 'postcss-sort-media-queries',
OnceExit (root, { AtRule }) {
let atRules = [];
root.walkAtRules('media', atRule => {
if (opts.onlyTopLevel && atRule.parent.type === 'root') {
let query = atRule.params
if (!atRules[query]) {
atRules[query] = new AtRule({
name: atRule.name,
params: atRule.params,
source: atRule.source
})
}
atRule.nodes.forEach(node => {
atRules[query].append(node.clone())
})
atRule.remove()
}
if (!opts.onlyTopLevel) {
let query = atRule.params
if (!atRules[query]) {
atRules[query] = new AtRule({
name: atRule.name,
params: atRule.params,
source: atRule.source
})
}
atRule.nodes.forEach(node => {
atRules[query].append(node.clone())
})
atRule.remove()
}
})
if (atRules) {
sortAtRules(Object.keys(atRules), opts.sort, sortCSSmq).forEach(query => {
root.append(atRules[query])
})
}
}
}
}
module.exports.postcss = true