Skip to content

Commit

Permalink
Fix Compiled props being incorrectly forwarded when default values us…
Browse files Browse the repository at this point in the history
…ed (#1630)

* Fix properties fall-through when default values used

* Add changeset

* Address PR feedback
  • Loading branch information
dddlr authored Feb 19, 2024
1 parent 41bcb1e commit d5c6578
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/two-dryers-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@compiled/babel-plugin': patch
---

Fix props (used by Compiled) being incorrectly forwarded to React when default values are used.
28 changes: 26 additions & 2 deletions packages/babel-plugin/src/utils/normalize-props-usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,30 @@ const normalizeDestructuredString = (
});
};

/**
* Create a member expression from a list of strings. For example, if
* `objectChain = ['a', 'b', 'c']`, the generated member expression will be
* `a.b.c`.
* @param objectChain List of strings
* @returns A member expression.
*/
const createNestedMemberExpression = (objectChain: string[]): t.Identifier | t.MemberExpression => {
if (objectChain.length === 0) {
throw new Error(
'Could not build a Compiled component, due to objectChain being empty when generating a member expression. This is likely a bug with Compiled - please file a bug report.'
);
}
if (objectChain.length === 1) {
return t.identifier(objectChain[0]);
}

const [initial, last] = [
objectChain.slice(0, objectChain.length - 1),
objectChain[objectChain.length - 1],
];
return t.memberExpression(createNestedMemberExpression(initial), t.identifier(last));
};

const normalizeDestructuredObject = (
bindings: Record<string, Binding>,
values: Record<string, t.Expression>,
Expand All @@ -128,10 +152,10 @@ const normalizeDestructuredObject = (
// passing null to the function will still result in the
// default value being used.
reference.replaceWith(
t.logicalExpression('??', t.identifier(objectChain.join('.')), defaultValue)
t.logicalExpression('??', createNestedMemberExpression(objectChain), defaultValue)
);
} else {
reference.replaceWithSourceString(objectChain.join('.'));
reference.replaceWith(createNestedMemberExpression(objectChain));
}
});
}
Expand Down

0 comments on commit d5c6578

Please sign in to comment.