tailwindcss 0.0.0-insiders.ca1dfd6 → 0.0.0-insiders.cb6e45a

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