Sin descripción

formatVariantSelector.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. function _export(target, all) {
  6. for(var name in all)Object.defineProperty(target, name, {
  7. enumerable: true,
  8. get: all[name]
  9. });
  10. }
  11. _export(exports, {
  12. formatVariantSelector: function() {
  13. return formatVariantSelector;
  14. },
  15. eliminateIrrelevantSelectors: function() {
  16. return eliminateIrrelevantSelectors;
  17. },
  18. finalizeSelector: function() {
  19. return finalizeSelector;
  20. },
  21. handleMergePseudo: function() {
  22. return handleMergePseudo;
  23. }
  24. });
  25. const _postcssselectorparser = /*#__PURE__*/ _interop_require_default(require("postcss-selector-parser"));
  26. const _unesc = /*#__PURE__*/ _interop_require_default(require("postcss-selector-parser/dist/util/unesc"));
  27. const _escapeClassName = /*#__PURE__*/ _interop_require_default(require("../util/escapeClassName"));
  28. const _prefixSelector = /*#__PURE__*/ _interop_require_default(require("../util/prefixSelector"));
  29. const _pseudoElements = require("./pseudoElements");
  30. function _interop_require_default(obj) {
  31. return obj && obj.__esModule ? obj : {
  32. default: obj
  33. };
  34. }
  35. /** @typedef {import('postcss-selector-parser').Root} Root */ /** @typedef {import('postcss-selector-parser').Selector} Selector */ /** @typedef {import('postcss-selector-parser').Pseudo} Pseudo */ /** @typedef {import('postcss-selector-parser').Node} Node */ /** @typedef {{format: string, isArbitraryVariant: boolean}[]} RawFormats */ /** @typedef {import('postcss-selector-parser').Root} ParsedFormats */ /** @typedef {RawFormats | ParsedFormats} AcceptedFormats */ let MERGE = ":merge";
  36. function formatVariantSelector(formats, { context , candidate }) {
  37. var _context_tailwindConfig_prefix;
  38. let prefix = (_context_tailwindConfig_prefix = context === null || context === void 0 ? void 0 : context.tailwindConfig.prefix) !== null && _context_tailwindConfig_prefix !== void 0 ? _context_tailwindConfig_prefix : "";
  39. // Parse the format selector into an AST
  40. let parsedFormats = formats.map((format)=>{
  41. let ast = (0, _postcssselectorparser.default)().astSync(format.format);
  42. return {
  43. ...format,
  44. ast: format.isArbitraryVariant ? ast : (0, _prefixSelector.default)(prefix, ast)
  45. };
  46. });
  47. // We start with the candidate selector
  48. let formatAst = _postcssselectorparser.default.root({
  49. nodes: [
  50. _postcssselectorparser.default.selector({
  51. nodes: [
  52. _postcssselectorparser.default.className({
  53. value: (0, _escapeClassName.default)(candidate)
  54. })
  55. ]
  56. })
  57. ]
  58. });
  59. // And iteratively merge each format selector into the candidate selector
  60. for (let { ast } of parsedFormats){
  61. [formatAst, ast] = handleMergePseudo(formatAst, ast);
  62. // 2. Merge the format selector into the current selector AST
  63. ast.walkNesting((nesting)=>nesting.replaceWith(...formatAst.nodes[0].nodes));
  64. // 3. Keep going!
  65. formatAst = ast;
  66. }
  67. return formatAst;
  68. }
  69. /**
  70. * Given any node in a selector this gets the "simple" selector it's a part of
  71. * A simple selector is just a list of nodes without any combinators
  72. * Technically :is(), :not(), :has(), etc… can have combinators but those are nested
  73. * inside the relevant node and won't be picked up so they're fine to ignore
  74. *
  75. * @param {Node} node
  76. * @returns {Node[]}
  77. **/ function simpleSelectorForNode(node) {
  78. /** @type {Node[]} */ let nodes = [];
  79. // Walk backwards until we hit a combinator node (or the start)
  80. while(node.prev() && node.prev().type !== "combinator"){
  81. node = node.prev();
  82. }
  83. // Now record all non-combinator nodes until we hit one (or the end)
  84. while(node && node.type !== "combinator"){
  85. nodes.push(node);
  86. node = node.next();
  87. }
  88. return nodes;
  89. }
  90. /**
  91. * Resorts the nodes in a selector to ensure they're in the correct order
  92. * Tags go before classes, and pseudo classes go after classes
  93. *
  94. * @param {Selector} sel
  95. * @returns {Selector}
  96. **/ function resortSelector(sel) {
  97. sel.sort((a, b)=>{
  98. if (a.type === "tag" && b.type === "class") {
  99. return -1;
  100. } else if (a.type === "class" && b.type === "tag") {
  101. return 1;
  102. } else if (a.type === "class" && b.type === "pseudo" && b.value.startsWith("::")) {
  103. return -1;
  104. } else if (a.type === "pseudo" && a.value.startsWith("::") && b.type === "class") {
  105. return 1;
  106. }
  107. return sel.index(a) - sel.index(b);
  108. });
  109. return sel;
  110. }
  111. function eliminateIrrelevantSelectors(sel, base) {
  112. let hasClassesMatchingCandidate = false;
  113. sel.walk((child)=>{
  114. if (child.type === "class" && child.value === base) {
  115. hasClassesMatchingCandidate = true;
  116. return false // Stop walking
  117. ;
  118. }
  119. });
  120. if (!hasClassesMatchingCandidate) {
  121. sel.remove();
  122. }
  123. // We do NOT recursively eliminate sub selectors that don't have the base class
  124. // as this is NOT a safe operation. For example, if we have:
  125. // `.space-x-2 > :not([hidden]) ~ :not([hidden])`
  126. // We cannot remove the [hidden] from the :not() because it would change the
  127. // meaning of the selector.
  128. // TODO: Can we do this for :matches, :is, and :where?
  129. }
  130. function finalizeSelector(current, formats, { context , candidate , base }) {
  131. var _context_tailwindConfig;
  132. var _context_tailwindConfig_separator;
  133. let separator = (_context_tailwindConfig_separator = context === null || context === void 0 ? void 0 : (_context_tailwindConfig = context.tailwindConfig) === null || _context_tailwindConfig === void 0 ? void 0 : _context_tailwindConfig.separator) !== null && _context_tailwindConfig_separator !== void 0 ? _context_tailwindConfig_separator : ":";
  134. // Split by the separator, but ignore the separator inside square brackets:
  135. //
  136. // E.g.: dark:lg:hover:[paint-order:markers]
  137. // ┬ ┬ ┬ ┬
  138. // │ │ │ ╰── We will not split here
  139. // ╰──┴─────┴─────────────── We will split here
  140. //
  141. base = base !== null && base !== void 0 ? base : candidate.split(new RegExp(`\\${separator}(?![^[]*\\])`)).pop();
  142. // Parse the selector into an AST
  143. let selector = (0, _postcssselectorparser.default)().astSync(current);
  144. // Normalize escaped classes, e.g.:
  145. //
  146. // The idea would be to replace the escaped `base` in the selector with the
  147. // `format`. However, in css you can escape the same selector in a few
  148. // different ways. This would result in different strings and therefore we
  149. // can't replace it properly.
  150. //
  151. // base: bg-[rgb(255,0,0)]
  152. // base in selector: bg-\\[rgb\\(255\\,0\\,0\\)\\]
  153. // escaped base: bg-\\[rgb\\(255\\2c 0\\2c 0\\)\\]
  154. //
  155. selector.walkClasses((node)=>{
  156. if (node.raws && node.value.includes(base)) {
  157. node.raws.value = (0, _escapeClassName.default)((0, _unesc.default)(node.raws.value));
  158. }
  159. });
  160. // Remove extraneous selectors that do not include the base candidate
  161. selector.each((sel)=>eliminateIrrelevantSelectors(sel, base));
  162. // If there are no formats that means there were no variants added to the candidate
  163. // so we can just return the selector as-is
  164. let formatAst = Array.isArray(formats) ? formatVariantSelector(formats, {
  165. context,
  166. candidate
  167. }) : formats;
  168. if (formatAst === null) {
  169. return selector.toString();
  170. }
  171. let simpleStart = _postcssselectorparser.default.comment({
  172. value: "/*__simple__*/"
  173. });
  174. let simpleEnd = _postcssselectorparser.default.comment({
  175. value: "/*__simple__*/"
  176. });
  177. // We can safely replace the escaped base now, since the `base` section is
  178. // now in a normalized escaped value.
  179. selector.walkClasses((node)=>{
  180. if (node.value !== base) {
  181. return;
  182. }
  183. let parent = node.parent;
  184. let formatNodes = formatAst.nodes[0].nodes;
  185. // Perf optimization: if the parent is a single class we can just replace it and be done
  186. if (parent.nodes.length === 1) {
  187. node.replaceWith(...formatNodes);
  188. return;
  189. }
  190. let simpleSelector = simpleSelectorForNode(node);
  191. parent.insertBefore(simpleSelector[0], simpleStart);
  192. parent.insertAfter(simpleSelector[simpleSelector.length - 1], simpleEnd);
  193. for (let child of formatNodes){
  194. parent.insertBefore(simpleSelector[0], child.clone());
  195. }
  196. node.remove();
  197. // Re-sort the simple selector to ensure it's in the correct order
  198. simpleSelector = simpleSelectorForNode(simpleStart);
  199. let firstNode = parent.index(simpleStart);
  200. parent.nodes.splice(firstNode, simpleSelector.length, ...resortSelector(_postcssselectorparser.default.selector({
  201. nodes: simpleSelector
  202. })).nodes);
  203. simpleStart.remove();
  204. simpleEnd.remove();
  205. });
  206. // Remove unnecessary pseudo selectors that we used as placeholders
  207. selector.walkPseudos((p)=>{
  208. if (p.value === MERGE) {
  209. p.replaceWith(p.nodes);
  210. }
  211. });
  212. // Move pseudo elements to the end of the selector (if necessary)
  213. selector.each((sel)=>(0, _pseudoElements.movePseudos)(sel));
  214. return selector.toString();
  215. }
  216. function handleMergePseudo(selector, format) {
  217. /** @type {{pseudo: Pseudo, value: string}[]} */ let merges = [];
  218. // Find all :merge() pseudo-classes in `selector`
  219. selector.walkPseudos((pseudo)=>{
  220. if (pseudo.value === MERGE) {
  221. merges.push({
  222. pseudo,
  223. value: pseudo.nodes[0].toString()
  224. });
  225. }
  226. });
  227. // Find all :merge() "attachments" in `format` and attach them to the matching selector in `selector`
  228. format.walkPseudos((pseudo)=>{
  229. if (pseudo.value !== MERGE) {
  230. return;
  231. }
  232. let value = pseudo.nodes[0].toString();
  233. // Does `selector` contain a :merge() pseudo-class with the same value?
  234. let existing = merges.find((merge)=>merge.value === value);
  235. // Nope so there's nothing to do
  236. if (!existing) {
  237. return;
  238. }
  239. // Everything after `:merge()` up to the next combinator is what is attached to the merged selector
  240. let attachments = [];
  241. let next = pseudo.next();
  242. while(next && next.type !== "combinator"){
  243. attachments.push(next);
  244. next = next.next();
  245. }
  246. let combinator = next;
  247. existing.pseudo.parent.insertAfter(existing.pseudo, _postcssselectorparser.default.selector({
  248. nodes: attachments.map((node)=>node.clone())
  249. }));
  250. pseudo.remove();
  251. attachments.forEach((node)=>node.remove());
  252. // What about this case:
  253. // :merge(.group):focus > &
  254. // :merge(.group):hover &
  255. if (combinator && combinator.type === "combinator") {
  256. combinator.remove();
  257. }
  258. });
  259. return [
  260. selector,
  261. format
  262. ];
  263. }