restructure.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. var canReorderSingle = require('./reorderable').canReorderSingle;
  2. var extractProperties = require('./extract-properties');
  3. var isMergeable = require('./is-mergeable');
  4. var tidyRuleDuplicates = require('./tidy-rule-duplicates');
  5. var Token = require('../../tokenizer/token');
  6. var cloneArray = require('../../utils/clone-array');
  7. var serializeBody = require('../../writer/one-time').body;
  8. var serializeRules = require('../../writer/one-time').rules;
  9. function naturalSorter(a, b) {
  10. return a > b ? 1 : -1;
  11. }
  12. function cloneAndMergeSelectors(propertyA, propertyB) {
  13. var cloned = cloneArray(propertyA);
  14. cloned[5] = cloned[5].concat(propertyB[5]);
  15. return cloned;
  16. }
  17. function restructure(tokens, context) {
  18. var options = context.options;
  19. var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
  20. var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
  21. var mergeLimit = options.compatibility.selectors.mergeLimit;
  22. var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
  23. var specificityCache = context.cache.specificity;
  24. var movableTokens = {};
  25. var movedProperties = [];
  26. var multiPropertyMoveCache = {};
  27. var movedToBeDropped = [];
  28. var maxCombinationsLevel = 2;
  29. var ID_JOIN_CHARACTER = '%';
  30. function sendToMultiPropertyMoveCache(position, movedProperty, allFits) {
  31. for (var i = allFits.length - 1; i >= 0; i--) {
  32. var fit = allFits[i][0];
  33. var id = addToCache(movedProperty, fit);
  34. if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) {
  35. removeAllMatchingFromCache(id);
  36. break;
  37. }
  38. }
  39. }
  40. function addToCache(movedProperty, fit) {
  41. var id = cacheId(fit);
  42. multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || [];
  43. multiPropertyMoveCache[id].push([movedProperty, fit]);
  44. return id;
  45. }
  46. function removeAllMatchingFromCache(matchId) {
  47. var matchSelectors = matchId.split(ID_JOIN_CHARACTER);
  48. var forRemoval = [];
  49. var i;
  50. for (var id in multiPropertyMoveCache) {
  51. var selectors = id.split(ID_JOIN_CHARACTER);
  52. for (i = selectors.length - 1; i >= 0; i--) {
  53. if (matchSelectors.indexOf(selectors[i]) > -1) {
  54. forRemoval.push(id);
  55. break;
  56. }
  57. }
  58. }
  59. for (i = forRemoval.length - 1; i >= 0; i--) {
  60. delete multiPropertyMoveCache[forRemoval[i]];
  61. }
  62. }
  63. function cacheId(cachedTokens) {
  64. var id = [];
  65. for (var i = 0, l = cachedTokens.length; i < l; i++) {
  66. id.push(serializeRules(cachedTokens[i][1]));
  67. }
  68. return id.join(ID_JOIN_CHARACTER);
  69. }
  70. function tokensToMerge(sourceTokens) {
  71. var uniqueTokensWithBody = [];
  72. var mergeableTokens = [];
  73. for (var i = sourceTokens.length - 1; i >= 0; i--) {
  74. if (!isMergeable(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
  75. continue;
  76. }
  77. mergeableTokens.unshift(sourceTokens[i]);
  78. if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1)
  79. uniqueTokensWithBody.push(sourceTokens[i]);
  80. }
  81. return uniqueTokensWithBody.length > 1 ?
  82. mergeableTokens :
  83. [];
  84. }
  85. function shortenIfPossible(position, movedProperty) {
  86. var name = movedProperty[0];
  87. var value = movedProperty[1];
  88. var key = movedProperty[4];
  89. var valueSize = name.length + value.length + 1;
  90. var allSelectors = [];
  91. var qualifiedTokens = [];
  92. var mergeableTokens = tokensToMerge(movableTokens[key]);
  93. if (mergeableTokens.length < 2)
  94. return;
  95. var allFits = findAllFits(mergeableTokens, valueSize, 1);
  96. var bestFit = allFits[0];
  97. if (bestFit[1] > 0)
  98. return sendToMultiPropertyMoveCache(position, movedProperty, allFits);
  99. for (var i = bestFit[0].length - 1; i >=0; i--) {
  100. allSelectors = bestFit[0][i][1].concat(allSelectors);
  101. qualifiedTokens.unshift(bestFit[0][i]);
  102. }
  103. allSelectors = tidyRuleDuplicates(allSelectors);
  104. dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens);
  105. }
  106. function fitSorter(fit1, fit2) {
  107. return fit1[1] > fit2[1] ? 1 : (fit1[1] == fit2[1] ? 0 : -1);
  108. }
  109. function findAllFits(mergeableTokens, propertySize, propertiesCount) {
  110. var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1);
  111. return combinations.sort(fitSorter);
  112. }
  113. function allCombinations(tokensVariant, propertySize, propertiesCount, level) {
  114. var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]];
  115. if (tokensVariant.length > 2 && level > 0) {
  116. for (var i = tokensVariant.length - 1; i >= 0; i--) {
  117. var subVariant = Array.prototype.slice.call(tokensVariant, 0);
  118. subVariant.splice(i, 1);
  119. differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1));
  120. }
  121. }
  122. return differenceVariants;
  123. }
  124. function sizeDifference(tokensVariant, propertySize, propertiesCount) {
  125. var allSelectorsSize = 0;
  126. for (var i = tokensVariant.length - 1; i >= 0; i--) {
  127. allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? serializeRules(tokensVariant[i][1]).length : -1;
  128. }
  129. return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1;
  130. }
  131. function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) {
  132. var i, j, k, m;
  133. var allProperties = [];
  134. for (i = mergeableTokens.length - 1; i >= 0; i--) {
  135. var mergeableToken = mergeableTokens[i];
  136. for (j = mergeableToken[2].length - 1; j >= 0; j--) {
  137. var mergeableProperty = mergeableToken[2][j];
  138. for (k = 0, m = properties.length; k < m; k++) {
  139. var property = properties[k];
  140. var mergeablePropertyName = mergeableProperty[1][1];
  141. var propertyName = property[0];
  142. var propertyBody = property[4];
  143. if (mergeablePropertyName == propertyName && serializeBody([mergeableProperty]) == propertyBody) {
  144. mergeableToken[2].splice(j, 1);
  145. break;
  146. }
  147. }
  148. }
  149. }
  150. for (i = properties.length - 1; i >= 0; i--) {
  151. allProperties.unshift(properties[i][3]);
  152. }
  153. var newToken = [Token.RULE, allSelectors, allProperties];
  154. tokens.splice(position, 0, newToken);
  155. }
  156. function dropPropertiesAt(position, movedProperty) {
  157. var key = movedProperty[4];
  158. var toMove = movableTokens[key];
  159. if (toMove && toMove.length > 1) {
  160. if (!shortenMultiMovesIfPossible(position, movedProperty))
  161. shortenIfPossible(position, movedProperty);
  162. }
  163. }
  164. function shortenMultiMovesIfPossible(position, movedProperty) {
  165. var candidates = [];
  166. var propertiesAndMergableTokens = [];
  167. var key = movedProperty[4];
  168. var j, k;
  169. var mergeableTokens = tokensToMerge(movableTokens[key]);
  170. if (mergeableTokens.length < 2)
  171. return;
  172. movableLoop:
  173. for (var value in movableTokens) {
  174. var tokensList = movableTokens[value];
  175. for (j = mergeableTokens.length - 1; j >= 0; j--) {
  176. if (tokensList.indexOf(mergeableTokens[j]) == -1)
  177. continue movableLoop;
  178. }
  179. candidates.push(value);
  180. }
  181. if (candidates.length < 2)
  182. return false;
  183. for (j = candidates.length - 1; j >= 0; j--) {
  184. for (k = movedProperties.length - 1; k >= 0; k--) {
  185. if (movedProperties[k][4] == candidates[j]) {
  186. propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]);
  187. break;
  188. }
  189. }
  190. }
  191. return processMultiPropertyMove(position, propertiesAndMergableTokens);
  192. }
  193. function processMultiPropertyMove(position, propertiesAndMergableTokens) {
  194. var valueSize = 0;
  195. var properties = [];
  196. var property;
  197. for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) {
  198. property = propertiesAndMergableTokens[i][0];
  199. var fullValue = property[4];
  200. valueSize += fullValue.length + (i > 0 ? 1 : 0);
  201. properties.push(property);
  202. }
  203. var mergeableTokens = propertiesAndMergableTokens[0][1];
  204. var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0];
  205. if (bestFit[1] > 0)
  206. return false;
  207. var allSelectors = [];
  208. var qualifiedTokens = [];
  209. for (i = bestFit[0].length - 1; i >= 0; i--) {
  210. allSelectors = bestFit[0][i][1].concat(allSelectors);
  211. qualifiedTokens.unshift(bestFit[0][i]);
  212. }
  213. allSelectors = tidyRuleDuplicates(allSelectors);
  214. dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens);
  215. for (i = properties.length - 1; i >= 0; i--) {
  216. property = properties[i];
  217. var index = movedProperties.indexOf(property);
  218. delete movableTokens[property[4]];
  219. if (index > -1 && movedToBeDropped.indexOf(index) == -1)
  220. movedToBeDropped.push(index);
  221. }
  222. return true;
  223. }
  224. function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) {
  225. var propertyName = property[0];
  226. var movedPropertyName = movedProperty[0];
  227. if (propertyName != movedPropertyName)
  228. return false;
  229. var key = movedProperty[4];
  230. var toMove = movableTokens[key];
  231. return toMove && toMove.indexOf(token) > -1;
  232. }
  233. for (var i = tokens.length - 1; i >= 0; i--) {
  234. var token = tokens[i];
  235. var isRule;
  236. var j, k, m;
  237. var samePropertyAt;
  238. if (token[0] == Token.RULE) {
  239. isRule = true;
  240. } else if (token[0] == Token.NESTED_BLOCK) {
  241. isRule = false;
  242. } else {
  243. continue;
  244. }
  245. // We cache movedProperties.length as it may change in the loop
  246. var movedCount = movedProperties.length;
  247. var properties = extractProperties(token);
  248. movedToBeDropped = [];
  249. var unmovableInCurrentToken = [];
  250. for (j = properties.length - 1; j >= 0; j--) {
  251. for (k = j - 1; k >= 0; k--) {
  252. if (!canReorderSingle(properties[j], properties[k], specificityCache)) {
  253. unmovableInCurrentToken.push(j);
  254. break;
  255. }
  256. }
  257. }
  258. for (j = properties.length - 1; j >= 0; j--) {
  259. var property = properties[j];
  260. var movedSameProperty = false;
  261. for (k = 0; k < movedCount; k++) {
  262. var movedProperty = movedProperties[k];
  263. if (movedToBeDropped.indexOf(k) == -1 && (!canReorderSingle(property, movedProperty, specificityCache) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) ||
  264. movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)) {
  265. dropPropertiesAt(i + 1, movedProperty, token);
  266. if (movedToBeDropped.indexOf(k) == -1) {
  267. movedToBeDropped.push(k);
  268. delete movableTokens[movedProperty[4]];
  269. }
  270. }
  271. if (!movedSameProperty) {
  272. movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1];
  273. if (movedSameProperty) {
  274. samePropertyAt = k;
  275. }
  276. }
  277. }
  278. if (!isRule || unmovableInCurrentToken.indexOf(j) > -1)
  279. continue;
  280. var key = property[4];
  281. if (movedSameProperty && movedProperties[samePropertyAt][5].length + property[5].length > mergeLimit) {
  282. dropPropertiesAt(i + 1, movedProperties[samePropertyAt]);
  283. movedProperties.splice(samePropertyAt, 1);
  284. movableTokens[key] = [token];
  285. movedSameProperty = false;
  286. } else {
  287. movableTokens[key] = movableTokens[key] || [];
  288. movableTokens[key].push(token);
  289. }
  290. if (movedSameProperty) {
  291. movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property);
  292. } else {
  293. movedProperties.push(property);
  294. }
  295. }
  296. movedToBeDropped = movedToBeDropped.sort(naturalSorter);
  297. for (j = 0, m = movedToBeDropped.length; j < m; j++) {
  298. var dropAt = movedToBeDropped[j] - j;
  299. movedProperties.splice(dropAt, 1);
  300. }
  301. }
  302. var position = tokens[0] && tokens[0][0] == Token.AT_RULE && tokens[0][1].indexOf('@charset') === 0 ? 1 : 0;
  303. for (; position < tokens.length - 1; position++) {
  304. var isImportRule = tokens[position][0] === Token.AT_RULE && tokens[position][1].indexOf('@import') === 0;
  305. var isComment = tokens[position][0] === Token.COMMENT;
  306. if (!(isImportRule || isComment))
  307. break;
  308. }
  309. for (i = 0; i < movedProperties.length; i++) {
  310. dropPropertiesAt(position, movedProperties[i]);
  311. }
  312. }
  313. module.exports = restructure;