tailwindcss 0.0.0-insiders.eebf529 → 0.0.0-insiders.ef2ebb2

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