tailwindcss 0.0.0-insiders.ca1dfd6 → 0.0.0-insiders.cab1fce

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 (148) hide show
  1. package/CHANGELOG.md +380 -1
  2. package/LICENSE +1 -2
  3. package/README.md +8 -4
  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 +3 -0
  9. package/defaultTheme.js +2 -1
  10. package/lib/cli-peer-dependencies.js +10 -5
  11. package/lib/cli.js +311 -213
  12. package/lib/constants.js +9 -9
  13. package/lib/corePluginList.js +11 -1
  14. package/lib/corePlugins.js +1895 -1773
  15. package/lib/css/preflight.css +19 -13
  16. package/lib/featureFlags.js +22 -16
  17. package/lib/index.js +17 -8
  18. package/lib/lib/cacheInvalidation.js +69 -0
  19. package/lib/lib/collapseAdjacentRules.js +30 -14
  20. package/lib/lib/collapseDuplicateDeclarations.js +80 -0
  21. package/lib/lib/defaultExtractor.js +187 -0
  22. package/lib/lib/detectNesting.js +17 -2
  23. package/lib/lib/evaluateTailwindFunctions.js +40 -24
  24. package/lib/lib/expandApplyAtRules.js +414 -157
  25. package/lib/lib/expandTailwindAtRules.js +156 -151
  26. package/lib/lib/generateRules.js +402 -68
  27. package/lib/lib/getModuleDependencies.js +14 -14
  28. package/lib/lib/normalizeTailwindDirectives.js +45 -36
  29. package/lib/lib/partitionApplyAtRules.js +53 -0
  30. package/lib/lib/regex.js +53 -0
  31. package/lib/lib/resolveDefaultsAtRules.js +105 -90
  32. package/lib/lib/setupContextUtils.js +416 -291
  33. package/lib/lib/setupTrackingContext.js +60 -56
  34. package/lib/lib/sharedState.js +38 -15
  35. package/lib/lib/substituteScreenAtRules.js +9 -6
  36. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  37. package/lib/postcss-plugins/nesting/index.js +17 -0
  38. package/lib/postcss-plugins/nesting/plugin.js +85 -0
  39. package/lib/processTailwindFeatures.js +21 -9
  40. package/lib/public/colors.js +244 -248
  41. package/lib/public/resolve-config.js +5 -5
  42. package/lib/util/buildMediaQuery.js +13 -24
  43. package/lib/util/cloneDeep.js +1 -1
  44. package/lib/util/cloneNodes.js +12 -1
  45. package/lib/util/color.js +43 -32
  46. package/lib/util/createPlugin.js +1 -2
  47. package/lib/util/createUtilityPlugin.js +13 -17
  48. package/lib/util/dataTypes.js +114 -74
  49. package/lib/util/defaults.js +6 -0
  50. package/lib/util/escapeClassName.js +5 -5
  51. package/lib/util/escapeCommas.js +1 -1
  52. package/lib/util/flattenColorPalette.js +2 -4
  53. package/lib/util/formatVariantSelector.js +194 -0
  54. package/lib/util/getAllConfigs.js +13 -5
  55. package/lib/util/hashConfig.js +5 -5
  56. package/lib/util/isKeyframeRule.js +1 -1
  57. package/lib/util/isPlainObject.js +1 -1
  58. package/lib/util/isValidArbitraryValue.js +64 -0
  59. package/lib/util/log.js +35 -19
  60. package/lib/util/nameClass.js +7 -6
  61. package/lib/util/negateValue.js +5 -3
  62. package/lib/util/normalizeConfig.js +233 -0
  63. package/lib/util/normalizeScreens.js +59 -0
  64. package/lib/util/parseAnimationValue.js +56 -56
  65. package/lib/util/parseBoxShadowValue.js +76 -0
  66. package/lib/util/parseDependency.js +32 -32
  67. package/lib/util/parseObjectStyles.js +6 -6
  68. package/lib/util/pluginUtils.js +67 -170
  69. package/lib/util/prefixSelector.js +4 -7
  70. package/lib/util/resolveConfig.js +123 -133
  71. package/lib/util/resolveConfigPath.js +17 -18
  72. package/lib/util/responsive.js +6 -6
  73. package/lib/util/splitAtTopLevelOnly.js +72 -0
  74. package/lib/util/toColorValue.js +1 -2
  75. package/lib/util/toPath.js +6 -1
  76. package/lib/util/transformThemeValue.js +42 -34
  77. package/lib/util/validateConfig.js +21 -0
  78. package/lib/util/withAlphaVariable.js +19 -19
  79. package/nesting/index.js +2 -12
  80. package/package.json +41 -42
  81. package/peers/index.js +11539 -10859
  82. package/plugin.d.ts +11 -0
  83. package/plugin.js +2 -1
  84. package/resolveConfig.js +2 -1
  85. package/scripts/create-plugin-list.js +2 -2
  86. package/scripts/generate-types.js +52 -0
  87. package/src/cli-peer-dependencies.js +7 -1
  88. package/src/cli.js +174 -41
  89. package/src/corePluginList.js +1 -1
  90. package/src/corePlugins.js +641 -596
  91. package/src/css/preflight.css +19 -13
  92. package/src/featureFlags.js +16 -10
  93. package/src/index.js +14 -6
  94. package/src/lib/cacheInvalidation.js +52 -0
  95. package/src/lib/collapseAdjacentRules.js +21 -2
  96. package/src/lib/collapseDuplicateDeclarations.js +93 -0
  97. package/src/lib/defaultExtractor.js +192 -0
  98. package/src/lib/detectNesting.js +22 -3
  99. package/src/lib/evaluateTailwindFunctions.js +24 -7
  100. package/src/lib/expandApplyAtRules.js +442 -154
  101. package/src/lib/expandTailwindAtRules.js +91 -65
  102. package/src/lib/generateRules.js +409 -43
  103. package/src/lib/normalizeTailwindDirectives.js +10 -3
  104. package/src/lib/partitionApplyAtRules.js +52 -0
  105. package/src/lib/regex.js +74 -0
  106. package/src/lib/resolveDefaultsAtRules.js +74 -53
  107. package/src/lib/setupContextUtils.js +388 -208
  108. package/src/lib/setupTrackingContext.js +15 -12
  109. package/src/lib/sharedState.js +42 -7
  110. package/src/lib/substituteScreenAtRules.js +6 -3
  111. package/src/postcss-plugins/nesting/README.md +42 -0
  112. package/src/postcss-plugins/nesting/index.js +13 -0
  113. package/src/postcss-plugins/nesting/plugin.js +80 -0
  114. package/src/processTailwindFeatures.js +17 -2
  115. package/src/public/colors.js +4 -9
  116. package/src/util/buildMediaQuery.js +14 -18
  117. package/src/util/cloneNodes.js +14 -1
  118. package/src/util/color.js +31 -14
  119. package/src/util/createUtilityPlugin.js +2 -2
  120. package/src/util/dataTypes.js +56 -16
  121. package/src/util/defaults.js +6 -0
  122. package/src/util/formatVariantSelector.js +213 -0
  123. package/src/util/getAllConfigs.js +7 -0
  124. package/src/util/isValidArbitraryValue.js +61 -0
  125. package/src/util/log.js +23 -22
  126. package/src/util/nameClass.js +2 -2
  127. package/src/util/negateValue.js +4 -2
  128. package/src/util/normalizeConfig.js +262 -0
  129. package/src/util/normalizeScreens.js +45 -0
  130. package/src/util/parseBoxShadowValue.js +72 -0
  131. package/src/util/pluginUtils.js +51 -147
  132. package/src/util/prefixSelector.js +7 -8
  133. package/src/util/resolveConfig.js +108 -79
  134. package/src/util/splitAtTopLevelOnly.js +71 -0
  135. package/src/util/toPath.js +23 -1
  136. package/src/util/transformThemeValue.js +24 -7
  137. package/src/util/validateConfig.js +13 -0
  138. package/stubs/defaultConfig.stub.js +157 -94
  139. package/stubs/simpleConfig.stub.js +0 -1
  140. package/types/config.d.ts +325 -0
  141. package/types/generated/.gitkeep +0 -0
  142. package/types/generated/colors.d.ts +276 -0
  143. package/types/generated/corePluginList.d.ts +1 -0
  144. package/types/index.d.ts +1 -0
  145. package/types.d.ts +1 -0
  146. package/lib/lib/setupWatchingContext.js +0 -284
  147. package/nesting/plugin.js +0 -41
  148. package/src/lib/setupWatchingContext.js +0 -306
