Skip to content

Commit

Permalink
[zero][vite] Modify plugin to transform node_modules (mui#39517)
Browse files Browse the repository at this point in the history
  • Loading branch information
brijeshb42 authored Oct 20, 2023
1 parent 1657fbd commit 9b74132
Show file tree
Hide file tree
Showing 15 changed files with 328 additions and 103 deletions.
6 changes: 6 additions & 0 deletions apps/local-library/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const bounceAnim: string;
export const Button: React.ComponentType<
JSX.IntrinsicElements['button'] & {
isRed?: boolean;
}
>;
31 changes: 31 additions & 0 deletions apps/local-library/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { keyframes, styled } from '@mui/zero-runtime';

export const bounceAnim = keyframes({
'from, 20%, 53%, 80%, to': {
transform: 'translate3d(0,0,0)',
},
'40%, 43%': {
transform: 'translate3d(0, -30px, 0)',
},
'70%': {
transform: 'translate3d(0, -15px, 0)',
},
'90%': {
transform: 'translate3d(0,-4px,0)',
},
});

export const Button = styled('button', {
name: 'MuiButton',
slot: 'Root',
})(
({ theme }) => ({
fontFamily: 'sans-serif',
backgroundColor: theme.palette.primary.main,
}),
{
fontFamily: 'sans-serif',
color: (props) => (props.isRed ? 'primary.main' : 'secondary.main'),
'--css-variable': (props) => (props.isRed ? 'palette.primary.main' : 'palette.secondary.main'),
},
);
7 changes: 7 additions & 0 deletions apps/local-library/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "local-ui-lib",
"version": "0.0.0",
"dependencies": {
"zero-runtime": "*"
}
}
1 change: 1 addition & 0 deletions apps/zero-runtime-vite-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jsdom": "^22.1.0",
"local-library": "file:../local-library",
"vite": "4.4.11",
"vitest": "^0.34.6"
},
Expand Down
50 changes: 3 additions & 47 deletions apps/zero-runtime-vite-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,52 +1,8 @@
import * as React from 'react';
import { styled, keyframes } from '@mui/zero-runtime';
import { styled } from '@mui/zero-runtime';
import { Button, bounceAnim } from 'local-library';
import Slider from './Slider/ZeroSlider';

const bounce = keyframes`
from, 20%, 53%, 80%, to {
transform: translate3d(0,0,0);
}
40%, 43% {
transform: translate3d(0, -30px, 0);
}
70% {
transform: translate3d(0, -15px, 0);
}
90% {
transform: translate3d(0,-4px,0);
}
`;

const bounceAnim = keyframes({
'from, 20%, 53%, 80%, to': {
transform: 'translate3d(0,0,0)',
},
'40%, 43%': {
transform: 'translate3d(0, -30px, 0)',
},
'70%': {
transform: 'translate3d(0, -15px, 0)',
},
'90%': {
transform: 'translate3d(0,-4px,0)',
},
});

const Button = styled('button', {
name: 'MuiButton',
slot: 'Root',
})(
({ theme }: any) => ({
fontFamily: 'sans-serif',
backgroundColor: [theme.palette.primary.main, 'text.primary', 'background.paper'],
}),
{
fontFamily: 'sans-serif',
// p: (props: any) => (props.isRed ? 10 : 20),
color: (props: any) => (props.isRed ? 'primary.main' : 'secondary.main'),
},
);

