Skip to content

Commit

Permalink
fix: Ignore complex values
Browse files Browse the repository at this point in the history
  • Loading branch information
sapegin committed Jul 30, 2020
1 parent 16651c9 commit 54873ba
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 4 deletions.
52 changes: 52 additions & 0 deletions src/util/__tests__/parseJavascript.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,58 @@ const PrimaryHeading = styled.h1({
`);
});

test('custom component, object notation, complex expression', () => {
const result = parseJavaScript(
`
import styled from 'styled-components';
const BoldParagraph = styled(Text)({
fontWeight: () => true ? 'bold' : 'normal'
})
`,
'test.js'
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"component": "Text",
"filename": "test.js",
"styles": Array [
Object {
"name": "font-weight",
"value": "(Expression)",
},
],
},
]
`);
});

test('custom component, object notation, complex expression 2', () => {
const result = parseJavaScript(
`
import styled from 'styled-components';
const BoldParagraph = styled(Text)({
fontWeight: (props) => props.bold ? 'bold' : 'normal'
})
`,
'test.js'
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"component": "Text",
"filename": "test.js",
"styles": Array [
Object {
"name": "font-weight",
"value": "(Expression)",
},
],
},
]
`);
});

test('HTML element, object notation as function', () => {
const result = parseJavaScript(
`
Expand Down
20 changes: 16 additions & 4 deletions src/util/parseJavascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,15 @@ function getValue(node, code, propsObjectName) {
return node.name;
}

// { color: props => props.theme.colors.primary }
if (node.type === 'ArrowFunctionExpression' && node.params.length === 1) {
return getThemeToken(node.body, code, node.params[0].name);
if (node.type === 'ArrowFunctionExpression') {
// { color: props => props.theme.colors.primary }
return normalizeExpression(
getThemeToken(
node.body,
code,
node.params.length === 1 ? node.params[0].name : ''
)
);
}

// { color: props.theme.colors.primary }
Expand Down Expand Up @@ -141,12 +147,18 @@ function getCssFromQuasi({ quasi: { quasis, expressions } }, code) {
return quasis.reduce((css, quasi, index) => {
css += quasi.value.raw;
if (expressions[index]) {
css += getValue(expressions[index], code);
css += normalizeExpression(getValue(expressions[index], code));
}
return css;
}, '');
}

// Don’t keep complex expression because they break Stylis,
// and not very useful to analyze anyway
function normalizeExpression(value) {
return value.match(/[:`]/) ? '(Expression)' : value;
}

/**
* Finds all styled components in a JavaScript files, and returns their
* styles and component names
Expand Down

0 comments on commit 54873ba

Please sign in to comment.