tailwindcss 0.0.0-insiders.7c337f2 → 0.0.0-insiders.7d8eb21

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 (161) hide show
  1. package/CHANGELOG.md +246 -6
  2. package/README.md +13 -9
  3. package/defaultTheme.d.ts +2 -1
  4. package/lib/cli/build/deps.js +54 -0
  5. package/lib/cli/build/index.js +48 -0
  6. package/lib/cli/build/plugin.js +362 -0
  7. package/lib/cli/build/utils.js +78 -0
  8. package/lib/cli/build/watching.js +178 -0
  9. package/lib/cli/help/index.js +71 -0
  10. package/lib/cli/index.js +18 -0
  11. package/lib/cli/init/index.js +46 -0
  12. package/lib/cli/shared.js +12 -0
  13. package/lib/cli-peer-dependencies.js +18 -5
  14. package/lib/cli.js +62 -592
  15. package/lib/constants.js +19 -12
  16. package/lib/corePluginList.js +5 -3
  17. package/lib/corePlugins.js +619 -347
  18. package/lib/css/preflight.css +7 -0
  19. package/lib/featureFlags.js +34 -22
  20. package/lib/index.js +16 -9
  21. package/lib/lib/cacheInvalidation.js +42 -21
  22. package/lib/lib/collapseAdjacentRules.js +16 -14
  23. package/lib/lib/collapseDuplicateDeclarations.js +13 -10
  24. package/lib/lib/content.js +177 -0
  25. package/lib/lib/defaultExtractor.js +230 -33
  26. package/lib/lib/detectNesting.js +13 -4
  27. package/lib/lib/evaluateTailwindFunctions.js +105 -42
  28. package/lib/lib/expandApplyAtRules.js +151 -92
  29. package/lib/lib/expandTailwindAtRules.js +134 -149
  30. package/lib/lib/findAtConfigPath.js +44 -0
  31. package/lib/lib/generateRules.js +404 -185
  32. package/lib/lib/getModuleDependencies.js +21 -18
  33. package/lib/lib/normalizeTailwindDirectives.js +11 -8
  34. package/lib/lib/offsets.js +285 -0
  35. package/lib/lib/partitionApplyAtRules.js +14 -11
  36. package/lib/lib/regex.js +60 -0
  37. package/lib/lib/remap-bitfield.js +87 -0
  38. package/lib/lib/resolveDefaultsAtRules.js +97 -79
  39. package/lib/lib/setupContextUtils.js +567 -242
  40. package/lib/lib/setupTrackingContext.js +77 -106
  41. package/lib/lib/sharedState.js +18 -10
  42. package/lib/lib/substituteScreenAtRules.js +9 -7
  43. package/lib/postcss-plugins/nesting/index.js +7 -5
  44. package/lib/postcss-plugins/nesting/plugin.js +10 -8
  45. package/lib/processTailwindFeatures.js +34 -31
  46. package/lib/public/colors.js +7 -5
  47. package/lib/public/create-plugin.js +6 -4
  48. package/lib/public/default-config.js +7 -5
  49. package/lib/public/default-theme.js +7 -5
  50. package/lib/public/resolve-config.js +13 -10
  51. package/lib/util/bigSign.js +4 -1
  52. package/lib/util/buildMediaQuery.js +10 -5
  53. package/lib/util/cloneDeep.js +6 -5
  54. package/lib/util/cloneNodes.js +9 -2
  55. package/lib/util/color.js +20 -17
  56. package/lib/util/configurePlugins.js +5 -2
  57. package/lib/util/createPlugin.js +6 -5
  58. package/lib/util/createUtilityPlugin.js +15 -13
  59. package/lib/util/dataTypes.js +75 -51
  60. package/lib/util/defaults.js +8 -5
  61. package/lib/util/escapeClassName.js +13 -10
  62. package/lib/util/escapeCommas.js +4 -1
  63. package/lib/util/flattenColorPalette.js +7 -8
  64. package/lib/util/formatVariantSelector.js +270 -103
  65. package/lib/util/getAllConfigs.js +34 -15
  66. package/lib/util/hashConfig.js +10 -7
  67. package/lib/util/isKeyframeRule.js +4 -1
  68. package/lib/util/isPlainObject.js +4 -1
  69. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +34 -26
  70. package/lib/util/log.js +14 -8
  71. package/lib/util/nameClass.js +19 -8
  72. package/lib/util/negateValue.js +20 -5
  73. package/lib/util/normalizeConfig.js +94 -53
  74. package/lib/util/normalizeScreens.js +115 -4
  75. package/lib/util/parseAnimationValue.js +43 -41
  76. package/lib/util/parseBoxShadowValue.js +12 -45
  77. package/lib/util/parseDependency.js +37 -55
  78. package/lib/util/parseGlob.js +34 -0
  79. package/lib/util/parseObjectStyles.js +15 -12
  80. package/lib/util/pluginUtils.js +146 -42
  81. package/lib/util/prefixSelector.js +26 -9
  82. package/lib/util/removeAlphaVariables.js +29 -0
  83. package/lib/util/resolveConfig.js +104 -105
  84. package/lib/util/resolveConfigPath.js +20 -17
  85. package/lib/util/responsive.js +12 -9
  86. package/lib/util/splitAtTopLevelOnly.js +43 -0
  87. package/lib/util/tap.js +4 -1
  88. package/lib/util/toColorValue.js +4 -1
  89. package/lib/util/toPath.js +18 -2
  90. package/lib/util/transformThemeValue.js +23 -11
  91. package/lib/util/validateConfig.js +24 -0
  92. package/lib/util/validateFormalSyntax.js +24 -0
  93. package/lib/util/withAlphaVariable.js +32 -24
  94. package/package.json +32 -29
  95. package/peers/index.js +6693 -3036
  96. package/plugin.d.ts +10 -5
  97. package/resolveConfig.d.ts +12 -0
  98. package/scripts/generate-types.js +53 -0
  99. package/scripts/release-channel.js +18 -0
  100. package/scripts/release-notes.js +21 -0
  101. package/scripts/type-utils.js +27 -0
  102. package/src/cli/build/deps.js +56 -0
  103. package/src/cli/build/index.js +49 -0
  104. package/src/cli/build/plugin.js +434 -0
  105. package/src/cli/build/utils.js +76 -0
  106. package/src/cli/build/watching.js +227 -0
  107. package/src/cli/help/index.js +70 -0
  108. package/src/cli/index.js +3 -0
  109. package/src/cli/init/index.js +50 -0
  110. package/src/cli/shared.js +5 -0
  111. package/src/cli-peer-dependencies.js +7 -1
  112. package/src/cli.js +46 -659
  113. package/src/corePlugins.js +346 -79
  114. package/src/css/preflight.css +7 -0
  115. package/src/featureFlags.js +12 -2
  116. package/src/index.js +5 -0
  117. package/src/lib/content.js +213 -0
  118. package/src/lib/defaultExtractor.js +202 -35
  119. package/src/lib/detectNesting.js +9 -1
  120. package/src/lib/evaluateTailwindFunctions.js +78 -7
  121. package/src/lib/expandApplyAtRules.js +129 -34
  122. package/src/lib/expandTailwindAtRules.js +12 -50
  123. package/src/lib/findAtConfigPath.js +48 -0
  124. package/src/lib/generateRules.js +379 -126
  125. package/src/lib/offsets.js +351 -0
  126. package/src/lib/regex.js +74 -0
  127. package/src/lib/remap-bitfield.js +82 -0
  128. package/src/lib/resolveDefaultsAtRules.js +53 -36
  129. package/src/lib/setupContextUtils.js +510 -120
  130. package/src/lib/setupTrackingContext.js +8 -45
  131. package/src/lib/sharedState.js +2 -0
  132. package/src/util/buildMediaQuery.js +5 -3
  133. package/src/util/cloneNodes.js +5 -1
  134. package/src/util/dataTypes.js +51 -26
  135. package/src/util/formatVariantSelector.js +317 -101
  136. package/src/util/getAllConfigs.js +19 -0
  137. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  138. package/src/util/log.js +1 -1
  139. package/src/util/nameClass.js +4 -0
  140. package/src/util/negateValue.js +10 -2
  141. package/src/util/normalizeConfig.js +40 -10
  142. package/src/util/normalizeScreens.js +99 -4
  143. package/src/util/parseBoxShadowValue.js +3 -50
  144. package/src/util/parseDependency.js +37 -42
  145. package/src/util/parseGlob.js +24 -0
  146. package/src/util/pluginUtils.js +132 -10
  147. package/src/util/prefixSelector.js +28 -10
  148. package/src/util/removeAlphaVariables.js +24 -0
  149. package/src/util/resolveConfig.js +70 -62
  150. package/src/util/splitAtTopLevelOnly.js +45 -0
  151. package/src/util/toPath.js +1 -1
  152. package/src/util/transformThemeValue.js +13 -3
  153. package/src/util/validateConfig.js +13 -0
  154. package/src/util/validateFormalSyntax.js +34 -0
  155. package/src/util/withAlphaVariable.js +1 -1
  156. package/stubs/defaultConfig.stub.js +165 -164
  157. package/stubs/simpleConfig.stub.js +1 -0
  158. package/types/config.d.ts +77 -37
  159. package/types/generated/default-theme.d.ts +342 -0
  160. package/types/index.d.ts +7 -1
  161. package/types.d.ts +0 -1