const ShowCaseDiv = styled('div')({
[`.${Button}`]: {
color: '#f94564',
Expand All @@ -59,7 +15,7 @@ const HalfWidth = styled.div({
maxHeight: 100,
padding: 20,
border: '1px solid #ccc',
animation: [`${bounce} 1s ease infinite`, `${bounceAnim} 1s ease infinite`],
animation: `${bounceAnim} 1s ease infinite`,
});

export default function App({ isRed }: any) {
Expand Down
1 change: 1 addition & 0 deletions apps/zero-runtime-vite-app/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default defineConfig({
zeroVitePlugin({
cssVariablesPrefix: 'app',
theme,
transformLibraries: ['local-library'],
}),
reactPlugin(),
splitVendorChunkPlugin(),
Expand Down
2 changes: 1 addition & 1 deletion packages/zero-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"build:types": "node ../../scripts/buildTypes.mjs",
"prebuild": "rimraf build tsconfig.build.tsbuildinfo",
"release": "yarn build && npm publish build",
"test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/zero-babel-plugin/**/*.test.{js,ts,tsx}'",
"test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/zero-runtime/**/*.test.{js,ts,tsx}'",
"typescript": "tslint -p tsconfig.json \"{src,test}/**/*.{spec,d}.{ts,tsx}\" && tsc -p tsconfig.json",
"typescript:module-augmentation": "node scripts/testModuleAugmentation.js"
},
Expand Down
27 changes: 25 additions & 2 deletions packages/zero-runtime/src/styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ function getVariantClasses(componentProps, variants) {
return variantClasses;
}

/**
* @param {string} propKey
* @returns {boolean}
*/
function defaultShouldForwardProp(propKey) {
return propKey !== 'sx' && propKey !== 'as' && propKey !== 'ownerState';
}

/**
* @typedef {typeof defaultShouldForwardProp} ShouldForwardProp
*/

/**
* @TODO - Filter props and only pass necessary props to children
*
Expand All @@ -27,6 +39,7 @@ function getVariantClasses(componentProps, variants) {
* @param {string} options.variants.className Classname generated for this specific variant through styled processor.
* @param {string} options.name
* @param {string} options.slot
* @param {ShouldForwardProp} options.shouldForwardProp
* @param {Object} options.defaultProps Default props object copied over and inlined from theme object
*/
export default function styled(tag, options = {}) {
Expand All @@ -38,6 +51,7 @@ export default function styled(tag, options = {}) {
name,
slot,
defaultProps = {},
shouldForwardProp = defaultShouldForwardProp,
} = options;
let componentName = 'Component';

Expand All @@ -62,6 +76,9 @@ export default function styled(tag, options = {}) {
const varStyles = Object.entries(cssVars).reduce(
(acc, [cssVariable, [variableFunction, isUnitLess]]) => {
const value = variableFunction(props);
if (typeof value === 'undefined') {
return acc;
}
if (typeof value === 'string' || isUnitLess) {
acc[`--${cssVariable}`] = value;
} else {
Expand All @@ -87,12 +104,18 @@ export default function styled(tag, options = {}) {
}

const finalClassName = clsx(classes, sxClass, className, getVariantClasses(props, variants));
const toPassProps = Object.keys(restProps)
.filter((item) => shouldForwardProp(item))
.reduce((acc, key) => {
acc[key] = restProps[key];
return acc;
}, {});

// eslint-disable-next-line no-underscore-dangle
if (!Component.__isStyled) {
return (
<Component
{...restProps}
{...toPassProps}
ref={ref}
className={finalClassName}
style={{
Expand All @@ -105,7 +128,7 @@ export default function styled(tag, options = {}) {

return (
<Component
{...restProps}
{...toPassProps}
ownerState={ownerState}
ref={ref}
className={finalClassName}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import type { ExpressionValue } from '@linaria/utils';
import { transformSync, type Node } from '@babel/core';
import { parseExpression } from '@babel/parser';
import type { Expression } from '@linaria/tags';
import type { Theme } from '@mui/material/styles';
import { unstable_defaultSxConfig as defaultSxConfig } from '@mui/system/styleFunctionSx';
import * as t from '@babel/types';
import { isUnitLess } from './isUnitLess';
import { cssFunctionTransformerPlugin } from './cssFunctionTransformerPlugin';
Expand Down Expand Up @@ -38,14 +36,10 @@ function transformThemeKeysInFn(
filename?: string,
) {
const { themeArgs: { theme } = {} } = options;
const userTheme = theme as Theme;
const config = userTheme?.unstable_sxConfig ?? defaultSxConfig;
const cssPropOptions = config[styleKey];
const { themeKey } = cssPropOptions;

// return the function as-is if sxConfig does not contain
// this css key
if (!theme || !config || !cssPropOptions || !themeKey) {
if (!theme) {
return parseExpression(functionString);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,7 @@ const cssFunctionTransformerPlugin = declare<BabelPluginOptions>((api, pluginOpt
};
const config = typedTheme?.unstable_sxConfig ?? defaultSxConfig;
const cssPropOptions = config[styleKey];
const { themeKey } = cssPropOptions;
if (!typedTheme || !config || !cssPropOptions || !themeKey) {
return {
name: '@mui/zero-internal/cssFunctionTransformerPlugin',
visitor: {},
};
}
const themeKey = cssPropOptions?.themeKey;
const finalPrefix = cssVariablesPrefix ? `${cssVariablesPrefix}-` : '';

return {
Expand Down Expand Up @@ -82,16 +76,19 @@ const cssFunctionTransformerPlugin = declare<BabelPluginOptions>((api, pluginOpt
if (themeKey === 'typography' && val === 'inherit') {
return;
}
const propertyThemeKey = themeKey ?? val.split('.')[0];
const themeValue =
get(typedTheme, `${themeKey}.${val}`) ??
(typedTheme.vars ? get(typedTheme.vars, `${themeKey}.${val}`) : undefined);
get(typedTheme, `${propertyThemeKey}.${val}`) ??
(typedTheme.vars ? get(typedTheme.vars, `${propertyThemeKey}.${val}`) : undefined);
if (!themeValue) {
console.warn(
`MUI: Value for key: ${val} does not exist in "theme.${themeKey}" or "theme.vars.${themeKey}"`,
`MUI: Value for key: ${val} does not exist in "theme.${propertyThemeKey}" or "theme.vars.${propertyThemeKey}"`,
);
}
const themeKeyArr = val.split('.').join('-');
path.replaceWith(t.stringLiteral(`var(--${finalPrefix}${themeKey}-${themeKeyArr})`));
path.replaceWith(
t.stringLiteral(`var(--${finalPrefix}${propertyThemeKey}-${themeKeyArr})`),
);
},
},
};
Expand Down
1 change: 1 addition & 0 deletions packages/zero-tag-processor/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type { PluginCustomOptions } from './cssFnValueToVariable';
3 changes: 2 additions & 1 deletion packages/zero-vite-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
},
"dependencies": {
"@babel/core": "^7.23.2",
"@linaria/vite": "^4.5.4",
"@linaria/logger": "^4.5.0",
"@linaria/utils": "^4.5.3",
"@mui/zero-tag-processor": "0.0.1-alpha.0"
},
"devDependencies": {
Expand Down
31 changes: 17 additions & 14 deletions packages/zero-vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import type { Plugin, PluginOption } from 'vite';
import { generateCss } from '@mui/zero-tag-processor/generateCss';
import { preprocessor } from '@mui/zero-tag-processor/preprocessor';
import { transformAsync } from '@babel/core';
import baseLinaria from '@linaria/vite';
import type { PluginCustomOptions } from '@mui/zero-tag-processor/utils';
import baseZeroVitePlugin, { type VitePluginOptions } from './zero-vite-plugin';

type LinariaOptions = Exclude<Parameters<typeof baseLinaria>[0], undefined>;

export interface ZeroVitePluginOptions extends LinariaOptions {
export interface ZeroVitePluginOptions extends VitePluginOptions {
/**
* The theme object that you want to be passed to the `styled` function
*/
Expand All @@ -22,19 +21,23 @@ export interface ZeroVitePluginOptions extends LinariaOptions {
injectDefaultThemeInRoot?: boolean;
}

type LinariaWrapperOptions = Exclude<ZeroVitePluginOptions, 'theme'> & {
themeArgs: Record<string, unknown>;
};
type WrapperOptions = VitePluginOptions & PluginCustomOptions;

const linaria = (options: LinariaWrapperOptions): Plugin => {
return baseLinaria({
const wrapperPlugin = (options: WrapperOptions): Plugin => {
return baseZeroVitePlugin({
preprocessor,
...options,
});
};

export function zeroVitePlugin(options: ZeroVitePluginOptions): PluginOption {
const { cssVariablesPrefix = 'mui', injectDefaultThemeInRoot = true, theme } = options ?? {};
const {
cssVariablesPrefix = 'mui',
injectDefaultThemeInRoot = true,
theme,
babelOptions = {},
...rest
} = options ?? {};

function injectMUITokensPlugin(): PluginOption {
return {
Expand Down Expand Up @@ -85,17 +88,17 @@ export function zeroVitePlugin(options: ZeroVitePluginOptions): PluginOption {
};
}

const linariaPlugin = linaria({
const zeroPlugin = wrapperPlugin({
cssVariablesPrefix,
themeArgs: {
theme,
},
...options,
babelOptions: {
...options?.babelOptions,
...babelOptions,
plugins: ['@babel/plugin-syntax-jsx'],
},
...rest,
});

return [injectMUITokensPlugin(), intermediateBabelPlugin(), linariaPlugin];
return [injectMUITokensPlugin(), intermediateBabelPlugin(), zeroPlugin];
}
Loading

0 comments on commit 9b74132

Please sign in to comment.