@@ -1,13 +1,188 @@
1
1
  import postcss from 'postcss'
2
+ import parser from 'postcss-selector-parser'
3
+
2
4
  import { resolveMatches } from './generateRules'
3
5
  import bigSign from '../util/bigSign'
4
6
  import escapeClassName from '../util/escapeClassName'
5
7
 
8
+ /** @typedef {Map<string, [any, import('postcss').Rule[]]>} ApplyCache */
9
+
10
+ function extractClasses(node) {
11
+ /** @type {Map<string, Set<string>>} */
12
+ let groups = new Map()
13
+
14
+ let container = postcss.root({ nodes: [node.clone()] })
15
+
16
+ container.walkRules((rule) => {
17
+ parser((selectors) => {
18
+ selectors.walkClasses((classSelector) => {
19
+ let parentSelector = classSelector.parent.toString()
20
+
21
+ let classes = groups.get(parentSelector)
22
+ if (!classes) {
23
+ groups.set(parentSelector, (classes = new Set()))
24
+ }
25
+
26
+ classes.add(classSelector.value)
27
+ })
28
+ }).processSync(rule.selector)
29
+ })
30
+
31
+ let normalizedGroups = Array.from(groups.values(), (classes) => Array.from(classes))
32
+ let classes = normalizedGroups.flat()
33
+
34
+ return Object.assign(classes, { groups: normalizedGroups })
35
+ }
36
+
37
+ let selectorExtractor = parser((root) => root.nodes.map((node) => node.toString()))
38
+
39
+ /**
40
+ * @param {string} ruleSelectors
41
+ */
42
+ function extractSelectors(ruleSelectors) {
43
+ return selectorExtractor.transformSync(ruleSelectors)
44
+ }
45
+
46
+ function extractBaseCandidates(candidates, separator) {
47
+ let baseClasses = new Set()
48
+
49
+ for (let candidate of candidates) {
50
+ baseClasses.add(candidate.split(separator).pop())
51
+ }
52
+
53
+ return Array.from(baseClasses)
54
+ }
55
+
6
56
  function prefix(context, selector) {
7
57
  let prefix = context.tailwindConfig.prefix
8
58
  return typeof prefix === 'function' ? prefix(selector) : prefix + selector
9
59
  }
