tailwindcss 0.0.0-insiders.7b94fea → 0.0.0-insiders.7d8eb21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/CHANGELOG.md +588 -3
  2. package/LICENSE +1 -2
  3. package/README.md +15 -7
  4. package/colors.d.ts +3 -0
  5. package/colors.js +2 -1
  6. package/defaultConfig.d.ts +3 -0
  7. package/defaultConfig.js +2 -1
  8. package/defaultTheme.d.ts +4 -0
  9. package/defaultTheme.js +2 -1
  10. package/lib/cli/build/deps.js +54 -0
  11. package/lib/cli/build/index.js +48 -0
  12. package/lib/cli/build/plugin.js +362 -0
  13. package/lib/cli/build/utils.js +78 -0
  14. package/lib/cli/build/watching.js +178 -0
  15. package/lib/cli/help/index.js +71 -0
  16. package/lib/cli/index.js +18 -0
  17. package/lib/cli/init/index.js +46 -0
  18. package/lib/cli/shared.js +12 -0
  19. package/lib/cli-peer-dependencies.js +20 -7
  20. package/lib/cli.js +108 -571
  21. package/lib/constants.js +27 -20
  22. package/lib/corePluginList.js +15 -4
  23. package/lib/corePlugins.js +2229 -1868
  24. package/lib/css/preflight.css +22 -9
  25. package/lib/featureFlags.js +39 -25
  26. package/lib/index.js +28 -12
  27. package/lib/lib/cacheInvalidation.js +90 -0
  28. package/lib/lib/collapseAdjacentRules.js +28 -10
  29. package/lib/lib/collapseDuplicateDeclarations.js +83 -0
  30. package/lib/lib/content.js +177 -0
  31. package/lib/lib/defaultExtractor.js +241 -0
  32. package/lib/lib/detectNesting.js +27 -3
  33. package/lib/lib/evaluateTailwindFunctions.js +117 -50
  34. package/lib/lib/expandApplyAtRules.js +457 -159
  35. package/lib/lib/expandTailwindAtRules.js +130 -127
  36. package/lib/lib/findAtConfigPath.js +44 -0
  37. package/lib/lib/generateRules.js +610 -141
  38. package/lib/lib/getModuleDependencies.js +11 -8
  39. package/lib/lib/normalizeTailwindDirectives.js +43 -32
  40. package/lib/lib/offsets.js +285 -0
  41. package/lib/lib/partitionApplyAtRules.js +56 -0
  42. package/lib/lib/regex.js +60 -0
  43. package/lib/lib/remap-bitfield.js +87 -0
  44. package/lib/lib/resolveDefaultsAtRules.js +114 -81
  45. package/lib/lib/setupContextUtils.js +718 -323
  46. package/lib/lib/setupTrackingContext.js +43 -71
  47. package/lib/lib/sharedState.js +50 -9
  48. package/lib/lib/substituteScreenAtRules.js +13 -8
  49. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  50. package/lib/postcss-plugins/nesting/index.js +19 -0
  51. package/lib/postcss-plugins/nesting/plugin.js +87 -0
  52. package/lib/processTailwindFeatures.js +36 -21
  53. package/lib/public/colors.js +247 -245
  54. package/lib/public/create-plugin.js +6 -4
  55. package/lib/public/default-config.js +7 -5
  56. package/lib/public/default-theme.js +7 -5
  57. package/lib/public/resolve-config.js +8 -5
  58. package/lib/util/bigSign.js +4 -1
  59. package/lib/util/buildMediaQuery.js +18 -24
  60. package/lib/util/cloneDeep.js +7 -6
  61. package/lib/util/cloneNodes.js +21 -3
  62. package/lib/util/color.js +54 -40
  63. package/lib/util/configurePlugins.js +5 -2
  64. package/lib/util/createPlugin.js +6 -6
  65. package/lib/util/createUtilityPlugin.js +12 -14
  66. package/lib/util/dataTypes.js +164 -100
  67. package/lib/util/defaults.js +12 -3
  68. package/lib/util/escapeClassName.js +9 -6
  69. package/lib/util/escapeCommas.js +5 -2
  70. package/lib/util/flattenColorPalette.js +9 -12
  71. package/lib/util/formatVariantSelector.js +353 -0
  72. package/lib/util/getAllConfigs.js +29 -10
  73. package/lib/util/hashConfig.js +6 -3
  74. package/lib/util/isKeyframeRule.js +5 -2
  75. package/lib/util/isPlainObject.js +5 -2
  76. package/lib/util/isSyntacticallyValidPropertyValue.js +72 -0
  77. package/lib/util/log.js +22 -12
  78. package/lib/util/nameClass.js +20 -8
  79. package/lib/util/negateValue.js +23 -6
  80. package/lib/util/normalizeConfig.js +147 -60
  81. package/lib/util/normalizeScreens.js +170 -0
  82. package/lib/util/parseAnimationValue.js +42 -40
  83. package/lib/util/parseBoxShadowValue.js +84 -0
  84. package/lib/util/parseDependency.js +38 -56
  85. package/lib/util/parseGlob.js +34 -0
  86. package/lib/util/parseObjectStyles.js +11 -8
  87. package/lib/util/pluginUtils.js +182 -181
  88. package/lib/util/prefixSelector.js +27 -13
  89. package/lib/util/removeAlphaVariables.js +29 -0
  90. package/lib/util/resolveConfig.js +97 -73
  91. package/lib/util/resolveConfigPath.js +11 -9
  92. package/lib/util/responsive.js +8 -5
  93. package/lib/util/splitAtTopLevelOnly.js +43 -0
  94. package/lib/util/tap.js +4 -1
  95. package/lib/util/toColorValue.js +5 -3
  96. package/lib/util/toPath.js +24 -3
  97. package/lib/util/transformThemeValue.js +49 -31
  98. package/lib/util/validateConfig.js +24 -0
  99. package/lib/util/validateFormalSyntax.js +24 -0
  100. package/lib/util/withAlphaVariable.js +23 -15
  101. package/nesting/index.js +2 -12
  102. package/package.json +51 -50
  103. package/peers/index.js +15019 -12583
  104. package/plugin.d.ts +11 -0
  105. package/plugin.js +2 -1
  106. package/resolveConfig.d.ts +12 -0
  107. package/resolveConfig.js +2 -1
  108. package/scripts/generate-types.js +105 -0
  109. package/scripts/release-channel.js +18 -0
  110. package/scripts/release-notes.js +21 -0
  111. package/scripts/type-utils.js +27 -0
  112. package/src/cli/build/deps.js +56 -0
  113. package/src/cli/build/index.js +49 -0
  114. package/src/cli/build/plugin.js +434 -0
  115. package/src/cli/build/utils.js +76 -0
  116. package/src/cli/build/watching.js +227 -0
  117. package/src/cli/help/index.js +70 -0
  118. package/src/cli/index.js +3 -0
  119. package/src/cli/init/index.js +50 -0
  120. package/src/cli/shared.js +5 -0
  121. package/src/cli-peer-dependencies.js +7 -1
  122. package/src/cli.js +50 -577
  123. package/src/corePluginList.js +1 -1
  124. package/src/corePlugins.js +886 -598
  125. package/src/css/preflight.css +22 -9
  126. package/src/featureFlags.js +24 -8
  127. package/src/index.js +19 -6
  128. package/src/lib/cacheInvalidation.js +52 -0
  129. package/src/lib/collapseAdjacentRules.js +21 -2
  130. package/src/lib/collapseDuplicateDeclarations.js +93 -0
  131. package/src/lib/content.js +213 -0
  132. package/src/lib/defaultExtractor.js +217 -0
  133. package/src/lib/detectNesting.js +30 -3
  134. package/src/lib/evaluateTailwindFunctions.js +84 -10
  135. package/src/lib/expandApplyAtRules.js +508 -153
  136. package/src/lib/expandTailwindAtRules.js +82 -79
  137. package/src/lib/findAtConfigPath.js +48 -0
  138. package/src/lib/generateRules.js +625 -111
  139. package/src/lib/normalizeTailwindDirectives.js +7 -1
  140. package/src/lib/offsets.js +351 -0
  141. package/src/lib/partitionApplyAtRules.js +52 -0
  142. package/src/lib/regex.js +74 -0
  143. package/src/lib/remap-bitfield.js +82 -0
  144. package/src/lib/resolveDefaultsAtRules.js +98 -60
  145. package/src/lib/setupContextUtils.js +666 -168
  146. package/src/lib/setupTrackingContext.js +16 -52
  147. package/src/lib/sharedState.js +44 -4
  148. package/src/lib/substituteScreenAtRules.js +6 -3
  149. package/src/postcss-plugins/nesting/README.md +42 -0
  150. package/src/postcss-plugins/nesting/index.js +13 -0
  151. package/src/postcss-plugins/nesting/plugin.js +80 -0
  152. package/src/processTailwindFeatures.js +17 -2
  153. package/src/util/buildMediaQuery.js +14 -16
  154. package/src/util/cloneNodes.js +19 -2
  155. package/src/util/color.js +31 -14
  156. package/src/util/createUtilityPlugin.js +2 -2
  157. package/src/util/dataTypes.js +86 -21
  158. package/src/util/defaults.js +6 -0
  159. package/src/util/formatVariantSelector.js +412 -0
  160. package/src/util/getAllConfigs.js +19 -0
  161. package/src/util/isSyntacticallyValidPropertyValue.js +61 -0
  162. package/src/util/log.js +11 -7
  163. package/src/util/nameClass.js +6 -2
  164. package/src/util/negateValue.js +14 -4
  165. package/src/util/normalizeConfig.js +72 -5
  166. package/src/util/normalizeScreens.js +140 -0
  167. package/src/util/parseBoxShadowValue.js +72 -0
  168. package/src/util/parseDependency.js +37 -42
  169. package/src/util/parseGlob.js +24 -0
  170. package/src/util/pluginUtils.js +169 -143
  171. package/src/util/prefixSelector.js +30 -13
  172. package/src/util/removeAlphaVariables.js +24 -0
  173. package/src/util/resolveConfig.js +81 -27
  174. package/src/util/splitAtTopLevelOnly.js +45 -0
  175. package/src/util/toPath.js +23 -1
  176. package/src/util/transformThemeValue.js +33 -8
  177. package/src/util/validateConfig.js +13 -0
  178. package/src/util/validateFormalSyntax.js +34 -0
  179. package/src/util/withAlphaVariable.js +1 -1
  180. package/stubs/defaultConfig.stub.js +246 -213
  181. package/stubs/simpleConfig.stub.js +1 -0
  182. package/types/config.d.ts +363 -0
  183. package/types/generated/.gitkeep +0 -0
  184. package/types/generated/colors.d.ts +276 -0
  185. package/types/generated/corePluginList.d.ts +1 -0
  186. package/types/generated/default-theme.d.ts +342 -0
  187. package/types/index.d.ts +7 -0
  188. package/lib/lib/setupWatchingContext.js +0 -284
  189. package/nesting/plugin.js +0 -41
  190. package/src/lib/setupWatchingContext.js +0 -304
