Skip to content

Commit

Permalink
feat: Support template literals in values
Browse files Browse the repository at this point in the history
  • Loading branch information
sapegin committed Jul 31, 2020
1 parent 6a5242d commit 03fa3bd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
27 changes: 27 additions & 0 deletions src/util/__tests__/parseJavascript.spec.js
Expand Up @@ -124,6 +124,33 @@ const PrimaryHeading = styled.h1({
`);
});

test('HTML element, object notation, template literal value', () => {
const result = parseJavaScript(
`
import styled from 'styled-components';
const SIZE = '1rem';
const PrimaryHeading = styled.h1({
width: \`\${SIZE}px\`
})
`,
'test.js'
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"component": "h1",
"filename": "test.js",
"styles": Array [
Object {
"name": "width",
"value": "(SIZE)px",
},
],
},
]
`);
});

test('HTML element, object notation, value from theme', () => {
const result = parseJavaScript(
`
Expand Down
17 changes: 11 additions & 6 deletions src/util/parseJavascript.js
Expand Up @@ -77,6 +77,11 @@ function getValue(node, code, propsObjectName) {
].join('');
}

// { margin: `${MARGIN}px` }
if (node.type === 'TemplateLiteral') {
return mergeQuasi(node, code);
}

console.warn('Can’t find value for', node);

return '';
Expand Down Expand Up @@ -104,7 +109,7 @@ function getStyles(node, code) {
}
});
} else if (node.type === 'TaggedTemplateExpression') {
const css = getCssFromQuasi(node, code);
const css = mergeQuasi(node.quasi, code);
styles.push(...getStylesFromCss(css));
}

Expand Down Expand Up @@ -176,13 +181,13 @@ function expandCssProp(rawProp, rawValue) {
}
}

function getCssFromQuasi({ quasi: { quasis, expressions } }, code) {
return quasis.reduce((css, quasi, index) => {
css += quasi.value.raw;
function mergeQuasi({ quasis, expressions }, code) {
return quasis.reduce((result, quasi, index) => {
result += quasi.value.raw;
if (expressions[index]) {
css += getValue(expressions[index], code);
result += getValue(expressions[index], code);
}
return css;
return result;
}, '');
}

Expand Down

0 comments on commit 03fa3bd

Please sign in to comment.