Skip to content

Commit

Permalink
fix: remove unsupported bound styles from Builder generator to avoid …
Browse files Browse the repository at this point in the history
…crashes (#1685)
  • Loading branch information
liamdebeasi authored Feb 13, 2025
1 parent 237dae9 commit f208f94
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/khaki-eggs-suffer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@builder.io/mitosis': patch
---

Builder: unsupported bound styles are removed to avoid crashes
43 changes: 43 additions & 0 deletions packages/core/src/__tests__/builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,49 @@ describe('Builder', () => {
`);
});

test('drop unsupported bound styles to avoid crashes', () => {
const jsx = `export default function MyComponent(props) {
return (
<div
style={{
fontSize: state.fontSize,
'&:hover': {
backgroundColor: state.foo === 1 ? "red" : "blue"
}
}}
/>
);
}`;

const mitosis = parseJsx(jsx);

const json = componentToBuilder()({ component: mitosis });
expect(json).toMatchInlineSnapshot(`
{
"data": {
"blocks": [
{
"@type": "@builder.io/sdk:Element",
"actions": {},
"bindings": {
"style.fontSize": "state.fontSize",
},
"children": [],
"code": {
"actions": {},
"bindings": {},
},
"properties": {},
"tagName": "div",
},
],
"jsCode": "",
"tsCode": "",
},
}
`);
});

test('map custom component bindings', () => {
const content = {
data: {
Expand Down
33 changes: 28 additions & 5 deletions packages/core/src/generators/builder/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,17 +468,40 @@ const mapBoundStyles = (bindings: { [key: string]: Binding | undefined }) => {
};
}
} else {
bindings[`style.${key}`] = {
code: parsed[key],
bindingType: 'expression',
type: 'single',
};
if (isGlobalStyle(key)) {
console.warn(
`The following bound styles are not supported by Builder JSON and have been removed:
"${key}": ${parsed[key]}
`,
);
} else {
bindings[`style.${key}`] = {
code: parsed[key],
bindingType: 'expression',
type: 'single',
};
}
}
}

delete bindings['style'];
};

function isGlobalStyle(key: string) {
// These are mapped to their respective responsiveStyle and support bindings
if (/max-width: (.*?)px/gm.exec(key)) {
return false;
}

return (
// pseudo class
key.startsWith('&:') ||
key.startsWith(':') ||
// @ rules
key.startsWith('@')
);
}

export const blockToBuilder = (
json: MitosisNode,
options: ToBuilderOptions = {},
Expand Down

0 comments on commit f208f94

Please sign in to comment.