-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
166 lines (130 loc) · 3.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
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
const path = require('path')
const { readFileSync } = require('fs')
var log = require('loglevel').getLogger('postcss-each-map')
const SEPARATOR = /\s+in\s+/
function checkParams (params) {
if (!SEPARATOR.test(params)) return 'Missed "in" keyword in @each-in-map'
const [names, map] = params.split(SEPARATOR).map(str => str.trim())
if (!names.match(/\$[_a-zA-Z]?\w+/)) return 'Missed variable names in @each-in-map'
if (!map.match(/(\w+\s?)+/)) return 'Missed map in @each-in-map'
return null
}
function tokenize (str, helpers) {
return helpers.postcss.list.comma(str).map(str => str.replace(/^\$/, ''))
}
function paramsList (params, helpers) {
const [names, map] = params.split(SEPARATOR).map(param => tokenize(param, helpers))
return {
names,
keyName: names[0],
valNames: names.slice(1),
map
}
}
function keysVals (map, numVals) {
log.debug('keysVals', map, numVals)
const keys =
Object.keys(map).flatMap(key => {
let length = 1
if (typeof (map[key]) === 'object' && Array.isArray(map[key])) {
length = map[key].length - (numVals - 1)
}
return Array(length).fill(key)
})
const vals = [Object.values(map)]
return {
keys,
vals
}
}
// [[1, 2, 3], [4, 5, 6], 7] -> [[1, 4, 7], [2, 5], [3, 6]]
function keysValsForDestructuring (map, numVals) {
log.debug('keysValsForDestructuring', map, numVals)
const keys = Object.keys(map)
const vals = Array.from(Array(numVals), () => new Array())
Object.values(map).forEach(value => {
if (typeof (value) === 'object' && Array.isArray(value)) {
value.forEach((v, i) => {
if (i < numVals) {
vals[i].push(v)
}
})
} else {
vals[0].push(value)
}
})
return {
keys,
vals
}
}
function valsAsString (vals) {
return vals.map(v => {
if (typeof v === 'object' && Array.isArray(v)) {
return `(${v.flat().join(', ')})`
}
return `(${v})`
}).join(', ')
}
function processRules (rule, params, helpers, maps) {
log.debug('processRules', params)
const map = maps[params.map[0]]
const numVals = params.valNames.length
if (numVals > 1) {
var { keys, vals } = keysValsForDestructuring(map, numVals)
} else {
var { keys, vals } = keysVals(map, numVals)
}
log.debug('(processRules) keys:', keys)
log.debug('(processRules) vals:', vals)
log.debug('(processRules) valsAsString:', valsAsString(vals))
const atRule = helpers.postcss.atRule({
name: 'each',
params: `${params.names.map(param => `$${param}`).join(', ')} in (${keys.join(', ')}), ${valsAsString(vals)}`,
source: rule.source
})
log.info(atRule.toString())
atRule.append(rule.nodes)
rule.replaceWith(atRule)
}
function eachInMap (rule, helpers, maps) {
log.debug('eachInMap', rule.params)
const params = ` ${rule.params} `
const error = checkParams(params)
if (error) throw rule.error(error)
const parsedParams = paramsList(params, helpers)
processRules(rule, parsedParams, helpers, maps)
rule.remove()
}
/**
* @type {import('postcss').PluginCreator}
*/
module.exports = (opts = {}) => {
opts = {
basePath: process.cwd(),
jsonPath: 'maps.json',
logLevel: 'warn',
...opts
}
log.setLevel(opts.logLevel)
if (!path.isAbsolute(opts.basePath)) {
opts.basePath = path.join(process.cwd(), opts.basePath)
}
opts.jsonPath = path.resolve(opts.basePath, opts.jsonPath)
log.debug('opts', opts)
let maps = {}
return {
postcssPlugin: 'postcss-each-in-map',
Once (root) {
const content = readFileSync(opts.jsonPath)
maps = JSON.parse(content)
log.debug('Loaded maps:', maps)
},
AtRule: {
'each-in-map': (node, helpers) => {
eachInMap(node, helpers, maps)
}
}
}
}
module.exports.postcss = true