tailwindcss 0.0.0-insiders.eebf529 → 0.0.0-insiders.eef91c9

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 (228) hide show
  1. package/LICENSE +1 -2
  2. package/README.md +15 -8
  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 +62 -0
  7. package/lib/cli/build/index.js +54 -0
  8. package/lib/cli/build/plugin.js +371 -0
  9. package/lib/cli/build/utils.js +88 -0
  10. package/lib/cli/build/watching.js +182 -0
  11. package/lib/cli/help/index.js +73 -0
  12. package/lib/cli/index.js +230 -0
  13. package/lib/cli/init/index.js +63 -0
  14. package/lib/cli-peer-dependencies.js +28 -7
  15. package/lib/cli.js +1 -704
  16. package/lib/corePluginList.js +17 -4
  17. package/lib/corePlugins.js +2533 -1870
  18. package/lib/css/preflight.css +35 -16
  19. package/lib/featureFlags.js +45 -26
  20. package/lib/index.js +1 -31
  21. package/lib/lib/cacheInvalidation.js +92 -0
  22. package/lib/lib/collapseAdjacentRules.js +30 -10
  23. package/lib/lib/collapseDuplicateDeclarations.js +60 -4
  24. package/lib/lib/content.js +181 -0
  25. package/lib/lib/defaultExtractor.js +251 -0
  26. package/lib/lib/evaluateTailwindFunctions.js +117 -50
  27. package/lib/lib/expandApplyAtRules.js +485 -160
  28. package/lib/lib/expandTailwindAtRules.js +166 -134
  29. package/lib/lib/findAtConfigPath.js +46 -0
  30. package/lib/lib/generateRules.js +578 -200
  31. package/lib/lib/getModuleDependencies.js +88 -37
  32. package/lib/lib/load-config.js +57 -0
  33. package/lib/lib/normalizeTailwindDirectives.js +46 -33
  34. package/lib/lib/offsets.js +355 -0
  35. package/lib/lib/partitionApplyAtRules.js +58 -0
  36. package/lib/lib/regex.js +74 -0
  37. package/lib/lib/remap-bitfield.js +89 -0
  38. package/lib/lib/resolveDefaultsAtRules.js +100 -58
  39. package/lib/lib/setupContextUtils.js +819 -324
  40. package/lib/lib/setupTrackingContext.js +71 -75
  41. package/lib/lib/sharedState.js +70 -10
  42. package/lib/lib/substituteScreenAtRules.js +14 -10
  43. package/lib/plugin.js +48 -0
  44. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  45. package/lib/postcss-plugins/nesting/index.js +21 -0
  46. package/lib/postcss-plugins/nesting/plugin.js +89 -0
  47. package/lib/processTailwindFeatures.js +38 -27
  48. package/lib/public/colors.js +272 -246
  49. package/lib/public/create-plugin.js +9 -5
  50. package/lib/public/default-config.js +10 -6
  51. package/lib/public/default-theme.js +10 -6
  52. package/lib/public/load-config.js +12 -0
  53. package/lib/public/resolve-config.js +11 -6
  54. package/lib/util/applyImportantSelector.js +36 -0
  55. package/lib/util/bigSign.js +6 -1
  56. package/lib/util/buildMediaQuery.js +13 -6
  57. package/lib/util/cloneDeep.js +9 -6
  58. package/lib/util/cloneNodes.js +44 -4
  59. package/lib/util/color.js +70 -38
  60. package/lib/util/colorNames.js +752 -0
  61. package/lib/util/configurePlugins.js +7 -2
  62. package/lib/util/createPlugin.js +8 -6
  63. package/lib/util/createUtilityPlugin.js +16 -16
  64. package/lib/util/dataTypes.js +301 -113
  65. package/lib/util/defaults.js +14 -3
  66. package/lib/util/escapeClassName.js +13 -8
  67. package/lib/util/escapeCommas.js +7 -2
  68. package/lib/util/flattenColorPalette.js +11 -12
  69. package/lib/util/formatVariantSelector.js +235 -151
  70. package/lib/util/getAllConfigs.js +33 -12
  71. package/lib/util/hashConfig.js +9 -4
  72. package/lib/util/isKeyframeRule.js +7 -2
  73. package/lib/util/isPlainObject.js +8 -3
  74. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +25 -15
  75. package/lib/util/log.js +27 -13
  76. package/lib/util/nameClass.js +27 -10
  77. package/lib/util/negateValue.js +25 -8
  78. package/lib/util/normalizeConfig.js +139 -65
  79. package/lib/util/normalizeScreens.js +128 -11
  80. package/lib/util/parseAnimationValue.js +44 -40
  81. package/lib/util/parseBoxShadowValue.js +34 -23
  82. package/lib/util/parseDependency.js +39 -55
  83. package/lib/util/parseGlob.js +36 -0
  84. package/lib/util/parseObjectStyles.js +15 -10
  85. package/lib/util/pluginUtils.js +172 -69
  86. package/lib/util/prefixSelector.js +30 -12
  87. package/lib/util/pseudoElements.js +212 -0
  88. package/lib/util/removeAlphaVariables.js +31 -0
  89. package/lib/util/resolveConfig.js +101 -79
  90. package/lib/util/resolveConfigPath.js +30 -12
  91. package/lib/util/responsive.js +11 -6
  92. package/lib/util/splitAtTopLevelOnly.js +51 -0
  93. package/lib/util/tap.js +6 -1
  94. package/lib/util/toColorValue.js +7 -3
  95. package/lib/util/toPath.js +26 -3
  96. package/lib/util/transformThemeValue.js +40 -30
  97. package/lib/util/validateConfig.js +37 -0
  98. package/lib/util/validateFormalSyntax.js +26 -0
  99. package/lib/util/withAlphaVariable.js +27 -15
  100. package/lib/value-parser/LICENSE +22 -0
  101. package/lib/value-parser/README.md +3 -0
  102. package/lib/value-parser/index.d.js +2 -0
  103. package/lib/value-parser/index.js +22 -0
  104. package/lib/value-parser/parse.js +259 -0
  105. package/lib/value-parser/stringify.js +38 -0
  106. package/lib/value-parser/unit.js +86 -0
  107. package/lib/value-parser/walk.js +16 -0
  108. package/loadConfig.d.ts +4 -0
  109. package/loadConfig.js +2 -0
  110. package/nesting/index.d.ts +4 -0
  111. package/nesting/index.js +2 -12
  112. package/package.json +62 -57
  113. package/peers/index.js +77144 -56580
  114. package/plugin.d.ts +11 -0
  115. package/resolveConfig.d.ts +31 -0
  116. package/scripts/generate-types.js +104 -0
  117. package/scripts/release-channel.js +18 -0
  118. package/scripts/release-notes.js +21 -0
  119. package/scripts/type-utils.js +27 -0
  120. package/src/cli/build/deps.js +56 -0
  121. package/src/cli/build/index.js +49 -0
  122. package/src/cli/build/plugin.js +437 -0
  123. package/src/cli/build/utils.js +76 -0
  124. package/src/cli/build/watching.js +229 -0
  125. package/src/cli/help/index.js +70 -0
  126. package/src/cli/index.js +216 -0
  127. package/src/cli/init/index.js +79 -0
  128. package/src/cli-peer-dependencies.js +7 -1
  129. package/src/cli.js +1 -766
  130. package/src/corePluginList.js +1 -1
  131. package/src/corePlugins.js +918 -301
  132. package/src/css/preflight.css +35 -16
  133. package/src/featureFlags.js +13 -5
  134. package/src/index.js +1 -34
  135. package/src/lib/cacheInvalidation.js +52 -0
  136. package/src/lib/collapseAdjacentRules.js +21 -2
  137. package/src/lib/collapseDuplicateDeclarations.js +66 -1
  138. package/src/lib/content.js +208 -0
  139. package/src/lib/defaultExtractor.js +230 -0
  140. package/src/lib/evaluateTailwindFunctions.js +83 -9
  141. package/src/lib/expandApplyAtRules.js +538 -152
  142. package/src/lib/expandTailwindAtRules.js +115 -87
  143. package/src/lib/findAtConfigPath.js +48 -0
  144. package/src/lib/generateRules.js +570 -148
  145. package/src/lib/getModuleDependencies.js +70 -30
  146. package/src/lib/load-config.ts +44 -0
  147. package/src/lib/normalizeTailwindDirectives.js +7 -1
  148. package/src/lib/offsets.js +432 -0
  149. package/src/lib/partitionApplyAtRules.js +52 -0
  150. package/src/lib/regex.js +74 -0
  151. package/src/lib/remap-bitfield.js +82 -0
  152. package/src/lib/resolveDefaultsAtRules.js +63 -17
  153. package/src/lib/setupContextUtils.js +752 -182
  154. package/src/lib/setupTrackingContext.js +52 -65
  155. package/src/lib/sharedState.js +54 -7
  156. package/src/plugin.js +47 -0
  157. package/src/postcss-plugins/nesting/README.md +42 -0
  158. package/src/postcss-plugins/nesting/index.js +13 -0
  159. package/src/postcss-plugins/nesting/plugin.js +80 -0
  160. package/src/processTailwindFeatures.js +13 -5
  161. package/src/public/colors.js +22 -0
  162. package/src/public/default-config.js +1 -1
  163. package/src/public/default-theme.js +2 -2
  164. package/src/public/load-config.js +2 -0
  165. package/src/util/applyImportantSelector.js +27 -0
  166. package/src/util/buildMediaQuery.js +5 -3
  167. package/src/util/cloneNodes.js +40 -2
  168. package/src/util/color.js +44 -12
  169. package/src/util/colorNames.js +150 -0
  170. package/src/util/dataTypes.js +190 -26
  171. package/src/util/defaults.js +6 -0
  172. package/src/util/formatVariantSelector.js +272 -144
  173. package/src/util/getAllConfigs.js +21 -2
  174. package/src/util/isPlainObject.js +1 -1
  175. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  176. package/src/util/log.js +11 -7
  177. package/src/util/nameClass.js +4 -0
  178. package/src/util/negateValue.js +11 -3
  179. package/src/util/normalizeConfig.js +57 -5
  180. package/src/util/normalizeScreens.js +99 -4
  181. package/src/util/parseBoxShadowValue.js +4 -3
  182. package/src/util/parseDependency.js +37 -42
  183. package/src/util/parseGlob.js +24 -0
  184. package/src/util/pluginUtils.js +139 -24
  185. package/src/util/prefixSelector.js +31 -10
  186. package/src/util/pseudoElements.js +171 -0
  187. package/src/util/removeAlphaVariables.js +24 -0
  188. package/src/util/resolveConfig.js +74 -26
  189. package/src/util/resolveConfigPath.js +12 -1
  190. package/src/util/splitAtTopLevelOnly.js +52 -0
  191. package/src/util/toPath.js +23 -1
  192. package/src/util/transformThemeValue.js +13 -3
  193. package/src/util/validateConfig.js +26 -0
  194. package/src/util/validateFormalSyntax.js +34 -0
  195. package/src/util/withAlphaVariable.js +1 -1
  196. package/src/value-parser/LICENSE +22 -0
  197. package/src/value-parser/README.md +3 -0
  198. package/src/value-parser/index.d.ts +177 -0
  199. package/src/value-parser/index.js +28 -0
  200. package/src/value-parser/parse.js +303 -0
  201. package/src/value-parser/stringify.js +41 -0
  202. package/src/value-parser/unit.js +118 -0
  203. package/src/value-parser/walk.js +18 -0
  204. package/stubs/.gitignore +1 -0
  205. package/stubs/.prettierrc.json +6 -0
  206. package/stubs/{defaultConfig.stub.js → config.full.js} +293 -181
  207. package/stubs/postcss.config.js +6 -0
  208. package/stubs/tailwind.config.cjs +2 -0
  209. package/stubs/tailwind.config.js +2 -0
  210. package/stubs/tailwind.config.ts +3 -0
  211. package/types/config.d.ts +376 -0
  212. package/types/generated/.gitkeep +0 -0
  213. package/types/generated/colors.d.ts +298 -0
  214. package/types/generated/corePluginList.d.ts +1 -0
  215. package/types/generated/default-theme.d.ts +397 -0
  216. package/types/index.d.ts +11 -0
  217. package/CHANGELOG.md +0 -1853
  218. package/lib/constants.js +0 -37
  219. package/lib/lib/detectNesting.js +0 -34
  220. package/lib/lib/setupWatchingContext.js +0 -288
  221. package/nesting/plugin.js +0 -41
  222. package/scripts/install-integrations.js +0 -27
  223. package/scripts/rebuildFixtures.js +0 -68
  224. package/src/constants.js +0 -17
  225. package/src/lib/detectNesting.js +0 -39
  226. package/src/lib/setupWatchingContext.js +0 -311
  227. /package/stubs/{simpleConfig.stub.js → config.simple.js} +0 -0
  228. /package/stubs/{defaultPostCssConfig.stub.js → postcss.config.cjs} +0 -0
