Skip to content

Commit

Permalink
Sort media queries in export code. Fixes #1506
Browse files Browse the repository at this point in the history
  • Loading branch information
artf committed Nov 20, 2018
1 parent fb98950 commit f61b411
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/code_manager/model/CssGenerator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isUndefined } from 'underscore';
import { isUndefined, each } from 'underscore';

const maxValue = Number.MAX_VALUE;

Expand Down Expand Up @@ -70,12 +70,10 @@ module.exports = require('backbone').Model.extend({
code += this.buildFromRule(rule, dump, opts);
});

console.log('at rules', atRules);

// Get at-rules
for (let atRule in atRules) {
this.sortMediaObject(atRules).forEach(item => {
let rulesStr = '';
const mRules = atRules[atRule];
const atRule = item.key;
const mRules = item.value;

mRules.forEach(rule => {
const ruleStr = this.buildFromRule(rule, dump, opts);
Expand All @@ -90,7 +88,7 @@ module.exports = require('backbone').Model.extend({
if (rulesStr) {
code += `${atRule}{${rulesStr}}`;
}
}
});

em && clearStyles && rules.remove(dump);
}
Expand Down Expand Up @@ -142,5 +140,19 @@ module.exports = require('backbone').Model.extend({
if (!length) return maxValue;

return parseFloat(length[1]);
},

/**
* Return a sorted array from media query object
* @param {Object} items
* @return {Array}
*/
sortMediaObject(items = {}) {
const result = {};
const itemsArr = [];
each(items, (value, key) => itemsArr.push({ key, value }));
return itemsArr.sort(
(a, b) => this.getQueryLength(b.key) - this.getQueryLength(a.key)
);
}
});
28 changes: 28 additions & 0 deletions test/specs/code_manager/model/CodeModels.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,34 @@ module.exports = {
const result = `#${id}{color:blue;}#${id}:${state}{color:red;}`;
expect(obj.build(comp, { cssc: cc, em })).toEqual(result);
});

test('Media queries are correctly cleaned for the length', () => {
[
['@media (max-width: 999px)', 999],
['@media (min-width: 123%)', 123],
['@media (min-width: 1040rem)', 1040]
].forEach(item => {
expect(obj.getQueryLength(item[0])).toBe(item[1]);
});
});

test('The media objects are correctly sorted', () => {
expect(
obj.sortMediaObject({
'@media (max-width: 480px)': 1,
'@font-face': 2,
'@media (max-width: 768px)': 3,
'@media (max-width: 1020ch)': 4,
'@media (max-width: 10%)': 5
})
).toEqual([
{ key: '@font-face', value: 2 },
{ key: '@media (max-width: 1020ch)', value: 4 },
{ key: '@media (max-width: 768px)', value: 3 },
{ key: '@media (max-width: 480px)', value: 1 },
{ key: '@media (max-width: 10%)', value: 5 }
]);
});
});
}
};

0 comments on commit f61b411

Please sign in to comment.