Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const scale = [1, 2, 4, 8];
- const breakpoints = ['@media (min-width: 20em)', '@media (min-width: 40em)'];
- const getValue = value => {
- if (Number.isFinite(value)) {
- value = `${value}px`;
- }
- return value;
- }
- const parseInterpolation = interpolation => {
- if (interpolation === undefined) return '';
- if (Array.isArray(interpolation)) return getValue(scale[interpolation[0]]);
- return interpolation;
- };
- const parseCssRule = rule => {
- let [property, value] = rule.split(':').map(str => str.trim());
- let resp = '';
- if (value.trim().startsWith('[')) {
- const scaleKeys = JSON.parse(value);
- value = getValue(scale[scaleKeys[0]]);
- resp = `${breakpoints[0]} {
- ${property}: ${getValue(scale[scaleKeys[0]])};
- }`;
- }
- return [
- [property, value].join(':'),
- resp
- ];
- }
- const parseRawCss = raw => {
- const { rules, responsive } = raw
- .split(';')
- .filter(str => str.trim().length > 0)
- .map(parseCssRule)
- .reduce((acc, [rule, resp]) => ({
- rules: acc.rules.concat(rule),
- responsive: acc.responsive.concat(resp)
- }), { rules: [], responsive: [] })
- return `
- ${rules.join(';')};
- ${responsive.join('\n')}
- `;
- }
- const styled = (strs, ...interpolations) => {
- const raw = strs.reduce((acc, str, i) => acc + parseInterpolation(interpolations[i - 1]) + str, '')
- return parseRawCss(raw);
- };
- const css = styled`
- padding: [1, 2];
- width: [1, 2];
- `
- console.log(css);
- /*
- padding:2px;width:2px;
- @media (min-width: 20em) {
- padding: 2px;
- }
- @media (min-width: 20em) {
- width: 2px;
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement