tailwindcss 0.0.0-insiders.4e21639 → 0.0.0-insiders.4e62334

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 (157) hide show
  1. package/CHANGELOG.md +435 -3
  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-peer-dependencies.js +20 -7
  11. package/lib/cli.js +460 -259
  12. package/lib/constants.js +27 -20
  13. package/lib/corePluginList.js +9 -3
  14. package/lib/corePlugins.js +1840 -1753
  15. package/lib/css/preflight.css +8 -9
  16. package/lib/featureFlags.js +29 -20
  17. package/lib/index.js +22 -11
  18. package/lib/lib/cacheInvalidation.js +90 -0
  19. package/lib/lib/collapseAdjacentRules.js +27 -9
  20. package/lib/lib/collapseDuplicateDeclarations.js +58 -4
  21. package/lib/lib/defaultExtractor.js +231 -0
  22. package/lib/lib/detectNesting.js +13 -10
  23. package/lib/lib/evaluateTailwindFunctions.js +119 -52
  24. package/lib/lib/expandApplyAtRules.js +440 -161
  25. package/lib/lib/expandTailwindAtRules.js +130 -128
  26. package/lib/lib/generateRules.js +410 -171
  27. package/lib/lib/getModuleDependencies.js +11 -8
  28. package/lib/lib/normalizeTailwindDirectives.js +43 -32
  29. package/lib/lib/offsets.js +199 -0
  30. package/lib/lib/partitionApplyAtRules.js +56 -0
  31. package/lib/lib/regex.js +60 -0
  32. package/lib/lib/resolveDefaultsAtRules.js +91 -55
  33. package/lib/lib/setupContextUtils.js +453 -347
  34. package/lib/lib/setupTrackingContext.js +52 -44
  35. package/lib/lib/sharedState.js +48 -9
  36. package/lib/lib/substituteScreenAtRules.js +13 -8
  37. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  38. package/lib/postcss-plugins/nesting/index.js +19 -0
  39. package/lib/postcss-plugins/nesting/plugin.js +87 -0
  40. package/lib/processTailwindFeatures.js +36 -25
  41. package/lib/public/colors.js +247 -245
  42. package/lib/public/create-plugin.js +6 -4
  43. package/lib/public/default-config.js +7 -5
  44. package/lib/public/default-theme.js +7 -5
  45. package/lib/public/resolve-config.js +8 -5
  46. package/lib/util/bigSign.js +4 -1
  47. package/lib/util/buildMediaQuery.js +16 -25
  48. package/lib/util/cloneDeep.js +7 -6
  49. package/lib/util/cloneNodes.js +21 -3
  50. package/lib/util/color.js +54 -40
  51. package/lib/util/configurePlugins.js +4 -1
  52. package/lib/util/createPlugin.js +6 -6
  53. package/lib/util/createUtilityPlugin.js +12 -14
  54. package/lib/util/dataTypes.js +119 -102
  55. package/lib/util/defaults.js +10 -1
  56. package/lib/util/escapeClassName.js +7 -4
  57. package/lib/util/escapeCommas.js +5 -2
  58. package/lib/util/flattenColorPalette.js +9 -12
  59. package/lib/util/formatVariantSelector.js +223 -40
  60. package/lib/util/getAllConfigs.js +27 -8
  61. package/lib/util/hashConfig.js +6 -3
  62. package/lib/util/isKeyframeRule.js +5 -2
  63. package/lib/util/isPlainObject.js +5 -2
  64. package/lib/util/isValidArbitraryValue.js +72 -0
  65. package/lib/util/log.js +22 -12
  66. package/lib/util/nameClass.js +17 -8
  67. package/lib/util/negateValue.js +22 -7
  68. package/lib/util/normalizeConfig.js +99 -54
  69. package/lib/util/normalizeScreens.js +73 -0
  70. package/lib/util/parseAnimationValue.js +42 -40
  71. package/lib/util/parseBoxShadowValue.js +30 -23
  72. package/lib/util/parseDependency.js +18 -15
  73. package/lib/util/parseObjectStyles.js +10 -7
  74. package/lib/util/pluginUtils.js +51 -42
  75. package/lib/util/prefixSelector.js +10 -8
  76. package/lib/util/removeAlphaVariables.js +29 -0
  77. package/lib/util/resolveConfig.js +91 -66
  78. package/lib/util/resolveConfigPath.js +11 -9
  79. package/lib/util/responsive.js +8 -5
  80. package/lib/util/splitAtTopLevelOnly.js +43 -0
  81. package/lib/util/tap.js +4 -1
  82. package/lib/util/toColorValue.js +5 -3
  83. package/lib/util/toPath.js +24 -3
  84. package/lib/util/transformThemeValue.js +37 -29
  85. package/lib/util/validateConfig.js +24 -0
  86. package/lib/util/withAlphaVariable.js +23 -15
  87. package/nesting/index.js +2 -12
  88. package/package.json +43 -43
  89. package/peers/index.js +11543 -8114
  90. package/plugin.d.ts +11 -0
  91. package/plugin.js +2 -1
  92. package/resolveConfig.d.ts +3 -0
  93. package/resolveConfig.js +2 -1
  94. package/scripts/generate-types.js +105 -0
  95. package/scripts/type-utils.js +27 -0
  96. package/src/cli-peer-dependencies.js +7 -1
  97. package/src/cli.js +293 -36
  98. package/src/corePluginList.js +1 -1
  99. package/src/corePlugins.js +428 -285
  100. package/src/css/preflight.css +8 -9
  101. package/src/featureFlags.js +9 -5
  102. package/src/index.js +14 -6
  103. package/src/lib/cacheInvalidation.js +52 -0
  104. package/src/lib/collapseAdjacentRules.js +21 -2
  105. package/src/lib/collapseDuplicateDeclarations.js +66 -1
  106. package/src/lib/defaultExtractor.js +208 -0
  107. package/src/lib/evaluateTailwindFunctions.js +84 -10
  108. package/src/lib/expandApplyAtRules.js +488 -153
  109. package/src/lib/expandTailwindAtRules.js +82 -80
  110. package/src/lib/generateRules.js +352 -120
  111. package/src/lib/normalizeTailwindDirectives.js +7 -1
  112. package/src/lib/offsets.js +239 -0
  113. package/src/lib/partitionApplyAtRules.js +52 -0
  114. package/src/lib/regex.js +74 -0
  115. package/src/lib/resolveDefaultsAtRules.js +59 -17
  116. package/src/lib/setupContextUtils.js +337 -174
  117. package/src/lib/setupTrackingContext.js +13 -8
  118. package/src/lib/sharedState.js +42 -4
  119. package/src/lib/substituteScreenAtRules.js +6 -3
  120. package/src/postcss-plugins/nesting/README.md +42 -0
  121. package/src/postcss-plugins/nesting/index.js +13 -0
  122. package/src/postcss-plugins/nesting/plugin.js +80 -0
  123. package/src/processTailwindFeatures.js +12 -2
  124. package/src/util/buildMediaQuery.js +14 -18
  125. package/src/util/cloneNodes.js +19 -2
  126. package/src/util/color.js +31 -14
  127. package/src/util/dataTypes.js +28 -19
  128. package/src/util/defaults.js +6 -0
  129. package/src/util/formatVariantSelector.js +237 -23
  130. package/src/util/getAllConfigs.js +19 -0
  131. package/src/util/isValidArbitraryValue.js +61 -0
  132. package/src/util/log.js +11 -7
  133. package/src/util/nameClass.js +1 -1
  134. package/src/util/negateValue.js +10 -2
  135. package/src/util/normalizeConfig.js +16 -3
  136. package/src/util/normalizeScreens.js +45 -0
  137. package/src/util/parseBoxShadowValue.js +4 -3
  138. package/src/util/pluginUtils.js +14 -2
  139. package/src/util/prefixSelector.js +7 -5
  140. package/src/util/removeAlphaVariables.js +24 -0
  141. package/src/util/resolveConfig.js +71 -17
  142. package/src/util/splitAtTopLevelOnly.js +45 -0
  143. package/src/util/toPath.js +23 -1
  144. package/src/util/transformThemeValue.js +13 -3
  145. package/src/util/validateConfig.js +13 -0
  146. package/src/util/withAlphaVariable.js +1 -1
  147. package/stubs/defaultConfig.stub.js +24 -3
  148. package/stubs/simpleConfig.stub.js +1 -0
  149. package/types/config.d.ts +334 -0
  150. package/types/generated/.gitkeep +0 -0
  151. package/types/generated/colors.d.ts +276 -0
  152. package/types/generated/corePluginList.d.ts +1 -0
  153. package/types/generated/default-theme.d.ts +331 -0
  154. package/types/index.d.ts +7 -0
  155. package/lib/lib/setupWatchingContext.js +0 -288
  156. package/nesting/plugin.js +0 -41
  157. package/src/lib/setupWatchingContext.js +0 -311
