tailwindcss 0.0.0-insiders.93e0fdf → 0.0.0-insiders.941ef21

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 (170) hide show
  1. package/CHANGELOG.md +293 -5
  2. package/README.md +13 -9
  3. package/colors.d.ts +3 -0
  4. package/defaultConfig.d.ts +3 -0
  5. package/defaultTheme.d.ts +4 -0
  6. package/lib/cli/build/deps.js +54 -0
  7. package/lib/cli/build/index.js +48 -0
  8. package/lib/cli/build/plugin.js +362 -0
  9. package/lib/cli/build/utils.js +78 -0
  10. package/lib/cli/build/watching.js +178 -0
  11. package/lib/cli/help/index.js +71 -0
  12. package/lib/cli/index.js +18 -0
  13. package/lib/cli/init/index.js +46 -0
  14. package/lib/cli/shared.js +12 -0
  15. package/lib/cli-peer-dependencies.js +20 -7
  16. package/lib/cli.js +109 -611
  17. package/lib/constants.js +27 -20
  18. package/lib/corePluginList.js +6 -3
  19. package/lib/corePlugins.js +2005 -1686
  20. package/lib/css/preflight.css +4 -4
  21. package/lib/featureFlags.js +36 -24
  22. package/lib/index.js +28 -10
  23. package/lib/lib/cacheInvalidation.js +90 -0
  24. package/lib/lib/collapseAdjacentRules.js +28 -10
  25. package/lib/lib/collapseDuplicateDeclarations.js +14 -11
  26. package/lib/lib/content.js +177 -0
  27. package/lib/lib/defaultExtractor.js +225 -33
  28. package/lib/lib/detectNesting.js +13 -10
  29. package/lib/lib/evaluateTailwindFunctions.js +118 -55
  30. package/lib/lib/expandApplyAtRules.js +439 -193
  31. package/lib/lib/expandTailwindAtRules.js +104 -109
  32. package/lib/lib/findAtConfigPath.js +44 -0
  33. package/lib/lib/generateRules.js +405 -197
  34. package/lib/lib/getModuleDependencies.js +11 -8
  35. package/lib/lib/normalizeTailwindDirectives.js +35 -32
  36. package/lib/lib/offsets.js +285 -0
  37. package/lib/lib/partitionApplyAtRules.js +11 -8
  38. package/lib/lib/regex.js +60 -0
  39. package/lib/lib/remap-bitfield.js +87 -0
  40. package/lib/lib/resolveDefaultsAtRules.js +89 -67
  41. package/lib/lib/setupContextUtils.js +617 -309
  42. package/lib/lib/setupTrackingContext.js +38 -67
  43. package/lib/lib/sharedState.js +25 -15
  44. package/lib/lib/substituteScreenAtRules.js +11 -9
  45. package/lib/postcss-plugins/nesting/README.md +2 -2
  46. package/lib/postcss-plugins/nesting/index.js +8 -6
  47. package/lib/postcss-plugins/nesting/plugin.js +48 -14
  48. package/lib/processTailwindFeatures.js +31 -28
  49. package/lib/public/colors.js +247 -245
  50. package/lib/public/create-plugin.js +6 -4
  51. package/lib/public/default-config.js +7 -5
  52. package/lib/public/default-theme.js +7 -5
  53. package/lib/public/resolve-config.js +8 -5
  54. package/lib/util/bigSign.js +4 -1
  55. package/lib/util/buildMediaQuery.js +11 -6
  56. package/lib/util/cloneDeep.js +7 -6
  57. package/lib/util/cloneNodes.js +21 -3
  58. package/lib/util/color.js +53 -54
  59. package/lib/util/configurePlugins.js +5 -2
  60. package/lib/util/createPlugin.js +6 -5
  61. package/lib/util/createUtilityPlugin.js +10 -8
  62. package/lib/util/dataTypes.js +143 -110
  63. package/lib/util/defaults.js +8 -5
  64. package/lib/util/escapeClassName.js +9 -6
  65. package/lib/util/escapeCommas.js +5 -2
  66. package/lib/util/flattenColorPalette.js +9 -10
  67. package/lib/util/formatVariantSelector.js +193 -86
  68. package/lib/util/getAllConfigs.js +29 -10
  69. package/lib/util/hashConfig.js +6 -3
  70. package/lib/util/isKeyframeRule.js +5 -2
  71. package/lib/util/isPlainObject.js +5 -2
  72. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +23 -15
  73. package/lib/util/log.js +20 -14
  74. package/lib/util/nameClass.js +20 -9
  75. package/lib/util/negateValue.js +22 -7
  76. package/lib/util/normalizeConfig.js +124 -83
  77. package/lib/util/normalizeScreens.js +119 -8
  78. package/lib/util/parseAnimationValue.js +42 -40
  79. package/lib/util/parseBoxShadowValue.js +29 -22
  80. package/lib/util/parseDependency.js +38 -56
  81. package/lib/util/parseGlob.js +34 -0
  82. package/lib/util/parseObjectStyles.js +11 -8
  83. package/lib/util/pluginUtils.js +155 -51
  84. package/lib/util/prefixSelector.js +7 -4
  85. package/lib/util/removeAlphaVariables.js +29 -0
  86. package/lib/util/resolveConfig.js +93 -72
  87. package/lib/util/resolveConfigPath.js +10 -7
  88. package/lib/util/responsive.js +8 -5
  89. package/lib/util/splitAtTopLevelOnly.js +43 -0
  90. package/lib/util/tap.js +4 -1
  91. package/lib/util/toColorValue.js +5 -2
  92. package/lib/util/toPath.js +20 -4
  93. package/lib/util/transformThemeValue.js +37 -25
  94. package/lib/util/validateConfig.js +24 -0
  95. package/lib/util/validateFormalSyntax.js +24 -0
  96. package/lib/util/withAlphaVariable.js +23 -15
  97. package/package.json +44 -37
  98. package/peers/index.js +11099 -7475
  99. package/plugin.d.ts +11 -0
  100. package/resolveConfig.d.ts +12 -0
  101. package/scripts/generate-types.js +105 -0
  102. package/scripts/release-channel.js +18 -0
  103. package/scripts/release-notes.js +21 -0
  104. package/scripts/type-utils.js +27 -0
  105. package/src/cli/build/deps.js +56 -0
  106. package/src/cli/build/index.js +49 -0
  107. package/src/cli/build/plugin.js +434 -0
  108. package/src/cli/build/utils.js +76 -0
  109. package/src/cli/build/watching.js +227 -0
  110. package/src/cli/help/index.js +70 -0
  111. package/src/cli/index.js +3 -0
  112. package/src/cli/init/index.js +50 -0
  113. package/src/cli/shared.js +5 -0
  114. package/src/cli-peer-dependencies.js +7 -1
  115. package/src/cli.js +50 -631
  116. package/src/corePluginList.js +1 -1
  117. package/src/corePlugins.js +399 -84
  118. package/src/css/preflight.css +4 -4
  119. package/src/featureFlags.js +14 -4
  120. package/src/index.js +20 -1
  121. package/src/lib/cacheInvalidation.js +52 -0
  122. package/src/lib/collapseAdjacentRules.js +21 -2
  123. package/src/lib/content.js +213 -0
  124. package/src/lib/defaultExtractor.js +196 -35
  125. package/src/lib/evaluateTailwindFunctions.js +78 -7
  126. package/src/lib/expandApplyAtRules.js +482 -183
  127. package/src/lib/expandTailwindAtRules.js +37 -55
  128. package/src/lib/findAtConfigPath.js +48 -0
  129. package/src/lib/generateRules.js +359 -112
  130. package/src/lib/offsets.js +351 -0
  131. package/src/lib/regex.js +74 -0
  132. package/src/lib/remap-bitfield.js +82 -0
  133. package/src/lib/resolveDefaultsAtRules.js +53 -32
  134. package/src/lib/setupContextUtils.js +517 -146
  135. package/src/lib/setupTrackingContext.js +11 -48
  136. package/src/lib/sharedState.js +3 -0
  137. package/src/postcss-plugins/nesting/README.md +2 -2
  138. package/src/postcss-plugins/nesting/plugin.js +36 -0
  139. package/src/util/buildMediaQuery.js +5 -3
  140. package/src/util/cloneNodes.js +19 -2
  141. package/src/util/color.js +25 -21
  142. package/src/util/dataTypes.js +54 -21
  143. package/src/util/formatVariantSelector.js +196 -62
  144. package/src/util/getAllConfigs.js +19 -0
  145. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  146. package/src/util/log.js +8 -8
  147. package/src/util/nameClass.js +4 -0
  148. package/src/util/negateValue.js +10 -2
  149. package/src/util/normalizeConfig.js +40 -10
  150. package/src/util/normalizeScreens.js +99 -4
  151. package/src/util/parseBoxShadowValue.js +3 -2
  152. package/src/util/parseDependency.js +37 -42
  153. package/src/util/parseGlob.js +24 -0
  154. package/src/util/pluginUtils.js +132 -10
  155. package/src/util/removeAlphaVariables.js +24 -0
  156. package/src/util/resolveConfig.js +70 -32
  157. package/src/util/splitAtTopLevelOnly.js +45 -0
  158. package/src/util/toPath.js +1 -1
  159. package/src/util/transformThemeValue.js +13 -3
  160. package/src/util/validateConfig.js +13 -0
  161. package/src/util/validateFormalSyntax.js +34 -0
  162. package/src/util/withAlphaVariable.js +1 -1
  163. package/stubs/defaultConfig.stub.js +168 -164
  164. package/stubs/simpleConfig.stub.js +1 -0
  165. package/types/config.d.ts +363 -0
  166. package/types/generated/.gitkeep +0 -0
  167. package/types/generated/colors.d.ts +276 -0
  168. package/types/generated/corePluginList.d.ts +1 -0
  169. package/types/generated/default-theme.d.ts +342 -0
  170. package/types/index.d.ts +7 -0
