index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var camel2hyphen = require('string-convert/camel2hyphen');
  2. var isDimension = function (feature) {
  3. var re = /[height|width]$/;
  4. return re.test(feature);
  5. };
  6. var obj2mq = function (obj) {
  7. var mq = '';
  8. var features = Object.keys(obj);
  9. features.forEach(function (feature, index) {
  10. var value = obj[feature];
  11. feature = camel2hyphen(feature);
  12. // Add px to dimension features
  13. if (isDimension(feature) && typeof value === 'number') {
  14. value = value + 'px';
  15. }
  16. if (value === true) {
  17. mq += feature;
  18. } else if (value === false) {
  19. mq += 'not ' + feature;
  20. } else {
  21. mq += '(' + feature + ': ' + value + ')';
  22. }
  23. if (index < features.length-1) {
  24. mq += ' and '
  25. }
  26. });
  27. return mq;
  28. };
  29. var json2mq = function (query) {
  30. var mq = '';
  31. if (typeof query === 'string') {
  32. return query;
  33. }
  34. // Handling array of media queries
  35. if (query instanceof Array) {
  36. query.forEach(function (q, index) {
  37. mq += obj2mq(q);
  38. if (index < query.length-1) {
  39. mq += ', '
  40. }
  41. });
  42. return mq;
  43. }
  44. // Handling single media query
  45. return obj2mq(query);
  46. };
  47. module.exports = json2mq;