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

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