@@ -3,19 +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
8
  import * as sharedState from './sharedState'
9
9
  import { formatVariantSelector, finalizeSelector } from '../util/formatVariantSelector'
10
10
  import { asClass } from '../util/nameClass'
11
11
  import { normalize } from '../util/dataTypes'
12
- import isValidArbitraryValue from '../util/isValidArbitraryValue'
12
+ import { isValidVariantFormatString, parseVariant } from './setupContextUtils'
13
+ import isValidArbitraryValue from '../util/isSyntacticallyValidPropertyValue'
14
+ import { splitAtTopLevelOnly } from '../util/splitAtTopLevelOnly.js'
15
+ import { flagEnabled } from '../featureFlags'
13
16
 
14
17
  let classNameParser = selectorParser((selectors) => {
15
18
  return selectors.first.filter(({ type }) => type === 'class').pop().value
16
19
  })
17
20
 
18
- function getClassNameFromSelector(selector) {
21
+ export function getClassNameFromSelector(selector) {
19
22
  return classNameParser.transformSync(selector)
20
23
  }
21
24
 
@@ -31,13 +34,24 @@ function* candidatePermutations(candidate) {
31
34
 
32
35
  while (lastIndex >= 0) {
33
36
  let dashIdx
37
+ let wasSlash = false
34
38
 
35
39
  if (lastIndex === Infinity && candidate.endsWith(']')) {
36
40
  let bracketIdx = candidate.indexOf('[')
37
41
 
38
42
  // If character before `[` isn't a dash or a slash, this isn't a dynamic class
39
43
  // eg. string[]
40
- dashIdx = ['-', '/'].includes(candidate[bracketIdx - 1]) ? bracketIdx - 1 : -1
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
41
55
  } else {
42
56
  dashIdx = candidate.lastIndexOf('-', lastIndex)
43
57
  }
@@ -47,11 +61,16 @@ function* candidatePermutations(candidate) {
47
61
  }
48
62
 
49
63
  let prefix = candidate.slice(0, dashIdx)
50
- let modifier = candidate.slice(dashIdx + 1)
51
-
52
- yield [prefix, modifier]
64
+ let modifier = candidate.slice(wasSlash ? dashIdx : dashIdx + 1)
53
65
 
54
66
  lastIndex = dashIdx - 1
67
+
68
+ // TODO: This feels a bit hacky
69
+ if (prefix === '' || modifier === '/') {
70
+ continue
71
+ }
72
+
73
+ yield [prefix, modifier]
55
74
  }
56
75
  }
57
76
 
@@ -88,7 +107,7 @@ function applyPrefix(matches, context) {
88
107
  return matches
89
108
  }
90
109
 
91
- function applyImportant(matches) {
110
+ function applyImportant(matches, classCandidate) {
92
111
  if (matches.length === 0) {
93
112
  return matches
94
113
  }
@@ -97,9 +116,15 @@ function applyImportant(matches) {
97
116
  for (let [meta, rule] of matches) {
98
117
  let container = postcss.root({ nodes: [rule.clone()] })
99
118
  container.walkRules((r) => {
100
- r.selector = updateAllClasses(r.selector, (className) => {
101
- return `!${className}`
102
- })
119
+ r.selector = updateAllClasses(
120
+ filterSelectorsForClass(r.selector, classCandidate),
121
+ (className) => {
122
+ if (className === classCandidate) {
123
+ return `!${className}`
124
+ }
125
+ return className
126
+ }
127
+ )
103
128
  r.walkDecls((d) => (d.important = true))
104
129
  })
105
130
  result.push([{ ...meta, important: true }, container.nodes[0]])
@@ -122,8 +147,61 @@ function applyVariant(variant, matches, context) {
122
147
  return matches
123
148
  }
124
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
+
125
203
  if (context.variantMap.has(variant)) {
126
- let variantFunctionTuples = context.variantMap.get(variant)
204
+ let variantFunctionTuples = context.variantMap.get(variant).slice()
127
205
  let result = []
128
206
 
129
207
  for (let [meta, rule] of matches) {
@@ -134,15 +212,17 @@ function applyVariant(variant, matches, context) {
134
212
 
135
213
  let container = postcss.root({ nodes: [rule.clone()] })
136
214
 
137
- for (let [variantSort, variantFunction] of variantFunctionTuples) {
138
- let clone = container.clone()
215
+ for (let [variantSort, variantFunction, containerFromArray] of variantFunctionTuples) {
216
+ let clone = (containerFromArray ?? container).clone()
139
217
  let collectedFormats = []
140
218
 
141
- let originals = new Map()
142
-
143
219
  function prepareBackup() {
144
- if (originals.size > 0) return // Already prepared, chicken out
145
- clone.walkRules((rule) => originals.set(rule, rule.selector))
220
+ // Already prepared, chicken out
221
+ if (clone.raws.neededBackup) {
222
+ return
223
+ }
224
+ clone.raws.neededBackup = true
225
+ clone.walkRules((rule) => (rule.raws.originalSelector = rule.selector))
146
226
  }
147
227
 
148
228
  function modifySelectors(modifierFunction) {
@@ -184,8 +264,29 @@ function applyVariant(variant, matches, context) {
184
264
  format(selectorFormat) {
185
265
  collectedFormats.push(selectorFormat)
186
266
  },
267
+ args,
187
268
  })
188
269
 
270
+ // It can happen that a list of format strings is returned from within the function. In that
271
+ // case, we have to process them as well. We can use the existing `variantSort`.
272
+ if (Array.isArray(ruleWithVariant)) {
273
+ for (let [idx, variantFunction] of ruleWithVariant.entries()) {
274
+ // This is a little bit scary since we are pushing to an array of items that we are
275
+ // currently looping over. However, you can also think of it like a processing queue
276
+ // where you keep handling jobs until everything is done and each job can queue more
277
+ // jobs if needed.
278
+ variantFunctionTuples.push([
279
+ context.offsets.applyParallelOffset(variantSort, idx),
280
+ variantFunction,
281
+
282
+ // If the clone has been modified we have to pass that back
283
+ // though so each rule can use the modified container
284
+ clone.clone(),
285
+ ])
286
+ }
287
+ continue
288
+ }
289
+
189
290
  if (typeof ruleWithVariant === 'string') {
190
291
  collectedFormats.push(ruleWithVariant)
191
292
  }
@@ -194,13 +295,15 @@ function applyVariant(variant, matches, context) {
194
295
  continue
195
296
  }
196
297
 
197
- // We filled the `originals`, therefore we assume that somebody touched
298
+ // We had to backup selectors, therefore we assume that somebody touched
198
299
  // `container` or `modifySelectors`. Let's see if they did, so that we
199
300
  // can restore the selectors, and collect the format strings.
200
- if (originals.size > 0) {
301
+ if (clone.raws.neededBackup) {
302
+ delete clone.raws.neededBackup
201
303
  clone.walkRules((rule) => {
202
- if (!originals.has(rule)) return
203
- let before = originals.get(rule)
304
+ let before = rule.raws.originalSelector
305
+ if (!before) return
306
+ delete rule.raws.originalSelector
204
307
  if (before === rule.selector) return // No mutation happened
205
308
 
206
309
  let modified = rule.selector
@@ -240,8 +343,13 @@ function applyVariant(variant, matches, context) {
240
343
  let withOffset = [
241
344
  {
242
345
  ...meta,
243
- sort: variantSort | meta.sort,
346
+ sort: context.offsets.applyVariantOffset(
347
+ meta.sort,
348
+ variantSort,
349
+ Object.assign(args, context.variantOptions.get(variant))
350
+ ),
244
351
  collectedFormats: (meta.collectedFormats ?? []).concat(collectedFormats),
352
+ isArbitraryVariant: isArbitraryValue(variant),
245
353
  },
246
354
  clone.nodes[0],
247
355
  ]
@@ -300,6 +408,19 @@ function looksLikeUri(declaration) {
300
408
  }
301
409
  }
302
410
 
411
+ function isParsableNode(node) {
412
+ let isParsable = true
413
+
414
+ node.walkDecls((decl) => {
415
+ if (!isParsableCssValue(decl.prop, decl.value)) {
416
+ isParsable = false
417
+ return false
418
+ }
419
+ })
420
+
421
+ return isParsable
422
+ }
423
+
303
424
  function isParsableCssValue(property, value) {
304
425
  // We don't want to to treat [https://example.com] as a custom property
305
426
  // Even though, according to the CSS grammar, it's a totally valid CSS declaration
@@ -337,9 +458,11 @@ function extractArbitraryProperty(classCandidate, context) {
337
458
  return null
338
459
  }
339
460
 
461
+ let sort = context.offsets.arbitraryProperty()
462
+
340
463
  return [
341
464
  [
342
- { sort: context.arbitraryPropertiesSort, layer: 'utilities' },
465
+ { sort, layer: 'utilities' },
343
466
  () => ({
344
467
  [asClass(classCandidate)]: {
345
468
  [property]: normalized,
@@ -366,7 +489,11 @@ function* resolveMatchedPlugins(classCandidate, context) {
366
489
  const twConfigPrefix = context.tailwindConfig.prefix
367
490
 
368
491
  const twConfigPrefixLen = twConfigPrefix.length
369
- if (candidatePrefix[twConfigPrefixLen] === '-') {
492
+
493
+ const hasMatchingPrefix =
494
+ candidatePrefix.startsWith(twConfigPrefix) || candidatePrefix.startsWith(`-${twConfigPrefix}`)
495
+
496
+ if (candidatePrefix[twConfigPrefixLen] === '-' && hasMatchingPrefix) {
370
497
  negative = true
371
498
  candidatePrefix = twConfigPrefix + candidatePrefix.slice(twConfigPrefixLen + 1)
372
499
  }
@@ -387,18 +514,22 @@ function splitWithSeparator(input, separator) {
387
514
  return [sharedState.NOT_ON_DEMAND]
388
515
  }
389
516
 
390
- return input.split(new RegExp(`\\${separator}(?![^[]*\\])`, 'g'))
517
+ return splitAtTopLevelOnly(input, separator)
391
518
  }
392
519
 
393
520
  function* recordCandidates(matches, classCandidate) {
394
521
  for (const match of matches) {
395
- match[1].raws.tailwind = { ...match[1].raws.tailwind, classCandidate }
522
+ match[1].raws.tailwind = {
523
+ ...match[1].raws.tailwind,
524
+ classCandidate,
525
+ preserveSource: match[0].options?.preserveSource ?? false,
526
+ }
396
527
 
397
528
  yield match
398
529
  }
399
530
  }
400
531
 
401
- function* resolveMatches(candidate, context) {
532
+ function* resolveMatches(candidate, context, original = candidate) {
402
533
  let separator = context.tailwindConfig.separator
403
534
  let [classCandidate, ...variants] = splitWithSeparator(candidate, separator).reverse()
404
535
  let important = false
@@ -408,6 +539,15 @@ function* resolveMatches(candidate, context) {
408
539
  classCandidate = classCandidate.slice(1)
409
540
  }
410
541
 
542
+ if (flagEnabled(context.tailwindConfig, 'variantGrouping')) {
543
+ if (classCandidate.startsWith('(') && classCandidate.endsWith(')')) {
544
+ let base = variants.slice().reverse().join(separator)
545
+ for (let part of splitAtTopLevelOnly(classCandidate.slice(1, -1), ',')) {
546
+ yield* resolveMatches(base + separator + part, context, original)
547
+ }
548
+ }
549
+ }
550
+
411
551
  // TODO: Reintroduce this in ways that doesn't break on false positives
412
552
  // function sortAgainst(toSort, against) {
413
553
  // return toSort.slice().sort((a, z) => {
@@ -448,65 +588,136 @@ function* resolveMatches(candidate, context) {
448
588
  }
449
589
 
450
590
  if (matchesPerPlugin.length > 0) {
451
- typesByMatches.set(matchesPerPlugin, sort.options?.type)
591
+ let matchingTypes = Array.from(
592
+ getMatchingTypes(
593
+ sort.options?.types ?? [],
594
+ modifier,
595
+ sort.options ?? {},
596
+ context.tailwindConfig
597
+ )
598
+ ).map(([_, type]) => type)
599
+
600
+ if (matchingTypes.length > 0) {
601
+ typesByMatches.set(matchesPerPlugin, matchingTypes)
602
+ }
603
+
452
604
  matches.push(matchesPerPlugin)
453
605
  }
454
606
  }
455
607
 
456
- // Only keep the result of the very first plugin if we are dealing with
457
- // arbitrary values, to protect against ambiguity.
458
- if (isArbitraryValue(modifier) && matches.length > 1) {
459
- let typesPerPlugin = matches.map((match) => new Set([...(typesByMatches.get(match) ?? [])]))
460
-
461
- // Remove duplicates, so that we can detect proper unique types for each plugin.
462
- for (let pluginTypes of typesPerPlugin) {
463
- for (let type of pluginTypes) {
464
- let removeFromOwnGroup = false
465
-
466
- for (let otherGroup of typesPerPlugin) {
467
- if (pluginTypes === otherGroup) continue
608
+ if (isArbitraryValue(modifier)) {
609
+ if (matches.length > 1) {
610
+ // Partition plugins in 2 categories so that we can start searching in the plugins that
611
+ // don't have `any` as a type first.
612
+ let [withAny, withoutAny] = matches.reduce(
613
+ (group, plugin) => {
614
+ let hasAnyType = plugin.some(([{ options }]) =>
615
+ options.types.some(({ type }) => type === 'any')
616
+ )
468
617
 
469
- if (otherGroup.has(type)) {
470
- otherGroup.delete(type)
471
- removeFromOwnGroup = true
618
+ if (hasAnyType) {
619
+ group[0].push(plugin)
620
+ } else {
621
+ group[1].push(plugin)
472
622
  }
623
+ return group
624
+ },
625
+ [[], []]
626
+ )
627
+
628
+ function findFallback(matches) {
629
+ // If only a single plugin matches, let's take that one
630
+ if (matches.length === 1) {
631
+ return matches[0]
473
632
  }
474
633
 
475
- if (removeFromOwnGroup) pluginTypes.delete(type)
634
+ // Otherwise, find the plugin that creates a valid rule given the arbitrary value, and
635
+ // also has the correct type which preferOnConflicts the plugin in case of clashes.
636
+ return matches.find((rules) => {
637
+ let matchingTypes = typesByMatches.get(rules)
638
+ return rules.some(([{ options }, rule]) => {
639
+ if (!isParsableNode(rule)) {
640
+ return false
641
+ }
642
+
643
+ return options.types.some(
644
+ ({ type, preferOnConflict }) => matchingTypes.includes(type) && preferOnConflict
645
+ )
646
+ })
647
+ })
476
648
  }
477
- }
478
649
 
479
- let messages = []
480
-
481
- for (let [idx, group] of typesPerPlugin.entries()) {
482
- for (let type of group) {
483
- let rules = matches[idx]
484
- .map(([, rule]) => rule)
485
- .flat()
486
- .map((rule) =>
487
- rule
488
- .toString()
489
- .split('\n')
490
- .slice(1, -1) // Remove selector and closing '}'
491
- .map((line) => line.trim())
492
- .map((x) => ` ${x}`) // Re-indent
493
- .join('\n')
494
- )
495
- .join('\n\n')
650
+ // Try to find a fallback plugin, because we already know that multiple plugins matched for
651
+ // the given arbitrary value.
652
+ let fallback = findFallback(withoutAny) ?? findFallback(withAny)
653
+ if (fallback) {
654
+ matches = [fallback]
655
+ }
496
656
 
497
- messages.push(` Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\``)
498
- break
657
+ // We couldn't find a fallback plugin which means that there are now multiple plugins that
658
+ // generated css for the current candidate. This means that the result is ambiguous and this
659
+ // should not happen. We won't generate anything right now, so let's report this to the user
660
+ // by logging some options about what they can do.
661
+ else {
662
+ let typesPerPlugin = matches.map(
663
+ (match) => new Set([...(typesByMatches.get(match) ?? [])])
664
+ )
665
+
666
+ // Remove duplicates, so that we can detect proper unique types for each plugin.
667
+ for (let pluginTypes of typesPerPlugin) {
668
+ for (let type of pluginTypes) {
669
+ let removeFromOwnGroup = false
670
+
671
+ for (let otherGroup of typesPerPlugin) {
672
+ if (pluginTypes === otherGroup) continue
673
+
674
+ if (otherGroup.has(type)) {
675
+ otherGroup.delete(type)
676
+ removeFromOwnGroup = true
677
+ }
678
+ }
679
+
680
+ if (removeFromOwnGroup) pluginTypes.delete(type)
681
+ }
682
+ }
683
+
684
+ let messages = []
685
+
686
+ for (let [idx, group] of typesPerPlugin.entries()) {
687
+ for (let type of group) {
688
+ let rules = matches[idx]
689
+ .map(([, rule]) => rule)
690
+ .flat()
691
+ .map((rule) =>
692
+ rule
693
+ .toString()
694
+ .split('\n')
695
+ .slice(1, -1) // Remove selector and closing '}'
696
+ .map((line) => line.trim())
697
+ .map((x) => ` ${x}`) // Re-indent
698
+ .join('\n')
699
+ )
700
+ .join('\n\n')
701
+
702
+ messages.push(
703
+ ` Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\``
704
+ )
705
+ break
706
+ }
707
+ }
708
+
709
+ log.warn([
710
+ `The class \`${candidate}\` is ambiguous and matches multiple utilities.`,
711
+ ...messages,
712
+ `If this is content and not a class, replace it with \`${candidate
713
+ .replace('[', '[')
714
+ .replace(']', ']')}\` to silence this warning.`,
715
+ ])
716
+ continue
499
717
  }
500
718
  }
501
719
 
502
- log.warn([
503
- `The class \`${candidate}\` is ambiguous and matches multiple utilities.`,
504
- ...messages,
505
- `If this is content and not a class, replace it with \`${candidate
506
- .replace('[', '[')
507
- .replace(']', ']')}\` to silence this warning.`,
508
- ])
509
- continue
720
+ matches = matches.map((list) => list.filter((match) => isParsableNode(match[1])))
510
721
  }
511
722
 
512
723
  matches = matches.flat()
@@ -514,7 +725,7 @@ function* resolveMatches(candidate, context) {
514
725
  matches = applyPrefix(matches, context)
515
726
 
516
727
  if (important) {
517
- matches = applyImportant(matches, context)
728
+ matches = applyImportant(matches, classCandidate)
518
729
  }
519
730
 
520
731
  for (let variant of variants) {
@@ -522,6 +733,8 @@ function* resolveMatches(candidate, context) {
522
733
  }
523
734
 
524
735
  for (let match of matches) {
736
+ let isValid = true
737
+
525
738
  match[1].raws.tailwind = { ...match[1].raws.tailwind, candidate }
526
739
 
527
740
  // Apply final format selector
@@ -531,15 +744,40 @@ function* resolveMatches(candidate, context) {
531
744
  container.walkRules((rule) => {
532
745
  if (inKeyframes(rule)) return
533
746
 
534
- rule.selector = finalizeSelector(finalFormat, {
747
+ let selectorOptions = {
535
748
  selector: rule.selector,
536
- candidate,
749
+ candidate: original,
750
+ base: candidate
751
+ .split(new RegExp(`\\${context?.tailwindConfig?.separator ?? ':'}(?![^[]*\\])`))
752
+ .pop(),
753
+ isArbitraryVariant: match[0].isArbitraryVariant,
754
+
537
755
  context,
538
- })
756
+ }
757
+
758
+ try {
759
+ rule.selector = finalizeSelector(finalFormat, selectorOptions)
760
+ } catch {
761
+ // The selector we produced is invalid
762
+ // This could be because:
763
+ // - A bug exists
764
+ // - A plugin introduced an invalid variant selector (ex: `addVariant('foo', '&;foo')`)
765
+ // - The user used an invalid arbitrary variant (ex: `[&;foo]:underline`)
766
+ // Either way the build will fail because of this
767
+ // We would rather that the build pass "silently" given that this could
768
+ // happen because of picking up invalid things when scanning content
769
+ // So we'll throw out the candidate instead
770
+ isValid = false
771
+ return false
772
+ }
539
773
  })
540
774
  match[1] = container.nodes[0]
541
775
  }
542
776
 
777
+ if (!isValid) {
778
+ continue
779
+ }
780
+
543
781
  yield match
544
782
  }
545
783
  }
@@ -549,16 +787,45 @@ function inKeyframes(rule) {
549
787
  return rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes'
550
788
  }
551
789
 
790
+ function getImportantStrategy(important) {
791
+ if (important === true) {
792
+ return (rule) => {
793
+ if (inKeyframes(rule)) {
794
+ return
795
+ }
796
+
797
+ rule.walkDecls((d) => {
798
+ if (d.parent.type === 'rule' && !inKeyframes(d.parent)) {
799
+ d.important = true
800
+ }
801
+ })
802
+ }
803
+ }
804
+
805
+ if (typeof important === 'string') {
806
+ return (rule) => {
807
+ if (inKeyframes(rule)) {
808
+ return
809
+ }
810
+
811
+ rule.selectors = rule.selectors.map((selector) => {
812
+ return `${important} ${selector}`
813
+ })
814
+ }
815
+ }
816
+ }
817
+
552
818
  function generateRules(candidates, context) {
553
819
  let allRules = []
820
+ let strategy = getImportantStrategy(context.tailwindConfig.important)
554
821
 
555
822
  for (let candidate of candidates) {
556
823
  if (context.notClassCache.has(candidate)) {
557
824
  continue
558
825
  }
559
826
 
560
- if (context.classCache.has(candidate)) {
561
- allRules.push(context.classCache.get(candidate))
827
+ if (context.candidateRuleCache.has(candidate)) {
828
+ allRules = allRules.concat(Array.from(context.candidateRuleCache.get(candidate)))
562
829
  continue
563
830
  }
564
831
 
@@ -570,47 +837,27 @@ function generateRules(candidates, context) {
570
837
  }
571
838
 
572
839
  context.classCache.set(candidate, matches)
573
- allRules.push(matches)
574
- }
575
840
 
576
- // Strategy based on `tailwindConfig.important`
577
- let strategy = ((important) => {
578
- if (important === true) {
579
- return (rule) => {
580
- rule.walkDecls((d) => {
581
- if (d.parent.type === 'rule' && !inKeyframes(d.parent)) {
582
- d.important = true
583
- }
584
- })
585
- }
586
- }
841
+ let rules = context.candidateRuleCache.get(candidate) ?? new Set()
842
+ context.candidateRuleCache.set(candidate, rules)
587
843
 
588
- if (typeof important === 'string') {
589
- return (rule) => {
590
- rule.selectors = rule.selectors.map((selector) => {
591
- return `${important} ${selector}`
592
- })
593
- }
594
- }
595
- })(context.tailwindConfig.important)
844
+ for (const match of matches) {
845
+ let [{ sort, options }, rule] = match
596
846
 
597
- return allRules.flat(1).map(([{ sort, layer, options }, rule]) => {
598
- if (options.respectImportant) {
599
- if (strategy) {
847
+ if (options.respectImportant && strategy) {
600
848
  let container = postcss.root({ nodes: [rule.clone()] })
601
- container.walkRules((r) => {
602
- if (inKeyframes(r)) {
603
- return
604
- }
605
-
606
- strategy(r)
607
- })
849
+ container.walkRules(strategy)
608
850
  rule = container.nodes[0]
609
851
  }
852
+
853
+ let newEntry = [sort, rule]
854
+ rules.add(newEntry)
855
+ context.ruleCache.add(newEntry)
856
+ allRules.push(newEntry)
610
857
  }
858
+ }
611
859
 
612
- return [sort | context.layerOrder[layer], rule]
613
- })
860
+ return allRules
614
861
  }
615
862
 
616
863
  function isArbitraryValue(input) {