Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix broken css prop ternaries when referencing cssMap objects. #1767

Merged
merged 3 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cyan-waves-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@compiled/babel-plugin': minor
---

Fix supporting ternaries referencing cssMap style objects when extracting styles.
49 changes: 46 additions & 3 deletions packages/babel-plugin/src/css-map/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,18 @@ describe('css map basic functionality', () => {
import { cssMap } from '@compiled/react';

const styles = cssMap(${styles});

const Component = () => <div>
<span css={styles.danger} />
<span css={styles.success} />
</div>
`);

expect(actual).toInclude(
'const styles={danger:"_syaz5scu _bfhk5scu",success:"_syazbf54 _bfhkbf54"};'
);
expect(actual).toIncludeMultiple([
'const styles={danger:"_syaz5scu _bfhk5scu",success:"_syazbf54 _bfhkbf54"};',
'<span className={ax([styles.danger])}/>',
'<span className={ax([styles.success])}/>',
]);
});

it('should transform css map even with an empty object', () => {
Expand All @@ -45,6 +52,42 @@ describe('css map basic functionality', () => {
expect(actual).toInclude('const styles={danger:"",success:"_syazbf54 _bfhkbf54"};');
});

it('should transform ternary-based conditional referencing cssMap declarations', () => {
const actual = transform(`
import { cssMap } from '@compiled/react';

const styles = cssMap({
root: { display: 'block' },
positive: { background: 'white', color: 'black' },
negative: { background: 'green', color: 'red' },
bold: { fontWeight: 'bold' },
normal: { fontWeight: 'normal' },
});

const Component = ({ isPrimary, weight }) => (
<div
css={[
styles.root,
weight in styles ? styles[weight] : styles.normal,
isPrimary ? styles.positive : styles.negative,
]}
/>
);
`);

expect(actual).toIncludeMultiple([
'._1e0c1ule{display:block}',
'._bfhk1x77{background-color:white}',
'._syaz11x8{color:black}',
'._bfhkbf54{background-color:green}',
'._syaz5scu{color:red}',
'._k48p8n31{font-weight:bold}',
'._k48p4jg8{font-weight:normal}',
'const styles={root:"_1e0c1ule",positive:"_bfhk1x77 _syaz11x8",negative:"_bfhkbf54 _syaz5scu",bold:"_k48p8n31",normal:"_k48p4jg8"}',
'<div className={ax([styles.root,weight in styles?styles[weight]:styles.normal,isPrimary?styles.positive:styles.negative])}/>',
]);
});

it('should error out if variants are not defined at the top-most scope of the module.', () => {
expect(() => {
transform(`
Expand Down
54 changes: 45 additions & 9 deletions packages/babel-plugin/src/utils/css-builders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,8 @@ const extractConditionalExpression = (node: t.ConditionalExpression, meta: Metad
}
} else if (t.isConditionalExpression(pathNode)) {
cssOutput = extractConditionalExpression(pathNode, meta);
} else if (t.isMemberExpression(pathNode)) {
cssOutput = extractMemberExpression(pathNode, meta, false);
}

if (cssOutput) {
Expand Down Expand Up @@ -663,6 +665,44 @@ const extractObjectExpression = (node: t.ObjectExpression, meta: Metadata): CSSO
return { css: mergeSubsequentUnconditionalCssItems(css), variables };
};

/**
* Extracts CSS data from a member expression node (eg. `styles.primary`)
*
* @param node Node we're interested in extracting CSS from.
* @param meta {Metadata} Useful metadata that can be used during the transformation
* @param fallbackToEvaluate {Boolean} Whether to fallback to re-evaluating the expression if it's not a cssMap identifier
*/
function extractMemberExpression(
node: t.MemberExpression,
meta: Metadata,
fallbackToEvaluate?: true
): CSSOutput;
function extractMemberExpression(
node: t.MemberExpression,
meta: Metadata,
fallbackToEvaluate: false
): CSSOutput | undefined;
function extractMemberExpression(
node: t.MemberExpression,
meta: Metadata,
fallbackToEvaluate = true
): CSSOutput | undefined {
const bindingIdentifier = findBindingIdentifier(node);
if (bindingIdentifier && meta.state.cssMap[bindingIdentifier.name]) {
return {
css: [{ type: 'map', expression: node, name: bindingIdentifier.name, css: '' }],
variables: [],
};
}

if (fallbackToEvaluate) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel a bit annoyed by adding this false here, but I get into this endless loop with non-cssMap objects, eg. loading ? colors.N20 : colors.N40 where it blew up in a test.

This keeps it 1:1 with the current state by default and lets this if (bindingIdentifier && meta.state.cssMap[bindingIdentifier.name]) { flow be reused in extractConditionalExpression, so it feels sane to me.

const { value, meta: updatedMeta } = evaluateExpression(node, meta);
return buildCss(value, updatedMeta);
}

return undefined;
}

/**
* Extracts CSS data from a template literal node.
*
Expand Down Expand Up @@ -880,15 +920,7 @@ export const buildCss = (node: t.Expression | t.Expression[], meta: Metadata): C
}

if (t.isMemberExpression(node)) {
const bindingIdentifier = findBindingIdentifier(node);
if (bindingIdentifier && meta.state.cssMap[bindingIdentifier.name]) {
return {
css: [{ type: 'map', expression: node, name: bindingIdentifier.name, css: '' }],
variables: [],
};
}
const { value, meta: updatedMeta } = evaluateExpression(node, meta);
return buildCss(value, updatedMeta);
return extractMemberExpression(node, meta);
}

if (t.isArrowFunctionExpression(node)) {
Expand All @@ -903,6 +935,10 @@ export const buildCss = (node: t.Expression | t.Expression[], meta: Metadata): C
if (t.isConditionalExpression(node.body)) {
return extractConditionalExpression(node.body, meta);
}

if (t.isMemberExpression(node.body)) {
return extractMemberExpression(node.body, meta);
}
}

if (t.isIdentifier(node)) {
Expand Down
Loading