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

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