@@ -11,22 +11,48 @@ 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
- import { generateRules } from './generateRules'
20
+ import isSyntacticallyValidPropertyValue from '../util/isSyntacticallyValidPropertyValue'
21
+ import { generateRules, getClassNameFromSelector } from './generateRules'
23
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
+ }
24
36
 
25
37
  function prefix(context, selector) {
26
38
  let prefix = context.tailwindConfig.prefix
27
39
  return typeof prefix === 'function' ? prefix(selector) : prefix + selector
28
40
  }
29
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
+
30
56
  function parseVariantFormatString(input) {
31
57
  if (input.includes('{')) {
32
58
  if (!isBalanced(input)) throw new Error(`Your { and } are unbalanced.`)
@@ -170,6 +196,41 @@ function withIdentifiers(styles) {
170
196
  })
171
197
  }
172
198
 
199
+ export function isValidVariantFormatString(format) {
200
+ return format.startsWith('@') || format.includes('&')
201
+ }
202
+
203
+ export function parseVariant(variant) {
204
+ variant = variant
205
+ .replace(/\n+/g, '')
206
+ .replace(/\s{1,}/g, ' ')
207
+ .trim()
208
+
209
+ let fns = parseVariantFormatString(variant)
210
+ .map((str) => {
211
+ if (!str.startsWith('@')) {
212
+ return ({ format }) => format(str)
213
+ }
214
+
215
+ let [, name, params] = /@(.*?)( .+|[({].*)/g.exec(str)
216
+ return ({ wrap }) => wrap(postcss.atRule({ name, params: params.trim() }))
217
+ })
218
+ .reverse()
219
+
220
+ return (api) => {
221
+ for (let fn of fns) {
222
+ fn(api)
223
+ }
224
+ }
225
+ }
226
+
227
+ /**
228
+ *
229
+ * @param {any} tailwindConfig
230
+ * @param {any} context
231
+ * @param {object} param2
232
+ * @param {Offsets} param2.offsets
233
+ */
173
234
  function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offsets, classList }) {
174
235
  function getConfigValue(path, defaultValue) {
175
236
  return path ? dlv(tailwindConfig, path, defaultValue) : tailwindConfig
@@ -191,51 +252,19 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
191
252
  return context.tailwindConfig.prefix + identifier
192
253
  }
193
254
 
194
- return {
195
- addVariant(variantName, variantFunctions, options = {}) {
196
- variantFunctions = [].concat(variantFunctions).map((variantFunction) => {
197
- if (typeof variantFunction !== 'string') {
198
- // Safelist public API functions
199
- return ({ modifySelectors, container, separator }) => {
200
- return variantFunction({ modifySelectors, container, separator })
201
- }
202
- }
203
-
204
- variantFunction = variantFunction
205
- .replace(/\n+/g, '')
206
- .replace(/\s{1,}/g, ' ')
207
- .trim()
208
-
209
- let fns = parseVariantFormatString(variantFunction)
210
- .map((str) => {
211
- if (!str.startsWith('@')) {
212
- return ({ format }) => format(str)
213
- }
214
-
215
- let [, name, params] = /@(.*?) (.*)/g.exec(str)
216
- return ({ wrap }) => wrap(postcss.atRule({ name, params }))
217
- })
218
- .reverse()
219
-
220
- return (api) => {
221
- for (let fn of fns) {
222
- fn(api)
223
- }
224
- }
225
- })
255
+ function resolveThemeValue(path, defaultValue, opts = {}) {
256
+ let parts = toPath(path)
257
+ let value = getConfigValue(['theme', ...parts], defaultValue)
258
+ return transformThemeValue(parts[0])(value, opts)
259
+ }
226
260
 
227
- insertInto(variantList, variantName, options)
228
- variantMap.set(variantName, variantFunctions)
229
- },
261
+ let variantIdentifier = 0
262
+ let api = {
230
263
  postcss,
231
264
  prefix: applyConfiguredPrefix,
232
265
  e: escapeClassName,
233
266
  config: getConfigValue,
234
- theme(path, defaultValue) {
235
- const [pathRoot, ...subPaths] = toPath(path)
236
- const value = getConfigValue(['theme', pathRoot, ...subPaths], defaultValue)
237
- return transformThemeValue(pathRoot)(value)
238
- },
267
+ theme: resolveThemeValue,
239
268
  corePlugins: (path) => {
240
269
  if (Array.isArray(tailwindConfig.corePlugins)) {
241
270
  return tailwindConfig.corePlugins.includes(path)
@@ -250,7 +279,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
250
279
  addBase(base) {
251
280
  for (let [identifier, rule] of withIdentifiers(base)) {
252
281
  let prefixedIdentifier = prefixIdentifier(identifier, {})
253
- let offset = offsets.base++
282
+ let offset = offsets.create('base')
254
283
 
255
284
  if (!context.candidateRuleMap.has(prefixedIdentifier)) {
256
285
  context.candidateRuleMap.set(prefixedIdentifier, [])
@@ -279,11 +308,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
279
308
 
280
309
  context.candidateRuleMap
281
310
  .get(prefixedIdentifier)
282
- .push([{ sort: offsets.base++, layer: 'defaults' }, rule])
311
+ .push([{ sort: offsets.create('defaults'), layer: 'defaults' }, rule])
283
312
  }
284
313
  },
285
314
  addComponents(components, options) {
286
315
  let defaultOptions = {
316
+ preserveSource: false,
287
317
  respectPrefix: true,
288
318
  respectImportant: false,
289
319
  }
@@ -301,11 +331,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
301
331
 
302
332
  context.candidateRuleMap
303
333
  .get(prefixedIdentifier)
304
- .push([{ sort: offsets.components++, layer: 'components', options }, rule])
334
+ .push([{ sort: offsets.create('components'), layer: 'components', options }, rule])
305
335
  }
306
336
  },
307
337
  addUtilities(utilities, options) {
308
338
  let defaultOptions = {
339
+ preserveSource: false,
309
340
  respectPrefix: true,
310
341
  respectImportant: true,
311
342
  }
@@ -323,18 +354,19 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
323
354
 
324
355
  context.candidateRuleMap
325
356
  .get(prefixedIdentifier)
326
- .push([{ sort: offsets.utilities++, layer: 'utilities', options }, rule])
357
+ .push([{ sort: offsets.create('utilities'), layer: 'utilities', options }, rule])
327
358
  }
328
359
  },
329
360
  matchUtilities: function (utilities, options) {
330
361
  let defaultOptions = {
331
362
  respectPrefix: true,
332
363
  respectImportant: true,
364
+ modifiers: false,
333
365
  }
334
366
 
335
- options = { ...defaultOptions, ...options }
367
+ options = normalizeOptionTypes({ ...defaultOptions, ...options })
336
368
 
337
- let offset = offsets.utilities++
369
+ let offset = offsets.create('utilities')
338
370
 
339
371
  for (let identifier in utilities) {
340
372
  let prefixedIdentifier = prefixIdentifier(identifier, options)
@@ -343,24 +375,51 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
343
375
  classList.add([prefixedIdentifier, options])
344
376
 
345
377
  function wrapped(modifier, { isOnlyPlugin }) {
346
- let { type = 'any' } = options
347
- type = [].concat(type)
348
- let [value, coercedType] = coerceValue(type, modifier, options, tailwindConfig)
378
+ let [value, coercedType, utilityModifier] = coerceValue(
379
+ options.types,
380
+ modifier,
381
+ options,
382
+ tailwindConfig
383
+ )
349
384
 
350
385
  if (value === undefined) {
351
386
  return []
352
387
  }
353
388
 
354
- if (!type.includes(coercedType) && !isOnlyPlugin) {
355
- return []
389
+ if (!options.types.some(({ type }) => type === coercedType)) {
390
+ if (isOnlyPlugin) {
391
+ log.warn([
392
+ `Unnecessary typehint \`${coercedType}\` in \`${identifier}-${modifier}\`.`,
393
+ `You can safely update it to \`${identifier}-${modifier.replace(
394
+ coercedType + ':',
395
+ ''
396
+ )}\`.`,
397
+ ])
398
+ } else {
399
+ return []
400
+ }
356
401
  }
357
402
 
358
- if (!isValidArbitraryValue(value)) {
403
+ if (!isSyntacticallyValidPropertyValue(value)) {
359
404
  return []
360
405
  }
361
406
 
407
+ let extras = {
408
+ get modifier() {
409
+ if (!options.modifiers) {
410
+ log.warn(`modifier-used-without-options-for-${identifier}`, [
411
+ 'Your plugin must set `modifiers: true` in its options to support modifiers.',
412
+ ])
413
+ }
414
+
415
+ return utilityModifier
416
+ },
417
+ }
418
+
419
+ let modifiersEnabled = flagEnabled(tailwindConfig, 'generalizedModifiers')
420
+
362
421
  let ruleSets = []
363
- .concat(rule(value))
422
+ .concat(modifiersEnabled ? rule(value, extras) : rule(value))
364
423
  .filter(Boolean)
365
424
  .map((declaration) => ({
366
425
  [nameClass(identifier, modifier)]: declaration,
@@ -382,11 +441,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
382
441
  let defaultOptions = {
383
442
  respectPrefix: true,
384
443
  respectImportant: false,
444
+ modifiers: false,
385
445
  }
386
446
 
387
- options = { ...defaultOptions, ...options }
447
+ options = normalizeOptionTypes({ ...defaultOptions, ...options })
388
448
 
389
- let offset = offsets.components++
449
+ let offset = offsets.create('components')
390
450
 
391
451
  for (let identifier in components) {
392
452
  let prefixedIdentifier = prefixIdentifier(identifier, options)
@@ -395,15 +455,18 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
395
455
  classList.add([prefixedIdentifier, options])
396
456
 
397
457
  function wrapped(modifier, { isOnlyPlugin }) {
398
- let { type = 'any' } = options
399
- type = [].concat(type)
400
- let [value, coercedType] = coerceValue(type, modifier, options, tailwindConfig)
458
+ let [value, coercedType, utilityModifier] = coerceValue(
459
+ options.types,
460
+ modifier,
461
+ options,
462
+ tailwindConfig
463
+ )
401
464
 
402
465
  if (value === undefined) {
403
466
  return []
404
467
  }
405
468
 
406
- if (!type.includes(coercedType)) {
469
+ if (!options.types.some(({ type }) => type === coercedType)) {
407
470
  if (isOnlyPlugin) {
408
471
  log.warn([
409
472
  `Unnecessary typehint \`${coercedType}\` in \`${identifier}-${modifier}\`.`,
@@ -417,12 +480,26 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
417
480
  }
418
481
  }
419
482
 
420
- if (!isValidArbitraryValue(value)) {
483
+ if (!isSyntacticallyValidPropertyValue(value)) {
421
484
  return []
422
485
  }
423
486
 
487
+ let extras = {
488
+ get modifier() {
489
+ if (!options.modifiers) {
490
+ log.warn(`modifier-used-without-options-for-${identifier}`, [
491
+ 'Your plugin must set `modifiers: true` in its options to support modifiers.',
492
+ ])
493
+ }
494
+
495
+ return utilityModifier
496
+ },
497
+ }
498
+
499
+ let modifiersEnabled = flagEnabled(tailwindConfig, 'generalizedModifiers')
500
+
424
501
  let ruleSets = []
425
- .concat(rule(value))
502
+ .concat(modifiersEnabled ? rule(value, extras) : rule(value))
426
503
  .filter(Boolean)
427
504
  .map((declaration) => ({
428
505
  [nameClass(identifier, modifier)]: declaration,
@@ -440,7 +517,109 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs
440
517
  context.candidateRuleMap.get(prefixedIdentifier).push(withOffsets)
441
518
  }
442
519
  },
520
+ addVariant(variantName, variantFunctions, options = {}) {
521
+ variantFunctions = [].concat(variantFunctions).map((variantFunction) => {
522
+ if (typeof variantFunction !== 'string') {
523
+ // Safelist public API functions
524
+ return (api = {}) => {
525
+ let { args, modifySelectors, container, separator, wrap, format } = api
526
+ let result = variantFunction(
527
+ Object.assign(
528
+ { modifySelectors, container, separator },
529
+ options.type === VARIANT_TYPES.MatchVariant && { args, wrap, format }
530
+ )
531
+ )
532
+
533
+ if (typeof result === 'string' && !isValidVariantFormatString(result)) {
534
+ throw new Error(
535
+ `Your custom variant \`${variantName}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`
536
+ )
537
+ }
538
+
539
+ if (Array.isArray(result)) {
540
+ return result
541
+ .filter((variant) => typeof variant === 'string')
542
+ .map((variant) => parseVariant(variant))
543
+ }
544
+
545
+ // result may be undefined with legacy variants that use APIs like `modifySelectors`
546
+ // result may also be a postcss node if someone was returning the result from `modifySelectors`
547
+ return result && typeof result === 'string' && parseVariant(result)(api)
548
+ }
549
+ }
550
+
551
+ if (!isValidVariantFormatString(variantFunction)) {
552
+ throw new Error(
553
+ `Your custom variant \`${variantName}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`
554
+ )
555
+ }
556
+
557
+ return parseVariant(variantFunction)
558
+ })
559
+
560
+ insertInto(variantList, variantName, options)
561
+ variantMap.set(variantName, variantFunctions)
562
+ context.variantOptions.set(variantName, options)
563
+ },
564
+ matchVariant(variant, variantFn, options) {
565
+ // A unique identifier that "groups" these variants together.
566
+ // This is for internal use only which is why it is not present in the types
567
+ let id = options?.id ?? ++variantIdentifier
568
+ let isSpecial = variant === '@'
569
+
570
+ let modifiersEnabled = flagEnabled(tailwindConfig, 'generalizedModifiers')
571
+
572
+ for (let [key, value] of Object.entries(options?.values ?? {})) {
573
+ if (key === 'DEFAULT') continue
574
+
575
+ api.addVariant(
576
+ isSpecial ? `${variant}${key}` : `${variant}-${key}`,
577
+ ({ args, container }) => {
578
+ return variantFn(
579
+ value,
580
+ modifiersEnabled ? { modifier: args?.modifier, container } : { container }
581
+ )
582
+ },
583
+
584
+ {
585
+ ...options,
586
+ value,
587
+ id,
588
+ type: VARIANT_TYPES.MatchVariant,
589
+ variantInfo: VARIANT_INFO.Base,
590
+ }
591
+ )
592
+ }
593
+
594
+ let hasDefault = 'DEFAULT' in (options?.values ?? {})
595
+
596
+ api.addVariant(
597
+ variant,
598
+ ({ args, container }) => {
599
+ if (args?.value === sharedState.NONE && !hasDefault) {
600
+ return null
601
+ }
602
+
603
+ return variantFn(
604
+ args?.value === sharedState.NONE
605
+ ? options.values.DEFAULT
606
+ : // Falling back to args if it is a string, otherwise '' for older intellisense
607
+ // (JetBrains) plugins.
608
+ args?.value ?? (typeof args === 'string' ? args : ''),
609
+ modifiersEnabled ? { modifier: args?.modifier, container } : { container }
610
+ )
611
+ },
612
+ {
613
+ ...options,
614
+ id,
615
+ type: VARIANT_TYPES.MatchVariant,
616
+ variantInfo: VARIANT_INFO.Dynamic,
617
+ }
618
+ )
619
+ },
443
620
  }
621
+
622
+ return api
444
623
  }
445
624
 
446
625
  let fileModifiedMapCache = new WeakMap()
@@ -513,14 +692,14 @@ function collectLayerPlugins(root) {
513
692
  } else if (layerRule.params === 'components') {
514
693
  for (let node of layerRule.nodes) {
515
694
  layerPlugins.push(function ({ addComponents }) {
516
- addComponents(node, { respectPrefix: false })
695
+ addComponents(node, { respectPrefix: false, preserveSource: true })
517
696
  })
518
697
  }
519
698
  layerRule.remove()
520
699
  } else if (layerRule.params === 'utilities') {
521
700
  for (let node of layerRule.nodes) {
522
701
  layerPlugins.push(function ({ addUtilities }) {
523
- addUtilities(node, { respectPrefix: false })
702
+ addUtilities(node, { respectPrefix: false, preserveSource: true })
524
703
  })
525
704
  }
526
705
  layerRule.remove()
@@ -556,10 +735,14 @@ function resolvePlugins(context, root) {
556
735
  let beforeVariants = [
557
736
  variantPlugins['pseudoElementVariants'],
558
737
  variantPlugins['pseudoClassVariants'],
738
+ variantPlugins['ariaVariants'],
739
+ variantPlugins['dataVariants'],
559
740
  ]
560
741
  let afterVariants = [
742
+ variantPlugins['supportsVariants'],
561
743
  variantPlugins['directionVariants'],
562
744
  variantPlugins['reducedMotionVariants'],
745
+ variantPlugins['prefersContrastVariants'],
563
746
  variantPlugins['darkVariants'],
564
747
  variantPlugins['printVariant'],
565
748
  variantPlugins['screenVariants'],
@@ -572,13 +755,10 @@ function resolvePlugins(context, root) {
572
755
  function registerPlugins(plugins, context) {
573
756
  let variantList = []
574
757
  let variantMap = new Map()
575
- let offsets = {
576
- defaults: 0n,
577
- base: 0n,
578
- components: 0n,
579
- utilities: 0n,
580
- user: 0n,
581
- }
758
+ context.variantMap = variantMap
759
+
760
+ let offsets = new Offsets()
761
+ context.offsets = offsets
582
762
 
583
763
  let classList = new Set()
584
764
 
@@ -599,49 +779,17 @@ function registerPlugins(plugins, context) {
599
779
  }
600
780
  }
601
781
 
602
- let highestOffset = ((args) => args.reduce((m, e) => (e > m ? e : m)))([
603
- offsets.base,
604
- offsets.defaults,
605
- offsets.components,
606
- offsets.utilities,
607
- offsets.user,
608
- ])
609
- let reservedBits = BigInt(highestOffset.toString(2).length)
610
-
611
- // A number one less than the top range of the highest offset area
612
- // so arbitrary properties are always sorted at the end.
613
- context.arbitraryPropertiesSort = ((1n << reservedBits) << 0n) - 1n
614
-
615
- context.layerOrder = {
616
- defaults: (1n << reservedBits) << 0n,
617
- base: (1n << reservedBits) << 1n,
618
- components: (1n << reservedBits) << 2n,
619
- utilities: (1n << reservedBits) << 3n,
620
- user: (1n << reservedBits) << 4n,
621
- }
622
-
623
- reservedBits += 5n
624
-
625
- let offset = 0
626
- context.variantOrder = new Map(
627
- variantList
628
- .map((variant, i) => {
629
- let variantFunctions = variantMap.get(variant).length
630
- let bits = (1n << BigInt(i + offset)) << reservedBits
631
- offset += variantFunctions - 1
632
- return [variant, bits]
633
- })
634
- .sort(([, a], [, z]) => bigSign(a - z))
635
- )
636
-
637
- context.minimumScreen = [...context.variantOrder.values()].shift()
782
+ // Make sure to record bit masks for every variant
783
+ offsets.recordVariants(variantList, (variant) => variantMap.get(variant).length)
638
784
 
639
785
  // Build variantMap
640
786
  for (let [variantName, variantFunctions] of variantMap.entries()) {
641
- let sort = context.variantOrder.get(variantName)
642
787
  context.variantMap.set(
643
788
  variantName,
644
- variantFunctions.map((variantFunction, idx) => [sort << BigInt(idx), variantFunction])
789
+ variantFunctions.map((variantFunction, idx) => [
790
+ offsets.forVariant(variantName, idx),
791
+ variantFunction,
792
+ ])
645
793
  )
646
794
  }
647
795
 
@@ -670,6 +818,7 @@ function registerPlugins(plugins, context) {
670
818
  if (checks.length > 0) {
671
819
  let patternMatchingCount = new Map()
672
820
  let prefixLength = context.tailwindConfig.prefix.length
821
+ let checkImportantUtils = checks.some((check) => check.pattern.source.includes('!'))
673
822
 
674
823
  for (let util of classList) {
675
824
  let utils = Array.isArray(util)
@@ -695,6 +844,21 @@ function registerPlugins(plugins, context) {
695
844
  ]
696
845
  }
697
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
+ if (checkImportantUtils && options?.respectImportant) {
859
+ classes = [...classes, ...classes.map((cls) => '!' + cls)]
860
+ }
861
+
698
862
  return classes
699
863
  })()
700
864
  : [util]
@@ -736,26 +900,41 @@ function registerPlugins(plugins, context) {
736
900
  }
737
901
  }
738
902
 
903
+ let darkClassName = [].concat(context.tailwindConfig.darkMode ?? 'media')[1] ?? 'dark'
904
+
739
905
  // A list of utilities that are used by certain Tailwind CSS utilities but
740
906
  // that don't exist on their own. This will result in them "not existing" and
741
907
  // sorting could be weird since you still require them in order to make the
742
- // host utitlies work properly. (Thanks Biology)
743
- let parasiteUtilities = new Set([prefix(context, 'group'), prefix(context, 'peer')])
908
+ // host utilities work properly. (Thanks Biology)
909
+ let parasiteUtilities = [
910
+ prefix(context, darkClassName),
911
+ prefix(context, 'group'),
912
+ prefix(context, 'peer'),
913
+ ]
744
914
  context.getClassOrder = function getClassOrder(classes) {
745
- let sortedClassNames = new Map()
746
- for (let [sort, rule] of generateRules(new Set(classes), context)) {
747
- if (sortedClassNames.has(rule.raws.tailwind.candidate)) continue
748
- sortedClassNames.set(rule.raws.tailwind.candidate, sort)
915
+ // Non-util classes won't be generated, so we default them to null
916
+ let sortedClassNames = new Map(classes.map((className) => [className, null]))
917
+
918
+ // Sort all classes in order
919
+ // Non-tailwind classes won't be generated and will be left as `null`
920
+ let rules = generateRules(new Set(classes), context)
921
+ rules = context.offsets.sort(rules)
922
+
923
+ let idx = BigInt(parasiteUtilities.length)
924
+
925
+ for (const [, rule] of rules) {
926
+ sortedClassNames.set(rule.raws.tailwind.candidate, idx++)
749
927
  }
750
928
 
751
929
  return classes.map((className) => {
752
930
  let order = sortedClassNames.get(className) ?? null
931
+ let parasiteIndex = parasiteUtilities.indexOf(className)
753
932
 
754
- if (order === null && parasiteUtilities.has(className)) {
933
+ if (order === null && parasiteIndex !== -1) {
755
934
  // This will make sure that it is at the very beginning of the
756
935
  // `components` layer which technically means 'before any
757
936
  // components'.
758
- order = context.layerOrder.components
937
+ order = BigInt(parasiteIndex)
759
938
  }
760
939
 
761
940
  return [className, order]
@@ -773,6 +952,11 @@ function registerPlugins(plugins, context) {
773
952
  let negativeClasses = []
774
953
 
775
954
  for (let [key, value] of Object.entries(options?.values ?? {})) {
955
+ // Ignore undefined and null values
956
+ if (value == null) {
957
+ continue
958
+ }
959
+
776
960
  output.push(formatClass(utilName, key))
777
961
  if (options?.supportsNegativeValues && negateValue(value)) {
778
962
  negativeClasses.push(formatClass(utilName, `-${key}`))
@@ -787,21 +971,223 @@ function registerPlugins(plugins, context) {
787
971
 
788
972
  return output
789
973
  }
974
+
975
+ // Generate a list of available variants with meta information of the type of variant.
976
+ context.getVariants = function getVariants() {
977
+ let result = []
978
+ for (let [name, options] of context.variantOptions.entries()) {
979
+ if (options.variantInfo === VARIANT_INFO.Base) continue
980
+
981
+ result.push({
982
+ name,
983
+ isArbitrary: options.type === Symbol.for('MATCH_VARIANT'),
984
+ values: Object.keys(options.values ?? {}),
985
+ hasDash: name !== '@',
986
+ selectors({ modifier, value } = {}) {
987
+ let candidate = '__TAILWIND_PLACEHOLDER__'
988
+
989
+ let rule = postcss.rule({ selector: `.${candidate}` })
990
+ let container = postcss.root({ nodes: [rule.clone()] })
991
+
992
+ let before = container.toString()
993
+
994
+ let fns = (context.variantMap.get(name) ?? []).flatMap(([_, fn]) => fn)
995
+ let formatStrings = []
996
+ for (let fn of fns) {
997
+ let localFormatStrings = []
998
+
999
+ let api = {
1000
+ args: { modifier, value: options.values?.[value] ?? value },
1001
+ separator: context.tailwindConfig.separator,
1002
+ modifySelectors(modifierFunction) {
1003
+ // Run the modifierFunction over each rule
1004
+ container.each((rule) => {
1005
+ if (rule.type !== 'rule') {
1006
+ return
1007
+ }
1008
+
1009
+ rule.selectors = rule.selectors.map((selector) => {
1010
+ return modifierFunction({
1011
+ get className() {
1012
+ return getClassNameFromSelector(selector)
1013
+ },
1014
+ selector,
1015
+ })
1016
+ })
1017
+ })
1018
+
1019
+ return container
1020
+ },
1021
+ format(str) {
1022
+ localFormatStrings.push(str)
1023
+ },
1024
+ wrap(wrapper) {
1025
+ localFormatStrings.push(`@${wrapper.name} ${wrapper.params} { & }`)
1026
+ },
1027
+ container,
1028
+ }
1029
+
1030
+ let ruleWithVariant = fn(api)
1031
+ if (localFormatStrings.length > 0) {
1032
+ formatStrings.push(localFormatStrings)
1033
+ }
1034
+
1035
+ if (Array.isArray(ruleWithVariant)) {
1036
+ for (let variantFunction of ruleWithVariant) {
1037
+ localFormatStrings = []
1038
+ variantFunction(api)
1039
+ formatStrings.push(localFormatStrings)
1040
+ }
1041
+ }
1042
+ }
1043
+
1044
+ // Reverse engineer the result of the `container`
1045
+ let manualFormatStrings = []
1046
+ let after = container.toString()
1047
+
1048
+ if (before !== after) {
1049
+ // Figure out all selectors
1050
+ container.walkRules((rule) => {
1051
+ let modified = rule.selector
1052
+
1053
+ // Rebuild the base selector, this is what plugin authors would do
1054
+ // as well. E.g.: `${variant}${separator}${className}`.
1055
+ // However, plugin authors probably also prepend or append certain
1056
+ // classes, pseudos, ids, ...
1057
+ let rebuiltBase = selectorParser((selectors) => {
1058
+ selectors.walkClasses((classNode) => {
1059
+ classNode.value = `${name}${context.tailwindConfig.separator}${classNode.value}`
1060
+ })
1061
+ }).processSync(modified)
1062
+
1063
+ // Now that we know the original selector, the new selector, and
1064
+ // the rebuild part in between, we can replace the part that plugin
1065
+ // authors need to rebuild with `&`, and eventually store it in the
1066
+ // collectedFormats. Similar to what `format('...')` would do.
1067
+ //
1068
+ // E.g.:
1069
+ // variant: foo
1070
+ // selector: .markdown > p
1071
+ // modified (by plugin): .foo .foo\\:markdown > p
1072
+ // rebuiltBase (internal): .foo\\:markdown > p
1073
+ // format: .foo &
1074
+ manualFormatStrings.push(modified.replace(rebuiltBase, '&').replace(candidate, '&'))
1075
+ })
1076
+
1077
+ // Figure out all atrules
1078
+ container.walkAtRules((atrule) => {
1079
+ manualFormatStrings.push(`@${atrule.name} (${atrule.params}) { & }`)
1080
+ })
1081
+ }
1082
+
1083
+ let isArbitraryVariant = !(value in (options.values ?? {}))
1084
+
1085
+ formatStrings = formatStrings.map((format) =>
1086
+ format.map((str) => ({
1087
+ format: str,
1088
+ isArbitraryVariant,
1089
+ }))
1090
+ )
1091
+
1092
+ manualFormatStrings = manualFormatStrings.map((format) => ({
1093
+ format,
1094
+ isArbitraryVariant,
1095
+ }))
1096
+
1097
+ let opts = {
1098
+ candidate,
1099
+ context,
1100
+ }
1101
+
1102
+ let result = formatStrings.map((formats) =>
1103
+ finalizeSelector(`.${candidate}`, formatVariantSelector(formats, opts), opts)
1104
+ .replace(`.${candidate}`, '&')
1105
+ .replace('{ & }', '')
1106
+ .trim()
1107
+ )
1108
+
1109
+ if (manualFormatStrings.length > 0) {
1110
+ result.push(
1111
+ formatVariantSelector(manualFormatStrings, opts)
1112
+ .toString()
1113
+ .replace(`.${candidate}`, '&')
1114
+ )
1115
+ }
1116
+
1117
+ return result
1118
+ },
1119
+ })
1120
+ }
1121
+
1122
+ return result
1123
+ }
1124
+ }
1125
+
1126
+ /**
1127
+ * Mark as class as retroactively invalid
1128
+ *
1129
+ *
1130
+ * @param {string} candidate
1131
+ */
1132
+ function markInvalidUtilityCandidate(context, candidate) {
1133
+ if (!context.classCache.has(candidate)) {
1134
+ return
1135
+ }
1136
+
1137
+ // Mark this as not being a real utility
1138
+ context.notClassCache.add(candidate)
1139
+
1140
+ // Remove it from any candidate-specific caches
1141
+ context.classCache.delete(candidate)
1142
+ context.applyClassCache.delete(candidate)
1143
+ context.candidateRuleMap.delete(candidate)
1144
+ context.candidateRuleCache.delete(candidate)
1145
+
1146
+ // Ensure the stylesheet gets rebuilt
1147
+ context.stylesheetCache = null
1148
+ }
1149
+
1150
+ /**
1151
+ * Mark as class as retroactively invalid
1152
+ *
1153
+ * @param {import('postcss').Node} node
1154
+ */
1155
+ function markInvalidUtilityNode(context, node) {
1156
+ let candidate = node.raws.tailwind.candidate
1157
+
1158
+ if (!candidate) {
1159
+ return
1160
+ }
1161
+
1162
+ for (const entry of context.ruleCache) {
1163
+ if (entry[1].raws.tailwind.candidate === candidate) {
1164
+ context.ruleCache.delete(entry)
1165
+ // context.postCssNodeCache.delete(node)
1166
+ }
1167
+ }
1168
+
1169
+ markInvalidUtilityCandidate(context, candidate)
790
1170
  }
791
1171
 
792
1172
  export function createContext(tailwindConfig, changedContent = [], root = postcss.root()) {
793
1173
  let context = {
794
1174
  disposables: [],
795
1175
  ruleCache: new Set(),
1176
+ candidateRuleCache: new Map(),
796
1177
  classCache: new Map(),
797
1178
  applyClassCache: new Map(),
798
- notClassCache: new Set(),
1179
+ // Seed the not class cache with the blocklist (which is only strings)
1180
+ notClassCache: new Set(tailwindConfig.blocklist ?? []),
799
1181
  postCssNodeCache: new Map(),
800
1182
  candidateRuleMap: new Map(),
801
1183
  tailwindConfig,
802
1184
  changedContent: changedContent,
803
1185
  variantMap: new Map(),
804
1186
  stylesheetCache: null,
1187
+ variantOptions: new Map(),
1188
+
1189
+ markInvalidUtilityCandidate: (candidate) => markInvalidUtilityCandidate(context, candidate),
1190
+ markInvalidUtilityNode: (node) => markInvalidUtilityNode(context, node),
805
1191
  }
806
1192
 
807
1193
  let resolvedPlugins = resolvePlugins(context, root)
@@ -880,6 +1266,10 @@ export function getContext(
880
1266
 
881
1267
  let context = createContext(tailwindConfig, [], root)
882
1268
 
1269
+ Object.assign(context, {
1270
+ userConfigPath,
1271
+ })
1272
+
883
1273
  trackModified([...contextDependencies], getFileModifiedMap(context))
884
1274
 
885
1275
  // ---