-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
105 lines (87 loc) · 2.65 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
const fs = require('fs');
const postcss = require('postcss')
const yaml = require('js-yaml')
function checkMultipliers(multipliers) {
if (typeof multipliers === 'undefined') {
multipliers = ['1x'];
} else if (!multipliers.includes('1x')) {
multipliers.unshift('1x');
}
return multipliers;
}
function getMappedGroupsList(fileContent, themeName) {
const items = Object.keys(fileContent);
const allGroups = items.map(item => {
if (typeof fileContent[item].group === 'undefined') {
return themeName;
}
return fileContent[item].group;
});
const uniqueGroups = [...new Set(allGroups)];
const groups = new Map();
uniqueGroups.forEach(group => {
let queriesByGroup;
if (group === themeName) {
queriesByGroup = items.filter(item => {
return (
typeof fileContent[item].group === 'undefined' ||
fileContent[item].group === themeName
);
});
} else {
queriesByGroup = items.filter(item => fileContent[item].group === group);
}
groups.set(group, queriesByGroup);
});
return groups;
}
function getBreakpointsByGroupsList(groups, fileContent) {
const output = {};
groups.forEach((breakpoints, group) => {
group = group.replace('.', '_');
output[group] = {};
breakpoints.forEach(bp => {
const breakpoint = fileContent[bp];
const multipliers = checkMultipliers(breakpoint.multipliers);
const breakpointLabel = breakpoint.label
.replace(/\s+/g, '_')
.toLowerCase();
multipliers.forEach(mp => {
const multiplier = mp ? `_${mp}` : '';
output[group][breakpointLabel + multiplier] = generateQuery(
breakpoint,
mp === '1x' ? null : mp,
);
});
});
});
return output;
}
function generateQuery(breakpoint, multiplier) {
const resQuery = multiplier ? xToResolution(multiplier) : '';
return breakpoint.mediaQuery + resQuery;
}
function xToResolution(mp) {
return ` and (min-resolution: ${parseInt(mp)}dppx)`;
}
module.exports = postcss.plugin('postcss-drupal-breakpoints', function (opts) {
opts = opts || {}
const importFrom = opts.importFrom
const themeName = opts.themeName
try {
const doc = yaml.safeLoad(fs.readFileSync(importFrom))
const groups = getMappedGroupsList(doc, themeName)
const breakpoints = getBreakpointsByGroupsList(groups, doc);
return function (root) {
root.walkAtRules(atRule => {
if (atRule.name === 'drupal-breakpoint') {
const media = breakpoints[themeName][atRule.params]
atRule.name = 'media'
atRule.params = media
}
})
}
} catch (e) {
console.log(e);
}
})