10
60
 
61
+ function* pathToRoot(node) {
62
+ yield node
63
+ while (node.parent) {
64
+ yield node.parent
65
+ node = node.parent
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Only clone the node itself and not its children
71
+ *
72
+ * @param {*} node
73
+ * @param {*} overrides
74
+ * @returns
75
+ */
76
+ function shallowClone(node, overrides = {}) {
77
+ let children = node.nodes
78
+ node.nodes = []
79
+
80
+ let tmp = node.clone(overrides)
81
+
82
+ node.nodes = children
83
+
84
+ return tmp
85
+ }
86
+
87
+ /**
88
+ * Clone just the nodes all the way to the top that are required to represent
89
+ * this singular rule in the tree.
90
+ *
91
+ * For example, if we have CSS like this:
92
+ * ```css
93
+ * @media (min-width: 768px) {
94
+ * @supports (display: grid) {
95
+ * .foo {
96
+ * display: grid;
97
+ * grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
98
+ * }
99
+ * }
100
+ *
101
+ * @supports (backdrop-filter: blur(1px)) {
102
+ * .bar {
103
+ * backdrop-filter: blur(1px);
104
+ * }
105
+ * }
106
+ *
107
+ * .baz {
108
+ * color: orange;
109
+ * }
110
+ * }
111
+ * ```
112
+ *
113
+ * And we're cloning `.bar` it'll return a cloned version of what's required for just that single node:
114
+ *
115
+ * ```css
116
+ * @media (min-width: 768px) {
117
+ * @supports (backdrop-filter: blur(1px)) {
118
+ * .bar {
119
+ * backdrop-filter: blur(1px);
120
+ * }
121
+ * }
122
+ * }
123
+ * ```
124
+ *
125
+ * @param {import('postcss').Node} node
126
+ */
127
+ function nestedClone(node) {
128
+ for (let parent of pathToRoot(node)) {
129
+ if (node === parent) {
130
+ continue
131
+ }
132
+
133
+ if (parent.type === 'root') {
134
+ break
135
+ }
136
+
137
+ node = shallowClone(parent, {
138
+ nodes: [node],
139
+ })
140
+ }
141
+
142
+ return node
143
+ }
144
+
145
+ /**
146
+ * @param {import('postcss').Root} root
147
+ */
148
+ function buildLocalApplyCache(root, context) {
149
+ /** @type {ApplyCache} */
150
+ let cache = new Map()
151
+
152
+ let highestOffset = context.layerOrder.user >> 4n
153
+
154
+ root.walkRules((rule, idx) => {
155
+ // Ignore rules generated by Tailwind
156
+ for (let node of pathToRoot(rule)) {
157
+ if (node.raws.tailwind?.layer !== undefined) {
158
+ return
159
+ }
160
+ }
161
+
162
+ // Clone what's required to represent this singular rule in the tree
163
+ let container = nestedClone(rule)
164
+
165
+ for (let className of extractClasses(rule)) {
166
+ let list = cache.get(className) || []
167
+ cache.set(className, list)
168
+
169
+ list.push([
170
+ {
171
+ layer: 'user',
172
+ sort: BigInt(idx) + highestOffset,
173
+ important: false,
174
+ },
175
+ container,
176
+ ])
177
+ }
178
+ })
179
+
180
+ return cache
181
+ }
182
+
183
+ /**
184
+ * @returns {ApplyCache}
185
+ */
11
186
  function buildApplyCache(applyCandidates, context) {
12
187
  for (let candidate of applyCandidates) {
13
188
  if (context.notClassCache.has(candidate) || context.applyClassCache.has(candidate)) {
@@ -35,6 +210,43 @@ function buildApplyCache(applyCandidates, context) {
35
210
  return context.applyClassCache
36
211
  }
37
212
 
213
+ /**
214
+ * Build a cache only when it's first used
215
+ *
216
+ * @param {() => ApplyCache} buildCacheFn
217
+ * @returns {ApplyCache}
218
+ */
219
+ function lazyCache(buildCacheFn) {
220
+ let cache = null
221
+
222
+ return {
223
+ get: (name) => {
224
+ cache = cache || buildCacheFn()
225
+
226
+ return cache.get(name)
227
+ },
228
+ has: (name) => {
229
+ cache = cache || buildCacheFn()
230
+
231
+ return cache.has(name)
232
+ },
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Take a series of multiple caches and merge
238
+ * them so they act like one large cache
239
+ *
240
+ * @param {ApplyCache[]} caches
241
+ * @returns {ApplyCache}
242
+ */
243
+ function combineCaches(caches) {
244
+ return {
245
+ get: (name) => caches.flatMap((cache) => cache.get(name) || []),
246
+ has: (name) => caches.some((cache) => cache.has(name)),
247
+ }
248
+ }
249
+
38
250
  function extractApplyCandidates(params) {
39
251
  let candidates = params.split(/[\s\t\n]+/g)
40
252
 
@@ -45,48 +257,7 @@ function extractApplyCandidates(params) {
45
257
  return [candidates, false]
46
258
  }
47
259
 
48
- function partitionApplyParents(root) {
49
- let applyParents = new Set()
50
-
51
- root.walkAtRules('apply', (rule) => {
52
- applyParents.add(rule.parent)
53
- })
54
-
55
- for (let rule of applyParents) {
56
- let nodeGroups = []
57
- let lastGroup = []
58
-
59
- for (let node of rule.nodes) {
60
- if (node.type === 'atrule' && node.name === 'apply') {
61
- if (lastGroup.length > 0) {
62
- nodeGroups.push(lastGroup)
63
- lastGroup = []
64
- }
65
- nodeGroups.push([node])
66
- } else {
67
- lastGroup.push(node)
68
- }
69
- }
70
-
71
- if (lastGroup.length > 0) {
72
- nodeGroups.push(lastGroup)
73
- }
74
-
75
- if (nodeGroups.length === 1) {
76
- continue
77
- }
78
-
79
- for (let group of [...nodeGroups].reverse()) {
80
- let newParent = rule.clone({ nodes: [] })
81
- newParent.append(group)
82
- rule.after(newParent)
83
- }
84
-
85
- rule.remove()
86
- }
87
- }
88
-
89
- function processApply(root, context) {
260
+ function processApply(root, context, localCache) {
90
261
  let applyCandidates = new Set()
91
262
 
92
263
  // Collect all @apply rules and candidates
@@ -102,150 +273,267 @@ function processApply(root, context) {
102
273
  })
103
274
 
104
275
  // Start the @apply process if we have rules with @apply in them
105
- if (applies.length > 0) {
106
- // Fill up some caches!
107
- let applyClassCache = buildApplyCache(applyCandidates, context)
108
-
109
- /**
110
- * When we have an apply like this:
111
- *
112
- * .abc {
113
- * @apply hover:font-bold;
114
- * }
115
- *
116
- * What we essentially will do is resolve to this:
117
- *
118
- * .abc {
119
- * @apply .hover\:font-bold:hover {
120
- * font-weight: 500;
121
- * }
122
- * }
123
- *
124
- * Notice that the to-be-applied class is `.hover\:font-bold:hover` and that the utility candidate was `hover:font-bold`.
125
- * What happens in this function is that we prepend a `.` and escape the candidate.
126
- * This will result in `.hover\:font-bold`
127
- * Which means that we can replace `.hover\:font-bold` with `.abc` in `.hover\:font-bold:hover` resulting in `.abc:hover`
128
- */
129
- // TODO: Should we use postcss-selector-parser for this instead?
130
- function replaceSelector(selector, utilitySelectors, candidate) {
131
- let needle = `.${escapeClassName(candidate)}`
132
- let utilitySelectorsList = utilitySelectors.split(/\s*,\s*/g)
133
-
134
- return selector
135
- .split(/\s*,\s*/g)
136
- .map((s) => {
137
- let replaced = []
138
-
139
- for (let utilitySelector of utilitySelectorsList) {
140
- let replacedSelector = utilitySelector.replace(needle, s)
141
- if (replacedSelector === utilitySelector) {
142
- continue
143
- }
144
- replaced.push(replacedSelector)
276
+ if (applies.length === 0) {
277
+ return
278
+ }
279
+
280
+ // Fill up some caches!
281
+ let applyClassCache = combineCaches([localCache, buildApplyCache(applyCandidates, context)])
282
+
283
+ /**
284
+ * When we have an apply like this:
285
+ *
286
+ * .abc {
287
+ * @apply hover:font-bold;
288
+ * }
289
+ *
290
+ * What we essentially will do is resolve to this:
291
+ *
292
+ * .abc {
293
+ * @apply .hover\:font-bold:hover {
294
+ * font-weight: 500;
295
+ * }
296
+ * }
297
+ *
298
+ * Notice that the to-be-applied class is `.hover\:font-bold:hover` and that the utility candidate was `hover:font-bold`.
299
+ * What happens in this function is that we prepend a `.` and escape the candidate.
300
+ * This will result in `.hover\:font-bold`
301
+ * Which means that we can replace `.hover\:font-bold` with `.abc` in `.hover\:font-bold:hover` resulting in `.abc:hover`
302
+ */
303
+ // TODO: Should we use postcss-selector-parser for this instead?
304
+ function replaceSelector(selector, utilitySelectors, candidate) {
305
+ let needle = `.${escapeClassName(candidate)}`
306
+ let needles = [...new Set([needle, needle.replace(/\\2c /g, '\\,')])]
307
+ let utilitySelectorsList = extractSelectors(utilitySelectors)
308
+
309
+ return extractSelectors(selector)
310
+ .map((s) => {
311
+ let replaced = []
312
+
313
+ for (let utilitySelector of utilitySelectorsList) {
314
+ let replacedSelector = utilitySelector
315
+ for (const needle of needles) {
316
+ replacedSelector = replacedSelector.replace(needle, s)
145
317
  }
146
- return replaced.join(', ')
147
- })
148
- .join(', ')
149
- }
318
+ if (replacedSelector === utilitySelector) {
319
+ continue
320
+ }
321
+ replaced.push(replacedSelector)
322
+ }
323
+ return replaced.join(', ')
324
+ })
325
+ .join(', ')
326
+ }
150
327
 
151
- let perParentApplies = new Map()
328
+ let perParentApplies = new Map()
152
329
 
153
- // Collect all apply candidates and their rules
154
- for (let apply of applies) {
155
- let candidates = perParentApplies.get(apply.parent) || []
330
+ // Collect all apply candidates and their rules
331
+ for (let apply of applies) {
332
+ let [candidates] = perParentApplies.get(apply.parent) || [[], apply.source]
156
333
 
157
- perParentApplies.set(apply.parent, candidates)
334
+ perParentApplies.set(apply.parent, [candidates, apply.source])
158
335
 
159
- let [applyCandidates, important] = extractApplyCandidates(apply.params)
336
+ let [applyCandidates, important] = extractApplyCandidates(apply.params)
160
337
 
161
- if (apply.parent.type === 'atrule') {
162
- if (apply.parent.name === 'screen') {
163
- const screenType = apply.parent.params
338
+ if (apply.parent.type === 'atrule') {
339
+ if (apply.parent.name === 'screen') {
340
+ const screenType = apply.parent.params
164
341
 
165
- throw apply.error(
166
- `@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${applyCandidates
167
- .map((c) => `${screenType}:${c}`)
168
- .join(' ')} instead.`
169
- )
170
- }
342
+ throw apply.error(
343
+ `@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${applyCandidates
344
+ .map((c) => `${screenType}:${c}`)
345
+ .join(' ')} instead.`
346
+ )
347
+ }
171
348
 
349
+ throw apply.error(
350
+ `@apply is not supported within nested at-rules like @${apply.parent.name}. You can fix this by un-nesting @${apply.parent.name}.`
351
+ )
352
+ }
353
+
354
+ for (let applyCandidate of applyCandidates) {
355
+ if ([prefix(context, 'group'), prefix(context, 'peer')].includes(applyCandidate)) {
356
+ // TODO: Link to specific documentation page with error code.
357
+ throw apply.error(`@apply should not be used with the '${applyCandidate}' utility`)
358
+ }
359
+
360
+ if (!applyClassCache.has(applyCandidate)) {
172
361
  throw apply.error(
173
- `@apply is not supported within nested at-rules like @${apply.parent.name}. You can fix this by un-nesting @${apply.parent.name}.`
362
+ `The \`${applyCandidate}\` class does not exist. If \`${applyCandidate}\` is a custom class, make sure it is defined within a \`@layer\` directive.`
174
363
  )
175
364
  }
176
365
 
177
- for (let applyCandidate of applyCandidates) {
178
- if (!applyClassCache.has(applyCandidate)) {
179
- if (applyCandidate === prefix(context, 'group')) {
180
- // TODO: Link to specific documentation page with error code.
181
- throw apply.error(`@apply should not be used with the '${applyCandidate}' utility`)
182
- }
366
+ let rules = applyClassCache.get(applyCandidate)
367
+
368
+ candidates.push([applyCandidate, important, rules])
369
+ }
370
+ }
371
+
372
+ for (const [parent, [candidates, atApplySource]] of perParentApplies) {
373
+ let siblings = []
374
+
375
+ for (let [applyCandidate, important, rules] of candidates) {
376
+ let potentialApplyCandidates = [
377
+ applyCandidate,
378
+ ...extractBaseCandidates([applyCandidate], context.tailwindConfig.separator),
379
+ ]
380
+
381
+ for (let [meta, node] of rules) {
382
+ let parentClasses = extractClasses(parent)
383
+ let nodeClasses = extractClasses(node)
183
384
 
184
- throw apply.error(
185
- `The \`${applyCandidate}\` class does not exist. If \`${applyCandidate}\` is a custom class, make sure it is defined within a \`@layer\` directive.`
385
+ // When we encounter a rule like `.dark .a, .b { … }` we only want to be left with `[.dark, .a]` if the base applyCandidate is `.a` or with `[.b]` if the base applyCandidate is `.b`
386
+ // So we've split them into groups
387
+ nodeClasses = nodeClasses.groups
388
+ .filter((classList) =>
389
+ classList.some((className) => potentialApplyCandidates.includes(className))
390
+ )
391
+ .flat()
392
+
393
+ // Add base utility classes from the @apply node to the list of
394
+ // classes to check whether it intersects and therefore results in a
395
+ // circular dependency or not.
396
+ //
397
+ // E.g.:
398
+ // .foo {
399
+ // @apply hover:a; // This applies "a" but with a modifier
400
+ // }
401
+ //
402
+ // We only have to do that with base classes of the `node`, not of the `parent`
403
+ // E.g.:
404
+ // .hover\:foo {
405
+ // @apply bar;
406
+ // }
407
+ // .bar {
408
+ // @apply foo;
409
+ // }
410
+ //
411
+ // This should not result in a circular dependency because we are
412
+ // just applying `.foo` and the rule above is `.hover\:foo` which is
413
+ // unrelated. However, if we were to apply `hover:foo` then we _did_
414
+ // have to include this one.
415
+ nodeClasses = nodeClasses.concat(
416
+ extractBaseCandidates(nodeClasses, context.tailwindConfig.separator)
417
+ )
418
+
419
+ let intersects = parentClasses.some((selector) => nodeClasses.includes(selector))
420
+ if (intersects) {
421
+ throw node.error(
422
+ `You cannot \`@apply\` the \`${applyCandidate}\` utility here because it creates a circular dependency.`
186
423
  )
187
424
  }
188
425
 
189
- let rules = applyClassCache.get(applyCandidate)
426
+ let root = postcss.root({ nodes: [node.clone()] })
190
427
 
191
- candidates.push([applyCandidate, important, rules])
192
- }
193
- }
428
+ // Make sure every node in the entire tree points back at the @apply rule that generated it
429
+ root.walk((node) => {
430
+ node.source = atApplySource
431
+ })
194
432
 
195
- for (const [parent, candidates] of perParentApplies) {
196
- let siblings = []
433
+ let canRewriteSelector =
434
+ node.type !== 'atrule' || (node.type === 'atrule' && node.name !== 'keyframes')
435
+
436
+ if (canRewriteSelector) {
437
+ root.walkRules((rule) => {
438
+ // Let's imagine you have the following structure:
439
+ //
440
+ // .foo {
441
+ // @apply bar;
442
+ // }
443
+ //
444
+ // @supports (a: b) {
445
+ // .bar {
446
+ // color: blue
447
+ // }
448
+ //
449
+ // .something-unrelated {}
450
+ // }
451
+ //
452
+ // In this case we want to apply `.bar` but it happens to be in
453
+ // an atrule node. We clone that node instead of the nested one
454
+ // because we still want that @supports rule to be there once we
455
+ // applied everything.
456
+ //
457
+ // However it happens to be that the `.something-unrelated` is
458
+ // also in that same shared @supports atrule. This is not good,
459
+ // and this should not be there. The good part is that this is
460
+ // a clone already and it can be safely removed. The question is
461
+ // how do we know we can remove it. Basically what we can do is
462
+ // match it against the applyCandidate that you want to apply. If
463
+ // it doesn't match the we can safely delete it.
464
+ //
465
+ // If we didn't do this, then the `replaceSelector` function
466
+ // would have replaced this with something that didn't exist and
467
+ // therefore it removed the selector altogether. In this specific
468
+ // case it would result in `{}` instead of `.something-unrelated {}`
469
+ if (!extractClasses(rule).some((candidate) => candidate === applyCandidate)) {
470
+ rule.remove()
471
+ return
472
+ }
197
473
 
198
- for (let [applyCandidate, important, rules] of candidates) {
199
- for (let [meta, node] of rules) {
200
- let root = postcss.root({ nodes: [node.clone()] })
201
- let canRewriteSelector =
202
- node.type !== 'atrule' || (node.type === 'atrule' && node.name !== 'keyframes')
474
+ // Strip the important selector from the parent selector if at the beginning
475
+ let importantSelector =
476
+ typeof context.tailwindConfig.important === 'string'
477
+ ? context.tailwindConfig.important
478
+ : null
203
479
 
204
- if (canRewriteSelector) {
205
- root.walkRules((rule) => {
206
- rule.selector = replaceSelector(parent.selector, rule.selector, applyCandidate)
480
+ // We only want to move the "important" selector if this is a Tailwind-generated utility
481
+ // We do *not* want to do this for user CSS that happens to be structured the same
482
+ let isGenerated = parent.raws.tailwind !== undefined
207
483
 
208
- rule.walkDecls((d) => {
209
- d.important = meta.important || important
210
- })
211
- })
212
- }
484
+ let parentSelector =
485
+ isGenerated && importantSelector && parent.selector.indexOf(importantSelector) === 0
486
+ ? parent.selector.slice(importantSelector.length)
487
+ : parent.selector
213
488
 
214
- // Insert it
215
- siblings.push([
216
- // Ensure that when we are sorting, that we take the layer order into account
217
- { ...meta, sort: meta.sort | context.layerOrder[meta.layer] },
218
- root.nodes[0],
219
- ])
220
- }
221
- }
489
+ rule.selector = replaceSelector(parentSelector, rule.selector, applyCandidate)
222
490
 
223
- // Inject the rules, sorted, correctly
224
- let nodes = siblings.sort(([a], [z]) => bigSign(a.sort - z.sort)).map((s) => s[1])
491
+ // And then re-add it if it was removed
492
+ if (importantSelector && parentSelector !== parent.selector) {
493
+ rule.selector = `${importantSelector} ${rule.selector}`
494
+ }
225
495
 
226
- // console.log(parent)
227
- // `parent` refers to the node at `.abc` in: .abc { @apply mt-2 }
228
- parent.after(nodes)
229
- }
496
+ rule.walkDecls((d) => {
497
+ d.important = meta.important || important
498
+ })
499
+ })
500
+ }
230
501
 
231
- for (let apply of applies) {
232
- // If there are left-over declarations, just remove the @apply
233
- if (apply.parent.nodes.length > 1) {
234
- apply.remove()
235
- } else {
236
- // The node is empty, drop the full node
237
- apply.parent.remove()
502
+ // Insert it
503
+ siblings.push([
504
+ // Ensure that when we are sorting, that we take the layer order into account
505
+ { ...meta, sort: meta.sort | context.layerOrder[meta.layer] },
506
+ root.nodes[0],
507
+ ])
238
508
  }
239
509
  }
240
510
 
241
- // Do it again, in case we have other `@apply` rules
242
- processApply(root, context)
511
+ // Inject the rules, sorted, correctly
512
+ let nodes = siblings.sort(([a], [z]) => bigSign(a.sort - z.sort)).map((s) => s[1])
513
+
514
+ // `parent` refers to the node at `.abc` in: .abc { @apply mt-2 }
515
+ parent.after(nodes)
243
516
  }
517
+
518
+ for (let apply of applies) {
519
+ // If there are left-over declarations, just remove the @apply
520
+ if (apply.parent.nodes.length > 1) {
521
+ apply.remove()
522
+ } else {
523
+ // The node is empty, drop the full node
524
+ apply.parent.remove()
525
+ }
526
+ }
527
+
528
+ // Do it again, in case we have other `@apply` rules
529
+ processApply(root, context, localCache)
244
530
  }
245
531
 
246
532
  export default function expandApplyAtRules(context) {
247
533
  return (root) => {
248
- partitionApplyParents(root)
249
- processApply(root, context)
534
+ // Build a cache of the user's CSS so we can use it to resolve classes used by @apply
535
+ let localCache = lazyCache(() => buildLocalApplyCache(root, context))
536
+
537
+ processApply(root, context, localCache)
250
538
  }
251
539
  }