@@ -3,14 +3,22 @@ import selectorParser from 'postcss-selector-parser'
3
3
  import parseObjectStyles from '../util/parseObjectStyles'
4
4
  import isPlainObject from '../util/isPlainObject'
5
5
  import prefixSelector from '../util/prefixSelector'
6
- import { updateAllClasses } from '../util/pluginUtils'
6
+ import { updateAllClasses, filterSelectorsForClass, getMatchingTypes } from '../util/pluginUtils'
7
7
  import log from '../util/log'
8
+ import * as sharedState from './sharedState'
9
+ import { formatVariantSelector, finalizeSelector } from '../util/formatVariantSelector'
10
+ import { asClass } from '../util/nameClass'
11
+ import { normalize } from '../util/dataTypes'
12
+ import { isValidVariantFormatString, parseVariant } from './setupContextUtils'
13
+ import isValidArbitraryValue from '../util/isSyntacticallyValidPropertyValue'
14
+ import { splitAtTopLevelOnly } from '../util/splitAtTopLevelOnly.js'
15
+ import { flagEnabled } from '../featureFlags'
8
16
 
9
17
  let classNameParser = selectorParser((selectors) => {
10
18
  return selectors.first.filter(({ type }) => type === 'class').pop().value
11
19
  })
12
20
 