@@ -4,6 +4,7 @@ import postcss from 'postcss'
4
4
  import dlv from 'dlv'
5
5
  import selectorParser from 'postcss-selector-parser'
6
6
 
7
+ import { flagEnabled } from '../featureFlags.js'
7
8
  import transformThemeValue from '../util/transformThemeValue'
8
9
  import parseObjectStyles from '../util/parseObjectStyles'
9
10
  import prefixSelector from '../util/prefixSelector'
@@ -11,13 +12,23 @@ import isPlainObject from '../util/isPlainObject'
11
12
  import escapeClassName from '../util/escapeClassName'
12
13
  import nameClass, { formatClass } from '../util/nameClass'
13
14
  import { coerceValue } from '../util/pluginUtils'
14
- import bigSign from '../util/bigSign'
15
15
  import { variantPlugins, corePlugins } from '../corePlugins'
16
16
  import * as sharedState from './sharedState'
17
17
  import { env } from './sharedState'
18
18
  import { toPath } from '../util/toPath'
19
19
  import log from '../util/log'
20
20
  import negateValue from '../util/negateValue'
21
+ import isValidArbitraryValue from '../util/isValidArbitraryValue'
22
+ import { generateRules } from './generateRules'
23
+ import { hasContentChanged } from './cacheInvalidation.js'
24
+ import { Offsets } from './offsets.js'
25
+
26
+ let MATCH_VARIANT = Symbol()
27
+
28
+ function prefix(context, selector) {
29
+ let prefix = context.tailwindConfig.prefix
30
+ return typeof prefix === 'function' ? prefix(selector) : prefix + selector
31
+ }
21
32
 