@@ -11,42 +11,95 @@ import isPlainObject from '../util/isPlainObject'
11
11
  import escapeClassName from '../util/escapeClassName'
12
12
  import nameClass, { formatClass } from '../util/nameClass'
13
13
  import { coerceValue } from '../util/pluginUtils'
14
- import bigSign from '../util/bigSign'
15
14
  import { variantPlugins, corePlugins } from '../corePlugins'
16
15
  import * as sharedState from './sharedState'
17
16
  import { env } from './sharedState'
18
17
  import { toPath } from '../util/toPath'
19
18
  import log from '../util/log'
20
19
  import negateValue from '../util/negateValue'
21
- import isValidArbitraryValue from '../util/isValidArbitraryValue'
22
-
23
- function parseVariantFormatString(input) {
24
- if (input.includes('{')) {
25
- if (!isBalanced(input)) throw new Error(`Your { and } are unbalanced.`)
20
+ import isSyntacticallyValidPropertyValue from '../util/isSyntacticallyValidPropertyValue'
21
+ import { generateRules, getClassNameFromSelector } from './generateRules'
22
+ import { hasContentChanged } from './cacheInvalidation.js'
23
+ import { Offsets } from './offsets.js'
24
+ import { flagEnabled } from '../featureFlags.js'
25
+ import { finalizeSelector, formatVariantSelector } from '../util/formatVariantSelector'
26
+
27
+ export const INTERNAL_FEATURES = Symbol()
28
+
29
+ const VARIANT_TYPES = {
30
+ AddVariant: Symbol.for('ADD_VARIANT'),
31
+ MatchVariant: Symbol.for('MATCH_VARIANT'),
32
+ }
26
33
 
27
- return input
28
- .split(/{(.*)}/gim)
29
- .flatMap((line) => parseVariantFormatString(line))
30
- .filter(Boolean)
31
- }
34
+ const VARIANT_INFO = {
35
+ Base: 1 << 0,
36
+ Dynamic: 1 << 1,
37
+ }
32
38
 
33
- return [input.trim()]
39
+ function prefix(context, selector) {
40
+ let prefix = context.tailwindConfig.prefix
41
+ return typeof prefix === 'function' ? prefix(selector) : prefix + selector
34
42
  }
35
43
 
36
- function isBalanced(input) {
37
- let count = 0
44
+ function normalizeOptionTypes({ type = 'any', ...options }) {
45
+ let types = [].concat(type)
46
+
47
+ return {
48
+ ...options,
49
+ types: types.map((type) => {
50
+ if (Array.isArray(type)) {
51
+ return { type: type[0], ...type[1] }
52
+ }
53
+ return { type, preferOnConflict: false }
54
+ }),
55
+ }
56
+ }
38
57
 
39
- for (let char of input) {
40
- if (char === '{') {
41
- count++
58
+ function parseVariantFormatString(input) {
59
+ /** @type {string[]} */
60
+ let parts = []
61
+
62
+ // When parsing whitespace around special characters are insignificant
63
+ // However, _inside_ of a variant they could be
64
+ // Because the selector could look like this
65
+ // @media { &[data-name="foo bar"] }
66
+ // This is why we do not skip whitespace
67
+
68
+ let current = ''
69
+ let depth = 0
70
+
71
+ for (let idx = 0; idx < input.length; idx++) {
72
+ let char = input[idx]
73
+
74
+ if (char === '\\') {
75
+ // Escaped characters are not special
76
+ current += '\\' + input[++idx]
77
+ } else if (char === '{') {
78
+ // Nested rule: start
79
+ ++depth
80
+ parts.push(current.trim())
81
+ current = ''
42
82
  } else if (char === '}') {
43
- if (--count < 0) {
44
- return false // unbalanced
83
+ // Nested rule: end
84
+ if (--depth < 0) {
85
+ throw new Error(`Your { and } are unbalanced.`)
45
86
  }
87
+
88
+ parts.push(current.trim())
89
+ current = ''
90
+ } else {
91
+ // Normal character
92
+ current += char
46
93
  }
47
94
  }
48
95
 
49
- return count === 0
96
+ if (current.length > 0) {
97
+ parts.push(current.trim())
98
+ }
99
+
100
+ parts = parts.filter((part) => part !== '')
101
+
102
+ return parts
50
103
  }
51
104
 
52
105
  function insertInto(list, value, { before = [] } = {}) {
@@ -78,35 +131,66 @@ function parseStyles(styles) {
78
131
  })
79
132
  }
80
133
 
81
- function getClasses(selector) {
134
+ function getClasses(selector, mutate) {
82
135
  let parser = selectorParser((selectors) => {
83
136
  let allClasses = []
137
+
138
+ if (mutate) {
139
+ mutate(selectors)
140
+ }
141
+
84
142
  selectors.walkClasses((classNode) => {
85
143
  allClasses.push(classNode.value)
86
144
  })
145
+
87
146
  return allClasses
88
147
  })
89
148
  return parser.transformSync(selector)
90
149
  }
91
150
 
92
- function extractCandidates(node) {
151
+ /**
152
+ * Ignore everything inside a :not(...). This allows you to write code like
153
+ * `div:not(.foo)`. If `.foo` is never found in your code, then we used to
154
+ * not generated it. But now we will ignore everything inside a `:not`, so
155
+ * that it still gets generated.
156
+ *
157
+ * @param {selectorParser.Root} selectors
158
+ */
159
+ function ignoreNot(selectors) {
160
+ selectors.walkPseudos((pseudo) => {
161
+ if (pseudo.value === ':not') {
162
+ pseudo.remove()
163
+ }
164
+ })
165
+ }
166
+
167
+ function extractCandidates(node, state = { containsNonOnDemandable: false }, depth = 0) {
93
168
  let classes = []
169
+ let selectors = []
94
170
 
95
171
  if (node.type === 'rule') {
96
- for (let selector of node.selectors) {
97
- let classCandidates = getClasses(selector)
98
- // At least one of the selectors contains non-"on-demandable" candidates.
99
- if (classCandidates.length === 0) return []
172
+ // Handle normal rules
173
+ selectors.push(...node.selectors)
174
+ } else if (node.type === 'atrule') {
175
+ // Handle at-rules (which contains nested rules)
176
+ node.walkRules((rule) => selectors.push(...rule.selectors))
177
+ }
178
+
179
+ for (let selector of selectors) {
180
+ let classCandidates = getClasses(selector, ignoreNot)
181
+
182
+ // At least one of the selectors contains non-"on-demandable" candidates.
183
+ if (classCandidates.length === 0) {
184
+ state.containsNonOnDemandable = true
185
+ }
100
186
 
101
- classes = [...classes, ...classCandidates]
187
+ for (let classCandidate of classCandidates) {
188
+ classes.push(classCandidate)
102
189
  }
103
- return classes
104
190
  }
105
191
 
106
- if (node.type === 'atrule') {
107
- node.walkRules((rule) => {
108
- classes = [...classes, ...rule.selectors.flatMap((selector) => getClasses(selector))]
109
- })
192
+ if (depth === 0) {
193
+ return [state.containsNonOnDemandable || classes.length === 0, classes]
110
194
  }
111
195
 
112
196
  return classes
@@ -115,13 +199,16 @@ function extractCandidates(node) {
115
199
  function withIdentifiers(styles) {
116
200
  return parseStyles(styles).flatMap((node) => {
117
201
  let nodeMap = new Map()
118
- let candidates = extractCandidates(node)
202
+ let [containsNonOnDemandableSelectors, candidates] = extractCandidates(node)
119
203
 
120
- // If this isn't "on-demandable", assign it a universal candidate.
121
- if (candidates.length === 0) {
122
- return [['*', node]]
204
+ // If this isn't "on-demandable", assign it a universal candidate to always include it.
205
+ if (containsNonOnDemandableSelectors) {
206
+ candidates.unshift(sharedState.NOT_ON_DEMAND)
123
207
  }
124
208
 
209
+ // However, it could be that it also contains "on-demandable" candidates.
210
+ // E.g.: `span, .foo {}`, in that case it should still be possible to use
211
+ // `@apply foo` for example.
125
212
  return candidates.map((c) => {
126
213
  if (!nodeMap.has(node)) {
127
214
  nodeMap.set(node, node)
@@ -131,6 +218,41 @@ function withIdentifiers(styles) {
131
218
  })
132
219
  }
133
220
 
221
+ export function isValidVariantFormatString(format) {
222
+ return format.startsWith('@') || format.includes('&')
223
+ }
224
+
225
+ export function parseVariant(variant) {
226
+ variant = variant
227
+ .replace(/\n+/g, '')
228
+ .replace(/\s{1,}/g, ' ')
229
+ .trim()
230
+
231
+ let fns = parseVariantFormatString(variant)
232
+ .map((str) => {
233
+ if (!str.startsWith('@')) {
234
+ return ({ format }) => format(str)
235
+ }
236
+
237
+ let [, name, params] = /@(\S*)( .+|[({].*)?/g.exec(str)
238
+ return ({ wrap }) => wrap(postcss.atRule({ name, params: params?.trim() ?? '' }))
239
+ })
240
+ .reverse()
241
+
242
+ return (api) => {
243
+ for (let fn of fns) {
244
+ fn(api)
245
+ }
246
+ }
247
+ }
248
+
249
+ /**
250
+ *
251
+ * @param {any} tailwindConfig
252
+ * @param {any} context
253
+ * @param {object} param2
254
+ * @param {Offsets} param2.offsets
255
+ */
134
256
  function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offsets, classList }) {
135
257
  function getConfigValue(path, defaultValue) {
136
258
  return path ? dlv(tailwindConfig, path, defaultValue) : tailwindConfig
@@ -141,8 +263,8 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
141
263
  }
142
264
 
143
265
  function prefixIdentifier(identifier, options) {
144
- if (identifier === '*') {
145
- return '*'
266
+ if (identifier === sharedState.NOT_ON_DEMAND) {
267
+ return sharedState.NOT_ON_DEMAND
146
268
  }
147
269
 
148
270
  if (!options.respectPrefix) {
@@ -152,51 +274,19 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
152
274
  return context.tailwindConfig.prefix + identifier
153
275
  }
154
276
 
155
- return {
156
- addVariant(variantName, variantFunctions, options = {}) {
157
- variantFunctions = [].concat(variantFunctions).map((variantFunction) => {
158
- if (typeof variantFunction !== 'string') {
159
- // Safelist public API functions
160
- return ({ modifySelectors, container, separator }) => {
161
- return variantFunction({ modifySelectors, container, separator })
162
- }
163
- }
164
-
165
- variantFunction = variantFunction
166
- .replace(/\n+/g, '')
167
- .replace(/\s{1,}/g, ' ')
168
- .trim()
169
-
170
- let fns = parseVariantFormatString(variantFunction)
171
- .map((str) => {
172
- if (!str.startsWith('@')) {
173
- return ({ format }) => format(str)
174
- }
175
-
176
- let [, name, params] = /@(.*?) (.*)/g.exec(str)
177
- return ({ wrap }) => wrap(postcss.atRule({ name, params }))
178
- })
179
- .reverse()
180
-
181
- return (api) => {
182
- for (let fn of fns) {
183
- fn(api)
184
- }
185
- }
186
- })
277
+ function resolveThemeValue(path, defaultValue, opts = {}) {
278
+ let parts = toPath(path)
279
+ let value = getConfigValue(['theme', ...parts], defaultValue)
280
+ return transformThemeValue(parts[0])(value, opts)
281
+ }
187
282
 
188
- insertInto(variantList, variantName, options)
189
- variantMap.set(variantName, variantFunctions)
190
- },
283
+ let variantIdentifier = 0
284
+ let api = {
191
285
  postcss,
192
286
  prefix: applyConfiguredPrefix,
193
287
  e: escapeClassName,
194
288
  config: getConfigValue,
195
- theme(path, defaultValue) {
196
- const [pathRoot, ...subPaths] = toPath(path)
197
- const value = getConfigValue(['theme', pathRoot, ...subPaths], defaultValue)
198
- return transformThemeValue(pathRoot)(value)
199
- },
289
+ theme: resolveThemeValue,
200
290
  corePlugins: (path) => {
201
291
  if (Array.isArray(tailwindConfig.corePlugins)) {
202
292
  return tailwindConfig.corePlugins.includes(path)
@@ -208,21 +298,31 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
208
298
  // Preserved for backwards compatibility but not used in v3.0+
209
299
  return []
210
300
  },
211
- addUserCss(userCss) {
212
- for (let [identifier, rule] of withIdentifiers(userCss)) {
213
- let offset = offsets.user++
301
+ addBase(base) {
302
+ for (let [identifier, rule] of withIdentifiers(base)) {
303
+ let prefixedIdentifier = prefixIdentifier(identifier, {})
304
+ let offset = offsets.create('base')
214
305
 
215
- if (!context.candidateRuleMap.has(identifier)) {
216
- context.candidateRuleMap.set(identifier, [])
306
+ if (!context.candidateRuleMap.has(prefixedIdentifier)) {
307
+ context.candidateRuleMap.set(prefixedIdentifier, [])
217
308
  }
218
309
 
219
- context.candidateRuleMap.get(identifier).push([{ sort: offset, layer: 'user' }, rule])
310
+ context.candidateRuleMap
311
+ .get(prefixedIdentifier)
312
+ .push([{ sort: offset, layer: 'base' }, rule])
220
313
  }
221
314
  },
222
- addBase(base) {
223
- for (let [identifier, rule] of withIdentifiers(base)) {
315
+ /**
316
+ * @param {string} group
317
+ * @param {Record<string, string | string[]>} declarations
318
+ */
319
+ addDefaults(group, declarations) {
320
+ const groups = {
321
+ [`@defaults ${group}`]: declarations,
322
+ }
323
+
324
+ for (let [identifier, rule] of withIdentifiers(groups)) {
224
325
  let prefixedIdentifier = prefixIdentifier(identifier, {})
225
- let offset = offsets.base++
226
326
 
227
327
  if (!context.candidateRuleMap.has(prefixedIdentifier)) {
228
328
  context.candidateRuleMap.set(prefixedIdentifier, [])
@@ -230,11 +330,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
230
330
 
231
331
  context.candidateRuleMap
232
332
  .get(prefixedIdentifier)
233
- .push([{ sort: offset, layer: 'base' }, rule])
333
+ .push([{ sort: offsets.create('defaults'), layer: 'defaults' }, rule])
234
334
  }
235
335
  },
236
336
  addComponents(components, options) {
237
337
  let defaultOptions = {
338
+ preserveSource: false,
238
339
  respectPrefix: true,
239
340
  respectImportant: false,
240
341
  }
@@ -243,7 +344,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
243
344
 
244
345
  for (let [identifier, rule] of withIdentifiers(components)) {
245
346
  let prefixedIdentifier = prefixIdentifier(identifier, options)
246
- let offset = offsets.components++
247
347
 
248
348
  classList.add(prefixedIdentifier)
249
349
 
@@ -253,11 +353,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
253
353
 
254
354
  context.candidateRuleMap
255
355
  .get(prefixedIdentifier)
256
- .push([{ sort: offset, layer: 'components', options }, rule])
356
+ .push([{ sort: offsets.create('components'), layer: 'components', options }, rule])
257
357
  }
258
358
  },
259
359
  addUtilities(utilities, options) {
260
360
  let defaultOptions = {
361
+ preserveSource: false,
261
362
  respectPrefix: true,
262
363
  respectImportant: true,
263
364
  }
@@ -266,7 +367,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
266
367
 
267
368
  for (let [identifier, rule] of withIdentifiers(utilities)) {
268
369
  let prefixedIdentifier = prefixIdentifier(identifier, options)
269
- let offset = offsets.utilities++
270
370
 
271
371
  classList.add(prefixedIdentifier)
272
372
 
@@ -276,18 +376,19 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
276
376
 
277
377
  context.candidateRuleMap
278
378
  .get(prefixedIdentifier)
279
- .push([{ sort: offset, layer: 'utilities', options }, rule])
379
+ .push([{ sort: offsets.create('utilities'), layer: 'utilities', options }, rule])
280
380
  }
281
381
  },
282
382
  matchUtilities: function (utilities, options) {
283
383
  let defaultOptions = {
284
384
  respectPrefix: true,
285
385
  respectImportant: true,
386
+ modifiers: false,
286
387
  }
287
388
 
288
- options = { ...defaultOptions, ...options }
389
+ options = normalizeOptionTypes({ ...defaultOptions, ...options })
289
390
 
290
- let offset = offsets.utilities++
391
+ let offset = offsets.create('utilities')
291
392
 
292
393
  for (let identifier in utilities) {
293
394
  let prefixedIdentifier = prefixIdentifier(identifier, options)
@@ -296,24 +397,51 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
296
397
  classList.add([prefixedIdentifier, options])
297
398
 
298
399
  function wrapped(modifier, { isOnlyPlugin }) {
299
- let { type = 'any' } = options
300
- type = [].concat(type)
301
- let [value, coercedType] = coerceValue(type, modifier, options, tailwindConfig)
400
+ let [value, coercedType, utilityModifier] = coerceValue(
401
+ options.types,
402
+ modifier,
403
+ options,
404
+ tailwindConfig
405
+ )
302
406
 
303
407
  if (value === undefined) {
304
408
  return []
305
409
  }
306
410
 
307
- if (!type.includes(coercedType) && !isOnlyPlugin) {
308
- return []
411
+ if (!options.types.some(({ type }) => type === coercedType)) {
412
+ if (isOnlyPlugin) {
413
+ log.warn([
414
+ `Unnecessary typehint \`${coercedType}\` in \`${identifier}-${modifier}\`.`,
415
+ `You can safely update it to \`${identifier}-${modifier.replace(
416
+ coercedType + ':',
417
+ ''
418
+ )}\`.`,
419
+ ])
420
+ } else {
421
+ return []
422
+ }
309
423
  }
310
424
 
311
- if (!isValidArbitraryValue(value)) {
425
+ if (!isSyntacticallyValidPropertyValue(value)) {
312
426
  return []
313
427
  }
314
428
 
429
+ let extras = {
430
+ get modifier() {
431
+ if (!options.modifiers) {
432
+ log.warn(`modifier-used-without-options-for-${identifier}`, [
433
+ 'Your plugin must set `modifiers: true` in its options to support modifiers.',
434
+ ])
435
+ }
436
+
437
+ return utilityModifier
438
+ },
439
+ }
440
+
441
+ let modifiersEnabled = flagEnabled(tailwindConfig, 'generalizedModifiers')
442
+
315
443
  let ruleSets = []
316
- .concat(rule(value))
444
+ .concat(modifiersEnabled ? rule(value, extras) : rule(value))
317
445
  .filter(Boolean)
318
446
  .map((declaration) => ({
319
447
  [nameClass(identifier, modifier)]: declaration,
@@ -335,11 +463,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
335
463
  let defaultOptions = {
336
464
  respectPrefix: true,
337
465
  respectImportant: false,
466
+ modifiers: false,
338
467
  }
339
468
 
340
- options = { ...defaultOptions, ...options }
469
+ options = normalizeOptionTypes({ ...defaultOptions, ...options })
341
470
 
342
- let offset = offsets.components++
471
+ let offset = offsets.create('components')
343
472
 
344
473
  for (let identifier in components) {
345
474
  let prefixedIdentifier = prefixIdentifier(identifier, options)
@@ -348,15 +477,18 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
348
477
  classList.add([prefixedIdentifier, options])
349
478
 
350
479
  function wrapped(modifier, { isOnlyPlugin }) {
351
- let { type = 'any' } = options
352
- type = [].concat(type)
353
- let [value, coercedType] = coerceValue(type, modifier, options, tailwindConfig)
480
+ let [value, coercedType, utilityModifier] = coerceValue(
481
+ options.types,
482
+ modifier,
483
+ options,
484
+ tailwindConfig
485
+ )
354
486
 
355
487
  if (value === undefined) {
356
488
  return []
357
489
  }
358
490
 
359
- if (!type.includes(coercedType)) {
491
+ if (!options.types.some(({ type }) => type === coercedType)) {
360
492
  if (isOnlyPlugin) {
361
493
  log.warn([
362
494
  `Unnecessary typehint \`${coercedType}\` in \`${identifier}-${modifier}\`.`,
@@ -370,12 +502,26 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
370
502
  }
371
503
  }
372
504
 
373
- if (!isValidArbitraryValue(value)) {
505
+ if (!isSyntacticallyValidPropertyValue(value)) {
374
506
  return []
375
507
  }
376
508
 
509
+ let extras = {
510
+ get modifier() {
511
+ if (!options.modifiers) {
512
+ log.warn(`modifier-used-without-options-for-${identifier}`, [
513
+ 'Your plugin must set `modifiers: true` in its options to support modifiers.',
514
+ ])
515
+ }
516
+
517
+ return utilityModifier
518
+ },
519
+ }
520
+
521
+ let modifiersEnabled = flagEnabled(tailwindConfig, 'generalizedModifiers')
522
+
377
523
  let ruleSets = []
378
- .concat(rule(value))
524
+ .concat(modifiersEnabled ? rule(value, extras) : rule(value))
379
525
  .filter(Boolean)
380
526
  .map((declaration) => ({
381
527
  [nameClass(identifier, modifier)]: declaration,
@@ -393,7 +539,109 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
393
539
  context.candidateRuleMap.get(prefixedIdentifier).push(withOffsets)
394
540
  }
395
541
  },
542
+ addVariant(variantName, variantFunctions, options = {}) {
543
+ variantFunctions = [].concat(variantFunctions).map((variantFunction) => {
544
+ if (typeof variantFunction !== 'string') {
545
+ // Safelist public API functions
546
+ return (api = {}) => {
547
+ let { args, modifySelectors, container, separator, wrap, format } = api
548
+ let result = variantFunction(
549
+ Object.assign(
550
+ { modifySelectors, container, separator },
551
+ options.type === VARIANT_TYPES.MatchVariant && { args, wrap, format }
552
+ )
553
+ )
554
+
555
+ if (typeof result === 'string' && !isValidVariantFormatString(result)) {
556
+ throw new Error(
557
+ `Your custom variant \`${variantName}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`
558
+ )
559
+ }
560
+
561
+ if (Array.isArray(result)) {
562
+ return result
563
+ .filter((variant) => typeof variant === 'string')
564
+ .map((variant) => parseVariant(variant))
565
+ }
566
+
567
+ // result may be undefined with legacy variants that use APIs like `modifySelectors`
568
+ // result may also be a postcss node if someone was returning the result from `modifySelectors`
569
+ return result && typeof result === 'string' && parseVariant(result)(api)
570
+ }
571
+ }
572
+
573
+ if (!isValidVariantFormatString(variantFunction)) {
574
+ throw new Error(
575
+ `Your custom variant \`${variantName}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`
576
+ )
577
+ }
578
+
579
+ return parseVariant(variantFunction)
580
+ })
581
+
582
+ insertInto(variantList, variantName, options)
583
+ variantMap.set(variantName, variantFunctions)
584
+ context.variantOptions.set(variantName, options)
585
+ },
586
+ matchVariant(variant, variantFn, options) {
587
+ // A unique identifier that "groups" these variants together.
588
+ // This is for internal use only which is why it is not present in the types
589
+ let id = options?.id ?? ++variantIdentifier
590
+ let isSpecial = variant === '@'
591
+
592
+ let modifiersEnabled = flagEnabled(tailwindConfig, 'generalizedModifiers')
593
+
594
+ for (let [key, value] of Object.entries(options?.values ?? {})) {
595
+ if (key === 'DEFAULT') continue
596
+
597
+ api.addVariant(
598
+ isSpecial ? `${variant}${key}` : `${variant}-${key}`,
599
+ ({ args, container }) => {
600
+ return variantFn(
601
+ value,
602
+ modifiersEnabled ? { modifier: args?.modifier, container } : { container }
603
+ )
604
+ },
605
+
606
+ {
607
+ ...options,
608
+ value,
609
+ id,
610
+ type: VARIANT_TYPES.MatchVariant,
611
+ variantInfo: VARIANT_INFO.Base,
612
+ }
613
+ )
614
+ }
615
+
616
+ let hasDefault = 'DEFAULT' in (options?.values ?? {})
617
+
618
+ api.addVariant(
619
+ variant,
620
+ ({ args, container }) => {
621
+ if (args?.value === sharedState.NONE && !hasDefault) {
622
+ return null
623
+ }
624
+
625
+ return variantFn(
626
+ args?.value === sharedState.NONE
627
+ ? options.values.DEFAULT
628
+ : // Falling back to args if it is a string, otherwise '' for older intellisense
629
+ // (JetBrains) plugins.
630
+ args?.value ?? (typeof args === 'string' ? args : ''),
631
+ modifiersEnabled ? { modifier: args?.modifier, container } : { container }
632
+ )
633
+ },
634
+ {
635
+ ...options,
636
+ id,
637
+ type: VARIANT_TYPES.MatchVariant,
638
+ variantInfo: VARIANT_INFO.Dynamic,
639
+ }
640
+ )
641
+ },
396
642
  }
643
+
644
+ return api
397
645
  }
398
646
 
399
647
  let fileModifiedMapCache = new WeakMap()
@@ -406,6 +654,7 @@ export function getFileModifiedMap(context) {
406
654
 
407
655
  function trackModified(files, fileModifiedMap) {
408
656
  let changed = false
657
+ let mtimesToCommit = new Map()
409
658
 
410
659
  for (let file of files) {
411
660
  if (!file) continue
@@ -413,16 +662,23 @@ function trackModified(files, fileModifiedMap) {
413
662
  let parsed = url.parse(file)
414
663
  let pathname = parsed.hash ? parsed.href.replace(parsed.hash, '') : parsed.href
415
664
  pathname = parsed.search ? pathname.replace(parsed.search, '') : pathname
416
- let newModified = fs.statSync(decodeURIComponent(pathname)).mtimeMs
665
+ let newModified = fs.statSync(decodeURIComponent(pathname), { throwIfNoEntry: false })?.mtimeMs
666
+ if (!newModified) {
667
+ // It could happen that a file is passed in that doesn't exist. E.g.:
668
+ // postcss-cli will provide you a fake path when reading from stdin. This
669
+ // path then looks like /path-to-your-project/stdin In that case we just
670
+ // want to ignore it and don't track changes at all.
671
+ continue
672
+ }
417
673
 
418
674
  if (!fileModifiedMap.has(file) || newModified > fileModifiedMap.get(file)) {
419
675
  changed = true
420
676
  }
421
677
 
422
- fileModifiedMap.set(file, newModified)
678
+ mtimesToCommit.set(file, newModified)
423
679
  }
424
680
 
425
- return changed
681
+ return [changed, mtimesToCommit]
426
682
  }
427
683
 
428
684
  function extractVariantAtRules(node) {
@@ -459,29 +715,20 @@ function collectLayerPlugins(root) {
459
715
  } else if (layerRule.params === 'components') {
460
716
  for (let node of layerRule.nodes) {
461
717
  layerPlugins.push(function ({ addComponents }) {
462
- addComponents(node, { respectPrefix: false })
718
+ addComponents(node, { respectPrefix: false, preserveSource: true })
463
719
  })
464
720
  }
465
721
  layerRule.remove()
466
722
  } else if (layerRule.params === 'utilities') {
467
723
  for (let node of layerRule.nodes) {
468
724
  layerPlugins.push(function ({ addUtilities }) {
469
- addUtilities(node, { respectPrefix: false })
725
+ addUtilities(node, { respectPrefix: false, preserveSource: true })
470
726
  })
471
727
  }
472
728
  layerRule.remove()
473
729
  }
474
730
  })
475
731
 
476
- root.walkRules((rule) => {
477
- // At this point it is safe to include all the left-over css from the
478
- // user's css file. This is because the `@tailwind` and `@layer` directives
479
- // will already be handled and will be removed from the css tree.
480
- layerPlugins.push(function ({ addUserCss }) {
481
- addUserCss(rule, { respectPrefix: false })
482
- })
483
- })
484
-
485
732
  return layerPlugins
486
733
  }
487
734
 
@@ -509,30 +756,56 @@ function resolvePlugins(context, root) {
509
756
  // TODO: This is a workaround for backwards compatibility, since custom variants
510
757
  // were historically sorted before screen/stackable variants.
511
758
  let beforeVariants = [
759
+ variantPlugins['childVariant'],
512
760
  variantPlugins['pseudoElementVariants'],
513
761
  variantPlugins['pseudoClassVariants'],
762
+ variantPlugins['hasVariants'],
763
+ variantPlugins['ariaVariants'],
764
+ variantPlugins['dataVariants'],
514
765
  ]
515
766
  let afterVariants = [
516
- variantPlugins['directionVariants'],
767
+ variantPlugins['supportsVariants'],
517
768
  variantPlugins['reducedMotionVariants'],
518
- variantPlugins['darkVariants'],
519
- variantPlugins['printVariant'],
769
+ variantPlugins['prefersContrastVariants'],
520
770
  variantPlugins['screenVariants'],
521
771
  variantPlugins['orientationVariants'],
772
+ variantPlugins['directionVariants'],
773
+ variantPlugins['darkVariants'],
774
+ variantPlugins['forcedColorsVariants'],
775
+ variantPlugins['printVariant'],
522
776
  ]
523
777
 
778
+ // This is a compatibility fix for the pre 3.4 dark mode behavior
779
+ // `class` retains the old behavior, but `selector` keeps the new behavior
780
+ let isLegacyDarkMode =
781
+ context.tailwindConfig.darkMode === 'class' ||
782
+ (Array.isArray(context.tailwindConfig.darkMode) &&
783
+ context.tailwindConfig.darkMode[0] === 'class')
784
+
785
+ if (isLegacyDarkMode) {
786
+ afterVariants = [
787
+ variantPlugins['supportsVariants'],
788
+ variantPlugins['reducedMotionVariants'],
789
+ variantPlugins['prefersContrastVariants'],
790
+ variantPlugins['darkVariants'],
791
+ variantPlugins['screenVariants'],
792
+ variantPlugins['orientationVariants'],
793
+ variantPlugins['directionVariants'],
794
+ variantPlugins['forcedColorsVariants'],
795
+ variantPlugins['printVariant'],
796
+ ]
797
+ }
798
+
524
799
  return [...corePluginList, ...beforeVariants, ...userPlugins, ...afterVariants, ...layerPlugins]
525
800
  }
526
801
 
527
802
  function registerPlugins(plugins, context) {
528
803
  let variantList = []
529
804
  let variantMap = new Map()
530
- let offsets = {
531
- base: 0n,
532
- components: 0n,
533
- utilities: 0n,
534
- user: 0n,
535
- }
805
+ context.variantMap = variantMap
806
+
807
+ let offsets = new Offsets()
808
+ context.offsets = offsets
536
809
 
537
810
  let classList = new Set()
538
811
 
@@ -553,47 +826,17 @@ function registerPlugins(plugins, context) {
553
826
  }
554
827
  }
555
828
 
556
- let highestOffset = ((args) => args.reduce((m, e) => (e > m ? e : m)))([
557
- offsets.base,
558
- offsets.components,
559
- offsets.utilities,
560
- offsets.user,
561
- ])
562
- let reservedBits = BigInt(highestOffset.toString(2).length)
563
-
564
- // A number one less than the top range of the highest offset area
565
- // so arbitrary properties are always sorted at the end.
566
- context.arbitraryPropertiesSort = ((1n << reservedBits) << 0n) - 1n
567
-
568
- context.layerOrder = {
569
- base: (1n << reservedBits) << 0n,
570
- components: (1n << reservedBits) << 1n,
571
- utilities: (1n << reservedBits) << 2n,
572
- user: (1n << reservedBits) << 3n,
573
- }
574
-
575
- reservedBits += 4n
576
-
577
- let offset = 0
578
- context.variantOrder = new Map(
579
- variantList
580
- .map((variant, i) => {
581
- let variantFunctions = variantMap.get(variant).length
582
- let bits = (1n << BigInt(i + offset)) << reservedBits
583
- offset += variantFunctions - 1
584
- return [variant, bits]
585
- })
586
- .sort(([, a], [, z]) => bigSign(a - z))
587
- )
588
-
589
- context.minimumScreen = [...context.variantOrder.values()].shift()
829
+ // Make sure to record bit masks for every variant
830
+ offsets.recordVariants(variantList, (variant) => variantMap.get(variant).length)
590
831
 
591
832
  // Build variantMap
592
833
  for (let [variantName, variantFunctions] of variantMap.entries()) {
593
- let sort = context.variantOrder.get(variantName)
594
834
  context.variantMap.set(
595
835
  variantName,
596
- variantFunctions.map((variantFunction, idx) => [sort << BigInt(idx), variantFunction])
836
+ variantFunctions.map((variantFunction, idx) => [
837
+ offsets.forVariant(variantName, idx),
838
+ variantFunction,
839
+ ])
597
840
  )
598
841
  }
599
842
 
@@ -611,7 +854,7 @@ function registerPlugins(plugins, context) {
611
854
  log.warn('root-regex', [
612
855
  'Regular expressions in `safelist` work differently in Tailwind CSS v3.0.',
613
856
  'Update your `safelist` configuration to eliminate this warning.',
614
- // TODO: Add https://tw.wtf/regex-safelist
857
+ 'https://tailwindcss.com/docs/content-configuration#safelisting-classes',
615
858
  ])
616
859
  continue
617
860
  }
@@ -621,12 +864,49 @@ function registerPlugins(plugins, context) {
621
864
 
622
865
  if (checks.length > 0) {
623
866
  let patternMatchingCount = new Map()
867
+ let prefixLength = context.tailwindConfig.prefix.length
868
+ let checkImportantUtils = checks.some((check) => check.pattern.source.includes('!'))
624
869
 
625
870
  for (let util of classList) {
626
871
  let utils = Array.isArray(util)
627
872
  ? (() => {
628
873
  let [utilName, options] = util
629
- return Object.keys(options?.values ?? {}).map((value) => formatClass(utilName, value))
874
+ let values = Object.keys(options?.values ?? {})
875
+ let classes = values.map((value) => formatClass(utilName, value))
876
+
877
+ if (options?.supportsNegativeValues) {
878
+ // This is the normal negated version
879
+ // e.g. `-inset-1` or `-tw-inset-1`
880
+ classes = [...classes, ...classes.map((cls) => '-' + cls)]
881
+
882
+ // This is the negated version *after* the prefix
883
+ // e.g. `tw--inset-1`
884
+ // The prefix is already attached to util name
885
+ // So we add the negative after the prefix
886
+ classes = [
887
+ ...classes,
888
+ ...classes.map(
889
+ (cls) => cls.slice(0, prefixLength) + '-' + cls.slice(prefixLength)
890
+ ),
891
+ ]
892
+ }
893
+
894
+ if (options.types.some(({ type }) => type === 'color')) {
895
+ classes = [
896
+ ...classes,
897
+ ...classes.flatMap((cls) =>
898
+ Object.keys(context.tailwindConfig.theme.opacity).map(
899
+ (opacity) => `${cls}/${opacity}`
900
+ )
901
+ ),
902
+ ]
903
+ }
904
+
905
+ if (checkImportantUtils && options?.respectImportant) {
906
+ classes = [...classes, ...classes.map((cls) => '!' + cls)]
907
+ }
908
+
909
+ return classes
630
910
  })()
631
911
  : [util]
632
912
 
@@ -661,25 +941,95 @@ function registerPlugins(plugins, context) {
661
941
  log.warn([
662
942
  `The safelist pattern \`${regex}\` doesn't match any Tailwind CSS classes.`,
663
943
  'Fix this pattern or remove it from your `safelist` configuration.',
944
+ 'https://tailwindcss.com/docs/content-configuration#safelisting-classes',
664
945
  ])
665
946
  }
666
947
  }
667
948
  }
668
949
 
950
+ let darkClassName = [].concat(context.tailwindConfig.darkMode ?? 'media')[1] ?? 'dark'
951
+
952
+ // A list of utilities that are used by certain Tailwind CSS utilities but
953
+ // that don't exist on their own. This will result in them "not existing" and
954
+ // sorting could be weird since you still require them in order to make the
955
+ // host utilities work properly. (Thanks Biology)
956
+ let parasiteUtilities = [
957
+ prefix(context, darkClassName),
958
+ prefix(context, 'group'),
959
+ prefix(context, 'peer'),
960
+ ]
961
+ context.getClassOrder = function getClassOrder(classes) {
962
+ // Sort classes so they're ordered in a deterministic manner
963
+ let sorted = [...classes].sort((a, z) => {
964
+ if (a === z) return 0
965
+ if (a < z) return -1
966
+ return 1
967
+ })
968
+
969
+ // Non-util classes won't be generated, so we default them to null
970
+ let sortedClassNames = new Map(sorted.map((className) => [className, null]))
971
+
972
+ // Sort all classes in order
973
+ // Non-tailwind classes won't be generated and will be left as `null`
974
+ let rules = generateRules(new Set(sorted), context, true)
975
+ rules = context.offsets.sort(rules)
976
+
977
+ let idx = BigInt(parasiteUtilities.length)
978
+
979
+ for (const [, rule] of rules) {
980
+ let candidate = rule.raws.tailwind.candidate
981
+
982
+ // When multiple rules match a candidate
983
+ // always take the position of the first one
984
+ sortedClassNames.set(candidate, sortedClassNames.get(candidate) ?? idx++)
985
+ }
986
+
987
+ return classes.map((className) => {
988
+ let order = sortedClassNames.get(className) ?? null
989
+ let parasiteIndex = parasiteUtilities.indexOf(className)
990
+
991
+ if (order === null && parasiteIndex !== -1) {
992
+ // This will make sure that it is at the very beginning of the
993
+ // `components` layer which technically means 'before any
994
+ // components'.
995
+ order = BigInt(parasiteIndex)
996
+ }
997
+
998
+ return [className, order]
999
+ })
1000
+ }
1001
+
669
1002
  // Generate a list of strings for autocompletion purposes, e.g.
670
1003
  // ['uppercase', 'lowercase', ...]
671
- context.getClassList = function () {
1004
+ context.getClassList = function getClassList(options = {}) {
672
1005
  let output = []
673
1006
 
674
1007
  for (let util of classList) {
675
1008
  if (Array.isArray(util)) {
676
- let [utilName, options] = util
1009
+ let [utilName, utilOptions] = util
677
1010
  let negativeClasses = []
678
1011
 
679
- for (let [key, value] of Object.entries(options?.values ?? {})) {
680
- output.push(formatClass(utilName, key))
681
- if (options?.supportsNegativeValues && negateValue(value)) {
682
- negativeClasses.push(formatClass(utilName, `-${key}`))
1012
+ let modifiers = Object.keys(utilOptions?.modifiers ?? {})
1013
+
1014
+ if (utilOptions?.types?.some(({ type }) => type === 'color')) {
1015
+ modifiers.push(...Object.keys(context.tailwindConfig.theme.opacity ?? {}))
1016
+ }
1017
+
1018
+ let metadata = { modifiers }
1019
+ let includeMetadata = options.includeMetadata && modifiers.length > 0
1020
+
1021
+ for (let [key, value] of Object.entries(utilOptions?.values ?? {})) {
1022
+ // Ignore undefined and null values
1023
+ if (value == null) {
1024
+ continue
1025
+ }
1026
+
1027
+ let cls = formatClass(utilName, key)
1028
+ output.push(includeMetadata ? [cls, metadata] : cls)
1029
+
1030
+ if (utilOptions?.supportsNegativeValues && negateValue(value)) {
1031
+ let cls = formatClass(utilName, `-${key}`)
1032
+ negativeClasses.push(includeMetadata ? [cls, metadata] : cls)
683
1033
  }
684
1034
  }
685
1035
 
@@ -691,21 +1041,235 @@ function registerPlugins(plugins, context) {
691
1041
 
692
1042
  return output
693
1043
  }
1044
+
1045
+ // Generate a list of available variants with meta information of the type of variant.
1046
+ context.getVariants = function getVariants() {
1047
+ // We use a unique, random ID for candidate names to avoid conflicts
1048
+ // We can't use characters like `_`, `:`, `@` or `.` because they might
1049
+ // be used as a separator
1050
+ let id = Math.random().toString(36).substring(7).toUpperCase()
1051
+
1052
+ let result = []
1053
+ for (let [name, options] of context.variantOptions.entries()) {
1054
+ if (options.variantInfo === VARIANT_INFO.Base) continue
1055
+
1056
+ result.push({
1057
+ name,
1058
+ isArbitrary: options.type === Symbol.for('MATCH_VARIANT'),
1059
+ values: Object.keys(options.values ?? {}),
1060
+ hasDash: name !== '@',
1061
+ selectors({ modifier, value } = {}) {
1062
+ let candidate = `TAILWINDPLACEHOLDER${id}`
1063
+
1064
+ let rule = postcss.rule({ selector: `.${candidate}` })
1065
+ let container = postcss.root({ nodes: [rule.clone()] })
1066
+
1067
+ let before = container.toString()
1068
+
1069
+ let fns = (context.variantMap.get(name) ?? []).flatMap(([_, fn]) => fn)
1070
+ let formatStrings = []
1071
+ for (let fn of fns) {
1072
+ let localFormatStrings = []
1073
+
1074
+ let api = {
1075
+ args: { modifier, value: options.values?.[value] ?? value },
1076
+ separator: context.tailwindConfig.separator,
1077
+ modifySelectors(modifierFunction) {
1078
+ // Run the modifierFunction over each rule
1079
+ container.each((rule) => {
1080
+ if (rule.type !== 'rule') {
1081
+ return
1082
+ }
1083
+
1084
+ rule.selectors = rule.selectors.map((selector) => {
1085
+ return modifierFunction({
1086
+ get className() {
1087
+ return getClassNameFromSelector(selector)
1088
+ },
1089
+ selector,
1090
+ })
1091
+ })
1092
+ })
1093
+
1094
+ return container
1095
+ },
1096
+ format(str) {
1097
+ localFormatStrings.push(str)
1098
+ },
1099
+ wrap(wrapper) {
1100
+ localFormatStrings.push(`@${wrapper.name} ${wrapper.params} { & }`)
1101
+ },
1102
+ container,
1103
+ }
1104
+
1105
+ let ruleWithVariant = fn(api)
1106
+ if (localFormatStrings.length > 0) {
1107
+ formatStrings.push(localFormatStrings)
1108
+ }
1109
+
1110
+ if (Array.isArray(ruleWithVariant)) {
1111
+ for (let variantFunction of ruleWithVariant) {
1112
+ localFormatStrings = []
1113
+ variantFunction(api)
1114
+ formatStrings.push(localFormatStrings)
1115
+ }
1116
+ }
1117
+ }
1118
+
1119
+ // Reverse engineer the result of the `container`
1120
+ let manualFormatStrings = []
1121
+ let after = container.toString()
1122
+
1123
+ if (before !== after) {
1124
+ // Figure out all selectors
1125
+ container.walkRules((rule) => {
1126
+ let modified = rule.selector
1127
+
1128
+ // Rebuild the base selector, this is what plugin authors would do
1129
+ // as well. E.g.: `${variant}${separator}${className}`.
1130
+ // However, plugin authors probably also prepend or append certain
1131
+ // classes, pseudos, ids, ...
1132
+ let rebuiltBase = selectorParser((selectors) => {
1133
+ selectors.walkClasses((classNode) => {
1134
+ classNode.value = `${name}${context.tailwindConfig.separator}${classNode.value}`
1135
+ })
1136
+ }).processSync(modified)
1137
+
1138
+ // Now that we know the original selector, the new selector, and
1139
+ // the rebuild part in between, we can replace the part that plugin
1140
+ // authors need to rebuild with `&`, and eventually store it in the
1141
+ // collectedFormats. Similar to what `format('...')` would do.
1142
+ //
1143
+ // E.g.:
1144
+ // variant: foo
1145
+ // selector: .markdown > p
1146
+ // modified (by plugin): .foo .foo\\:markdown > p
1147
+ // rebuiltBase (internal): .foo\\:markdown > p
1148
+ // format: .foo &
1149
+ manualFormatStrings.push(modified.replace(rebuiltBase, '&').replace(candidate, '&'))
1150
+ })
1151
+
1152
+ // Figure out all atrules
1153
+ container.walkAtRules((atrule) => {
1154
+ manualFormatStrings.push(`@${atrule.name} (${atrule.params}) { & }`)
1155
+ })
1156
+ }
1157
+
1158
+ let isArbitraryVariant = !(value in (options.values ?? {}))
1159
+ let internalFeatures = options[INTERNAL_FEATURES] ?? {}
1160
+
1161
+ let respectPrefix = (() => {
1162
+ if (isArbitraryVariant) return false
1163
+ if (internalFeatures.respectPrefix === false) return false
1164
+ return true
1165
+ })()
1166
+
1167
+ formatStrings = formatStrings.map((format) =>
1168
+ format.map((str) => ({
1169
+ format: str,
1170
+ respectPrefix,
1171
+ }))
1172
+ )
1173
+
1174
+ manualFormatStrings = manualFormatStrings.map((format) => ({
1175
+ format,
1176
+ respectPrefix,
1177
+ }))
1178
+
1179
+ let opts = {
1180
+ candidate,
1181
+ context,
1182
+ }
1183
+
1184
+ let result = formatStrings.map((formats) =>
1185
+ finalizeSelector(`.${candidate}`, formatVariantSelector(formats, opts), opts)
1186
+ .replace(`.${candidate}`, '&')
1187
+ .replace('{ & }', '')
1188
+ .trim()
1189
+ )
1190
+
1191
+ if (manualFormatStrings.length > 0) {
1192
+ result.push(
1193
+ formatVariantSelector(manualFormatStrings, opts)
1194
+ .toString()
1195
+ .replace(`.${candidate}`, '&')
1196
+ )
1197
+ }
1198
+
1199
+ return result
1200
+ },
1201
+ })
1202
+ }
1203
+
1204
+ return result
1205
+ }
1206
+ }
1207
+
1208
+ /**
1209
+ * Mark as class as retroactively invalid
1210
+ *
1211
+ *
1212
+ * @param {string} candidate
1213
+ */
1214
+ function markInvalidUtilityCandidate(context, candidate) {
1215
+ if (!context.classCache.has(candidate)) {
1216
+ return
1217
+ }
1218
+
1219
+ // Mark this as not being a real utility
1220
+ context.notClassCache.add(candidate)
1221
+
1222
+ // Remove it from any candidate-specific caches
1223
+ context.classCache.delete(candidate)
1224
+ context.applyClassCache.delete(candidate)
1225
+ context.candidateRuleMap.delete(candidate)
1226
+ context.candidateRuleCache.delete(candidate)
1227
+
1228
+ // Ensure the stylesheet gets rebuilt
1229
+ context.stylesheetCache = null
1230
+ }
1231
+
1232
+ /**
1233
+ * Mark as class as retroactively invalid
1234
+ *
1235
+ * @param {import('postcss').Node} node
1236
+ */
1237
+ function markInvalidUtilityNode(context, node) {
1238
+ let candidate = node.raws.tailwind.candidate
1239
+
1240
+ if (!candidate) {
1241
+ return
1242
+ }
1243
+
1244
+ for (const entry of context.ruleCache) {
1245
+ if (entry[1].raws.tailwind.candidate === candidate) {
1246
+ context.ruleCache.delete(entry)
1247
+ // context.postCssNodeCache.delete(node)
1248
+ }
1249
+ }
1250
+
1251
+ markInvalidUtilityCandidate(context, candidate)
694
1252
  }
695
1253
 
696
1254
  export function createContext(tailwindConfig, changedContent = [], root = postcss.root()) {
697
1255
  let context = {
698
1256
  disposables: [],
699
1257
  ruleCache: new Set(),
1258
+ candidateRuleCache: new Map(),
700
1259
  classCache: new Map(),
701
1260
  applyClassCache: new Map(),
702
- notClassCache: new Set(),
1261
+ // Seed the not class cache with the blocklist (which is only strings)
1262
+ notClassCache: new Set(tailwindConfig.blocklist ?? []),
703
1263
  postCssNodeCache: new Map(),
704
1264
  candidateRuleMap: new Map(),
705
1265
  tailwindConfig,
706
1266
  changedContent: changedContent,
707
1267
  variantMap: new Map(),
708
1268
  stylesheetCache: null,
1269
+ variantOptions: new Map(),
1270
+
1271
+ markInvalidUtilityCandidate: (candidate) => markInvalidUtilityCandidate(context, candidate),
1272
+ markInvalidUtilityNode: (node) => markInvalidUtilityNode(context, node),
709
1273
  }
710
1274
 
711
1275
  let resolvedPlugins = resolvePlugins(context, root)
@@ -743,15 +1307,17 @@ export function getContext(
743
1307
  existingContext = context
744
1308
  }
745
1309
 
1310
+ let cssDidChange = hasContentChanged(sourcePath, root)
1311
+
746
1312
  // If there's already a context in the cache and we don't need to
747
1313
  // reset the context, return the cached context.
748
1314
  if (existingContext) {
749
- let contextDependenciesChanged = trackModified(
1315
+ let [contextDependenciesChanged, mtimesToCommit] = trackModified(
750
1316
  [...contextDependencies],
751
1317
  getFileModifiedMap(existingContext)
752
1318
  )
753
- if (!contextDependenciesChanged) {
754
- return [existingContext, false]
1319
+ if (!contextDependenciesChanged && !cssDidChange) {
1320
+ return [existingContext, false, mtimesToCommit]
755
1321
  }
756
1322
  }
757
1323
 
@@ -782,7 +1348,11 @@ export function getContext(
782
1348
 
783
1349
  let context = createContext(tailwindConfig, [], root)
784
1350
 
785
- trackModified([...contextDependencies], getFileModifiedMap(context))
1351
+ Object.assign(context, {
1352
+ userConfigPath,
1353
+ })
1354
+
1355
+ let [, mtimesToCommit] = trackModified([...contextDependencies], getFileModifiedMap(context))
786
1356
 
787
1357
  // ---
788
1358
 
@@ -797,5 +1367,5 @@ export function getContext(
797
1367
 
798
1368
  contextSourcesMap.get(context).add(sourcePath)
799
1369
 
800
- return [context, true]
1370
+ return [context, true, mtimesToCommit]
801
1371
  }