json2mq.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * source by `json2mq`
  3. * https://github.com/akiran/json2mq.git
  4. */
  5. const camel2hyphen = function (str) {
  6. return str.replace(/[A-Z]/g, function (match) {
  7. return '-' + match.toLowerCase();
  8. }).toLowerCase();
  9. };
  10. const isDimension = function (feature) {
  11. const re = /[height|width]$/;
  12. return re.test(feature);
  13. };
  14. const obj2mq = function (obj) {
  15. let mq = '';
  16. const features = Object.keys(obj);
  17. features.forEach(function (feature, index) {
  18. let value = obj[feature];
  19. feature = camel2hyphen(feature);
  20. // Add px to dimension features
  21. if (isDimension(feature) && typeof value === 'number') {
  22. value = value + 'px';
  23. }
  24. if (value === true) {
  25. mq += feature;
  26. } else if (value === false) {
  27. mq += 'not ' + feature;
  28. } else {
  29. mq += '(' + feature + ': ' + value + ')';
  30. }
  31. if (index < features.length - 1) {
  32. mq += ' and ';
  33. }
  34. });
  35. return mq;
  36. };
  37. export default function (query) {
  38. let mq = '';
  39. if (typeof query === 'string') {
  40. return query;
  41. }
  42. // Handling array of media queries
  43. if (query instanceof Array) {
  44. query.forEach(function (q, index) {
  45. mq += obj2mq(q);
  46. if (index < query.length - 1) {
  47. mq += ', ';
  48. }
  49. });
  50. return mq;
  51. }
  52. // Handling single media query
  53. return obj2mq(query);
  54. }