forked from SE7ENSKY/group-css-media-queries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (92 loc) · 2.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
// Generated by CoffeeScript 1.10.0
(function() {
var parseCss, stringifyCss,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
parseCss = require('css-parse');
stringifyCss = require('css-stringify');
module.exports = function(css) {
var emToPxRatio, i, intervalRules, len, m, media, mediaRules, medias, onlyMaxRules, onlyMinRules, otherRules, parsed, ref, rootRules, rule, rules;
parsed = parseCss(css);
medias = {};
rootRules = [];
ref = parsed.stylesheet.rules;
for (i = 0, len = ref.length; i < len; i++) {
rule = ref[i];
if (rule.type === 'media') {
if (!medias[rule.media]) {
medias[rule.media] = [];
}
medias[rule.media] = medias[rule.media].concat(rule.rules);
} else {
rootRules.push(rule);
}
}
mediaRules = [];
for (media in medias) {
rules = medias[media];
rule = {
type: "media",
media: media,
rules: rules
};
if (media.indexOf("min-width") !== -1) {
m = media.match(/min-width\s*:\s*(\d+)(px|em)?/);
if (m && m[1]) {
rule.minWidth = parseInt(m[1]);
}
if (m[2]) {
rule.unit = m[2];
}
}
if (media.indexOf("max-width") !== -1) {
m = media.match(/max-width\s*:\s*(\d+)(px|em)?/);
if (m && m[1]) {
rule.maxWidth = parseInt(m[1]);
}
if (m[2]) {
rule.unit = m[2];
}
}
mediaRules.push(rule);
}
onlyMinRules = mediaRules.filter(function(rule) {
return (rule.minWidth != null) && (rule.maxWidth == null);
});
onlyMaxRules = mediaRules.filter(function(rule) {
return (rule.maxWidth != null) && (rule.minWidth == null);
});
intervalRules = mediaRules.filter(function(rule) {
return (rule.minWidth != null) && (rule.maxWidth != null);
});
otherRules = mediaRules.filter(function(rule) {
return indexOf.call(onlyMinRules.concat(onlyMaxRules).concat(intervalRules), rule) < 0;
});
emToPxRatio = 16;
onlyMinRules.sort(function(a, b) {
var aPxValue, bPxValue;
aPxValue = a.minWidth;
bPxValue = b.minWidth;
if (a.unit === 'em') {
aPxValue *= emToPxRatio;
}
if (b.unit === 'em') {
bPxValue *= emToPxRatio;
}
return aPxValue - bPxValue;
});
onlyMaxRules.sort(function(a, b) {
var aPxValue, bPxValue;
aPxValue = a.maxWidth;
bPxValue = b.maxWidth;
if (a.unit === 'em') {
aPxValue *= emToPxRatio;
}
if (b.unit === 'em') {
bPxValue *= emToPxRatio;
}
return bPxValue - aPxValue;
});
parsed.stylesheet.rules = rootRules.concat(onlyMinRules).concat(onlyMaxRules).concat(intervalRules).concat(otherRules);
return stringifyCss(parsed);
};
}).call(this);