No Description

optimizer.js 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. var Tokenizer = require('./tokenizer');
  2. var PropertyOptimizer = require('../properties/optimizer');
  3. module.exports = function Optimizer(data, context, options) {
  4. var specialSelectors = {
  5. '*': /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:dir\([a-z-]*\)|:first(?![a-z-])|:fullscreen|:left|:read-only|:read-write|:right)/,
  6. 'ie8': /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not)/,
  7. 'ie7': /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:focus|:before|:after|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not)/
  8. };
  9. var minificationsMade = [];
  10. var propertyOptimizer = new PropertyOptimizer(options.compatibility, options.aggressiveMerging, context);
  11. var cleanUpSelector = function(selectors) {
  12. if (selectors.indexOf(',') == -1)
  13. return selectors;
  14. var plain = [];
  15. var cursor = 0;
  16. var lastComma = 0;
  17. var noBrackets = selectors.indexOf('(') == -1;
  18. var withinBrackets = function(idx) {
  19. if (noBrackets)
  20. return false;
  21. var previousOpening = selectors.lastIndexOf('(', idx);
  22. var previousClosing = selectors.lastIndexOf(')', idx);
  23. if (previousOpening == -1)
  24. return false;
  25. if (previousClosing > 0 && previousClosing < idx)
  26. return false;
  27. return true;
  28. };
  29. while (true) {
  30. var nextComma = selectors.indexOf(',', cursor + 1);
  31. var selector;
  32. if (nextComma === -1) {
  33. nextComma = selectors.length;
  34. } else if (withinBrackets(nextComma)) {
  35. cursor = nextComma + 1;
  36. continue;
  37. }
  38. selector = selectors.substring(lastComma, nextComma);
  39. lastComma = cursor = nextComma + 1;
  40. if (plain.indexOf(selector) == -1)
  41. plain.push(selector);
  42. if (nextComma === selectors.length)
  43. break;
  44. }
  45. return plain.sort().join(',');
  46. };
  47. var isSpecial = function(selector) {
  48. return specialSelectors[options.compatibility || '*'].test(selector);
  49. };
  50. var removeDuplicates = function(tokens) {
  51. var matched = {};
  52. var forRemoval = [];
  53. for (var i = 0, l = tokens.length; i < l; i++) {
  54. var token = tokens[i];
  55. if (typeof token == 'string' || token.block)
  56. continue;
  57. var id = token.body + '@' + token.selector;
  58. var alreadyMatched = matched[id];
  59. if (alreadyMatched) {
  60. forRemoval.push(alreadyMatched[0]);
  61. alreadyMatched.unshift(i);
  62. } else {
  63. matched[id] = [i];
  64. }
  65. }
  66. forRemoval = forRemoval.sort(function(a, b) {
  67. return a > b ? 1 : -1;
  68. });
  69. for (var j = 0, n = forRemoval.length; j < n; j++) {
  70. tokens.splice(forRemoval[j] - j, 1);
  71. }
  72. minificationsMade.unshift(forRemoval.length > 0);
  73. };
  74. var mergeAdjacent = function(tokens) {
  75. var forRemoval = [];
  76. var lastToken = { selector: null, body: null };
  77. for (var i = 0, l = tokens.length; i < l; i++) {
  78. var token = tokens[i];
  79. if (typeof token == 'string' || token.block)
  80. continue;
  81. if (token.selector == lastToken.selector) {
  82. var joinAt = [lastToken.body.split(';').length];
  83. lastToken.body = propertyOptimizer.process(lastToken.body + ';' + token.body, joinAt, false, token.selector);
  84. forRemoval.push(i);
  85. } else if (token.body == lastToken.body && !isSpecial(token.selector) && !isSpecial(lastToken.selector)) {
  86. lastToken.selector = cleanUpSelector(lastToken.selector + ',' + token.selector);
  87. forRemoval.push(i);
  88. } else {
  89. lastToken = token;
  90. }
  91. }
  92. for (var j = 0, m = forRemoval.length; j < m; j++) {
  93. tokens.splice(forRemoval[j] - j, 1);
  94. }
  95. minificationsMade.unshift(forRemoval.length > 0);
  96. };
  97. var reduceNonAdjacent = function(tokens) {
  98. var candidates = {};
  99. var moreThanOnce = [];
  100. for (var i = tokens.length - 1; i >= 0; i--) {
  101. var token = tokens[i];
  102. if (typeof token == 'string' || token.block)
  103. continue;
  104. var complexSelector = token.selector;
  105. var selectors = complexSelector.indexOf(',') > -1 && !isSpecial(complexSelector) ?
  106. complexSelector.split(',').concat(complexSelector) : // simplification, as :not() can have commas too
  107. [complexSelector];
  108. for (var j = 0, m = selectors.length; j < m; j++) {
  109. var selector = selectors[j];
  110. if (!candidates[selector])
  111. candidates[selector] = [];
  112. else
  113. moreThanOnce.push(selector);
  114. candidates[selector].push({
  115. where: i,
  116. partial: selector != complexSelector
  117. });
  118. }
  119. }
  120. var reducedInSimple = _reduceSimpleNonAdjacentCases(tokens, moreThanOnce, candidates);
  121. var reducedInComplex = _reduceComplexNonAdjacentCases(tokens, candidates);
  122. minificationsMade.unshift(reducedInSimple || reducedInComplex);
  123. };
  124. var _reduceSimpleNonAdjacentCases = function(tokens, matches, positions) {
  125. var reduced = false;
  126. for (var i = 0, l = matches.length; i < l; i++) {
  127. var selector = matches[i];
  128. var data = positions[selector];
  129. if (data.length < 2)
  130. continue;
  131. /* jshint loopfunc: true */
  132. _reduceSelector(tokens, selector, data, {
  133. filterOut: function(idx, bodies) {
  134. return data[idx].partial && bodies.length === 0;
  135. },
  136. callback: function(token, newBody, processedCount, tokenIdx) {
  137. if (!data[processedCount - tokenIdx - 1].partial) {
  138. token.body = newBody.join(';');
  139. reduced = true;
  140. }
  141. }
  142. });
  143. }
  144. return reduced;
  145. };
  146. var _reduceComplexNonAdjacentCases = function(tokens, positions) {
  147. var reduced = false;
  148. allSelectors:
  149. for (var complexSelector in positions) {
  150. if (complexSelector.indexOf(',') == -1) // simplification, as :not() can have commas too
  151. continue;
  152. var intoPosition = positions[complexSelector].pop().where;
  153. var intoToken = tokens[intoPosition];
  154. var selectors = isSpecial(complexSelector) ?
  155. [complexSelector] :
  156. complexSelector.split(',');
  157. var reducedBodies = [];
  158. for (var j = 0, m = selectors.length; j < m; j++) {
  159. var selector = selectors[j];
  160. var data = positions[selector];
  161. if (data.length < 2)
  162. continue allSelectors;
  163. /* jshint loopfunc: true */
  164. _reduceSelector(tokens, selector, data, {
  165. filterOut: function(idx) {
  166. return data[idx].where < intoPosition;
  167. },
  168. callback: function(token, newBody, processedCount, tokenIdx) {
  169. if (tokenIdx === 0)
  170. reducedBodies.push(newBody.join(';'));
  171. }
  172. });
  173. if (reducedBodies[reducedBodies.length - 1] != reducedBodies[0])
  174. continue allSelectors;
  175. }
  176. intoToken.body = reducedBodies[0];
  177. reduced = true;
  178. }
  179. return reduced;
  180. };
  181. var _reduceSelector = function(tokens, selector, data, options) {
  182. var bodies = [];
  183. var joinsAt = [];
  184. var splitBodies = [];
  185. var processedTokens = [];
  186. for (var j = data.length - 1, m = 0; j >= 0; j--) {
  187. if (options.filterOut(j, bodies))
  188. continue;
  189. var where = data[j].where;
  190. var token = tokens[where];
  191. var body = token.body;
  192. bodies.push(body);
  193. splitBodies.push(body.split(';'));
  194. processedTokens.push(where);
  195. }
  196. for (j = 0, m = bodies.length; j < m; j++) {
  197. if (bodies[j].length > 0)
  198. joinsAt.push((joinsAt[j - 1] || 0) + splitBodies[j].length);
  199. }
  200. var optimizedBody = propertyOptimizer.process(bodies.join(';'), joinsAt, true, selector);
  201. var optimizedProperties = optimizedBody.split(';');
  202. var processedCount = processedTokens.length;
  203. var propertyIdx = optimizedProperties.length - 1;
  204. var tokenIdx = processedCount - 1;
  205. while (tokenIdx >= 0) {
  206. if ((tokenIdx === 0 || splitBodies[tokenIdx].indexOf(optimizedProperties[propertyIdx]) > -1) && propertyIdx > -1) {
  207. propertyIdx--;
  208. continue;
  209. }
  210. var newBody = optimizedProperties.splice(propertyIdx + 1);
  211. options.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx);
  212. tokenIdx--;
  213. }
  214. };
  215. var optimize = function(tokens) {
  216. var noChanges = function() {
  217. return minificationsMade.length > 4 &&
  218. minificationsMade[0] === false &&
  219. minificationsMade[1] === false;
  220. };
  221. tokens = Array.isArray(tokens) ? tokens : [tokens];
  222. for (var i = 0, l = tokens.length; i < l; i++) {
  223. var token = tokens[i];
  224. if (token.selector) {
  225. token.selector = cleanUpSelector(token.selector);
  226. token.body = propertyOptimizer.process(token.body, false, false, token.selector);
  227. } else if (token.block) {
  228. optimize(token.body);
  229. }
  230. }
  231. // Run until 2 last operations do not yield any changes
  232. minificationsMade = [];
  233. while (true) {
  234. if (noChanges())
  235. break;
  236. removeDuplicates(tokens);
  237. if (noChanges())
  238. break;
  239. mergeAdjacent(tokens);
  240. if (noChanges())
  241. break;
  242. reduceNonAdjacent(tokens);
  243. }
  244. };
  245. var rebuild = function(tokens) {
  246. var rebuilt = [];
  247. tokens = Array.isArray(tokens) ? tokens : [tokens];
  248. for (var i = 0, l = tokens.length; i < l; i++) {
  249. var token = tokens[i];
  250. if (typeof token == 'string') {
  251. rebuilt.push(token);
  252. continue;
  253. }
  254. var name = token.block || token.selector;
  255. var body = token.block ? rebuild(token.body) : token.body;
  256. if (body.length > 0)
  257. rebuilt.push(name + '{' + body + '}');
  258. }
  259. return rebuilt.join(options.keepBreaks ? options.lineBreak : '');
  260. };
  261. return {
  262. process: function() {
  263. var tokenized = new Tokenizer(data, context).process();
  264. optimize(tokenized);
  265. return rebuild(tokenized);
  266. }
  267. };
  268. };