13
- function getClassNameFromSelector(selector) {
21
+ export function getClassNameFromSelector(selector) {
14
22
  return classNameParser.transformSync(selector)
15
23
  }
16
24
 
@@ -21,33 +29,49 @@ function getClassNameFromSelector(selector) {
21
29
  // Example with dynamic classes:
22
30
  // ['grid-cols', '[[linename],1fr,auto]']
23
31
  // ['grid', 'cols-[[linename],1fr,auto]']
24
- function* candidatePermutations(candidate, lastIndex = Infinity) {
25
- if (lastIndex < 0) {
26
- return
27
- }
28
-
29
- let dashIdx
30
-
31
- if (lastIndex === Infinity && candidate.endsWith(']')) {
32
- let bracketIdx = candidate.indexOf('[')
32
+ function* candidatePermutations(candidate) {
33
+ let lastIndex = Infinity
34
+
35
+ while (lastIndex >= 0) {
36
+ let dashIdx
37
+ let wasSlash = false
38
+
39
+ if (lastIndex === Infinity && candidate.endsWith(']')) {
40
+ let bracketIdx = candidate.indexOf('[')
41
+
42
+ // If character before `[` isn't a dash or a slash, this isn't a dynamic class
43
+ // eg. string[]
44
+ if (candidate[bracketIdx - 1] === '-') {
45
+ dashIdx = bracketIdx - 1
46
+ } else if (candidate[bracketIdx - 1] === '/') {
47
+ dashIdx = bracketIdx - 1
48
+ wasSlash = true
49
+ } else {
50
+ dashIdx = -1
51
+ }
52
+ } else if (lastIndex === Infinity && candidate.includes('/')) {
53
+ dashIdx = candidate.lastIndexOf('/')
54
+ wasSlash = true
55
+ } else {
56
+ dashIdx = candidate.lastIndexOf('-', lastIndex)
57
+ }
33
58
 
34
- // If character before `[` isn't a dash or a slash, this isn't a dynamic class
35
- // eg. string[]
36
- dashIdx = ['-', '/'].includes(candidate[bracketIdx - 1]) ? bracketIdx - 1 : -1
37
- } else {
38
- dashIdx = candidate.lastIndexOf('-', lastIndex)
39
- }
59
+ if (dashIdx < 0) {
60
+ break
61
+ }
40
62
 
41
- if (dashIdx < 0) {
42
- return
43
- }
63
+ let prefix = candidate.slice(0, dashIdx)
64
+ let modifier = candidate.slice(wasSlash ? dashIdx : dashIdx + 1)
44
65
 
45
- let prefix = candidate.slice(0, dashIdx)
46
- let modifier = candidate.slice(dashIdx + 1)
66
+ lastIndex = dashIdx - 1
47
67
 
48
- yield [prefix, modifier]
68
+ // TODO: This feels a bit hacky
69
+ if (prefix === '' || modifier === '/') {
70
+ continue
71
+ }
49
72
 
50
- yield* candidatePermutations(candidate, dashIdx - 1)
73
+ yield [prefix, modifier]
74
+ }
51
75
  }
52
76
 
53
77
  function applyPrefix(matches, context) {
@@ -59,9 +83,23 @@ function applyPrefix(matches, context) {
59
83
  let [meta] = match
60
84
  if (meta.options.respectPrefix) {
61
85
  let container = postcss.root({ nodes: [match[1].clone()] })
86
+ let classCandidate = match[1].raws.tailwind.classCandidate
87
+
62
88
  container.walkRules((r) => {
63
- r.selector = prefixSelector(context.tailwindConfig.prefix, r.selector)
89
+ // If this is a negative utility with a dash *before* the prefix we
90
+ // have to ensure that the generated selector matches the candidate
91
+
92
+ // Not doing this will cause `-tw-top-1` to generate the class `.tw--top-1`
93
+ // The disconnect between candidate <-> class can cause @apply to hard crash.
94
+ let shouldPrependNegative = classCandidate.startsWith('-')
95
+
96
+ r.selector = prefixSelector(
97
+ context.tailwindConfig.prefix,
98
+ r.selector,
99
+ shouldPrependNegative
100
+ )
64
101
  })
102
+
65
103
  match[1] = container.nodes[0]
66
104
  }
67
105
  }
@@ -69,7 +107,7 @@ function applyPrefix(matches, context) {
69
107
  return matches
70
108
  }
71
109
 
72
- function applyImportant(matches) {
110
+ function applyImportant(matches, classCandidate) {
73
111
  if (matches.length === 0) {
74
112
  return matches
75
113
  }
@@ -78,9 +116,15 @@ function applyImportant(matches) {
78
116
  for (let [meta, rule] of matches) {
79
117
  let container = postcss.root({ nodes: [rule.clone()] })
80
118
  container.walkRules((r) => {
81
- r.selector = updateAllClasses(r.selector, (className) => {
82
- return `!${className}`
83
- })
119
+ r.selector = updateAllClasses(
120
+ filterSelectorsForClass(r.selector, classCandidate),
121
+ (className) => {
122
+ if (className === classCandidate) {
123
+ return `!${className}`
124
+ }
125
+ return className
126
+ }
127
+ )
84
128
  r.walkDecls((d) => (d.important = true))
85
129
  })
86
130
  result.push([{ ...meta, important: true }, container.nodes[0]])
@@ -103,16 +147,87 @@ function applyVariant(variant, matches, context) {
103
147
  return matches
104
148
  }
105
149
 
150
+ /** @type {{modifier: string | null, value: string | null}} */
151
+ let args = { modifier: null, value: sharedState.NONE }
152
+
153
+ // Retrieve "modifier"
154
+ {
155
+ let match = /(.*)\/(.*)$/g.exec(variant)
156
+ if (match) {
157
+ variant = match[1]
158
+ args.modifier = match[2]
159
+
160
+ if (!flagEnabled(context.tailwindConfig, 'generalizedModifiers')) {
161
+ return []
162
+ }
163
+ }
164
+ }
165
+
166
+ // Retrieve "arbitrary value"
167
+ if (variant.endsWith(']') && !variant.startsWith('[')) {
168
+ // We either have:
169
+ // @[200px]
170
+ // group-[:hover]
171
+ //
172
+ // But we don't want:
173
+ // @-[200px] (`-` is incorrect)
174
+ // group[:hover] (`-` is missing)
175
+ let match = /(.)(-?)\[(.*)\]/g.exec(variant)
176
+ if (match) {
177
+ let [, char, seperator, value] = match
178
+ // @-[200px] case
179
+ if (char === '@' && seperator === '-') return []
180
+ // group[:hover] case
181
+ if (char !== '@' && seperator === '') return []
182
+
183
+ variant = variant.replace(`${seperator}[${value}]`, '')
184
+ args.value = value
185
+ }
186
+ }
187
+
188
+ // Register arbitrary variants
189
+ if (isArbitraryValue(variant) && !context.variantMap.has(variant)) {
190
+ let selector = normalize(variant.slice(1, -1))
191
+
192
+ if (!isValidVariantFormatString(selector)) {
193
+ return []
194
+ }
195
+
196
+ let fn = parseVariant(selector)
197
+
198
+ let sort = context.offsets.recordVariant(variant)
199
+
200
+ context.variantMap.set(variant, [[sort, fn]])
201
+ }
202
+
106
203
  if (context.variantMap.has(variant)) {
107
- let variantFunctionTuples = context.variantMap.get(variant)
204
+ let isArbitraryVariant = isArbitraryValue(variant)
205
+ let variantFunctionTuples = context.variantMap.get(variant).slice()
108
206
  let result = []
109
207
 
110
208
  for (let [meta, rule] of matches) {
209
+ // Don't generate variants for user css
210
+ if (meta.layer === 'user') {
211
+ continue
212
+ }
213
+
111
214
  let container = postcss.root({ nodes: [rule.clone()] })
112
215
 
113
- for (let [variantSort, variantFunction] of variantFunctionTuples) {
114
- let clone = container.clone()
216
+ for (let [variantSort, variantFunction, containerFromArray] of variantFunctionTuples) {
217
+ let clone = (containerFromArray ?? container).clone()
218
+ let collectedFormats = []
219
+
220
+ function prepareBackup() {
221
+ // Already prepared, chicken out
222
+ if (clone.raws.neededBackup) {
223
+ return
224
+ }
225
+ clone.raws.neededBackup = true
226
+ clone.walkRules((rule) => (rule.raws.originalSelector = rule.selector))
227
+ }
228
+
115
229
  function modifySelectors(modifierFunction) {
230
+ prepareBackup()
116
231
  clone.each((rule) => {
117
232
  if (rule.type !== 'rule') {
118
233
  return
@@ -127,20 +242,126 @@ function applyVariant(variant, matches, context) {
127
242
  })
128
243
  })
129
244
  })
245
+
130
246
  return clone
131
247
  }
132
248
 
133
249
  let ruleWithVariant = variantFunction({
134
- container: clone,
250
+ // Public API
251
+ get container() {
252
+ prepareBackup()
253
+ return clone
254
+ },
135
255
  separator: context.tailwindConfig.separator,
136
256
  modifySelectors,
257
+
258
+ // Private API for now
259
+ wrap(wrapper) {
260
+ let nodes = clone.nodes
261
+ clone.removeAll()
262
+ wrapper.append(nodes)
263
+ clone.append(wrapper)
264
+ },
265
+ format(selectorFormat) {
266
+ collectedFormats.push({
267
+ format: selectorFormat,
268
+ isArbitraryVariant,
269
+ })
270
+ },
271
+ args,
137
272
  })
138
273
 
274
+ // It can happen that a list of format strings is returned from within the function. In that
275
+ // case, we have to process them as well. We can use the existing `variantSort`.
276
+ if (Array.isArray(ruleWithVariant)) {
277
+ for (let [idx, variantFunction] of ruleWithVariant.entries()) {
278
+ // This is a little bit scary since we are pushing to an array of items that we are
279
+ // currently looping over. However, you can also think of it like a processing queue
280
+ // where you keep handling jobs until everything is done and each job can queue more
281
+ // jobs if needed.
282
+ variantFunctionTuples.push([
283
+ context.offsets.applyParallelOffset(variantSort, idx),
284
+ variantFunction,
285
+
286
+ // If the clone has been modified we have to pass that back
287
+ // though so each rule can use the modified container
288
+ clone.clone(),
289
+ ])
290
+ }
291
+ continue
292
+ }
293
+
294
+ if (typeof ruleWithVariant === 'string') {
295
+ collectedFormats.push({
296
+ format: ruleWithVariant,
297
+ isArbitraryVariant,
298
+ })
299
+ }
300
+
139
301
  if (ruleWithVariant === null) {
140
302
  continue
141
303
  }
142
304
 
143
- let withOffset = [{ ...meta, sort: variantSort | meta.sort }, clone.nodes[0]]
305
+ // We had to backup selectors, therefore we assume that somebody touched
306
+ // `container` or `modifySelectors`. Let's see if they did, so that we
307
+ // can restore the selectors, and collect the format strings.
308
+ if (clone.raws.neededBackup) {
309
+ delete clone.raws.neededBackup
310
+ clone.walkRules((rule) => {
311
+ let before = rule.raws.originalSelector
312
+ if (!before) return
313
+ delete rule.raws.originalSelector
314
+ if (before === rule.selector) return // No mutation happened
315
+
316
+ let modified = rule.selector
317
+
318
+ // Rebuild the base selector, this is what plugin authors would do
319
+ // as well. E.g.: `${variant}${separator}${className}`.
320
+ // However, plugin authors probably also prepend or append certain
321
+ // classes, pseudos, ids, ...
322
+ let rebuiltBase = selectorParser((selectors) => {
323
+ selectors.walkClasses((classNode) => {
324
+ classNode.value = `${variant}${context.tailwindConfig.separator}${classNode.value}`
325
+ })
326
+ }).processSync(before)
327
+
328
+ // Now that we know the original selector, the new selector, and
329
+ // the rebuild part in between, we can replace the part that plugin
330
+ // authors need to rebuild with `&`, and eventually store it in the
331
+ // collectedFormats. Similar to what `format('...')` would do.
332
+ //
333
+ // E.g.:
334
+ // variant: foo
335
+ // selector: .markdown > p
336
+ // modified (by plugin): .foo .foo\\:markdown > p
337
+ // rebuiltBase (internal): .foo\\:markdown > p
338
+ // format: .foo &
339
+ collectedFormats.push({
340
+ format: modified.replace(rebuiltBase, '&'),
341
+ isArbitraryVariant,
342
+ })
343
+ rule.selector = before
344
+ })
345
+ }
346
+
347
+ // This tracks the originating layer for the variant
348
+ // For example:
349
+ // .sm:underline {} is a variant of something in the utilities layer
350
+ // .sm:container {} is a variant of the container component
351
+ clone.nodes[0].raws.tailwind = { ...clone.nodes[0].raws.tailwind, parentLayer: meta.layer }
352
+
353
+ let withOffset = [
354
+ {
355
+ ...meta,
356
+ sort: context.offsets.applyVariantOffset(
357
+ meta.sort,
358
+ variantSort,
359
+ Object.assign(args, context.variantOptions.get(variant))
360
+ ),
361
+ collectedFormats: (meta.collectedFormats ?? []).concat(collectedFormats),
362
+ },
363
+ clone.nodes[0],
364
+ ]
144
365
  result.push(withOffset)
145
366
  }
146
367
  }
@@ -170,34 +391,154 @@ function parseRules(rule, cache, options = {}) {
170
391
  return [cache.get(rule), options]
171
392
  }
172
393
 
394
+ const IS_VALID_PROPERTY_NAME = /^[a-z_-]/
395
+
396
+ function isValidPropName(name) {
397
+ return IS_VALID_PROPERTY_NAME.test(name)
398
+ }
399
+
400
+ /**
401
+ * @param {string} declaration
402
+ * @returns {boolean}
403
+ */
404
+ function looksLikeUri(declaration) {
405
+ // Quick bailout for obvious non-urls
406
+ // This doesn't support schemes that don't use a leading // but that's unlikely to be a problem
407
+ if (!declaration.includes('://')) {
408
+ return false
409
+ }
410
+
411
+ try {
412
+ const url = new URL(declaration)
413
+ return url.scheme !== '' && url.host !== ''
414
+ } catch (err) {
415
+ // Definitely not a valid url
416
+ return false
417
+ }
418
+ }
419
+
420
+ function isParsableNode(node) {
421
+ let isParsable = true
422
+
423
+ node.walkDecls((decl) => {
424
+ if (!isParsableCssValue(decl.prop, decl.value)) {
425
+ isParsable = false
426
+ return false
427
+ }
428
+ })
429
+
430
+ return isParsable
431
+ }
432
+
433
+ function isParsableCssValue(property, value) {
434
+ // We don't want to to treat [https://example.com] as a custom property
435
+ // Even though, according to the CSS grammar, it's a totally valid CSS declaration
436
+ // So we short-circuit here by checking if the custom property looks like a url
437
+ if (looksLikeUri(`${property}:${value}`)) {
438
+ return false
439
+ }
440
+
441
+ try {
442
+ postcss.parse(`a{${property}:${value}}`).toResult()
443
+ return true
444
+ } catch (err) {
445
+ return false
446
+ }
447
+ }
448
+
449
+ function extractArbitraryProperty(classCandidate, context) {
450
+ let [, property, value] = classCandidate.match(/^\[([a-zA-Z0-9-_]+):(\S+)\]$/) ?? []
451
+
452
+ if (value === undefined) {
453
+ return null
454
+ }
455
+
456
+ if (!isValidPropName(property)) {
457
+ return null
458
+ }
459
+
460
+ if (!isValidArbitraryValue(value)) {
461
+ return null
462
+ }
463
+
464
+ let normalized = normalize(value)
465
+
466
+ if (!isParsableCssValue(property, normalized)) {
467
+ return null
468
+ }
469
+
470
+ let sort = context.offsets.arbitraryProperty()
471
+
472
+ return [
473
+ [
474
+ { sort, layer: 'utilities' },
475
+ () => ({
476
+ [asClass(classCandidate)]: {
477
+ [property]: normalized,
478
+ },
479
+ }),
480
+ ],
481
+ ]
482
+ }
483
+
173
484
  function* resolveMatchedPlugins(classCandidate, context) {
174
485
  if (context.candidateRuleMap.has(classCandidate)) {
175
486
  yield [context.candidateRuleMap.get(classCandidate), 'DEFAULT']
176
487
  }
177
488
 
489
+ yield* (function* (arbitraryPropertyRule) {
490
+ if (arbitraryPropertyRule !== null) {
491
+ yield [arbitraryPropertyRule, 'DEFAULT']
492
+ }
493
+ })(extractArbitraryProperty(classCandidate, context))
494
+
178
495
  let candidatePrefix = classCandidate
179
496
  let negative = false
180
497
 
181
- const twConfigPrefix = context.tailwindConfig.prefix || ''
498
+ const twConfigPrefix = context.tailwindConfig.prefix
499
+
182
500
  const twConfigPrefixLen = twConfigPrefix.length
183
- if (candidatePrefix[twConfigPrefixLen] === '-') {
501
+
502
+ const hasMatchingPrefix =
503
+ candidatePrefix.startsWith(twConfigPrefix) || candidatePrefix.startsWith(`-${twConfigPrefix}`)
504
+
505
+ if (candidatePrefix[twConfigPrefixLen] === '-' && hasMatchingPrefix) {
184
506
  negative = true
185
507
  candidatePrefix = twConfigPrefix + candidatePrefix.slice(twConfigPrefixLen + 1)
186
508
  }
187
509
 
510
+ if (negative && context.candidateRuleMap.has(candidatePrefix)) {
511
+ yield [context.candidateRuleMap.get(candidatePrefix), '-DEFAULT']
512
+ }
513
+
188
514
  for (let [prefix, modifier] of candidatePermutations(candidatePrefix)) {
189
515
  if (context.candidateRuleMap.has(prefix)) {
190
516
  yield [context.candidateRuleMap.get(prefix), negative ? `-${modifier}` : modifier]
191
- return
192
517
  }
193
518
  }
194
519
  }
195
520
 
196
521
  function splitWithSeparator(input, separator) {
197
- return input.split(new RegExp(`\\${separator}(?![^[]*\\])`, 'g'))
522
+ if (input === sharedState.NOT_ON_DEMAND) {
523
+ return [sharedState.NOT_ON_DEMAND]
524
+ }
525
+
526
+ return splitAtTopLevelOnly(input, separator)
527
+ }
528
+
529
+ function* recordCandidates(matches, classCandidate) {
530
+ for (const match of matches) {
531
+ match[1].raws.tailwind = {
532
+ ...match[1].raws.tailwind,
533
+ classCandidate,
534
+ preserveSource: match[0].options?.preserveSource ?? false,
535
+ }
536
+
537
+ yield match
538
+ }
198
539
  }
199
540
 
200
- function* resolveMatches(candidate, context) {
541
+ function* resolveMatches(candidate, context, original = candidate) {
201
542
  let separator = context.tailwindConfig.separator
202
543
  let [classCandidate, ...variants] = splitWithSeparator(candidate, separator).reverse()
203
544
  let important = false
@@ -207,6 +548,15 @@ function* resolveMatches(candidate, context) {
207
548
  classCandidate = classCandidate.slice(1)
208
549
  }
209
550
 
551
+ if (flagEnabled(context.tailwindConfig, 'variantGrouping')) {
552
+ if (classCandidate.startsWith('(') && classCandidate.endsWith(')')) {
553
+ let base = variants.slice().reverse().join(separator)
554
+ for (let part of splitAtTopLevelOnly(classCandidate.slice(1, -1), ',')) {
555
+ yield* resolveMatches(base + separator + part, context, original)
556
+ }
557
+ }
558
+ }
559
+
210
560
  // TODO: Reintroduce this in ways that doesn't break on false positives
211
561
  // function sortAgainst(toSort, against) {
212
562
  // return toSort.slice().sort((a, z) => {
@@ -238,7 +588,7 @@ function* resolveMatches(candidate, context) {
238
588
  }
239
589
  }
240
590
  // Only process static plugins on exact matches
241
- else if (modifier === 'DEFAULT') {
591
+ else if (modifier === 'DEFAULT' || modifier === '-DEFAULT') {
242
592
  let ruleSet = plugin
243
593
  let [rules, options] = parseRules(ruleSet, context.postCssNodeCache)
244
594
  for (let rule of rules) {
@@ -247,71 +597,144 @@ function* resolveMatches(candidate, context) {
247
597
  }
248
598
 
249
599
  if (matchesPerPlugin.length > 0) {
250
- typesByMatches.set(matchesPerPlugin, sort.options?.type)
600
+ let matchingTypes = Array.from(
601
+ getMatchingTypes(
602
+ sort.options?.types ?? [],
603
+ modifier,
604
+ sort.options ?? {},
605
+ context.tailwindConfig
606
+ )
607
+ ).map(([_, type]) => type)
608
+
609
+ if (matchingTypes.length > 0) {
610
+ typesByMatches.set(matchesPerPlugin, matchingTypes)
611
+ }
612
+
251
613
  matches.push(matchesPerPlugin)
252
614
  }
253
615
  }
254
616
 
255
- // Only keep the result of the very first plugin if we are dealing with
256
- // arbitrary values, to protect against ambiguity.
257
- if (isArbitraryValue(modifier) && matches.length > 1) {
258
- let typesPerPlugin = matches.map((match) => new Set([...(typesByMatches.get(match) ?? [])]))
259
-
260
- // Remove duplicates, so that we can detect proper unique types for each plugin.
261
- for (let pluginTypes of typesPerPlugin) {
262
- for (let type of pluginTypes) {
263
- let removeFromOwnGroup = false
264
-
265
- for (let otherGroup of typesPerPlugin) {
266
- if (pluginTypes === otherGroup) continue
617
+ if (isArbitraryValue(modifier)) {
618
+ if (matches.length > 1) {
619
+ // Partition plugins in 2 categories so that we can start searching in the plugins that
620
+ // don't have `any` as a type first.
621
+ let [withAny, withoutAny] = matches.reduce(
622
+ (group, plugin) => {
623
+ let hasAnyType = plugin.some(([{ options }]) =>
624
+ options.types.some(({ type }) => type === 'any')
625
+ )
267
626
 
268
- if (otherGroup.has(type)) {
269
- otherGroup.delete(type)
270
- removeFromOwnGroup = true
627
+ if (hasAnyType) {
628
+ group[0].push(plugin)
629
+ } else {
630
+ group[1].push(plugin)
271
631
  }
632
+ return group
633
+ },
634
+ [[], []]
635
+ )
636
+
637
+ function findFallback(matches) {
638
+ // If only a single plugin matches, let's take that one
639
+ if (matches.length === 1) {
640
+ return matches[0]
272
641
  }
273
642
 
274
- if (removeFromOwnGroup) pluginTypes.delete(type)
643
+ // Otherwise, find the plugin that creates a valid rule given the arbitrary value, and
644
+ // also has the correct type which preferOnConflicts the plugin in case of clashes.
645
+ return matches.find((rules) => {
646
+ let matchingTypes = typesByMatches.get(rules)
647
+ return rules.some(([{ options }, rule]) => {
648
+ if (!isParsableNode(rule)) {
649
+ return false
650
+ }
651
+
652
+ return options.types.some(
653
+ ({ type, preferOnConflict }) => matchingTypes.includes(type) && preferOnConflict
654
+ )
655
+ })
656
+ })
275
657
  }
276
- }
277
658
 
278
- let messages = []
279
-
280
- for (let [idx, group] of typesPerPlugin.entries()) {
281
- for (let type of group) {
282
- let rules = matches[idx]
283
- .map(([, rule]) => rule)
284
- .flat()
285
- .map((rule) =>
286
- rule
287
- .toString()
288
- .split('\n')
289
- .slice(1, -1) // Remove selector and closing '}'
290
- .map((line) => line.trim())
291
- .map((x) => ` ${x}`) // Re-indent
292
- .join('\n')
293
- )
294
- .join('\n\n')
659
+ // Try to find a fallback plugin, because we already know that multiple plugins matched for
660
+ // the given arbitrary value.
661
+ let fallback = findFallback(withoutAny) ?? findFallback(withAny)
662
+ if (fallback) {
663
+ matches = [fallback]
664
+ }
665
+
666
+ // We couldn't find a fallback plugin which means that there are now multiple plugins that
667
+ // generated css for the current candidate. This means that the result is ambiguous and this
668
+ // should not happen. We won't generate anything right now, so let's report this to the user
669
+ // by logging some options about what they can do.
670
+ else {
671
+ let typesPerPlugin = matches.map(
672
+ (match) => new Set([...(typesByMatches.get(match) ?? [])])
673
+ )
674
+
675
+ // Remove duplicates, so that we can detect proper unique types for each plugin.
676
+ for (let pluginTypes of typesPerPlugin) {
677
+ for (let type of pluginTypes) {
678
+ let removeFromOwnGroup = false
679
+
680
+ for (let otherGroup of typesPerPlugin) {
681
+ if (pluginTypes === otherGroup) continue
682
+
683
+ if (otherGroup.has(type)) {
684
+ otherGroup.delete(type)
685
+ removeFromOwnGroup = true
686
+ }
687
+ }
688
+
689
+ if (removeFromOwnGroup) pluginTypes.delete(type)
690
+ }
691
+ }
692
+
693
+ let messages = []
694
+
695
+ for (let [idx, group] of typesPerPlugin.entries()) {
696
+ for (let type of group) {
697
+ let rules = matches[idx]
698
+ .map(([, rule]) => rule)
699
+ .flat()
700
+ .map((rule) =>
701
+ rule
702
+ .toString()
703
+ .split('\n')
704
+ .slice(1, -1) // Remove selector and closing '}'
705
+ .map((line) => line.trim())
706
+ .map((x) => ` ${x}`) // Re-indent
707
+ .join('\n')
708
+ )
709
+ .join('\n\n')
710
+
711
+ messages.push(
712
+ ` Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\``
713
+ )
714
+ break
715
+ }
716
+ }
295
717
 
296
- messages.push(` Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\``)
297
- break
718
+ log.warn([
719
+ `The class \`${candidate}\` is ambiguous and matches multiple utilities.`,
720
+ ...messages,
721
+ `If this is content and not a class, replace it with \`${candidate
722
+ .replace('[', '&lsqb;')
723
+ .replace(']', '&rsqb;')}\` to silence this warning.`,
724
+ ])
725
+ continue
298
726
  }
299
727
  }
300
728
 
301
- log.warn([
302
- `The class \`${candidate}\` is ambiguous and matches multiple utilities.`,
303
- ...messages,
304
- `If this is content and not a class, replace it with \`${candidate
305
- .replace('[', '&lsqb;')
306
- .replace(']', '&rsqb;')}\` to silence this warning.`,
307
- ])
308
- continue
729
+ matches = matches.map((list) => list.filter((match) => isParsableNode(match[1])))
309
730
  }
310
731
 
311
- matches = applyPrefix(matches.flat(), context)
732
+ matches = matches.flat()
733
+ matches = Array.from(recordCandidates(matches, classCandidate))
734
+ matches = applyPrefix(matches, context)
312
735
 
313
736
  if (important) {
314
- matches = applyImportant(matches, context)
737
+ matches = applyImportant(matches, classCandidate)
315
738
  }
316
739
 
317
740
  for (let variant of variants) {
@@ -319,25 +742,122 @@ function* resolveMatches(candidate, context) {
319
742
  }
320
743
 
321
744
  for (let match of matches) {
745
+ match[1].raws.tailwind = { ...match[1].raws.tailwind, candidate }
746
+
747
+ // Apply final format selector
748
+ match = applyFinalFormat(match, { context, candidate, original })
749
+
750
+ // Skip rules with invalid selectors
751
+ // This will cause the candidate to be added to the "not class"
752
+ // cache skipping it entirely for future builds
753
+ if (match === null) {
754
+ continue
755
+ }
756
+
322
757
  yield match
323
758
  }
324
759
  }
325
760
  }
326
761
 
762
+ function applyFinalFormat(match, { context, candidate, original }) {
763
+ if (!match[0].collectedFormats) {
764
+ return match
765
+ }
766
+
767
+ let isValid = true
768
+ let finalFormat
769
+
770
+ try {
771
+ finalFormat = formatVariantSelector(match[0].collectedFormats, {
772
+ context,
773
+ candidate,
774
+ })
775
+ } catch {
776
+ // The format selector we produced is invalid
777
+ // This could be because:
778
+ // - A bug exists
779
+ // - A plugin introduced an invalid variant selector (ex: `addVariant('foo', '&;foo')`)
780
+ // - The user used an invalid arbitrary variant (ex: `[&;foo]:underline`)
781
+ // Either way the build will fail because of this
782
+ // We would rather that the build pass "silently" given that this could
783
+ // happen because of picking up invalid things when scanning content
784
+ // So we'll throw out the candidate instead
785
+
786
+ return null
787
+ }
788
+
789
+ let container = postcss.root({ nodes: [match[1].clone()] })
790
+
791
+ container.walkRules((rule) => {
792
+ if (inKeyframes(rule)) {
793
+ return
794
+ }
795
+
796
+ try {
797
+ rule.selector = finalizeSelector(rule.selector, finalFormat, {
798
+ candidate: original,
799
+ context,
800
+ })
801
+ } catch {
802
+ // If this selector is invalid we also want to skip it
803
+ // But it's likely that being invalid here means there's a bug in a plugin rather than too loosely matching content
804
+ isValid = false
805
+ return false
806
+ }
807
+ })
808
+
809
+ if (!isValid) {
810
+ return null
811
+ }
812
+
813
+ match[1] = container.nodes[0]
814
+
815
+ return match
816
+ }
817
+
327
818
  function inKeyframes(rule) {
328
819
  return rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes'
329
820
  }
330
821
 
822
+ function getImportantStrategy(important) {
823
+ if (important === true) {
824
+ return (rule) => {
825
+ if (inKeyframes(rule)) {
826
+ return
827
+ }
828
+
829
+ rule.walkDecls((d) => {
830
+ if (d.parent.type === 'rule' && !inKeyframes(d.parent)) {
831
+ d.important = true
832
+ }
833
+ })
834
+ }
835
+ }
836
+
837
+ if (typeof important === 'string') {
838
+ return (rule) => {
839
+ if (inKeyframes(rule)) {
840
+ return
841
+ }
842
+
843
+ rule.selectors = rule.selectors.map((selector) => {
844
+ return `${important} ${selector}`
845
+ })
846
+ }
847
+ }
848
+ }
849
+
331
850
  function generateRules(candidates, context) {
332
851
  let allRules = []
852
+ let strategy = getImportantStrategy(context.tailwindConfig.important)
333
853
 
334
854
  for (let candidate of candidates) {
335
855
  if (context.notClassCache.has(candidate)) {
336
856
  continue
337
857
  }
338
858
 
339
- if (context.classCache.has(candidate)) {
340
- allRules.push(context.classCache.get(candidate))
859
+ if (context.candidateRuleCache.has(candidate)) {
860
+ allRules = allRules.concat(Array.from(context.candidateRuleCache.get(candidate)))
341
861
  continue
342
862
  }
343
863
 
@@ -349,33 +869,27 @@ function generateRules(candidates, context) {
349
869
  }
350
870
 
351
871
  context.classCache.set(candidate, matches)
352
- allRules.push(matches)
353
- }
354
872
 
355
- return allRules.flat(1).map(([{ sort, layer, options }, rule]) => {
356
- if (options.respectImportant) {
357
- if (context.tailwindConfig.important === true) {
358
- rule.walkDecls((d) => {
359
- if (d.parent.type === 'rule' && !inKeyframes(d.parent)) {
360
- d.important = true
361
- }
362
- })
363
- } else if (typeof context.tailwindConfig.important === 'string') {
364
- let container = postcss.root({ nodes: [rule.clone()] })
365
- container.walkRules((r) => {
366
- if (inKeyframes(r)) {
367
- return
368
- }
873
+ let rules = context.candidateRuleCache.get(candidate) ?? new Set()
874
+ context.candidateRuleCache.set(candidate, rules)
369
875
 
370
- r.selectors = r.selectors.map((selector) => {
371
- return `${context.tailwindConfig.important} ${selector}`
372
- })
373
- })
876
+ for (const match of matches) {
877
+ let [{ sort, options }, rule] = match
878
+
879
+ if (options.respectImportant && strategy) {
880
+ let container = postcss.root({ nodes: [rule.clone()] })
881
+ container.walkRules(strategy)
374
882
  rule = container.nodes[0]
375
883
  }
884
+
885
+ let newEntry = [sort, rule]
886
+ rules.add(newEntry)
887
+ context.ruleCache.add(newEntry)
888
+ allRules.push(newEntry)
376
889
  }
377
- return [sort | context.layerOrder[layer], rule]
378
- })
890
+ }
891
+
892
+ return allRules
379
893
  }
380
894
 
381
895
  function isArbitraryValue(input) {