json2mq.js 1.4 KB

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