Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -3457,6 +3457,44 @@ describe('@stylexjs/babel-plugin', () => {
}"
`);
});

test('does not hoist $$css objects that reference local variables', () => {
expect(
transform(
`
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
root: { display: 'flex' },
});
function Foo({className}) {
return <div {...stylex.props(styles.root, className && {$$css: true, __: className})}>Hello, foo!</div>;
}
`,
),
).toMatchInlineSnapshot(`
"import _inject from "@stylexjs/stylex/lib/stylex-inject";
var _inject2 = _inject;
import * as stylex from '@stylexjs/stylex';
_inject2({
ltr: ".x78zum5{display:flex}",
priority: 3000
});
const styles = {
root: {
k1xSpc: "x78zum5",
$$css: true
}
};
function Foo({
className
}) {
return <div {...stylex.props(styles.root, className && {
$$css: true,
__: className
})}>Hello, foo!</div>;
}"
`);
});
});

describe('dealing with imports', () => {
Expand Down
27 changes: 26 additions & 1 deletion packages/@stylexjs/babel-plugin/src/visitors/stylex-props.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ export default function transformStylexProps(
(t.isStringLiteral(prop.key) && prop.key.value === '$$css')) &&
t.isBooleanLiteral(prop.value, { value: true }),
);
if (hasCssMarker) {
if (hasCssMarker && canHoistObject(objPath)) {
const hoisted = hoistExpression(objPath, objPath.node);
objPath.replaceWith(hoisted);
}
Expand Down Expand Up @@ -509,6 +509,31 @@ function genBitwiseOrOfConditions(
});
}

function canHoistObject(objPath: NodePath<t.ObjectExpression>): boolean {
const programScope = objPath.scope.getProgramParent();
for (const prop of objPath.node.properties) {
if (!t.isObjectProperty(prop)) {
return false;
}
if (prop.computed && t.isIdentifier(prop.key)) {
const binding = objPath.scope.getBinding(prop.key.name);
if (binding != null && binding.scope !== programScope) {
return false;
}
}
const val = prop.value;
if (t.isIdentifier(val)) {
const binding = objPath.scope.getBinding(val.name);
if (binding != null && binding.scope !== programScope) {
return false;
}
} else if (!t.isLiteral(val)) {
return false;
}
}
return true;
}

function getPropsLikeCall(
path: NodePath<t.CallExpression>,
state: StateManager,
Expand Down
Loading