-
-
Notifications
You must be signed in to change notification settings - Fork 32.8k
[pigment-css] Handle more scenarios while transforming sx prop #41372
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
[pigment] Handle more scenarios while transforming
sx prop. This now provides the ability to have simple expressions like conditional and logical expressions in the sx prop code.
- Loading branch information
commit 8f3c3987db9ac034b34e1de9c0031cb229eeba16
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,69 +1,82 @@ | ||
| import { addNamed } from '@babel/helper-module-imports'; | ||
| import { declare } from '@babel/helper-plugin-utils'; | ||
| import { sxObjectExtractor } from './sxObjectExtractor'; | ||
| import { NodePath } from '@babel/core'; | ||
| import * as Types from '@babel/types'; | ||
| import { sxPropConvertor } from './sxPropConverter'; | ||
brijeshb42 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| export const babelPlugin = declare((api) => { | ||
| api.assertVersion(7); | ||
| const { types: t } = api; | ||
| return { | ||
| name: '@pigmentcss/zero-babel-plugin', | ||
| visitor: { | ||
| JSXAttribute(path) { | ||
| const namePath = path.get('name'); | ||
| const openingElement = path.findParent((p) => p.isJSXOpeningElement()); | ||
| if ( | ||
| !openingElement || | ||
| !openingElement.isJSXOpeningElement() || | ||
| !namePath.isJSXIdentifier() || | ||
| namePath.node.name !== 'sx' | ||
| ) { | ||
| return; | ||
| } | ||
| const tagName = openingElement.get('name'); | ||
| if (!tagName.isJSXIdentifier()) { | ||
| return; | ||
| } | ||
| const valuePath = path.get('value'); | ||
| if (!valuePath.isJSXExpressionContainer()) { | ||
| return; | ||
| } | ||
| const expressionPath = valuePath.get('expression'); | ||
| if (!expressionPath.isExpression()) { | ||
| return; | ||
| } | ||
| if (!expressionPath.isObjectExpression() && !expressionPath.isArrowFunctionExpression()) { | ||
| return; | ||
| } | ||
| sxObjectExtractor(expressionPath); | ||
| const sxIdentifier = addNamed(namePath, 'sx', process.env.PACKAGE_NAME as string); | ||
| expressionPath.replaceWith( | ||
| t.callExpression(sxIdentifier, [expressionPath.node, t.identifier(tagName.node.name)]), | ||
| ); | ||
| }, | ||
| ObjectProperty(path) { | ||
| // @TODO - Maybe add support for React.createElement calls as well. | ||
| // Right now, it only checks for jsx(),jsxs(),jsxDEV() and jsxsDEV() calls. | ||
| const keyPath = path.get('key'); | ||
| if (!keyPath.isIdentifier() || keyPath.node.name !== 'sx') { | ||
| return; | ||
| } | ||
| const valuePath = path.get('value'); | ||
| if (!valuePath.isObjectExpression() && !valuePath.isArrowFunctionExpression()) { | ||
| return; | ||
| } | ||
| const parentJsxCall = path.findParent((p) => p.isCallExpression()); | ||
| if (!parentJsxCall || !parentJsxCall.isCallExpression()) { | ||
| return; | ||
| } | ||
| const callee = parentJsxCall.get('callee'); | ||
| if (!callee.isIdentifier() || !callee.node.name.includes('jsx')) { | ||
| return; | ||
| } | ||
| const jsxElement = parentJsxCall.get('arguments')[0]; | ||
| sxObjectExtractor(valuePath); | ||
| const sxIdentifier = addNamed(keyPath, 'sx', process.env.PACKAGE_NAME as string); | ||
| valuePath.replaceWith(t.callExpression(sxIdentifier, [valuePath.node, jsxElement.node])); | ||
| }, | ||
| }, | ||
| function replaceNodePath( | ||
| expressionPath: NodePath<Types.Expression>, | ||
| namePath: NodePath<Types.JSXIdentifier | Types.Identifier>, | ||
| importName: string, | ||
| t: typeof Types, | ||
| tagName: NodePath<Types.JSXIdentifier | Types.Identifier>, | ||
| ) { | ||
| const sxIdentifier = addNamed(namePath, importName, process.env.PACKAGE_NAME as string); | ||
|
|
||
| const wrapWithSxCall = (expPath: NodePath<Types.Expression>) => { | ||
| expPath.replaceWith( | ||
| t.callExpression(sxIdentifier, [expPath.node, t.identifier(tagName.node.name)]), | ||
| ); | ||
| }; | ||
| }); | ||
|
|
||
| sxPropConvertor(expressionPath, wrapWithSxCall); | ||
| } | ||
|
|
||
| export const babelPlugin = declare<{ propName?: string; importName?: string }>( | ||
| (api, { propName = 'sx', importName = 'sx' }) => { | ||
| api.assertVersion(7); | ||
| const { types: t } = api; | ||
| return { | ||
| name: '@pigmentcss/zero-babel-plugin', | ||
| visitor: { | ||
| JSXAttribute(path) { | ||
| const namePath = path.get('name'); | ||
| const openingElement = path.findParent((p) => p.isJSXOpeningElement()); | ||
| if ( | ||
| !openingElement || | ||
| !openingElement.isJSXOpeningElement() || | ||
| !namePath.isJSXIdentifier() || | ||
| namePath.node.name !== propName | ||
| ) { | ||
| return; | ||
| } | ||
| const tagName = openingElement.get('name'); | ||
| if (!tagName.isJSXIdentifier()) { | ||
| return; | ||
| } | ||
| const valuePath = path.get('value'); | ||
| if (!valuePath.isJSXExpressionContainer()) { | ||
| return; | ||
| } | ||
| const expressionPath = valuePath.get('expression'); | ||
| if (!expressionPath.isExpression()) { | ||
| return; | ||
| } | ||
| replaceNodePath(expressionPath, namePath, importName, t, tagName); | ||
| }, | ||
| ObjectProperty(path) { | ||
| // @TODO - Maybe add support for React.createElement calls as well. | ||
| // Right now, it only checks for jsx(),jsxs(),jsxDEV() and jsxsDEV() calls. | ||
| const keyPath = path.get('key'); | ||
| if (!keyPath.isIdentifier() || keyPath.node.name !== propName) { | ||
| return; | ||
| } | ||
| const valuePath = path.get('value'); | ||
| if (!valuePath.isObjectExpression() && !valuePath.isArrowFunctionExpression()) { | ||
| return; | ||
| } | ||
| const parentJsxCall = path.findParent((p) => p.isCallExpression()); | ||
| if (!parentJsxCall || !parentJsxCall.isCallExpression()) { | ||
| return; | ||
| } | ||
| const callee = parentJsxCall.get('callee'); | ||
| if (!callee.isIdentifier() || !callee.node.name.includes('jsx')) { | ||
| return; | ||
| } | ||
| const jsxElement = parentJsxCall.get('arguments')[0] as NodePath<Types.Identifier>; | ||
| replaceNodePath(valuePath, keyPath, importName, t, jsxElement); | ||
| }, | ||
| }, | ||
| }; | ||
| }, | ||
| ); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| import { NodePath } from '@babel/core'; | ||
| import { ArrowFunctionExpression, Expression, ObjectExpression } from '@babel/types'; | ||
| import { sxObjectExtractor } from './sxObjectExtractor'; | ||
|
|
||
| function isAllowedExpression( | ||
| node: NodePath<Expression>, | ||
| ): node is NodePath<ObjectExpression> | NodePath<ArrowFunctionExpression> { | ||
| return node.isObjectExpression() || node.isArrowFunctionExpression(); | ||
| } | ||
|
|
||
| export function sxPropConvertor( | ||
| node: NodePath<Expression>, | ||
| wrapWithSxCall: (expPath: NodePath<Expression>) => void, | ||
| ) { | ||
| if (node.isConditionalExpression()) { | ||
| const consequent = node.get('consequent'); | ||
| const alternate = node.get('alternate'); | ||
|
|
||
| if (isAllowedExpression(consequent)) { | ||
| sxObjectExtractor(consequent); | ||
| wrapWithSxCall(consequent); | ||
| } | ||
| if (isAllowedExpression(alternate)) { | ||
| sxObjectExtractor(alternate); | ||
| wrapWithSxCall(alternate); | ||
| } | ||
| } else if (node.isLogicalExpression()) { | ||
| const right = node.get('right'); | ||
| if (isAllowedExpression(right)) { | ||
| sxObjectExtractor(right); | ||
| wrapWithSxCall(right); | ||
| } | ||
| } else if (isAllowedExpression(node)) { | ||
| sxObjectExtractor(node); | ||
| wrapWithSxCall(node); | ||
| } else if (node.isIdentifier()) { | ||
| const rootScope = node.scope.getProgramParent(); | ||
| const binding = node.scope.getBinding(node.node.name); | ||
| // Simplest case, ie, const styles = {static object} | ||
| // and is used as <Component sx={styles} /> | ||
| if (binding?.scope === rootScope) { | ||
| wrapWithSxCall(node); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import * as fs from 'node:fs'; | ||
| import * as path from 'node:path'; | ||
| import { expect } from 'chai'; | ||
| import { asyncResolveFallback } from '@wyw-in-js/shared'; | ||
| import { transformAsync } from '@babel/core'; | ||
| import { TransformCacheCollection, transform, createFileReporter } from '@wyw-in-js/transform'; | ||
| import { preprocessor } from '@pigment-css/react/utils'; | ||
| import sxTransformPlugin from '../exports/sx-plugin'; | ||
|
|
||
| const files = fs | ||
| .readdirSync(path.join(__dirname, 'fixtures')) | ||
| .filter((file) => file.endsWith('.input.js')); | ||
|
|
||
| const theme = { | ||
| palette: { | ||
| primary: { | ||
| main: 'red', | ||
| }, | ||
| }, | ||
| size: { | ||
| font: { | ||
| h1: '3rem', | ||
| }, | ||
| }, | ||
| components: { | ||
| MuiSlider: { | ||
| styleOverrides: { | ||
| rail: { | ||
| fontSize: '3rem', | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }; | ||
|
|
||
| async function transformWithSx(code: string, filename: string) { | ||
| const babelResult = await transformAsync(code, { | ||
| babelrc: false, | ||
| configFile: false, | ||
| filename, | ||
| plugins: ['@babel/plugin-syntax-jsx', [sxTransformPlugin]], | ||
| }); | ||
| const pluginOptions = { | ||
| themeArgs: { | ||
| theme, | ||
| }, | ||
| babelOptions: { | ||
| configFile: false, | ||
| babelrc: false, | ||
| plugins: ['@babel/plugin-syntax-jsx'], | ||
| }, | ||
| tagResolver(source: string, tag: string) { | ||
| if (source !== '@pigment-css/react') { | ||
| return null; | ||
| } | ||
| return require.resolve(`../exports/${tag}`); | ||
| }, | ||
| }; | ||
| const cache = new TransformCacheCollection(); | ||
| const { emitter: eventEmitter } = createFileReporter(false); | ||
| return transform( | ||
| { | ||
| options: { | ||
| filename, | ||
| preprocessor, | ||
| pluginOptions, | ||
| }, | ||
| cache, | ||
| eventEmitter, | ||
| }, | ||
| babelResult?.code ?? code, | ||
| asyncResolveFallback, | ||
| ); | ||
| } | ||
|
|
||
| describe('zero-runtime', () => { | ||
| files.forEach((file) => { | ||
| it(`test input file ${file}`, async () => { | ||
| const inputFilePath = path.join(__dirname, 'fixtures', file); | ||
| const outputFilePath = path.join(__dirname, 'fixtures', file.replace('.input.', '.output.')); | ||
| const outputCssFilePath = path.join( | ||
| __dirname, | ||
| 'fixtures', | ||
| file.replace('.input.js', '.output.css'), | ||
| ); | ||
| const inputContent = fs.readFileSync(inputFilePath, 'utf8'); | ||
| const outputContent = fs.readFileSync(outputFilePath, 'utf8'); | ||
| const outputCssContent = fs.readFileSync(outputCssFilePath, 'utf8'); | ||
| const result = await transformWithSx(inputContent, inputFilePath); | ||
| expect(result.cssText).to.equal(outputCssContent); | ||
| expect(result.code.trim()).to.equal(outputContent.trim()); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
packages/pigment-react/tests/styled/fixtures/sxProps.input.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import { SliderRail } from './styled.input'; | ||
|
|
||
| function App() { | ||
| return <SliderRail sx={{ color: 'red' }} />; | ||
| } | ||
|
|
||
| function App2(props) { | ||
| return ( | ||
| <SliderRail | ||
| sx={ | ||
| props.variant === 'secondary' | ||
| ? { color: props.isRed ? 'red' : 'blue' } | ||
| : { backgroundColor: 'blue', color: 'white' } | ||
| } | ||
| /> | ||
| ); | ||
| } | ||
|
|
||
| function App3(props) { | ||
| return ( | ||
| <SliderRail sx={props.variant === 'secondary' && { color: props.isRed ? 'red' : 'blue' }} /> | ||
| ); | ||
| } | ||
|
|
||
| const textAlign = 'center'; | ||
| const styles4 = { | ||
| mb: 1, | ||
| textAlign, | ||
| }; | ||
|
|
||
| function App4(props) { | ||
| return <SliderRail sx={styles4} />; | ||
| } |
5 changes: 5 additions & 0 deletions
5
packages/pigment-react/tests/styled/fixtures/sxProps.output.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| .soujkwr.s1ne1757{color:red;} | ||
| .soujkwr.s1novky8{color:var(--s1novky8-0);} | ||
| .soujkwr.s1dedx85{background-color:blue;color:white;} | ||
| .soujkwr.s37rrrj{color:var(--s37rrrj-0);} | ||
| .soujkwr.swjt3r4{margin-bottom:8px;text-align:center;} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.