merge-media-queries.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var canReorder = require('./reorderable').canReorder;
  2. var extractProperties = require('./extractor');
  3. function mergeMediaQueries(tokens) {
  4. var candidates = {};
  5. var reduced = [];
  6. for (var i = tokens.length - 1; i >= 0; i--) {
  7. var token = tokens[i];
  8. if (token[0] != 'block')
  9. continue;
  10. var candidate = candidates[token[1][0]];
  11. if (!candidate) {
  12. candidate = [];
  13. candidates[token[1][0]] = candidate;
  14. }
  15. candidate.push(i);
  16. }
  17. for (var name in candidates) {
  18. var positions = candidates[name];
  19. positionLoop:
  20. for (var j = positions.length - 1; j > 0; j--) {
  21. var positionOne = positions[j];
  22. var tokenOne = tokens[positionOne];
  23. var positionTwo = positions[j - 1];
  24. var tokenTwo = tokens[positionTwo];
  25. directionLoop:
  26. for (var direction = 1; direction >= -1; direction -= 2) {
  27. var topToBottom = direction == 1;
  28. var from = topToBottom ? positionOne + 1 : positionTwo - 1;
  29. var to = topToBottom ? positionTwo : positionOne;
  30. var delta = topToBottom ? 1 : -1;
  31. var source = topToBottom ? tokenOne : tokenTwo;
  32. var target = topToBottom ? tokenTwo : tokenOne;
  33. var movedProperties = extractProperties(source);
  34. while (from != to) {
  35. var traversedProperties = extractProperties(tokens[from]);
  36. from += delta;
  37. if (!canReorder(movedProperties, traversedProperties))
  38. continue directionLoop;
  39. }
  40. target[2] = topToBottom ?
  41. source[2].concat(target[2]) :
  42. target[2].concat(source[2]);
  43. source[2] = [];
  44. reduced.push(target);
  45. continue positionLoop;
  46. }
  47. }
  48. }
  49. return reduced;
  50. }
  51. module.exports = mergeMediaQueries;