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

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