Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. const scale = [1, 2, 4, 8];
  2. const breakpoints = ['@media (min-width: 20em)', '@media (min-width: 40em)'];
  3.  
  4. const getValue = value => {
  5. if (Number.isFinite(value)) {
  6. value = `${value}px`;
  7. }
  8. return value;
  9. }
  10.  
  11. const parseInterpolation = interpolation => {
  12. if (interpolation === undefined) return '';
  13. if (Array.isArray(interpolation)) return getValue(scale[interpolation[0]]);
  14. return interpolation;
  15. };
  16.  
  17. const parseCssRule = rule => {
  18. let [property, value] = rule.split(':').map(str => str.trim());
  19. let resp = '';
  20. if (value.trim().startsWith('[')) {
  21. const scaleKeys = JSON.parse(value);
  22. value = getValue(scale[scaleKeys[0]]);
  23.  
  24. resp = `${breakpoints[0]} {
  25. ${property}: ${getValue(scale[scaleKeys[0]])};
  26. }`;
  27. }
  28. return [
  29. [property, value].join(':'),
  30. resp
  31. ];
  32. }
  33.  
  34. const parseRawCss = raw => {
  35. const { rules, responsive } = raw
  36. .split(';')
  37. .filter(str => str.trim().length > 0)
  38. .map(parseCssRule)
  39. .reduce((acc, [rule, resp]) => ({
  40. rules: acc.rules.concat(rule),
  41. responsive: acc.responsive.concat(resp)
  42. }), { rules: [], responsive: [] })
  43.  
  44. return `
  45. ${rules.join(';')};
  46. ${responsive.join('\n')}
  47. `;
  48. }
  49.  
  50. const styled = (strs, ...interpolations) => {
  51. const raw = strs.reduce((acc, str, i) => acc + parseInterpolation(interpolations[i - 1]) + str, '')
  52. return parseRawCss(raw);
  53. };
  54.  
  55. const css = styled`
  56. padding: [1, 2];
  57. width: [1, 2];
  58. `
  59.  
  60. console.log(css);
  61.  
  62. /*
  63. padding:2px;width:2px;
  64. @media (min-width: 20em) {
  65. padding: 2px;
  66. }
  67. @media (min-width: 20em) {
  68. width: 2px;
  69. }
  70. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement