index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _browserslist = require('browserslist');
  6. var _browserslist2 = _interopRequireDefault(_browserslist);
  7. var _postcss = require('postcss');
  8. var _postcss2 = _interopRequireDefault(_postcss);
  9. var _vendors = require('vendors');
  10. var _vendors2 = _interopRequireDefault(_vendors);
  11. var _cssnanoUtilSameParent = require('cssnano-util-same-parent');
  12. var _cssnanoUtilSameParent2 = _interopRequireDefault(_cssnanoUtilSameParent);
  13. var _ensureCompatibility = require('./lib/ensureCompatibility');
  14. var _ensureCompatibility2 = _interopRequireDefault(_ensureCompatibility);
  15. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  16. const prefixes = _vendors2.default.map(v => `-${v}-`);
  17. function intersect(a, b, not) {
  18. return a.filter(c => {
  19. const index = ~b.indexOf(c);
  20. return not ? !index : index;
  21. });
  22. }
  23. // Internet Explorer use :-ms-input-placeholder.
  24. // Microsoft Edge use ::-ms-input-placeholder.
  25. const findMsInputPlaceholder = selector => ~selector.search(/-ms-input-placeholder/i);
  26. const different = (a, b) => intersect(a, b, true).concat(intersect(b, a, true));
  27. const filterPrefixes = selector => intersect(prefixes, selector);
  28. function sameVendor(selectorsA, selectorsB) {
  29. let same = selectors => selectors.map(filterPrefixes).join();
  30. let findMsVendor = selectors => selectors.find(findMsInputPlaceholder);
  31. return same(selectorsA) === same(selectorsB) && !(findMsVendor(selectorsA) && findMsVendor(selectorsB));
  32. }
  33. const noVendor = selector => !filterPrefixes(selector).length;
  34. function canMerge(ruleA, ruleB, browsers, compatibilityCache) {
  35. const a = ruleA.selectors;
  36. const b = ruleB.selectors;
  37. const selectors = a.concat(b);
  38. if (!(0, _ensureCompatibility2.default)(selectors, browsers, compatibilityCache)) {
  39. return false;
  40. }
  41. const parent = (0, _cssnanoUtilSameParent2.default)(ruleA, ruleB);
  42. const { name } = ruleA.parent;
  43. if (parent && name && ~name.indexOf('keyframes')) {
  44. return false;
  45. }
  46. return parent && (selectors.every(noVendor) || sameVendor(a, b));
  47. }
  48. const getDecls = rule => rule.nodes && rule.nodes.map(String);
  49. const joinSelectors = (...rules) => rules.map(s => s.selector).join();
  50. function ruleLength(...rules) {
  51. return rules.map(r => r.nodes.length ? String(r) : '').join('').length;
  52. }
  53. function splitProp(prop) {
  54. const parts = prop.split('-');
  55. let base, rest;
  56. // Treat vendor prefixed properties as if they were unprefixed;
  57. // moving them when combined with non-prefixed properties can
  58. // cause issues. e.g. moving -webkit-background-clip when there
  59. // is a background shorthand definition.
  60. if (prop[0] === '-') {
  61. base = parts[2];
  62. rest = parts.slice(3);
  63. } else {
  64. base = parts[0];
  65. rest = parts.slice(1);
  66. }
  67. return [base, rest];
  68. }
  69. function isConflictingProp(propA, propB) {
  70. if (propA === propB) {
  71. return true;
  72. }
  73. const a = splitProp(propA);
  74. const b = splitProp(propB);
  75. return a[0] === b[0] && a[1].length !== b[1].length;
  76. }
  77. function hasConflicts(declProp, notMoved) {
  78. return notMoved.some(prop => isConflictingProp(prop, declProp));
  79. }
  80. function partialMerge(first, second) {
  81. let intersection = intersect(getDecls(first), getDecls(second));
  82. if (!intersection.length) {
  83. return second;
  84. }
  85. let nextRule = second.next();
  86. if (nextRule && nextRule.type === 'rule' && canMerge(second, nextRule)) {
  87. let nextIntersection = intersect(getDecls(second), getDecls(nextRule));
  88. if (nextIntersection.length > intersection.length) {
  89. first = second;second = nextRule;intersection = nextIntersection;
  90. }
  91. }
  92. const recievingBlock = second.clone();
  93. recievingBlock.selector = joinSelectors(first, second);
  94. recievingBlock.nodes = [];
  95. const difference = different(getDecls(first), getDecls(second));
  96. const filterConflicts = (decls, intersectn) => {
  97. let willNotMove = [];
  98. return decls.reduce((willMove, decl) => {
  99. let intersects = ~intersectn.indexOf(decl);
  100. let prop = decl.split(':')[0];
  101. let base = prop.split('-')[0];
  102. let canMove = difference.every(d => d.split(':')[0] !== base);
  103. if (intersects && canMove && !hasConflicts(prop, willNotMove)) {
  104. willMove.push(decl);
  105. } else {
  106. willNotMove.push(prop);
  107. }
  108. return willMove;
  109. }, []);
  110. };
  111. const containsAllDeclaration = intersectionList => {
  112. return intersectionList.some(declaration => {
  113. return declaration.split(':')[0].toLowerCase() === 'all';
  114. });
  115. };
  116. intersection = filterConflicts(getDecls(first).reverse(), intersection);
  117. intersection = filterConflicts(getDecls(second), intersection);
  118. // Rules with "all" declarations must be on top
  119. if (containsAllDeclaration(intersection)) {
  120. second.parent.insertBefore(first, recievingBlock);
  121. } else {
  122. second.parent.insertBefore(second, recievingBlock);
  123. }
  124. const firstClone = first.clone();
  125. const secondClone = second.clone();
  126. const moveDecl = callback => {
  127. return decl => {
  128. if (~intersection.indexOf(String(decl))) {
  129. callback.call(this, decl);
  130. }
  131. };
  132. };
  133. firstClone.walkDecls(moveDecl(decl => {
  134. decl.remove();
  135. recievingBlock.append(decl);
  136. }));
  137. secondClone.walkDecls(moveDecl(decl => decl.remove()));
  138. const merged = ruleLength(firstClone, recievingBlock, secondClone);
  139. const original = ruleLength(first, second);
  140. if (merged < original) {
  141. first.replaceWith(firstClone);
  142. second.replaceWith(secondClone);
  143. [firstClone, recievingBlock, secondClone].forEach(r => {
  144. if (!r.nodes.length) {
  145. r.remove();
  146. }
  147. });
  148. if (!secondClone.parent) {
  149. return recievingBlock;
  150. }
  151. return secondClone;
  152. } else {
  153. recievingBlock.remove();
  154. return second;
  155. }
  156. }
  157. function selectorMerger(browsers, compatibilityCache) {
  158. let cache = null;
  159. return function (rule) {
  160. // Prime the cache with the first rule, or alternately ensure that it is
  161. // safe to merge both declarations before continuing
  162. if (!cache || !canMerge(rule, cache, browsers, compatibilityCache)) {
  163. cache = rule;
  164. return;
  165. }
  166. // Ensure that we don't deduplicate the same rule; this is sometimes
  167. // caused by a partial merge
  168. if (cache === rule) {
  169. cache = rule;
  170. return;
  171. }
  172. // Merge when declarations are exactly equal
  173. // e.g. h1 { color: red } h2 { color: red }
  174. if (getDecls(rule).join(';') === getDecls(cache).join(';')) {
  175. rule.selector = joinSelectors(cache, rule);
  176. cache.remove();
  177. cache = rule;
  178. return;
  179. }
  180. // Merge when both selectors are exactly equal
  181. // e.g. a { color: blue } a { font-weight: bold }
  182. if (cache.selector === rule.selector) {
  183. const cached = getDecls(cache);
  184. rule.walk(decl => {
  185. if (~cached.indexOf(String(decl))) {
  186. return decl.remove();
  187. }
  188. cache.append(decl);
  189. });
  190. rule.remove();
  191. return;
  192. }
  193. // Partial merge: check if the rule contains a subset of the last; if
  194. // so create a joined selector with the subset, if smaller.
  195. cache = partialMerge(cache, rule);
  196. };
  197. }
  198. exports.default = _postcss2.default.plugin('postcss-merge-rules', () => {
  199. return (css, result) => {
  200. const resultOpts = result.opts || {};
  201. const browsers = (0, _browserslist2.default)(null, {
  202. stats: resultOpts.stats,
  203. path: __dirname,
  204. env: resultOpts.env
  205. });
  206. const compatibilityCache = {};
  207. css.walkRules(selectorMerger(browsers, compatibilityCache));
  208. };
  209. });
  210. module.exports = exports['default'];