This repository has been archived by the owner on Apr 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
generateRules.js
278 lines (226 loc) · 7.48 KB
/
generateRules.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
const postcss = require('postcss')
const parseObjectStyles = require('tailwindcss/lib/util/parseObjectStyles').default
const { isPlainObject, bigSign } = require('./utils')
const selectorParser = require('postcss-selector-parser')
const prefixSelector = require('tailwindcss/lib/util/prefixSelector').default
let classNameParser = selectorParser((selectors) => {
return selectors.first.filter(({ type }) => type === 'class').pop().value
})
function getClassNameFromSelector(selector) {
return classNameParser.transformSync(selector)
}
// Generate match permutations for a class candidate, like:
// ['ring-offset-blue', '100']
// ['ring-offset', 'blue-100']
// ['ring', 'offset-blue-100']
function* candidatePermutations(candidate, lastIndex = Infinity) {
if (lastIndex < 0) {
return
}
let dashIdx
if (candidate.endsWith(']', lastIndex + 1)) {
dashIdx = candidate.lastIndexOf('[') - 1
} else {
dashIdx = candidate.lastIndexOf('-', lastIndex)
}
if (dashIdx < 0) {
return
}
let prefix = candidate.slice(0, dashIdx)
let modifier = candidate.slice(dashIdx + 1)
yield [prefix, modifier]
yield* candidatePermutations(candidate, dashIdx - 1)
}
function applyPrefix(matches, context) {
if (matches.length === 0 || context.tailwindConfig.prefix === '') {
return matches
}
for (let match of matches) {
let [meta] = match
if (meta.options.respectPrefix) {
let container = postcss.root({ nodes: [match[1]] })
container.walkRules((r) => {
r.selector = prefixSelector(context.tailwindConfig.prefix, r.selector)
})
match[1] = container.nodes[0]
}
}
return matches
}
// Takes a list of rule tuples and applies a variant like `hover`, sm`,
// whatever to it. We used to do some extra caching here to avoid generating
// a variant of the same rule more than once, but this was never hit because
// we cache at the entire selector level further up the tree.
//
// Technically you can get a cache hit if you have `hover:focus:text-center`
// and `focus:hover:text-center` in the same project, but it doesn't feel
// worth the complexity for that case.
function applyVariant(variant, matches, context) {
if (matches.length === 0) {
return matches
}
if (context.variantMap.has(variant)) {
let [variantSort, applyThisVariant] = context.variantMap.get(variant)
let result = []
for (let [{ sort, layer, options }, rule] of matches) {
if (options.respectVariants === false) {
result.push([{ sort, layer, options }, rule])
continue
}
let container = postcss.root({ nodes: [rule] })
function modifySelectors(modifierFunction) {
container.each((rule) => {
if (rule.type !== 'rule') {
return
}
rule.selectors = rule.selectors.map((selector) => {
return modifierFunction({
get className() {
return getClassNameFromSelector(selector)
},
selector,
})
})
})
return container
}
let ruleWithVariant = applyThisVariant({
container,
separator: context.tailwindConfig.separator,
modifySelectors,
})
if (ruleWithVariant === null) {
continue
}
let withOffset = [{ sort: variantSort | sort, layer, options }, container.nodes[0]]
result.push(withOffset)
}
return result
}
return []
}
function parseRules(rule, cache, options = {}) {
// PostCSS node
if (!isPlainObject(rule) && !Array.isArray(rule)) {
return [[rule], options]
}
// Tuple
if (Array.isArray(rule)) {
return parseRules(rule[0], cache, rule[1])
}
// Simple object
if (!cache.has(rule)) {
cache.set(rule, parseObjectStyles(rule))
}
return [cache.get(rule), options]
}
function* resolveMatchedPlugins(classCandidate, context) {
if (context.candidateRuleMap.has(classCandidate)) {
yield [context.candidateRuleMap.get(classCandidate), 'DEFAULT']
}
let candidatePrefix = classCandidate
let negative = false
const twConfigPrefix = context.tailwindConfig.prefix || ''
const twConfigPrefixLen = twConfigPrefix.length
if (candidatePrefix[twConfigPrefixLen] === '-') {
negative = true
candidatePrefix = twConfigPrefix + candidatePrefix.slice(twConfigPrefixLen + 1)
}
for (let [prefix, modifier] of candidatePermutations(candidatePrefix)) {
if (context.candidateRuleMap.has(prefix)) {
yield [context.candidateRuleMap.get(prefix), negative ? `-${modifier}` : modifier]
return
}
}
}
function sortAgainst(toSort, against) {
return toSort.slice().sort((a, z) => {
return bigSign(against.get(a)[0] - against.get(z)[0])
})
}
function* resolveMatches(candidate, context) {
let separator = context.tailwindConfig.separator
let [classCandidate, ...variants] = candidate.split(separator).reverse()
// Strip prefix
// md:hover:tw-bg-black
// TODO: Reintroduce this in ways that doesn't break on false positives
// let sorted = sortAgainst(variants, context.variantMap)
// if (sorted.toString() !== variants.toString()) {
// let corrected = sorted.reverse().concat(classCandidate).join(':')
// throw new Error(`Class ${candidate} should be written as ${corrected}`)
// }
for (let matchedPlugins of resolveMatchedPlugins(classCandidate, context)) {
let pluginHelpers = {
candidate: classCandidate,
theme: context.tailwindConfig.theme,
}
let matches = []
let [plugins, modifier] = matchedPlugins
for (let [sort, plugin] of plugins) {
if (typeof plugin === 'function') {
for (let ruleSet of [].concat(plugin(modifier, pluginHelpers))) {
let [rules, options] = parseRules(ruleSet, context.postCssNodeCache)
for (let rule of rules) {
matches.push([{ ...sort, options: { ...sort.options, ...options } }, rule])
}
}
}
// Only process static plugins on exact matches
else if (modifier === 'DEFAULT') {
let ruleSet = plugin
let [rules, options] = parseRules(ruleSet, context.postCssNodeCache)
for (let rule of rules) {
matches.push([{ ...sort, options: { ...sort.options, ...options } }, rule])
}
}
}
matches = applyPrefix(matches, context)
for (let variant of variants) {
matches = applyVariant(variant, matches, context)
}
for (let match of matches) {
yield match
}
}
}
function inKeyframes(d) {
return (
d.parent.parent && d.parent.parent.type === 'atrule' && d.parent.parent.name === 'keyframes'
)
}
function makeImportant(rule) {
rule.walkDecls((d) => {
if (d.parent.type === 'rule' && !inKeyframes(d)) {
d.important = true
}
})
}
function generateRules(candidates, context) {
let allRules = []
for (let candidate of candidates) {
if (context.notClassCache.has(candidate)) {
continue
}
if (context.classCache.has(candidate)) {
allRules.push(context.classCache.get(candidate))
continue
}
let matches = Array.from(resolveMatches(candidate, context))
if (matches.length === 0) {
context.notClassCache.add(candidate)
continue
}
context.classCache.set(candidate, matches)
allRules.push(matches)
}
return allRules.flat(1).map(([{ sort, layer, options }, rule]) => {
if (context.tailwindConfig.important === true && options.respectImportant) {
makeImportant(rule)
}
return [sort | context.layerOrder[layer], rule]
})
}
module.exports = {
resolveMatches,
generateRules,
}