Skip to content

Commit

Permalink
Add packageMap option to replace import path with a configurable path
Browse files Browse the repository at this point in the history
from plugin options.
  • Loading branch information
brijeshb42 committed Jul 2, 2024
1 parent 8129df8 commit 863e795
Show file tree
Hide file tree
Showing 15 changed files with 193 additions and 24 deletions.
8 changes: 8 additions & 0 deletions packages/pigment-css-react/src/processors/base-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
BaseProcessor as WywBaseProcessor,
toValidCSSIdentifier,
} from '@wyw-in-js/processor-utils';
import type { PluginCustomOptions } from '../utils/cssFnValueToVariable';

export default abstract class BaseProcessor extends WywBaseProcessor {
variableIdx = 0;
Expand Down Expand Up @@ -42,4 +43,11 @@ export default abstract class BaseProcessor extends WywBaseProcessor {
valueSlug: slugify(`${source}${hasUnit}`),
};
}

protected getImportPath() {
const { packageMap } = this.options as PluginCustomOptions;
const { source: originalSource } = this.tagSource;
const transformedImport = packageMap?.[originalSource];
return transformedImport ?? `${process.env.PACKAGE_NAME as string}`;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class CreateExtendSxPropProcessor extends BaseProcessor {

const extendSxPropImportIdentifier = t.addNamedImport(
this.tagSource.imported,
process.env.PACKAGE_NAME as string,
this.getImportPath(),
);

this.replacer(t.callExpression(extendSxPropImportIdentifier, []), true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class CreateUseThemePropsProcessor extends BaseProcessor {

const useThemePropsImportIdentifier = t.addNamedImport(
this.tagSource.imported,
process.env.PACKAGE_NAME as string,
this.getImportPath(),
);

let replacement: Expression = t.stringLiteral(this.componentName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class GenerateAtomicsProcessor extends BaseProcessor {
return;
}
const { astService: t } = this;
const importName = t.addNamedImport('atomics', process.env.PACKAGE_NAME as string);
const importName = t.addNamedImport('atomics', this.getImportPath());
this.replacer(t.callExpression(importName, [valueToLiteral(this.runtimeConfig)]), true);
}
}
4 changes: 2 additions & 2 deletions packages/pigment-css-react/src/processors/styled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ export class StyledProcessor extends BaseProcessor {
return;
}
const themeImportIdentifier = this.astService.addDefaultImport(
`${process.env.PACKAGE_NAME}/theme`,
`${this.getImportPath()}/theme`,
'theme',
);
// all the variant definitions are collected here so that we can
Expand Down Expand Up @@ -416,7 +416,7 @@ export class StyledProcessor extends BaseProcessor {
}
}

const styledImportIdentifier = t.addNamedImport('styled', process.env.PACKAGE_NAME as string);
const styledImportIdentifier = t.addNamedImport('styled', this.getImportPath());
const styledCall = t.callExpression(
styledImportIdentifier,
componentMetaExpression ? [componentName, componentMetaExpression] : [componentName],
Expand Down
2 changes: 1 addition & 1 deletion packages/pigment-css-react/src/processors/useTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class UseThemeProcessor extends BaseProcessor {

doRuntimeReplacement() {
const t = this.astService;
const themeIdentifier = t.addDefaultImport(`${process.env.PACKAGE_NAME as string}/theme`);
const themeIdentifier = t.addDefaultImport(`${this.getImportPath()}/theme`);
this.replacer(themeIdentifier, false);
}

Expand Down
25 changes: 25 additions & 0 deletions packages/pigment-css-react/src/utils/cssFnValueToVariable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,31 @@ export type PluginCustomOptions = {
*/
getDirSelector?: (dir: 'ltr' | 'rtl') => string;
};
/**
* Customize the replacement package name that should be added in-place of
* the actually imported package name, ie,
*
* ```js
* import { styled } from '@pigment-css/react';
* ```
*
* will turn into
*
* ```js
* import { styled } from '@mui/material-pigment-css';
* ```
*
* if packageMap has this
*
* ```js
* {
* packageMap: {
* '@pigment-css/react': '@mui/material-pigment-css',
* }
* }
* ```
*/
packageMap?: Record<string, string>;
};

type CssFnValueToVariableParams = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { styled, keyframes } from '@pigment-css/react';

const rotateKeyframe = keyframes({
from: {
transform: 'translateX(0%)',
},
to: {
transform: 'translateX(100%)',
},
});

const Component = styled.div(({ theme }) => ({
animation: `${rotateKeyframe} 2s ease-out 0s infinite`,
marginLeft: 10,
}));

export const SliderRail = styled('span', {
name: 'MuiSlider',
slot: 'Rail',
})`
display: block;
position: absolute;
left: 0;
top: 0;
border-top-left-radius: 3px;
`;

const SliderRail2 = styled.span`
${SliderRail} {
padding-inline-start: none;
margin: 0px 10px 10px 30px;
}
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@keyframes rrqhzm2 {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
.ci0148v {
animation: rrqhzm2 2s ease-out 0s infinite;
margin-left: 10px;
}
.suo5xob {
display: block;
position: absolute;
left: 0;
top: 0;
border-top-left-radius: 3px;
}
.sudpq9z .suo5xob {
padding-inline-start: none;
margin: 0px 10px 10px 30px;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {
styled as _styled,
styled as _styled2,
styled as _styled3,
} from '@mui/material-pigment-css';
import _theme from '@mui/material-pigment-css/theme';
const Component = /*#__PURE__*/ _styled('div')({
classes: ['ci0148v'],
});
export const SliderRail = /*#__PURE__*/ _styled2('span', {
name: 'MuiSlider',
slot: 'Rail',
})({
classes: ['suo5xob'],
});
const SliderRail2 = /*#__PURE__*/ _styled3('span')({
classes: ['sudpq9z'],
});
14 changes: 14 additions & 0 deletions packages/pigment-css-react/tests/styled/styled.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,18 @@ describe('Pigment CSS - styled', () => {
expect(output.js).to.equal(fixture.js);
expect(output.css).to.equal(fixture.css);
});

it('should replace the import paths to the ones specific in packageMap', async () => {
const { output, fixture } = await runTransformation(
path.join(__dirname, 'fixtures/styled-import-replacement.input.js'),
{
packageMap: {
'@pigment-css/react': '@mui/material-pigment-css',
},
},
);

expect(output.js).to.equal(fixture.js);
expect(output.css).to.equal(fixture.css);
});
});
17 changes: 5 additions & 12 deletions packages/pigment-css-react/tests/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import * as prettier from 'prettier';
import sxTransformPlugin from '../exports/sx-plugin';
import pkgJson from '../package.json';

type TransformOptions = {
themeArgs?: { theme?: any };
css?: PluginCustomOptions['css'];
type TransformOptions = PluginCustomOptions & {
outputDir?: string;
};

Expand All @@ -35,15 +33,12 @@ export async function runTransformation(absolutePath: string, options?: Transfor
const cache = new TransformCacheCollection();
const { emitter: eventEmitter } = createFileReporter(false);
const inputFilePath = absolutePath;
const { outputDir, ...restOptions } = options ?? {};
let outputFilePath = (
options?.outputDir
? path.join(options.outputDir, inputFilePath.split(path.sep).pop() as string)
: absolutePath
outputDir ? path.join(outputDir, inputFilePath.split(path.sep).pop() as string) : absolutePath
).replace('.input.', '.output.');
let outputCssFilePath = (
options?.outputDir
? path.join(options.outputDir, inputFilePath.split(path.sep).pop() as string)
: absolutePath
outputDir ? path.join(outputDir, inputFilePath.split(path.sep).pop() as string) : absolutePath
)
.replace('.input.js', '.output.css')
.replace('.input.jsx', '.output.css');
Expand All @@ -65,9 +60,6 @@ export async function runTransformation(absolutePath: string, options?: Transfor
const babelResult = await runSxTransform(inputContent, inputFilePath);

const pluginOptions = {
themeArgs: {
theme: options?.themeArgs?.theme,
},
babelOptions: {
configFile: false,
babelrc: false,
Expand All @@ -83,6 +75,7 @@ export async function runTransformation(absolutePath: string, options?: Transfor
}
return require.resolve(`../${pkgJson['wyw-in-js'].tags[tag]}`.replace('.js', ''));
},
...restOptions,
};

const result = await wywTransform(
Expand Down
32 changes: 29 additions & 3 deletions packages/pigment-css-unplugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,24 @@ function isZeroRuntimeProcessableFile(fileName: string, transformLibraries: stri
);
}

const addMaterialUIOverriedContext = (originalContext: Record<string, unknown>) => {
const originalRequire = originalContext.require as (id: string) => any;
const newRequire = (id: string) => {
if (id === '@mui/styled-engine' || id === '@mui/styled-engine-sc') {
return {
__esModule: true,
default: () => () => () => null,
internal_processStyles: () => {},
keyframes: () => '',
css: () => '',
};
}
return originalRequire(id);
};
originalContext.require = newRequire;
return originalContext;
};

/**
* Next.js initializes the plugin multiple times. So all the calls
* have to share the same Maps.
Expand Down Expand Up @@ -213,18 +231,26 @@ export const plugin = createUnplugin<PigmentOptions, true>((options) => {
themeArgs: {
theme,
},
packageMap: transformLibraries.reduce(
(acc, lib) => {
acc[lib] = lib;
return acc;
},
{} as Record<string, string>,
),
features: {
useWeakRefInEval: false,
// If users know what they are doing, let them override to true
...rest.features,
},
overrideContext(context: Record<string, unknown>, filename: string) {
if (overrideContext) {
return overrideContext(context, filename);
}
if (!context.$RefreshSig$) {
context.$RefreshSig$ = outerNoop;
}
addMaterialUIOverriedContext(context);
if (overrideContext) {
return overrideContext(context, filename);
}
return context;
},
tagResolver(source: string, tag: string) {
Expand Down
7 changes: 7 additions & 0 deletions packages/pigment-css-vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ export function pigment(options: PigmentOptions) {
themeArgs: {
theme,
},
packageMap: transformLibraries.reduce(
(acc, lib) => {
acc[lib] = lib;
return acc;
},
{} as Record<string, string>,
),
preprocessor: preprocessor ?? withRtl,
babelOptions: {
...babelOptions,
Expand Down
28 changes: 25 additions & 3 deletions packages/pigment-css-vite-plugin/src/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,24 @@ function outerNoop() {
return innerNoop;
}

const addMaterialUIOverriedContext = (originalContext: Record<string, unknown>) => {
const originalRequire = originalContext.require as (id: string) => any;
const newRequire = (id: string) => {
if (id === '@mui/styled-engine' || id === '@mui/styled-engine-sc') {
return {
__esModule: true,
default: () => () => () => null,
internal_processStyles: () => {},
keyframes: () => '',
css: () => '',
};
}
return originalRequire(id);
};
originalContext.require = newRequire;
return originalContext;
};

export default function wywVitePlugin({
debug,
include,
Expand Down Expand Up @@ -203,12 +221,16 @@ export default function wywVitePlugin({
presets: Array.from(presets),
},
overrideContext(context: Record<string, unknown>, filename: string) {
if (overrideContext) {
return overrideContext(context, filename);
}
if (!context.$RefreshSig$) {
context.$RefreshSig$ = outerNoop;
}

addMaterialUIOverriedContext(context);

if (overrideContext) {
return overrideContext(context, filename);
}

return context;
},
tagResolver(source: string, tag: string) {
Expand Down

0 comments on commit 863e795

Please sign in to comment.