22
33
  function parseVariantFormatString(input) {
23
34
  if (input.includes('{')) {
@@ -77,50 +88,82 @@ function parseStyles(styles) {
77
88
  })
78
89
  }
79
90
 
80
- function getClasses(selector) {
91
+ function getClasses(selector, mutate) {
81
92
  let parser = selectorParser((selectors) => {
82
93
  let allClasses = []
94
+
95
+ if (mutate) {
96
+ mutate(selectors)
97
+ }
98
+
83
99
  selectors.walkClasses((classNode) => {
84
100
  allClasses.push(classNode.value)
85
101
  })
102
+
86
103
  return allClasses
87
104
  })
88
105
  return parser.transformSync(selector)
89
106
  }
90
107
 
91
- function extractCandidates(node) {
108
+ function extractCandidates(node, state = { containsNonOnDemandable: false }, depth = 0) {
92
109
  let classes = []
93
110
 
111
+ // Handle normal rules
94
112
  if (node.type === 'rule') {
113
+ // Ignore everything inside a :not(...). This allows you to write code like
114
+ // `div:not(.foo)`. If `.foo` is never found in your code, then we used to
115
+ // not generated it. But now we will ignore everything inside a `:not`, so
116
+ // that it still gets generated.
117
+ function ignoreNot(selectors) {
118
+ selectors.walkPseudos((pseudo) => {
119
+ if (pseudo.value === ':not') {
120
+ pseudo.remove()
121
+ }
122
+ })
123
+ }
124
+
95
125
  for (let selector of node.selectors) {
96
- let classCandidates = getClasses(selector)
126
+ let classCandidates = getClasses(selector, ignoreNot)
97
127
  // At least one of the selectors contains non-"on-demandable" candidates.
98
- if (classCandidates.length === 0) return []
128
+ if (classCandidates.length === 0) {
129
+ state.containsNonOnDemandable = true
130
+ }
99
131
 
100
- classes = [...classes, ...classCandidates]
132
+ for (let classCandidate of classCandidates) {
133
+ classes.push(classCandidate)
134
+ }
101
135
  }
102
- return classes
103
136
  }
104
137
 
105
- if (node.type === 'atrule') {
138
+ // Handle at-rules (which contains nested rules)
139
+ else if (node.type === 'atrule') {
106
140
  node.walkRules((rule) => {
107
- classes = [...classes, ...rule.selectors.flatMap((selector) => getClasses(selector))]
141
+ for (let classCandidate of rule.selectors.flatMap((selector) => getClasses(selector))) {
142
+ classes.push(classCandidate)
143
+ }
108
144
  })
109
145
  }
110
146
 
147
+ if (depth === 0) {
148
+ return [state.containsNonOnDemandable || classes.length === 0, classes]
149
+ }
150
+
111
151
  return classes
112
152
  }
113
153
 
114
154
  function withIdentifiers(styles) {
115
155
  return parseStyles(styles).flatMap((node) => {
116
156
  let nodeMap = new Map()
117
- let candidates = extractCandidates(node)
157
+ let [containsNonOnDemandableSelectors, candidates] = extractCandidates(node)
118
158
 
119
- // If this isn't "on-demandable", assign it a universal candidate.
120
- if (candidates.length === 0) {
121
- return [['*', node]]
159
+ // If this isn't "on-demandable", assign it a universal candidate to always include it.
160
+ if (containsNonOnDemandableSelectors) {
161
+ candidates.unshift(sharedState.NOT_ON_DEMAND)
122
162
  }
123
163
 
164
+ // However, it could be that it also contains "on-demandable" candidates.
165
+ // E.g.: `span, .foo {}`, in that case it should still be possible to use
166
+ // `@apply foo` for example.
124
167
  return candidates.map((c) => {
125
168
  if (!nodeMap.has(node)) {
126
169
  nodeMap.set(node, node)
@@ -130,64 +173,41 @@ function withIdentifiers(styles) {
130
173
  })
131
174
  }
132
175
 
133
- let matchingBrackets = new Map([
134
- ['{', '}'],
135
- ['[', ']'],
136
- ['(', ')'],
137
- ])
138
- let inverseMatchingBrackets = new Map(
139
- Array.from(matchingBrackets.entries()).map(([k, v]) => [v, k])
140
- )
141
-
142
- let quotes = new Set(['"', "'", '`'])
143
-
144
- // Arbitrary values must contain balanced brackets (), [] and {}. Escaped
145
- // values don't count, and brackets inside quotes also don't count.
146
- //
147
- // E.g.: w-[this-is]w-[weird-and-invalid]
148
- // E.g.: w-[this-is\\]w-\\[weird-but-valid]
149
- // E.g.: content-['this-is-also-valid]-weirdly-enough']
150
- function isValidArbitraryValue(value) {
151
- let stack = []
152
- let inQuotes = false
153
-
154
- for (let i = 0; i < value.length; i++) {
155
- let char = value[i]
156
-
157
- // Non-escaped quotes allow us to "allow" anything in between
158
- if (quotes.has(char) && value[i - 1] !== '\\') {
159
- inQuotes = !inQuotes
160
- }
161
-
162
- if (inQuotes) continue
163
- if (value[i - 1] === '\\') continue // Escaped
176
+ export function isValidVariantFormatString(format) {
177
+ return format.startsWith('@') || format.includes('&')
178
+ }
164
179
 
165
- if (matchingBrackets.has(char)) {
166
- stack.push(char)
167
- } else if (inverseMatchingBrackets.has(char)) {
168
- let inverse = inverseMatchingBrackets.get(char)
180
+ export function parseVariant(variant) {
181
+ variant = variant
182
+ .replace(/\n+/g, '')
183
+ .replace(/\s{1,}/g, ' ')
184
+ .trim()
169
185
 
170
- // Nothing to pop from, therefore it is unbalanced
171
- if (stack.length <= 0) {
172
- return false
186
+ let fns = parseVariantFormatString(variant)
187
+ .map((str) => {
188
+ if (!str.startsWith('@')) {
189
+ return ({ format }) => format(str)
173
190
  }
174
191
 
175
- // Popped value must match the inverse value, otherwise it is unbalanced
176
- if (stack.pop() !== inverse) {
177
- return false
178
- }
179
- }
180
- }
192
+ let [, name, params] = /@(.*?)( .+|[({].*)/g.exec(str)
193
+ return ({ wrap }) => wrap(postcss.atRule({ name, params: params.trim() }))
194
+ })
195
+ .reverse()
181
196
 
182
- // If there is still something on the stack, it is also unbalanced
183
- if (stack.length > 0) {
184
- return false
197
+ return (api) => {
198
+ for (let fn of fns) {
199
+ fn(api)
200
+ }
185
201
  }
186
-
187
- // All good, totally balanced!
188
- return true
189
202
  }
190
203
 
204
+ /**
205
+ *
206
+ * @param {any} tailwindConfig
207
+ * @param {any} context
208
+ * @param {object} param2
209
+ * @param {Offsets} param2.offsets
210
+ */
191
211
  function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offsets, classList }) {
192
212
  function getConfigValue(path, defaultValue) {
193
213
  return path ? dlv(tailwindConfig, path, defaultValue) : tailwindConfig
@@ -198,8 +218,8 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
198
218
  }
199
219
 
200
220
  function prefixIdentifier(identifier, options) {
201
- if (identifier === '*') {
202
- return '*'
221
+ if (identifier === sharedState.NOT_ON_DEMAND) {
222
+ return sharedState.NOT_ON_DEMAND
203
223
  }
204
224
 
205
225
  if (!options.respectPrefix) {
@@ -209,51 +229,25 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
209
229
  return context.tailwindConfig.prefix + identifier
210
230
  }
211
231
 
212
- return {
213
- addVariant(variantName, variantFunctions, options = {}) {
214
- variantFunctions = [].concat(variantFunctions).map((variantFunction) => {
215
- if (typeof variantFunction !== 'string') {
216
- // Safelist public API functions
217
- return ({ modifySelectors, container, separator }) => {
218
- return variantFunction({ modifySelectors, container, separator })
219
- }
220
- }
221
-
222
- variantFunction = variantFunction
223
- .replace(/\n+/g, '')
224
- .replace(/\s{1,}/g, ' ')
225
- .trim()
226
-
227
- let fns = parseVariantFormatString(variantFunction)
228
- .map((str) => {
229
- if (!str.startsWith('@')) {
230
- return ({ format }) => format(str)
231
- }
232
-
233
- let [, name, params] = /@(.*?) (.*)/g.exec(str)
234
- return ({ wrap }) => wrap(postcss.atRule({ name, params }))
235
- })
236
- .reverse()
232
+ function resolveThemeValue(path, defaultValue, opts = {}) {
233
+ const [pathRoot, ...subPaths] = toPath(path)
234
+ const value = getConfigValue(['theme', pathRoot, ...subPaths], defaultValue)
235
+ return transformThemeValue(pathRoot)(value, opts)
236
+ }
237
237
 
238
- return (api) => {
239
- for (let fn of fns) {
240
- fn(api)
241
- }
242
- }
243
- })
238
+ const theme = Object.assign(
239
+ (path, defaultValue = undefined) => resolveThemeValue(path, defaultValue),
240
+ {
241
+ withAlpha: (path, opacityValue) => resolveThemeValue(path, undefined, { opacityValue }),
242
+ }
243
+ )
244
244
 
245
- insertInto(variantList, variantName, options)
246
- variantMap.set(variantName, variantFunctions)
247
- },
245
+ let api = {
248
246
  postcss,
249
247
  prefix: applyConfiguredPrefix,
250
248
  e: escapeClassName,
251
249
  config: getConfigValue,
252
- theme(path, defaultValue) {
253
- const [pathRoot, ...subPaths] = toPath(path)
254
- const value = getConfigValue(['theme', pathRoot, ...subPaths], defaultValue)
255
- return transformThemeValue(pathRoot)(value)
256
- },
250
+ theme,
257
251
  corePlugins: (path) => {
258
252
  if (Array.isArray(tailwindConfig.corePlugins)) {
259
253
  return tailwindConfig.corePlugins.includes(path)
@@ -265,21 +259,31 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
265
259
  // Preserved for backwards compatibility but not used in v3.0+
266
260
  return []
267
261
  },
268
- addUserCss(userCss) {
269
- for (let [identifier, rule] of withIdentifiers(userCss)) {
270
- let offset = offsets.user++
262
+ addBase(base) {
263
+ for (let [identifier, rule] of withIdentifiers(base)) {
264
+ let prefixedIdentifier = prefixIdentifier(identifier, {})
265
+ let offset = offsets.create('base')
271
266
 
272
- if (!context.candidateRuleMap.has(identifier)) {
273
- context.candidateRuleMap.set(identifier, [])
267
+ if (!context.candidateRuleMap.has(prefixedIdentifier)) {
268
+ context.candidateRuleMap.set(prefixedIdentifier, [])
274
269
  }
275
270
 
276
- context.candidateRuleMap.get(identifier).push([{ sort: offset, layer: 'user' }, rule])
271
+ context.candidateRuleMap
272
+ .get(prefixedIdentifier)
273
+ .push([{ sort: offset, layer: 'base' }, rule])
277
274
  }
278
275
  },
279
- addBase(base) {
280
- for (let [identifier, rule] of withIdentifiers(base)) {
276
+ /**
277
+ * @param {string} group
278
+ * @param {Record<string, string | string[]>} declarations
279
+ */
280
+ addDefaults(group, declarations) {
281
+ const groups = {
282
+ [`@defaults ${group}`]: declarations,
283
+ }
284
+
285
+ for (let [identifier, rule] of withIdentifiers(groups)) {
281
286
  let prefixedIdentifier = prefixIdentifier(identifier, {})
282
- let offset = offsets.base++
283
287
 
284
288
  if (!context.candidateRuleMap.has(prefixedIdentifier)) {
285
289
  context.candidateRuleMap.set(prefixedIdentifier, [])
@@ -287,11 +291,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
287
291
 
288
292
  context.candidateRuleMap
289
293
  .get(prefixedIdentifier)
290
- .push([{ sort: offset, layer: 'base' }, rule])
294
+ .push([{ sort: offsets.create('defaults'), layer: 'defaults' }, rule])
291
295
  }
292
296
  },
293
297
  addComponents(components, options) {
294
298
  let defaultOptions = {
299
+ preserveSource: false,
295
300
  respectPrefix: true,
296
301
  respectImportant: false,
297
302
  }
@@ -300,7 +305,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
300
305
 
301
306
  for (let [identifier, rule] of withIdentifiers(components)) {
302
307
  let prefixedIdentifier = prefixIdentifier(identifier, options)
303
- let offset = offsets.components++
304
308
 
305
309
  classList.add(prefixedIdentifier)
306
310
 
@@ -310,11 +314,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
310
314
 
311
315
  context.candidateRuleMap
312
316
  .get(prefixedIdentifier)
313
- .push([{ sort: offset, layer: 'components', options }, rule])
317
+ .push([{ sort: offsets.create('components'), layer: 'components', options }, rule])
314
318
  }
315
319
  },
316
320
  addUtilities(utilities, options) {
317
321
  let defaultOptions = {
322
+ preserveSource: false,
318
323
  respectPrefix: true,
319
324
  respectImportant: true,
320
325
  }
@@ -323,7 +328,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
323
328
 
324
329
  for (let [identifier, rule] of withIdentifiers(utilities)) {
325
330
  let prefixedIdentifier = prefixIdentifier(identifier, options)
326
- let offset = offsets.utilities++
327
331
 
328
332
  classList.add(prefixedIdentifier)
329
333
 
@@ -333,7 +337,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
333
337
 
334
338
  context.candidateRuleMap
335
339
  .get(prefixedIdentifier)
336
- .push([{ sort: offset, layer: 'utilities', options }, rule])
340
+ .push([{ sort: offsets.create('utilities'), layer: 'utilities', options }, rule])
337
341
  }
338
342
  },
339
343
  matchUtilities: function (utilities, options) {
@@ -344,7 +348,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
344
348
 
345
349
  options = { ...defaultOptions, ...options }
346
350
 
347
- let offset = offsets.utilities++
351
+ let offset = offsets.create('utilities')
348
352
 
349
353
  for (let identifier in utilities) {
350
354
  let prefixedIdentifier = prefixIdentifier(identifier, options)
@@ -396,7 +400,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
396
400
 
397
401
  options = { ...defaultOptions, ...options }
398
402
 
399
- let offset = offsets.components++
403
+ let offset = offsets.create('components')
400
404
 
401
405
  for (let identifier in components) {
402
406
  let prefixedIdentifier = prefixIdentifier(identifier, options)
@@ -450,7 +454,68 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
450
454
  context.candidateRuleMap.get(prefixedIdentifier).push(withOffsets)
451
455
  }
452
456
  },
457
+ addVariant(variantName, variantFunctions, options = {}) {
458
+ variantFunctions = [].concat(variantFunctions).map((variantFunction) => {
459
+ if (typeof variantFunction !== 'string') {
460
+ // Safelist public API functions
461
+ return (api) => {
462
+ let { args, modifySelectors, container, separator, wrap, format } = api
463
+ let result = variantFunction(
464
+ Object.assign(
465
+ { modifySelectors, container, separator },
466
+ variantFunction[MATCH_VARIANT] && { args, wrap, format }
467
+ )
468
+ )
469
+
470
+ if (typeof result === 'string' && !isValidVariantFormatString(result)) {
471
+ throw new Error(
472
+ `Your custom variant \`${variantName}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`
473
+ )
474
+ }
475
+
476
+ if (Array.isArray(result)) {
477
+ return result
478
+ .filter((variant) => typeof variant === 'string')
479
+ .map((variant) => parseVariant(variant))
480
+ }
481
+
482
+ // result may be undefined with legacy variants that use APIs like `modifySelectors`
483
+ // result may also be a postcss node if someone was returning the result from `modifySelectors`
484
+ return result && typeof result === 'string' && parseVariant(result)(api)
485
+ }
486
+ }
487
+
488
+ if (!isValidVariantFormatString(variantFunction)) {
489
+ throw new Error(
490
+ `Your custom variant \`${variantName}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`
491
+ )
492
+ }
493
+
494
+ return parseVariant(variantFunction)
495
+ })
496
+
497
+ insertInto(variantList, variantName, options)
498
+ variantMap.set(variantName, variantFunctions)
499
+ },
500
+ }
501
+
502
+ if (flagEnabled(tailwindConfig, 'matchVariant')) {
503
+ api.matchVariant = function (variants, options) {
504
+ for (let variant in variants) {
505
+ for (let [k, v] of Object.entries(options?.values ?? {})) {
506
+ api.addVariant(`${variant}-${k}`, variants[variant](v))
507
+ }
508
+
509
+ api.addVariant(
510
+ variant,
511
+ Object.assign(({ args }) => variants[variant](args), { [MATCH_VARIANT]: true }),
512
+ options
513
+ )
514
+ }
515
+ }
453
516
  }
517
+
518
+ return api
454
519
  }
455
520
 
456
521
  let fileModifiedMapCache = new WeakMap()
@@ -470,7 +535,14 @@ function trackModified(files, fileModifiedMap) {
470
535
  let parsed = url.parse(file)
471
536
  let pathname = parsed.hash ? parsed.href.replace(parsed.hash, '') : parsed.href
472
537
  pathname = parsed.search ? pathname.replace(parsed.search, '') : pathname
473
- let newModified = fs.statSync(decodeURIComponent(pathname)).mtimeMs
538
+ let newModified = fs.statSync(decodeURIComponent(pathname), { throwIfNoEntry: false })?.mtimeMs
539
+ if (!newModified) {
540
+ // It could happen that a file is passed in that doesn't exist. E.g.:
541
+ // postcss-cli will provide you a fake path when reading from stdin. This
542
+ // path then looks like /path-to-your-project/stdin In that case we just
543
+ // want to ignore it and don't track changes at all.
544
+ continue
545
+ }
474
546
 
475
547
  if (!fileModifiedMap.has(file) || newModified > fileModifiedMap.get(file)) {
476
548
  changed = true
@@ -516,29 +588,20 @@ function collectLayerPlugins(root) {
516
588
  } else if (layerRule.params === 'components') {
517
589
  for (let node of layerRule.nodes) {
518
590
  layerPlugins.push(function ({ addComponents }) {
519
- addComponents(node, { respectPrefix: false })
591
+ addComponents(node, { respectPrefix: false, preserveSource: true })
520
592
  })
521
593
  }
522
594
  layerRule.remove()
523
595
  } else if (layerRule.params === 'utilities') {
524
596
  for (let node of layerRule.nodes) {
525
597
  layerPlugins.push(function ({ addUtilities }) {
526
- addUtilities(node, { respectPrefix: false })
598
+ addUtilities(node, { respectPrefix: false, preserveSource: true })
527
599
  })
528
600
  }
529
601
  layerRule.remove()
530
602
  }
531
603
  })
532
604
 
533
- root.walkRules((rule) => {
534
- // At this point it is safe to include all the left-over css from the
535
- // user's css file. This is because the `@tailwind` and `@layer` directives
536
- // will already be handled and will be removed from the css tree.
537
- layerPlugins.push(function ({ addUserCss }) {
538
- addUserCss(rule, { respectPrefix: false })
539
- })
540
- })
541
-
542
605
  return layerPlugins
543
606
  }
544
607
 
@@ -572,9 +635,11 @@ function resolvePlugins(context, root) {
572
635
  let afterVariants = [
573
636
  variantPlugins['directionVariants'],
574
637
  variantPlugins['reducedMotionVariants'],
638
+ variantPlugins['prefersContrastVariants'],
575
639
  variantPlugins['darkVariants'],
576
640
  variantPlugins['printVariant'],
577
641
  variantPlugins['screenVariants'],
642
+ variantPlugins['orientationVariants'],
578
643
  ]
579
644
 
580
645
  return [...corePluginList, ...beforeVariants, ...userPlugins, ...afterVariants, ...layerPlugins]
@@ -583,12 +648,10 @@ function resolvePlugins(context, root) {
583
648
  function registerPlugins(plugins, context) {
584
649
  let variantList = []
585
650
  let variantMap = new Map()
586
- let offsets = {
587
- base: 0n,
588
- components: 0n,
589
- utilities: 0n,
590
- user: 0n,
591
- }
651
+ context.variantMap = variantMap
652
+
653
+ let offsets = new Offsets()
654
+ context.offsets = offsets
592
655
 
593
656
  let classList = new Set()
594
657
 
@@ -609,43 +672,17 @@ function registerPlugins(plugins, context) {
609
672
  }
610
673
  }
611
674
 
612
- let highestOffset = ((args) => args.reduce((m, e) => (e > m ? e : m)))([
613
- offsets.base,
614
- offsets.components,
615
- offsets.utilities,
616
- offsets.user,
617
- ])
618
- let reservedBits = BigInt(highestOffset.toString(2).length)
619
-
620
- context.layerOrder = {
621
- base: (1n << reservedBits) << 0n,
622
- components: (1n << reservedBits) << 1n,
623
- utilities: (1n << reservedBits) << 2n,
624
- user: (1n << reservedBits) << 3n,
625
- }
626
-
627
- reservedBits += 4n
628
-
629
- let offset = 0
630
- context.variantOrder = new Map(
631
- variantList
632
- .map((variant, i) => {
633
- let variantFunctions = variantMap.get(variant).length
634
- let bits = (1n << BigInt(i + offset)) << reservedBits
635
- offset += variantFunctions - 1
636
- return [variant, bits]
637
- })
638
- .sort(([, a], [, z]) => bigSign(a - z))
639
- )
640
-
641
- context.minimumScreen = [...context.variantOrder.values()].shift()
675
+ // Make sure to record bit masks for every variant
676
+ offsets.recordVariants(variantList, (variant) => variantMap.get(variant).length)
642
677
 
643
678
  // Build variantMap
644
679
  for (let [variantName, variantFunctions] of variantMap.entries()) {
645
- let sort = context.variantOrder.get(variantName)
646
680
  context.variantMap.set(
647
681
  variantName,
648
- variantFunctions.map((variantFunction, idx) => [sort << BigInt(idx), variantFunction])
682
+ variantFunctions.map((variantFunction, idx) => [
683
+ offsets.forVariant(variantName, idx),
684
+ variantFunction,
685
+ ])
649
686
  )
650
687
  }
651
688
 
@@ -663,7 +700,7 @@ function registerPlugins(plugins, context) {
663
700
  log.warn('root-regex', [
664
701
  'Regular expressions in `safelist` work differently in Tailwind CSS v3.0.',
665
702
  'Update your `safelist` configuration to eliminate this warning.',
666
- // TODO: Add https://tw.wtf/regex-safelist
703
+ 'https://tailwindcss.com/docs/content-configuration#safelisting-classes',
667
704
  ])
668
705
  continue
669
706
  }
@@ -673,12 +710,44 @@ function registerPlugins(plugins, context) {
673
710
 
674
711
  if (checks.length > 0) {
675
712
  let patternMatchingCount = new Map()
713
+ let prefixLength = context.tailwindConfig.prefix.length
676
714
 
677
715
  for (let util of classList) {
678
716
  let utils = Array.isArray(util)
679
717
  ? (() => {
680
718
  let [utilName, options] = util
681
- return Object.keys(options?.values ?? {}).map((value) => formatClass(utilName, value))
719
+ let values = Object.keys(options?.values ?? {})
720
+ let classes = values.map((value) => formatClass(utilName, value))
721
+
722
+ if (options?.supportsNegativeValues) {
723
+ // This is the normal negated version
724
+ // e.g. `-inset-1` or `-tw-inset-1`
725
+ classes = [...classes, ...classes.map((cls) => '-' + cls)]
726
+
727
+ // This is the negated version *after* the prefix
728
+ // e.g. `tw--inset-1`
729
+ // The prefix is already attached to util name
730
+ // So we add the negative after the prefix
731
+ classes = [
732
+ ...classes,
733
+ ...classes.map(
734
+ (cls) => cls.slice(0, prefixLength) + '-' + cls.slice(prefixLength)
735
+ ),
736
+ ]
737
+ }
738
+
739
+ if ([].concat(options?.type).includes('color')) {
740
+ classes = [
741
+ ...classes,
742
+ ...classes.flatMap((cls) =>
743
+ Object.keys(context.tailwindConfig.theme.opacity).map(
744
+ (opacity) => `${cls}/${opacity}`
745
+ )
746
+ ),
747
+ ]
748
+ }
749
+
750
+ return classes
682
751
  })()
683
752
  : [util]
684
753
 
@@ -713,14 +782,56 @@ function registerPlugins(plugins, context) {
713
782
  log.warn([
714
783
  `The safelist pattern \`${regex}\` doesn't match any Tailwind CSS classes.`,
715
784
  'Fix this pattern or remove it from your `safelist` configuration.',
785
+ 'https://tailwindcss.com/docs/content-configuration#safelisting-classes',
716
786
  ])
717
787
  }
718
788
  }
719
789
  }
720
790
 
791
+ let darkClassName = [].concat(context.tailwindConfig.darkMode ?? 'media')[1] ?? 'dark'
792
+
793
+ // A list of utilities that are used by certain Tailwind CSS utilities but
794
+ // that don't exist on their own. This will result in them "not existing" and
795
+ // sorting could be weird since you still require them in order to make the
796
+ // host utilities work properly. (Thanks Biology)
797
+ let parasiteUtilities = [
798
+ prefix(context, darkClassName),
799
+ prefix(context, 'group'),
800
+ prefix(context, 'peer'),
801
+ ]
802
+ context.getClassOrder = function getClassOrder(classes) {
803
+ // Non-util classes won't be generated, so we default them to null
804
+ let sortedClassNames = new Map(classes.map((className) => [className, null]))
805
+
806
+ // Sort all classes in order
807
+ // Non-tailwind classes won't be generated and will be left as `null`
808
+ let rules = generateRules(new Set(classes), context)
809
+ rules = context.offsets.sort(rules)
810
+
811
+ let idx = BigInt(parasiteUtilities.length)
812
+
813
+ for (const [, rule] of rules) {
814
+ sortedClassNames.set(rule.raws.tailwind.candidate, idx++)
815
+ }
816
+
817
+ return classes.map((className) => {
818
+ let order = sortedClassNames.get(className) ?? null
819
+ let parasiteIndex = parasiteUtilities.indexOf(className)
820
+
821
+ if (order === null && parasiteIndex !== -1) {
822
+ // This will make sure that it is at the very beginning of the
823
+ // `components` layer which technically means 'before any
824
+ // components'.
825
+ order = BigInt(parasiteIndex)
826
+ }
827
+
828
+ return [className, order]
829
+ })
830
+ }
831
+
721
832
  // Generate a list of strings for autocompletion purposes, e.g.
722
833
  // ['uppercase', 'lowercase', ...]
723
- context.getClassList = function () {
834
+ context.getClassList = function getClassList() {
724
835
  let output = []
725
836
 
726
837
  for (let util of classList) {
@@ -745,10 +856,57 @@ function registerPlugins(plugins, context) {
745
856
  }
746
857
  }
747
858
 
859
+ /**
860
+ * Mark as class as retroactively invalid
861
+ *
862
+ *
863
+ * @param {string} candidate
864
+ */
865
+ function markInvalidUtilityCandidate(context, candidate) {
866
+ if (!context.classCache.has(candidate)) {
867
+ return
868
+ }
869
+
870
+ // Mark this as not being a real utility
871
+ context.notClassCache.add(candidate)
872
+
873
+ // Remove it from any candidate-specific caches
874
+ context.classCache.delete(candidate)
875
+ context.applyClassCache.delete(candidate)
876
+ context.candidateRuleMap.delete(candidate)
877
+ context.candidateRuleCache.delete(candidate)
878
+
879
+ // Ensure the stylesheet gets rebuilt
880
+ context.stylesheetCache = null
881
+ }
882
+
883
+ /**
884
+ * Mark as class as retroactively invalid
885
+ *
886
+ * @param {import('postcss').Node} node
887
+ */
888
+ function markInvalidUtilityNode(context, node) {
889
+ let candidate = node.raws.tailwind.candidate
890
+
891
+ if (!candidate) {
892
+ return
893
+ }
894
+
895
+ for (const entry of context.ruleCache) {
896
+ if (entry[1].raws.tailwind.candidate === candidate) {
897
+ context.ruleCache.delete(entry)
898
+ // context.postCssNodeCache.delete(node)
899
+ }
900
+ }
901
+
902
+ markInvalidUtilityCandidate(context, candidate)
903
+ }
904
+
748
905
  export function createContext(tailwindConfig, changedContent = [], root = postcss.root()) {
749
906
  let context = {
750
907
  disposables: [],
751
908
  ruleCache: new Set(),
909
+ candidateRuleCache: new Map(),
752
910
  classCache: new Map(),
753
911
  applyClassCache: new Map(),
754
912
  notClassCache: new Set(),
@@ -758,6 +916,9 @@ export function createContext(tailwindConfig, changedContent = [], root = postcs
758
916
  changedContent: changedContent,
759
917
  variantMap: new Map(),
760
918
  stylesheetCache: null,
919
+
920
+ markInvalidUtilityCandidate: (candidate) => markInvalidUtilityCandidate(context, candidate),
921
+ markInvalidUtilityNode: (node) => markInvalidUtilityNode(context, node),
761
922
  }
762
923
 
763
924
  let resolvedPlugins = resolvePlugins(context, root)
@@ -795,6 +956,8 @@ export function getContext(
795
956
  existingContext = context
796
957
  }
797
958
 
959
+ let cssDidChange = hasContentChanged(sourcePath, root)
960
+
798
961
  // If there's already a context in the cache and we don't need to
799
962
  // reset the context, return the cached context.
800
963
  if (existingContext) {
@@ -802,7 +965,7 @@ export function getContext(
802
965
  [...contextDependencies],
803
966
  getFileModifiedMap(existingContext)
804
967
  )
805
- if (!contextDependenciesChanged) {
968
+ if (!contextDependenciesChanged && !cssDidChange) {
806
969
  return [existingContext, false]
807
970
  }
808
971
  }