index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/date-pickers-moved-to-x.js
const exports = { AdapterDateFns: { default: 'AdapterDateFns', named: [], }, AdapterDayjs: { default: 'AdapterDayjs', named: [], }, AdapterLuxon: { default: 'AdapterLuxon', named: [], }, AdapterMoment: { default: 'AdapterMoment', named: [], }, CalendarPicker: { default: 'CalendarPicker', named: [ 'calendarPickerClasses', 'CalendarPickerClasses', 'CalendarPickerClassKey', 'CalendarPickerProps', 'CalendarPickerView', ], }, CalendarPickerSkeleton: { default: 'CalendarPickerSkeleton', named: [ 'calendarPickerSkeletonClasses', 'CalendarPickerSkeletonClassKey', 'CalendarPickerSkeletonProps', 'getCalendarPickerSkeletonUtilityClass', ], }, ClockPicker: { default: 'ClockPicker', named: [ 'clockPickerClasses', 'ClockPickerClasses', 'ClockPickerClassKey', 'ClockPickerProps', 'ClockPickerView', ], }, DatePicker: { default: 'DatePicker', named: ['DatePickerProps'], }, DateRangePicker: { default: 'DateRangePicker', named: ['DateRange', 'DateRangePickerProps'], isPro: true, }, DateRangePickerDay: { default: 'DateRangePickerDay', named: [ 'dateRangePickerDayClasses', 'DateRangePickerDayClasses', 'DateRangePickerDayClassKey', 'DateRangePickerDayProps', 'getDateRangePickerDayUtilityClass', ], isPro: true, }, DateTimePicker: { default: 'DateTimePicker', named: ['DateTimePickerProps'], }, DesktopDatePicker: { default: 'DesktopDatePicker', named: ['DesktopDatePickerProps'], }, DesktopDateRangePicker: { default: 'DesktopDateRangePicker', named: ['DesktopDateRangePickerProps'], isPro: true, }, DesktopDateTimePicker: { default: 'DesktopDateTimePicker', named: ['DesktopDateTimePickerProps'], }, DesktopTimePicker: { default: 'DesktopTimePicker', named: ['DesktopTimePickerProps'], }, LocalizationProvider: { default: 'LocalizationProvider', named: [ 'LocalizationProviderProps', 'MuiPickersAdapter', 'MuiPickersAdapterContext', 'MuiPickersAdapterContextValue', ], }, MobileDatePicker: { default: 'MobileDatePicker', named: ['MobileDatePickerProps'], }, MobileDateRangePicker: { default: 'MobileDateRangePicker', named: ['MobileDateRangePickerProps'], isPro: true, }, MobileDateTimePicker: { default: 'MobileDateTimePicker', named: ['MobileDateTimePickerProps'], }, MobileTimePicker: { default: 'MobileTimePicker', named: ['MobileTimePickerProps'], }, MonthPicker: { default: 'MonthPicker', named: [ 'monthPickerClasses', 'getMonthPickerUtilityClass', 'MonthPickerClassKey', 'MonthPickerProps', ], }, PickersDay: { default: 'PickersDay', named: [ 'pickersDayClasses', 'getPickersDayUtilityClass', 'PickersDayClassKey', 'PickersDayProps', ], }, StaticDatePicker: { default: 'StaticDatePicker', named: ['StaticDatePickerProps'], }, StaticDateRangePicker: { default: 'StaticDateRangePicker', named: ['StaticDateRangePickerProps'], isPro: true, }, StaticDateTimePicker: { default: 'StaticDateTimePicker', named: ['StaticDateTimePickerProps'], }, StaticTimePicker: { default: 'StaticTimePicker', named: ['StaticTimePickerProps'], }, TimePicker: { default: 'TimePicker', named: ['TimePickerProps'], }, YearPicker: { default: 'YearPicker', named: [ 'yearPickerClasses', 'getYearPickerUtilityClass', 'YearPickerClassKey', 'YearPickerProps', ], }, }; const buildLookup = () => { return Object.fromEntries( Object.entries(exports).flatMap(([entryPoint, entryPointData]) => [entryPointData.default, ...entryPointData.named].map((exportName) => [ exportName, { entryPoint, isPro: entryPointData.isPro }, ]), ), ); }; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(fileInfo, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions || { quote: 'single' }; const lookup = buildLookup(); const root = j(fileInfo.source); root .find(j.ImportDeclaration) .forEach((path) => { const importSource = path.node.source.value; const subPackageImportMatch = importSource.match(/@mui\/lab\/(.*)/); if (subPackageImportMatch !== null) { const subModule = subPackageImportMatch[1]; if (subModule.startsWith('internal')) { console.warn('Imports from `@mui/lab/internal` are not supported'); return; } if (exports[subModule]) { /** * @type {import('jscodeshift').ASTPath} */ const sourcePath = path.get('source'); const targetPackage = exports[subModule].isPro ? '@mui/x-date-pickers-pro' : '@mui/x-date-pickers'; const targetImportPath = `${targetPackage}/${subModule}`; sourcePath.replace(j.stringLiteral(targetImportPath)); const importDeclaration = path.value; importDeclaration.specifiers = importDeclaration.specifiers.map((specifier) => { if (specifier.type === 'ImportDefaultSpecifier') { const localName = specifier.local.name; return j.importSpecifier(j.identifier(subModule), j.identifier(localName)); } return specifier; }); } } else if (importSource === '@mui/lab') { // Sieve import specifiers into /core and /lab const xImportSpecifiers = []; const labImportSpecifiers = []; let isPro = false; path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportSpecifier') { const lookupValue = lookup[specifier.imported.name]; if (lookupValue) { xImportSpecifiers.push(specifier); if (lookupValue.isPro) { isPro = true; } } else { labImportSpecifiers.push(specifier); } } else { // `import Lab from '@material-ui/lab'` // `import * as Lab from '@material-ui/lab'` // These imports would require scope analysis. console.warn(`Can't handle ${specifier.type}`); } }); if (xImportSpecifiers.length > 0) { const targetPackage = isPro ? '@mui/x-date-pickers-pro' : '@mui/x-date-pickers'; path.replace( j.importDeclaration(xImportSpecifiers, j.stringLiteral(targetPackage)), j.importDeclaration(labImportSpecifiers, j.stringLiteral('@mui/lab')), ); } } }) .toSource(printOptions); return root.toSource(printOptions); }
6,500
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/date-pickers-moved-to-x.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './date-pickers-moved-to-x'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('date-pickers-moved-to-x', () => { it('transforms exports as needed (lab sub module)', () => { const actual = transform( { source: read('./date-pickers-moved-to-x.test/actual-sub-module.js'), path: require.resolve('./date-pickers-moved-to-x.test/actual-sub-module.js'), }, { jscodeshift }, {}, ); const expected = read('./date-pickers-moved-to-x.test/expected-sub-module.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent (lab sub module)', () => { const actual = transform( { source: read('./date-pickers-moved-to-x.test/expected-sub-module.js'), path: require.resolve('./date-pickers-moved-to-x.test/expected-sub-module.js'), }, { jscodeshift }, {}, ); const expected = read('./date-pickers-moved-to-x.test/expected-sub-module.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms exports as needed (lab root with only community exports)', () => { const actual = transform( { source: read('./date-pickers-moved-to-x.test/actual-root-community.js'), path: require.resolve('./date-pickers-moved-to-x.test/actual-root-community.js'), }, { jscodeshift }, {}, ); const expected = read('./date-pickers-moved-to-x.test/expected-root-community.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent (lab root with only community exports)', () => { const actual = transform( { source: read('./date-pickers-moved-to-x.test/expected-root-community.js'), path: require.resolve('./date-pickers-moved-to-x.test/expected-root-community.js'), }, { jscodeshift }, {}, ); const expected = read('./date-pickers-moved-to-x.test/expected-root-community.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms exports as needed (lab root with pro exports)', () => { const actual = transform( { source: read('./date-pickers-moved-to-x.test/actual-root-pro.js'), path: require.resolve('./date-pickers-moved-to-x.test/actual-root-pro.js'), }, { jscodeshift }, {}, ); const expected = read('./date-pickers-moved-to-x.test/expected-root-pro.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent (lab root with pro exports)', () => { const actual = transform( { source: read('./date-pickers-moved-to-x.test/expected-root-pro.js'), path: require.resolve('./date-pickers-moved-to-x.test/expected-root-pro.js'), }, { jscodeshift }, {}, ); const expected = read('./date-pickers-moved-to-x.test/expected-root-pro.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,501
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/dialog-props.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; return j(file.source) .findJSXElements('Dialog') .forEach((path) => { const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { if (node.type === 'JSXAttribute' && node.name.name === 'disableBackdropClick') { delete attributes[index]; } }); }) .toSource(printOptions); }
6,502
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/dialog-props.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './dialog-props'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('dialog-props', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./dialog-props.test/actual.js'), path: require.resolve('./dialog-props.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./dialog-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./dialog-props.test/expected.js'), path: require.resolve('./dialog-props.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./dialog-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,503
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/dialog-title-props.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; return j(file.source) .findJSXElements('DialogTitle') .forEach((path) => { const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { if (node.type === 'JSXAttribute' && node.name.name === 'disableTypography') { delete attributes[index]; } }); }) .toSource(printOptions); }
6,504
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/dialog-title-props.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './dialog-title-props'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('dialog-title-props', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./dialog-title-props.test/actual.js'), path: require.resolve('./dialog-title-props.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./dialog-title-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./dialog-title-props.test/expected.js'), path: require.resolve('./dialog-title-props.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./dialog-title-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,505
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/emotion-prepend-cache.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options = {}) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', trailingComma: true }; let emotionCacheName; root.find(j.ImportDeclaration).forEach((path) => { if (path.node.source.value === '@emotion/cache') { path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportDefaultSpecifier') { emotionCacheName = specifier.local.name; } }); } }); root.find(j.CallExpression, { callee: { name: emotionCacheName } }).forEach(({ node }) => { const objExpression = node.arguments[0]; if (objExpression && objExpression.type === 'ObjectExpression') { const prop = objExpression.properties.find((p) => p.key.name === 'prepend'); if (!prop) { objExpression.properties.push(j.property('init', j.identifier('prepend'), j.literal(true))); } else if (prop && prop.kind === 'init' && prop.value.value === false) { prop.value = j.literal(true); } } }); return root.toSource(printOptions); }
6,506
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/emotion-prepend-cache.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './emotion-prepend-cache'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('emotion-prepend-cache', () => { it('append to createCache', () => { const actual = transform( { source: read('./emotion-prepend-cache.test/default-naming.actual.js'), path: require.resolve('./emotion-prepend-cache.test/default-naming.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./emotion-prepend-cache.test/default-naming.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./emotion-prepend-cache.test/default-naming.expected.js'), path: require.resolve('./emotion-prepend-cache.test/default-naming.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./emotion-prepend-cache.test/default-naming.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('append to custom naming', () => { const actual = transform( { source: read('./emotion-prepend-cache.test/custom-naming.actual.js'), path: require.resolve('./emotion-prepend-cache.test/custom-naming.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./emotion-prepend-cache.test/custom-naming.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('turn existing prepend to true', () => { const actual = transform( { source: read('./emotion-prepend-cache.test/replace-existing-prepend.actual.js'), path: require.resolve( './emotion-prepend-cache.test/replace-existing-prepend.actual.js', ), }, { jscodeshift }, {}, ); const expected = read('./emotion-prepend-cache.test/replace-existing-prepend.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,507
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/expansion-panel-component.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file) { return file.source.replace(/([^a-zA-Z])ExpansionPanel/gm, '$1Accordion'); }
6,508
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/expansion-panel-component.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './expansion-panel-component'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('expansion-panel-component', () => { it('transforms as needed', () => { const actual = transform( { source: read('./expansion-panel-component.test/actual.js'), path: require.resolve('./expansion-panel-component.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./expansion-panel-component.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./expansion-panel-component.test/expected.js'), path: require.resolve('./expansion-panel-component.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./expansion-panel-component.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,509
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/fab-variant.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; const source = j(file.source) .findJSXElements('Fab') .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if (node.type === 'JSXAttribute' && node.name.name === 'variant') { if (node.value.value === 'round' || node.value.expression?.value === 'round') { node.value = j.literal('circular'); } } if (node.type === 'JSXAttribute' && node.name.name === 'classes') { (node.value?.expression?.properties || []).forEach((subNode) => { if (subNode.key.name === 'round') { subNode.key.name = 'circular'; } }); } }); }) .toSource(printOptions); return source.replace(/\.MuiFab-round/gm, '.MuiFab-circular'); }
6,510
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/fab-variant.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './fab-variant'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('fab-variant', () => { it('transforms as needed', () => { const actual = transform( { source: read('./fab-variant.test/actual.js'), path: require.resolve('./fab-variant.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./fab-variant.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./fab-variant.test/expected.js'), path: require.resolve('./fab-variant.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./fab-variant.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,511
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/fade-rename-alpha.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', }; let importFound = false; root.find(j.ImportDeclaration).forEach((path) => { if (path.node.source.value.match(/^@material-ui\/core\/?(styles)?$/)) { path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportSpecifier' && specifier.imported.name === 'fade') { specifier.imported = j.identifier('alpha'); importFound = true; } }); } }); if (importFound) { return root .find(j.CallExpression, { callee: { name: 'fade' } }) .forEach((path) => { path.node.callee.name = 'alpha'; }) .toSource(printOptions); } return file.source; }
6,512
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/fade-rename-alpha.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './fade-rename-alpha'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('fade-rename-alpha', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./fade-rename-alpha.test/actual.js'), path: require.resolve('./fade-rename-alpha.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./fade-rename-alpha.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./fade-rename-alpha.test/expected.js'), path: require.resolve('./fade-rename-alpha.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./fade-rename-alpha.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should not modify local functions', () => { const actual = transform( { source: read('./fade-rename-alpha.test/unmodified.js'), path: require.resolve('./fade-rename-alpha.test/unmodified.js'), }, { jscodeshift }, {}, ); const expected = read('./fade-rename-alpha.test/unmodified.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,513
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/grid-justify-justifycontent.js
import renameProps from '../util/renameProps'; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; return renameProps({ root, componentName: 'Grid', props: { justify: 'justifyContent' }, }).toSource(printOptions); }
6,514
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/grid-justify-justifycontent.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './grid-justify-justifycontent'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('grid-justify-justifycontent', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./grid-justify-justifycontent.test/actual.js'), path: require.resolve('./grid-justify-justifycontent.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./grid-justify-justifycontent.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./grid-justify-justifycontent.test/expected.js'), path: require.resolve('./grid-justify-justifycontent.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./grid-justify-justifycontent.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,515
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/grid-list-component.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file) { return file.source .replace(/([^a-zA-Z])GridListTileBar/gm, '$1ImageListItemBar') .replace(/([^a-zA-Z])GridListTile/gm, '$1ImageListItem') .replace(/([^a-zA-Z])GridList/gm, '$1ImageList'); }
6,516
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/grid-list-component.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './grid-list-component'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('grid-list-component', () => { it('transforms MuiThemeProvider as needed', () => { const actual = transform( { source: read('./grid-list-component.test/actual.js'), path: require.resolve('./grid-list-component.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./grid-list-component.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./grid-list-component.test/expected.js'), path: require.resolve('./grid-list-component.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./grid-list-component.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,517
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/hidden-down-props.js
import renameProps from '../util/renameProps'; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; return renameProps({ root, componentName: 'Hidden', props: { xsDown: 'smDown', smDown: 'mdDown', mdDown: 'lgDown', lgDown: 'xlDown', xlDown: 'xlDown', }, }).toSource(printOptions); }
6,518
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/icon-button-size.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; return j(file.source) .findJSXElements('IconButton') .forEach((path) => { const hasSizeAttribute = path.node.openingElement.attributes.some((node) => { return node.type === 'JSXAttribute' && node.name.name === 'size'; }); if (!hasSizeAttribute) { path.node.openingElement.attributes.push( j.jsxAttribute(j.jsxIdentifier('size'), j.literal('large')), ); } }) .toSource(printOptions); }
6,519
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/icon-button-size.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './icon-button-size'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('icon-button-size', () => { it('transforms as needed', () => { const actual = transform( { source: read('./icon-button-size.test/actual.js'), path: require.resolve('./icon-button-size.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./icon-button-size.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./icon-button-size.test/expected.js'), path: require.resolve('./icon-button-size.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./icon-button-size.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,520
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-avatar-remove-imgProps.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; root .find(j.ImportDeclaration) .filter(({ node }) => { const sourceVal = node.source.value; return [ '@mui/joy', // Process only Joy UI components '@mui/joy/Avatar', // Filter default imports of components other than `Avatar` ].includes(sourceVal); }) .forEach((path) => { path.node.specifiers.forEach((elementNode) => { if ( (elementNode.type === 'ImportSpecifier' && elementNode.imported?.name === 'Avatar') || elementNode.type === 'ImportDefaultSpecifier' ) { // Process only Joy `Avatar` component root.findJSXElements(elementNode.local.name).forEach((elementPath) => { if (elementPath.node.type !== 'JSXElement') { return; } const slotPropsAttributeNode = elementPath.node.openingElement.attributes.find( (attributeNode) => attributeNode.type === 'JSXAttribute' && attributeNode.name.name === 'slotProps' && attributeNode.value.expression?.type === 'ObjectExpression', ); const newAttributeNodes = []; elementPath.node.openingElement.attributes.forEach((attributeNode) => { if (attributeNode.type !== 'JSXAttribute') { return; } if (attributeNode.name.name !== 'imgProps') { newAttributeNodes.push(attributeNode); return; } const val = attributeNode.value; if (!val?.expression) { return; } if (slotPropsAttributeNode) { const imgObjInSlotProps = slotPropsAttributeNode.value.expression.properties.find( (propNode) => propNode.key.name === 'img' && propNode.value.type === 'ObjectExpression', ); if (imgObjInSlotProps) { const newProperties = [ ...imgObjInSlotProps.value.properties, ...attributeNode.value.expression.properties, ]; imgObjInSlotProps.value.properties = newProperties; } else { slotPropsAttributeNode.value.expression.properties.push( j.objectProperty(j.identifier('img'), attributeNode.value), ); } } else { newAttributeNodes.push( j.jsxAttribute( j.jsxIdentifier('slotProps'), j.jsxExpressionContainer( j.objectExpression([ j.objectProperty(j.identifier('img'), attributeNode.value.expression), ]), ), ), ); } }); elementPath.node.openingElement.attributes = newAttributeNodes; }); } }); }); const transformed = root.findJSXElements(); return transformed.toSource(printOptions); }
6,521
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-avatar-remove-imgProps.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './joy-avatar-remove-imgProps'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('joy-avatar-remove-imgProps', () => { it('transforms `imgProps` prop to `slotProps.img`', () => { const actual = transform( { source: read('./joy-avatar-remove-imgProps.test/actual.js'), path: require.resolve('./joy-rename-components-to-slots.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./joy-avatar-remove-imgProps.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,522
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/root-ref.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source .replace(/\n?import.*core\/RootRef['"];?/gm, '') .replace(/\n?import {\s?RootRef\s?} from ['"]@material-ui\/core\/?['"];?/gm, '') .replace(/({.*)(RootRef,?)(.*})/gm, '$1$3') .replace(/<RootRef.*>/gm, '<>') .replace(/<\/RootRef>/gm, '</>'); }
6,523
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-rename-classname-prefix.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source.replace(/Joy([A-Z]+)/gm, 'Mui$1'); }
6,524
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-rename-classname-prefix.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './joy-rename-classname-prefix'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('joy-rename-classname-prefix', () => { it('transforms classname prefix from Joy to Mui', () => { const actual = transform( { source: read('./joy-rename-classname-prefix.test/actual.js'), path: require.resolve('./joy-rename-classname-prefix.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./joy-rename-classname-prefix.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,525
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-rename-components-to-slots.js
function transformComponentsProp(attributeNode) { attributeNode.name.name = 'slots'; const valueExpression = attributeNode.value.expression; if (valueExpression?.type !== 'ObjectExpression') { return; } valueExpression.properties.forEach((property) => { property.key.name = property.key.name[0].toLowerCase() + property.key.name.slice(1); if (property.shorthand) { property.shorthand = false; } }); } function transformComponentsPropsProp(attributeNode) { attributeNode.name.name = 'slotProps'; } /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; root .find(j.ImportDeclaration) .filter(({ node }) => { return node.source.value.startsWith('@mui/joy'); }) .forEach((path) => { path.node.specifiers.forEach((node) => { // Process only Joy UI components root.findJSXElements(node.local.name).forEach((elementPath) => { if (elementPath.node.type !== 'JSXElement') { return; } elementPath.node.openingElement.attributes.forEach((elementNode) => { if (elementNode.type !== 'JSXAttribute') { return; } switch (elementNode.name.name) { case 'components': transformComponentsProp(elementNode); break; case 'componentsProps': transformComponentsPropsProp(elementNode); break; default: } }); }); }); }); const transformed = root.findJSXElements(); return transformed.toSource(printOptions); }
6,526
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-rename-components-to-slots.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './joy-rename-components-to-slots'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('joy-rename-components-to-slots', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./joy-rename-components-to-slots.test/actual.js'), path: require.resolve('./joy-rename-components-to-slots.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./joy-rename-components-to-slots.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,527
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-rename-row-prop.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; root .find(j.ImportDeclaration) .filter(({ node }) => { return node.source.value.startsWith('@mui/joy'); }) .forEach((path) => { path.node.specifiers.forEach((node) => { // Process only Joy UI components root.findJSXElements(node.local.name).forEach((elementPath) => { if (elementPath.node.type !== 'JSXElement') { return; } elementPath.node.openingElement.attributes.forEach((attributeNode) => { if (attributeNode.type !== 'JSXAttribute') { return; } if (attributeNode.name.name === 'row') { const val = attributeNode.value; if (val === null || val?.expression?.value === true) { attributeNode.name.name = 'orientation'; attributeNode.value = j.jsxExpressionContainer(j.literal('horizontal')); } } }); }); }); }); const transformed = root.findJSXElements(); return transformed.toSource(printOptions); }
6,528
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-rename-row-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './joy-rename-row-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('joy-rename-row-prop', () => { it('transforms `row` prop to `orientation="horizontal"`', () => { const actual = transform( { source: read('./joy-rename-row-prop.test/actual.js'), path: require.resolve('./joy-rename-components-to-slots.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./joy-rename-row-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,529
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-text-field-to-input.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; root .find(j.ImportDeclaration) .filter(({ node }) => { const sourceVal = node.source.value; if (sourceVal === '@mui/joy/TextField') { node.source.value = '@mui/joy/Input'; } return [ '@mui/joy', // Process only Joy UI components '@mui/joy/TextField', // Filter default imports of components other than TextField ].includes(sourceVal); }) .forEach((path) => { path.node.specifiers.forEach((elementNode) => { if ( (elementNode.type === 'ImportSpecifier' && elementNode.imported?.name === 'TextField') || elementNode.type === 'ImportDefaultSpecifier' ) { if (elementNode.imported?.name === 'TextField') { elementNode.imported.name = 'Input'; } let newElementName; root.findJSXElements(elementNode.local.name).forEach((elementPath) => { if (elementPath.node.type !== 'JSXElement') { return; } newElementName = elementPath.node.openingElement.name.name.replace( /TextField/gm, 'Input', ); elementPath.node.openingElement.name.name = newElementName; const formControlAttributeNodes = []; const formLabelAttributeNodes = []; const formHelperTextAttributeNodes = []; const inputAttributeNodes = []; let formLabelValue; let formHelperTextValue; elementPath.node.openingElement.attributes.forEach((attributeNode) => { if (attributeNode.type !== 'JSXAttribute') { return; } const attributeName = attributeNode.name.name; switch (attributeName) { case 'size': case 'color': case 'required': formControlAttributeNodes.push(attributeNode); break; case 'slotProps': if (attributeNode.value.expression?.type === 'ObjectExpression') { attributeNode.value.expression.properties.forEach((propNode) => { if (propNode.value.type !== 'ObjectExpression') { return; } propNode.value.properties.forEach((prop) => { const key = prop.key.value; const newAttributeNode = j.jsxAttribute( j.jsxIdentifier(key), j.jsxExpressionContainer(prop.value), ); switch (propNode.key.name) { case 'root': formControlAttributeNodes.push(newAttributeNode); break; case 'label': formLabelAttributeNodes.push(newAttributeNode); break; case 'input': inputAttributeNodes.push(newAttributeNode); break; case 'helperText': formHelperTextAttributeNodes.push(newAttributeNode); break; default: } }); }); } break; case 'slots': if (attributeNode.value.expression?.type === 'ObjectExpression') { attributeNode.value.expression.properties.forEach((propNode) => { const newAttributeNode = j.jsxAttribute( j.jsxIdentifier('component'), j.jsxExpressionContainer(propNode.value), ); switch (propNode.key.name) { case 'root': formControlAttributeNodes.push(newAttributeNode); break; case 'label': formLabelAttributeNodes.push(newAttributeNode); break; case 'input': inputAttributeNodes.push(newAttributeNode); break; case 'helperText': formHelperTextAttributeNodes.push(newAttributeNode); break; default: } }); } break; case 'label': formLabelValue = attributeNode.value.value; break; case 'helperText': formHelperTextValue = attributeNode.value.value; break; case 'id': formControlAttributeNodes.push(attributeNode); formLabelAttributeNodes.push( j.jsxAttribute( j.jsxIdentifier('id'), j.literal(`${attributeNode.value.value}-label`), ), ); formHelperTextAttributeNodes.push( j.jsxAttribute( j.jsxIdentifier('id'), j.literal(`${attributeNode.value.value}-helper-text`), ), ); break; default: } if ( ![ 'size', 'color', 'slotProps', 'slots', 'label', 'helperText', 'id', 'required', ].includes(attributeName) ) { inputAttributeNodes.push(attributeNode); } }); elementPath.node.openingElement.attributes = inputAttributeNodes; if (formControlAttributeNodes.length > 0 || formLabelValue || formHelperTextValue) { const formControlIdentifier = j.jsxIdentifier('FormControl'); const childrenOfFormControl = []; if (formLabelValue) { const formLabelIdentifier = j.jsxIdentifier('FormLabel'); const formLabelElement = j.jsxElement( j.jsxOpeningElement(formLabelIdentifier, formLabelAttributeNodes), j.jsxClosingElement(formLabelIdentifier), [j.jsxText('\n'), j.jsxText(formLabelValue), j.jsxText('\n')], ); childrenOfFormControl.push(formLabelElement, j.jsxText('\n')); } childrenOfFormControl.push(elementPath.node, j.jsxText('\n')); if (formHelperTextValue) { const formHelperTextIdentifier = j.jsxIdentifier('FormHelperText'); const formHelperTextElement = j.jsxElement( j.jsxOpeningElement(formHelperTextIdentifier, formHelperTextAttributeNodes), j.jsxClosingElement(formHelperTextIdentifier), [j.jsxText('\n'), j.jsxText(formHelperTextValue), j.jsxText('\n')], ); childrenOfFormControl.push(formHelperTextElement); } elementPath.replace( j.jsxElement( j.jsxOpeningElement(formControlIdentifier, formControlAttributeNodes), j.jsxClosingElement(formControlIdentifier), [j.jsxText('\n'), ...childrenOfFormControl, j.jsxText('\n')], ), ); } }); if (newElementName) { elementNode.local.name = newElementName; } } }); }); const transformed = root.findJSXElements(); return transformed.toSource(printOptions); }
6,530
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/joy-text-field-to-input.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './joy-text-field-to-input'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('joy-text-field-to-input', () => { it('transform Joy TextField into Joy Input', () => { const actual = transform( { source: read('./joy-text-field-to-input.test/actual.js'), path: require.resolve('./joy-text-field-to-input.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./joy-text-field-to-input.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,531
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/jss-to-styled.js
const nodePath = require('path'); /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); /** * @param {string} filePath * @example computePrefixFromPath('/a/b/c/Anonymous.tsx') === 'Anonymous' * @example computePrefixFromPath('/a/b/c/Anonymous.server.tsx') === 'Anonymous' */ function computePrefixFromPath(filePath) { return nodePath.basename(filePath, nodePath.extname(filePath)).split('.')[0]; } /** * * @param {import('jscodeshift').CallExpression} withStylesCall */ function getPrefix(withStylesCall) { let prefix; // 1. check from withStylesFn if (withStylesCall && withStylesCall.arguments[1] && withStylesCall.arguments[1].properties) { const name = withStylesCall.arguments[1].properties.find((prop) => prop.key.name === 'name'); prefix = name.value.value; } if (!prefix) { // 2. check name from export default root.find(j.ExportDefaultDeclaration).forEach((path) => { prefix = path.node.declaration.name; }); } if (!prefix) { // 3. use name export that is Capitalize root.find(j.ExportNamedDeclaration).forEach((path) => { if (path.node.declaration.type !== 'VariableDeclaration') { return; } const name = path.node.declaration.declarations[0].id.name; if (!prefix && name.match(/^[A-Z]/)) { prefix = name; } }); } if (!prefix) { prefix = computePrefixFromPath(file.path); } return prefix; } function getFirstJsxName() { const matches = file.source.match(/<\/?(\w*)[\s\S]*?>/gm); if (matches) { const closingTag = matches.slice(-1)[0]; // Self closing tag if (closingTag.endsWith('/>') && closingTag !== '</>') { const end = closingTag.indexOf(' ') > 0 ? closingTag.indexOf(' ') : closingTag.length - 1; return closingTag.substring(1, end); } return closingTag.substring(2, closingTag.length - 1); } return null; } function getRootClassKeys() { const name = getFirstJsxName(); if (name) { const rootClassKeys = []; root .findJSXElements(name) .at(0) .forEach((path) => { const existingClassName = path.node.openingElement.attributes.find( (attr) => attr.name && attr.name.name === 'className', ); if (existingClassName) { if (existingClassName.value.type === 'StringLiteral') { // className="string" } if (existingClassName.value.type === 'JSXExpressionContainer') { if (existingClassName.value.expression.type === 'StringLiteral') { // className={'string'} } if (existingClassName.value.expression.type === 'MemberExpression') { // className={classes.root} if (existingClassName.value.expression.object.name === 'classes') { rootClassKeys.push(existingClassName.value.expression.property.name); } } if (existingClassName.value.expression.type === 'CallExpression') { // className={clsx(classes.root)} existingClassName.value.expression.arguments.forEach((arg) => { if (arg.type === 'MemberExpression') { if (arg.object.name === 'classes') { rootClassKeys.push(arg.property.name); } } if (arg.type === 'ObjectExpression') { arg.properties.forEach((prop) => { if (prop.key.object && prop.key.object.name === 'classes') { rootClassKeys.push(prop.key.property.name); } }); } }); } } } }); return rootClassKeys; } return []; } function isTagNameFragment(tagName) { return tagName === 'React.Fragment' || tagName === 'Fragment' || tagName === ''; } function isTagNameSuspense(tagName) { return tagName === 'React.Suspense' || tagName === 'Suspense'; } function createStyledComponent(componentName, styledComponentName, stylesFn) { let styleArg = null; const rootIsFragment = isTagNameFragment(componentName); if (rootIsFragment) { // The root is React.Fragment styleArg = j.stringLiteral('div'); } else if (componentName.match(/^[A-Z]/)) { // The root is a component styleArg = j.identifier(componentName); } else { styleArg = j.stringLiteral(componentName); } const declaration = j.variableDeclaration('const', [ j.variableDeclarator( j.identifier(styledComponentName), j.callExpression(j.callExpression(j.identifier('styled'), [styleArg]), [stylesFn]), ), ]); if (rootIsFragment) { declaration.comments = [ j.commentLine( ' TODO jss-to-styled codemod: The Fragment root was replaced by div. Change the tag if needed.', ), ]; } return declaration; } const classesCount = {}; /** * * @param {import('jscodeshift').ObjectExpression} objExpression * @param {import('jscodeshift').ObjectExpression} prevObj */ function createClasses(objExpression, prevObj) { const classes = prevObj || j.objectExpression([]); objExpression.properties.forEach((prop) => { if (!classesCount[prop.key.name]) { classesCount[prop.key.name] = 1; } else { classesCount[prop.key.name] += 1; } const resolvedKey = classesCount[prop.key.name] === 1 ? prop.key.name : `${prop.key.name}${classesCount[prop.key.name]}`; classes.properties.push( j.objectProperty( j.identifier(resolvedKey), j.templateLiteral( [ j.templateElement({ raw: '', cooked: '' }, false), j.templateElement({ raw: `-${resolvedKey}`, cooked: `-${resolvedKey}` }, true), ], [j.identifier('PREFIX')], ), ), ); }); return classes; } /** * * @param {import('jscodeshift').ArrowFunctionExpression | import('jscodeshift').FunctionDeclaration} functionExpression */ function getReturnStatement(functionExpression) { if (functionExpression.type === 'ObjectExpression') { return functionExpression; } if (functionExpression.type === 'ArrowFunctionExpression') { if (functionExpression.body.type === 'BlockStatement') { const returnStatement = functionExpression.body.body.find( (b) => b.type === 'ReturnStatement', ); return returnStatement.argument; } if (functionExpression.body.type === 'ObjectExpression') { return functionExpression.body; } if (functionExpression.body.type === 'CallExpression') { if (functionExpression.body.callee.name === 'createStyles') { return functionExpression.body.arguments[0]; } } } if (functionExpression.type === 'FunctionDeclaration') { const returnStatement = functionExpression.body.body.find( (b) => b.type === 'ReturnStatement', ); return returnStatement.argument; } if (functionExpression.type === 'CallExpression') { if (functionExpression.callee.name === 'createStyles') { return functionExpression.arguments[0]; } } return null; } /** * @param {import('jscodeshift').ObjectExpression | import('jscodeshift').ArrowFunctionExpression | import('jscodeshift').FunctionDeclaration} expression */ function getObjectExpression(expression) { let objectExpression; if (expression.type === 'ObjectExpression') { objectExpression = expression; } if (expression.type === 'ArrowFunctionExpression') { if (expression.body.type === 'BlockStatement') { const returnStatement = expression.body.body.find((b) => b.type === 'ReturnStatement'); objectExpression = returnStatement.argument; } if (expression.body.type === 'ObjectExpression') { expression.body.extra.parenthesized = false; objectExpression = expression.body; } } if (expression.type === 'FunctionDeclaration') { expression.type = 'FunctionExpression'; const returnStatement = expression.body.body.find((b) => b.type === 'ReturnStatement'); objectExpression = returnStatement.argument; } return objectExpression; } const stylesCount = {}; /** * * @param {import('jscodeshift').ObjectExpression | import('jscodeshift').ArrowFunctionExpression | import('jscodeshift').FunctionDeclaration} functionExpression * @param {string[]} rootKeys * @param {import('jscodeshift').ObjectExpression | import('jscodeshift').ArrowFunctionExpression | import('jscodeshift').FunctionDeclaration} prevStyleArg */ function convertToStyledArg(functionExpression, rootKeys, prevStyleArg) { const objectExpression = getObjectExpression(functionExpression); if (objectExpression) { objectExpression.properties.forEach((prop) => { if (!stylesCount[prop.key.name]) { stylesCount[prop.key.name] = 1; } else { stylesCount[prop.key.name] += 1; } const resolvedKey = stylesCount[prop.key.name] === 1 ? prop.key.name : `${prop.key.name}${stylesCount[prop.key.name]}`; const selector = rootKeys.includes(resolvedKey) ? '&.' : '& .'; prop.key = j.templateLiteral( [ j.templateElement({ raw: selector, cooked: selector }, false), j.templateElement({ raw: '', cooked: '' }, true), ], [j.identifier(`classes.${resolvedKey}`)], ); prop.computed = true; return prop; }); } if (functionExpression.params) { functionExpression.params = functionExpression.params.map((param) => { if (param.type === 'ObjectPattern') { return j.objectPattern([j.objectProperty(j.identifier('theme'), param)]); } const prop = j.objectProperty(param, param); prop.shorthand = true; return j.objectPattern([prop]); }); } if (prevStyleArg) { const prevObjectExpression = getObjectExpression(prevStyleArg); if (objectExpression) { // merge object prevObjectExpression.properties = [ ...prevObjectExpression.properties, ...objectExpression.properties, ]; } if (functionExpression.params && prevStyleArg.type === 'ObjectExpression') { // turn prevStyleArg to ArrowFunction prevStyleArg = j.arrowFunctionExpression(functionExpression.params, prevStyleArg); } return prevStyleArg; } return functionExpression; } const printOptions = options.printOptions || { quote: 'single', }; /** * find withStyles, makeStyles arg variable * ex. withStyles(styles, options) * - styles: can be variable or () => { ... } * - options: { name } */ /** * get the styles ASP * - ArrowFunctionExpression * - FunctionDeclaration */ const withStylesCall = root.find(j.CallExpression, { callee: { name: 'withStyles' } }).nodes()[0]; const makeStylesCall = root.find(j.CallExpression, { callee: { name: 'makeStyles' } }).nodes()[0]; if (!withStylesCall && !makeStylesCall) { return file.source; } const rootJsxName = getFirstJsxName(); if (isTagNameSuspense(rootJsxName)) { return file.source; } const styledComponentName = rootJsxName.match(/^[A-Z]/) && !isTagNameFragment(rootJsxName) ? `Styled${rootJsxName}`.replace('.', '') : 'Root'; const prefix = getPrefix(withStylesCall || makeStylesCall); const rootClassKeys = getRootClassKeys(); const result = {}; const componentClassesCount = {}; const withStylesComponents = []; if (withStylesCall) { let stylesFnName; root.find(j.CallExpression, { callee: { name: 'withStyles' } }).forEach((path) => { const arg = path.node.arguments[0]; if (arg.type === 'Identifier') { stylesFnName = arg.name; } const objectExpression = getReturnStatement(arg); if (objectExpression) { // do this first, because objectExpression will be mutated in `createClasses` below. if (path.parent.parent && path.parent.parent.node.id) { // save withStylesComponent name, to add classes on JSX withStylesComponents.push({ variableName: path.parent.parent.node.id.name, classes: j.objectExpression( objectExpression.properties.map((prop) => { if (!componentClassesCount[prop.key.name]) { componentClassesCount[prop.key.name] = 1; } else { componentClassesCount[prop.key.name] += 1; } const resolvedKey = componentClassesCount[prop.key.name] === 1 ? prop.key.name : `${prop.key.name}${componentClassesCount[prop.key.name]}`; return j.property( 'init', j.identifier(prop.key.name), j.memberExpression(j.identifier('classes'), j.identifier(resolvedKey)), ); }), ), }); } result.classes = createClasses(objectExpression, result.classes); result.styledArg = convertToStyledArg(arg, rootClassKeys, result.styledArg); } }); root .find(j.VariableDeclarator, { id: { name: stylesFnName } }) .forEach((path) => { let fnArg = path.node.init; const objectExpression = getReturnStatement(fnArg); if (fnArg.type === 'ArrowFunctionExpression') { if (fnArg.body.type === 'CallExpression') { if (fnArg.body.callee.name === 'createStyles') { fnArg.body = fnArg.body.arguments[0]; } } } if (fnArg.type === 'CallExpression') { if (fnArg.callee.name === 'createStyles') { fnArg = fnArg.arguments[0]; } } if (objectExpression) { result.classes = createClasses(objectExpression, result.classes); result.styledArg = convertToStyledArg(fnArg, rootClassKeys); } }) .remove(); root .find(j.FunctionDeclaration, { id: { name: stylesFnName } }) .forEach((path) => { const returnStatement = path.node.body.body.find((b) => b.type === 'ReturnStatement'); result.classes = createClasses(returnStatement.argument, result.classes); result.styledArg = convertToStyledArg(path.node, rootClassKeys); }) .remove(); } if (makeStylesCall) { let stylesFnName; root .find(j.CallExpression, { callee: { name: 'makeStyles' } }) .at(0) .forEach((path) => { let arg = path.node.arguments[0]; if (arg.type === 'Identifier') { stylesFnName = arg.name; } const objectExpression = getReturnStatement(arg); if (arg.type === 'ArrowFunctionExpression') { if (arg.body.type === 'CallExpression') { if (arg.body.callee.name === 'createStyles') { arg.body = arg.body.arguments[0]; } } } if (arg.type === 'CallExpression') { if (arg.callee.name === 'createStyles') { arg = arg.arguments[0]; } } if (objectExpression) { result.classes = createClasses(objectExpression, result.classes); result.styledArg = convertToStyledArg(arg, rootClassKeys); } }); root .find(j.VariableDeclarator, { id: { name: stylesFnName } }) .at(0) .forEach((path) => { const objectExpression = getReturnStatement(path.node.init); if (objectExpression) { result.classes = createClasses(objectExpression, result.classes); result.styledArg = convertToStyledArg(path.node.init, rootClassKeys); } }) .remove(); root .find(j.FunctionDeclaration, { id: { name: stylesFnName } }) .at(0) .forEach((path) => { const returnStatement = path.node.body.body.find((b) => b.type === 'ReturnStatement'); result.classes = createClasses(returnStatement.argument, result.classes); result.styledArg = convertToStyledArg(path.node, rootClassKeys); }) .remove(); root .find(j.VariableDeclaration) .filter((path) => path.node.declarations.some((d) => d.id.name === 'useStyles')) .remove(); } /** * create `classes` * create styled `Root` */ root .find(j.ImportDeclaration) .at(-1) .forEach((path) => { path.insertAfter( j.variableDeclaration('const', [ j.variableDeclarator(j.identifier('PREFIX'), j.stringLiteral(prefix)), ]), j.variableDeclaration('const', [ j.variableDeclarator(j.identifier('classes'), result.classes), ]), createStyledComponent(rootJsxName, styledComponentName, result.styledArg), ); }); function transformJsxRootToStyledComponent(path) { if (path.node.openingFragment) { path.node.type = 'JSXElement'; path.node.openingElement = { type: 'JSXOpeningElement', name: styledComponentName }; path.node.closingElement = { type: 'JSXClosingElement', name: styledComponentName }; } else if ( path.node.openingElement && path.node.openingElement.name && path.node.openingElement.name.name === undefined ) { path.node.openingElement.name = styledComponentName; if (path.node.closingElement) { path.node.closingElement.name = styledComponentName; } } else { path.node.openingElement.name.name = styledComponentName; if (path.node.closingElement) { path.node.closingElement.name.name = styledComponentName; } } } /** * apply <StyledComponent /> */ if (rootJsxName === '') { root.find(j.JSXFragment).at(0).forEach(transformJsxRootToStyledComponent); } else if (rootJsxName.indexOf('.') > 0) { let converted = false; root.find(j.JSXElement).forEach((path) => { if (!converted && path.node.openingElement.name.type === 'JSXMemberExpression') { const tagName = `${path.node.openingElement.name.object.name}.${path.node.openingElement.name.property.name}`; if (tagName === rootJsxName) { converted = true; transformJsxRootToStyledComponent(path); } } }); } else { root.findJSXElements(rootJsxName).at(0).forEach(transformJsxRootToStyledComponent); } /** * Attach classes to components created by withStyles * ex. const Button1 = withStyles(...)(Button) */ withStylesComponents.forEach((data) => { root.find(j.JSXOpeningElement, { name: { name: data.variableName } }).forEach((path) => { if (!path.node.attributes) { path.node.attributes = []; } path.node.attributes.push( j.jsxAttribute(j.jsxIdentifier('classes'), j.jsxExpressionContainer(data.classes)), ); }); }); /** * import styled if not exist */ const imports = root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/core\/styles$/)) .forEach(({ node }) => { const existed = node.specifiers.find((s) => s.imported.name === 'styled'); if (!existed) { node.specifiers.push(j.importSpecifier(j.identifier('styled'))); } }); if (!imports.size()) { root .find(j.ImportDeclaration) .at(0) .forEach((path) => path.insertAfter( j.importDeclaration( [j.importSpecifier(j.identifier('styled'))], j.literal('@mui/material/styles'), ), ), ); } /** * remove import */ root .find(j.ImportDeclaration) .filter((path) => path.node.source.value.match( /^(@material-ui|@mui)\/styles\/?(withStyles|makeStyles|createStyles)?$/, ), ) .forEach((path) => { path.node.specifiers = path.node.specifiers.filter( (s) => s.local.name !== 'withStyles' && s.local.name !== 'makeStyles' && s.local.name !== 'createStyles', ); }) .filter((path) => !path.node.specifiers.length) .remove(); /** * remove withStyles calls that create new component */ root.find(j.CallExpression, { callee: { name: 'withStyles' } }).forEach((path) => { if ( path.parent.parent.parent.node.type === 'VariableDeclaration' && path.parent.parent.parent.parent.node.type !== 'ExportNamedDeclaration' && path.parent.node.arguments[0].type === 'Identifier' ) { path.parent.parent.node.init = j.identifier(path.parent.node.arguments[0].name); } }); return root .toSource(printOptions) .replace(/withStyles\([^)]*\),?/gm, '') .replace(/([^=]{.*)classes[^.],?(.*})/gm, '$1$2') .replace(/^.*useStyles(.*);?/gm, ''); }
6,532
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/jss-to-styled.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './jss-to-styled'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('jss-to-styled', () => { it('falls back to the filename for naming', () => { const actual = transform( { source: read('./jss-to-styled.test/Anonymous.actual.js'), path: require.resolve('./jss-to-styled.test/Anonymous.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/Anonymous.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); describe('first', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/first.actual.js'), path: require.resolve('./jss-to-styled.test/first.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/first.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/first.expected.js'), path: require.resolve('./jss-to-styled.test/first.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/first.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('second', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/second.actual.js'), path: require.resolve('./jss-to-styled.test/second.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/second.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/second.expected.js'), path: require.resolve('./jss-to-styled.test/second.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/second.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('third', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/third.actual.js'), path: require.resolve('./jss-to-styled.test/third.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/third.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/third.expected.js'), path: require.resolve('./jss-to-styled.test/third.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/third.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('fourth', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/fourth.actual.js'), path: require.resolve('./jss-to-styled.test/fourth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/fourth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/fourth.expected.js'), path: require.resolve('./jss-to-styled.test/fourth.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/fourth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('fifth', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/fifth.actual.js'), path: require.resolve('./jss-to-styled.test/fifth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/fifth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/fifth.expected.js'), path: require.resolve('./jss-to-styled.test/fifth.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/fifth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('sixth', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/sixth.actual.js'), path: require.resolve('./jss-to-styled.test/sixth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/sixth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/sixth.expected.js'), path: require.resolve('./jss-to-styled.test/sixth.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/sixth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('seventh', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/seventh.actual.js'), path: require.resolve('./jss-to-styled.test/seventh.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/seventh.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/seventh.expected.js'), path: require.resolve('./jss-to-styled.test/seventh.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/seventh.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('with createStyles', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles.actual.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles.actual.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles.expected.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles.expected.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); describe('with createStyles on withStyles', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles1.actual.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles1.actual.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles1.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles1.expected.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles1.expected.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles1.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('with createStyles on withStyles directly', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles2.actual.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles2.actual.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles2.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles2.expected.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles2.expected.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles2.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('with createStyles directly', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles3.actual.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles3.actual.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles3.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/withCreateStyles3.expected.tsx'), path: require.resolve('./jss-to-styled.test/withCreateStyles3.expected.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/withCreateStyles3.expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('transforms React.Fragment', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/eighth.actual.js'), path: require.resolve('./jss-to-styled.test/eighth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/eighth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/eighth.expected.js'), path: require.resolve('./jss-to-styled.test/eighth.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/eighth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('transforms Fragment', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/nineth.actual.js'), path: require.resolve('./jss-to-styled.test/nineth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/nineth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/nineth.expected.js'), path: require.resolve('./jss-to-styled.test/nineth.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/nineth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('transforms <>', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/tenth.actual.js'), path: require.resolve('./jss-to-styled.test/tenth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/tenth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/tenth.expected.js'), path: require.resolve('./jss-to-styled.test/tenth.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/tenth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('transforms SomeNamespace.SomeComponent', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/eleventh.actual.js'), path: require.resolve('./jss-to-styled.test/eleventh.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/eleventh.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/eleventh.expected.js'), path: require.resolve('./jss-to-styled.test/eleventh.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/eleventh.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('does not transform React.Suspense', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/twelfth.actual.js'), path: require.resolve('./jss-to-styled.test/twelfth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/twelfth.actual.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/twelfth.actual.js'), path: require.resolve('./jss-to-styled.test/twelfth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/twelfth.actual.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('bugs - #28317 export function declaration', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/exportFunction.actual.js'), path: require.resolve('./jss-to-styled.test/exportFunction.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/exportFunction.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/exportFunction.expected.js'), path: require.resolve('./jss-to-styled.test/exportFunction.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/exportFunction.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('bugs - #28317 export class declaration', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/exportClass.actual.js'), path: require.resolve('./jss-to-styled.test/exportClass.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/exportClass.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/exportClass.expected.js'), path: require.resolve('./jss-to-styled.test/exportClass.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/exportClass.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); describe('bugs - #29363 multiple makeStyles with the same classKeys', () => { it('transforms as needed', () => { const actual = transform( { source: read('./jss-to-styled.test/multipleWithStyles.actual.js'), path: require.resolve('./jss-to-styled.test/multipleWithStyles.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/multipleWithStyles.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-styled.test/multipleWithStyles.expected.js'), path: require.resolve('./jss-to-styled.test/multipleWithStyles.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-styled.test/multipleWithStyles.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,533
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/jss-to-tss-react.js
const ruleEndRegEx = /[^a-zA-Z0-9_]+/; function transformNestedKeys(j, comments, propValueNode, ruleRegEx, nestedKeys) { propValueNode.properties.forEach((prop) => { if (prop.value?.type === 'ObjectExpression') { if (typeof prop.key.value === 'string' && ruleRegEx !== null) { let ruleIndex = prop.key.value.search(ruleRegEx); let searchStartIndex = 0; const elements = []; const identifiers = []; while (ruleIndex >= 0) { const valueStartingAtRuleName = prop.key.value.substring(ruleIndex + 1); const ruleEndIndex = valueStartingAtRuleName.search(ruleEndRegEx); const ruleName = ruleEndIndex >= 0 ? prop.key.value.substring(ruleIndex + 1, ruleIndex + 1 + ruleEndIndex) : valueStartingAtRuleName; if (!nestedKeys.includes(ruleName)) { nestedKeys.push(ruleName); } const before = prop.key.value.substring(searchStartIndex, ruleIndex); elements.push(j.templateElement({ raw: `${before}.`, cooked: `${before}.` }, false)); identifiers.push(j.identifier(`classes.${ruleName}`)); searchStartIndex = ruleIndex + ruleName.length + 1; const after = prop.key.value.substring(searchStartIndex); ruleIndex = after.search(ruleRegEx); if (ruleIndex >= 0) { ruleIndex += searchStartIndex; } else { elements.push(j.templateElement({ raw: after, cooked: after }, false)); } } if (identifiers.length > 0) { prop.key = j.templateLiteral(elements, identifiers); prop.computed = true; } } transformNestedKeys(j, comments, prop.value, ruleRegEx, nestedKeys); } else if (prop.value?.type === 'ArrowFunctionExpression') { comments.push( j.commentLine( ' TODO jss-to-tss-react codemod: Unable to handle style definition reliably. ArrowFunctionExpression in CSS prop.', true, ), ); } }); } function transformStylesExpression(j, comments, stylesExpression, nestedKeys, setStylesExpression) { const ruleNames = []; const paramNames = []; let objectExpression; if (stylesExpression.type === 'ObjectExpression') { objectExpression = stylesExpression; } else if (stylesExpression.type === 'ArrowFunctionExpression') { if (stylesExpression.body.type === 'BlockStatement') { const returnStatement = stylesExpression.body.body.find((b) => b.type === 'ReturnStatement'); if (returnStatement.argument.type === 'ObjectExpression') { objectExpression = returnStatement.argument; } } else if (stylesExpression.body.type === 'ObjectExpression') { objectExpression = stylesExpression.body; } } if (objectExpression !== undefined) { objectExpression.properties.forEach((prop) => { if (prop.key?.name) { ruleNames.push(prop.key.name); } else if (prop.key?.value === '@global') { comments.push( j.commentLine( ` TODO jss-to-tss-react codemod: '@global' is not supported by tss-react.`, true, ), ); comments.push( j.commentLine( ` See https://mui.com/material-ui/customization/how-to-customize/#4-global-css-override for alternatives.`, true, ), ); } }); let ruleRegExString = '('; ruleNames.forEach((ruleName, index) => { if (index > 0) { ruleRegExString += '|'; } ruleRegExString += `\\$${ruleName}`; }); ruleRegExString += ')'; const ruleRegEx = ruleNames.length === 0 ? null : new RegExp(ruleRegExString, 'g'); objectExpression.properties.forEach((prop) => { if (prop.value) { if (prop.value.type !== 'ObjectExpression') { if ( prop.value.type === 'ArrowFunctionExpression' && prop.value.body.type === 'ObjectExpression' && prop.value.params[0].type === 'ObjectPattern' ) { prop.value.params[0].properties.forEach((property) => { const name = property.key.name; if (!paramNames.includes(name)) { paramNames.push(name); } }); prop.value = prop.value.body; } else { let extraComment = `Unexpected value type of ${prop.value.type}.`; if (prop.value.type === 'ArrowFunctionExpression') { if (prop.value.body.type === 'ObjectExpression') { let example = ''; if (prop.value.params[0].type === 'Identifier') { example = ' (e.g. `(props) => ({...})` instead of `({color}) => ({...})`)'; } extraComment = ` Arrow function has parameter type of ${prop.value.params[0].type} instead of ObjectPattern${example}.`; } else { extraComment = ` Arrow function has body type of ${prop.value.body.type} instead of ObjectExpression.`; } } comments.push( j.commentLine( ` TODO jss-to-tss-react codemod: Unable to handle style definition reliably. Unsupported arrow function syntax.`, true, ), ); comments.push(j.commentLine(extraComment, true)); return; } } transformNestedKeys(j, comments, prop.value, ruleRegEx, nestedKeys); } }); if (paramNames.length > 0 || nestedKeys.length > 0) { let arrowFunction; if (stylesExpression.type === 'ArrowFunctionExpression') { arrowFunction = stylesExpression; } else { arrowFunction = j.arrowFunctionExpression([], objectExpression); setStylesExpression(arrowFunction); } if (arrowFunction.params.length === 0) { arrowFunction.params.push(j.identifier('_theme')); } let paramsString = '_params'; if (paramNames.length > 0) { paramsString = `{ ${paramNames.join(', ')} }`; } arrowFunction.params.push(j.identifier(paramsString)); if (nestedKeys.length > 0) { arrowFunction.params.push(j.identifier('classes')); } if (arrowFunction.body.type === 'ObjectExpression') { // In some cases, some needed parentheses were being lost without this. arrowFunction.body = j.parenthesizedExpression(objectExpression); } } } } function addCommentsToNode(node, commentsToAdd, addToBeginning = false) { if (!node.comments) { node.comments = []; } if (addToBeginning) { node.comments.unshift(...commentsToAdd); } else { node.comments.push(...commentsToAdd); } } function addCommentsToDeclaration(declaration, commentsToAdd) { let commentsPath = declaration; if (declaration.parentPath.node.type === 'ExportNamedDeclaration') { commentsPath = declaration.parentPath; } addCommentsToNode(commentsPath.node, commentsToAdd); } function addCommentsToClosestDeclaration(j, path, commentsToAdd) { j(path) .closest(j.VariableDeclaration) .forEach((declaration) => { addCommentsToDeclaration(declaration, commentsToAdd); }); } function getFirstNode(j, root) { return root.find(j.Program).get('body', 0).node; } /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single' }; const originalFirstNode = getFirstNode(j, root); let importsChanged = false; let foundCreateStyles = false; let foundMakeStyles = false; let foundWithStyles = false; /** * transform imports */ root.find(j.ImportDeclaration).forEach((path) => { const importSource = path.node.source.value; const originalComments = path.node.comments; if ( importSource === '@material-ui/core/styles' || importSource === '@material-ui/core' || importSource === '@mui/styles' ) { const specifiersToMove = []; const specifiersToStay = []; path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportSpecifier') { if (specifier.imported.name === 'makeStyles') { foundMakeStyles = true; specifiersToMove.push(specifier); } else if (specifier.imported.name === 'withStyles') { foundWithStyles = true; specifiersToMove.push(specifier); } else if (specifier.imported.name === 'createStyles') { foundCreateStyles = true; } else { specifiersToStay.push(specifier); } } }); if (specifiersToMove.length > 0) { path.replace( j.importDeclaration(specifiersToMove, j.stringLiteral('tss-react/mui')), specifiersToStay.length > 0 ? j.importDeclaration(specifiersToStay, j.stringLiteral(importSource)) : undefined, ); importsChanged = true; } } else if ( importSource === '@material-ui/styles/makeStyles' || importSource === '@mui/styles/makeStyles' ) { foundMakeStyles = true; path.replace( j.importDeclaration( [j.importSpecifier(j.identifier('makeStyles'))], j.stringLiteral('tss-react/mui'), ), ); importsChanged = true; } else if ( importSource === '@material-ui/styles/withStyles' || importSource === '@mui/styles/withStyles' ) { foundWithStyles = true; path.replace( j.importDeclaration( [j.importSpecifier(j.identifier('withStyles'))], j.stringLiteral('tss-react/mui'), ), ); importsChanged = true; } path.node.comments = originalComments; }); if (!importsChanged) { return file.source; } const isTypeScript = file.path.endsWith('.tsx') || file.path.endsWith('.ts'); if (foundMakeStyles) { let clsxOrClassnamesName = null; root.find(j.ImportDeclaration).forEach((path) => { const importSource = path.node.source.value; if (importSource === 'clsx' || importSource === 'classnames') { path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportDefaultSpecifier') { clsxOrClassnamesName = specifier.local.name; } }); let commentsToPreserve = null; if (originalFirstNode === path.node) { // For a removed import, only preserve the comments if it is the first node in the file, // otherwise the comments are probably about the removed import and no longer relevant. commentsToPreserve = path.node.comments; } j(path).remove(); if (commentsToPreserve) { addCommentsToNode(getFirstNode(j, root), commentsToPreserve, true); } } }); /** * Convert makeStyles syntax */ const styleHooks = []; root .find(j.CallExpression, { callee: { name: 'makeStyles' } }) .forEach((path) => { let paramsTypes = null; if (foundCreateStyles) { j(path) .find(j.CallExpression, { callee: { name: 'createStyles' } }) .replaceWith((createStylesPath) => { if ( isTypeScript && createStylesPath.node.typeParameters && createStylesPath.node.typeParameters.params.length > 1 ) { paramsTypes = createStylesPath.node.typeParameters.params[1]; } return createStylesPath.node.arguments[0]; }); } const nestedKeys = []; let makeStylesOptions = null; if (path.node.arguments.length > 1) { makeStylesOptions = path.node.arguments[1]; } let stylesExpression = path.node.arguments[0]; const commentsToAdd = []; transformStylesExpression( j, commentsToAdd, path.node.arguments[0], nestedKeys, (newStylesExpression) => { stylesExpression = newStylesExpression; }, ); addCommentsToClosestDeclaration(j, path, commentsToAdd); let makeStylesIdentifier = 'makeStyles'; if (isTypeScript && (nestedKeys.length > 0 || paramsTypes !== null)) { let paramsTypeString = 'void'; if (paramsTypes !== null) { paramsTypeString = j(paramsTypes).toSource(printOptions); } let nestedKeysString = ''; if (nestedKeys.length > 0) { const nestedKeysUnion = nestedKeys.join("' | '"); nestedKeysString = `, '${nestedKeysUnion}'`; } makeStylesIdentifier += `<${paramsTypeString}${nestedKeysString}>`; } j(path).replaceWith( j.callExpression( j.callExpression( j.identifier(makeStylesIdentifier), makeStylesOptions === null ? [] : [makeStylesOptions], ), [stylesExpression], ), ); }) .closest(j.VariableDeclarator) .forEach((path) => { styleHooks.push(path.node.id.name); j(path) .closest(j.ExportNamedDeclaration) .forEach(() => { const comments = [ j.commentLine( ` TODO jss-to-tss-react codemod: usages of this hook outside of this file will not be converted.`, true, ), ]; addCommentsToClosestDeclaration(j, path, comments); }); }); /** * Convert classes assignment syntax in calls to the hook (e.g. useStyles) and * convert usages of clsx or classnames to cx. */ styleHooks.forEach((hookName) => { root .find(j.CallExpression, { callee: { name: hookName } }) .forEach((hookCall) => { if (hookCall.node.arguments.length === 1) { const hookArg = hookCall.node.arguments[0]; if (hookArg.type === 'Identifier') { const secondArg = j.objectExpression([]); secondArg.properties.push( j.objectProperty(j.identifier('props'), j.identifier(hookArg.name)), ); hookCall.node.arguments.push(secondArg); } else if (hookArg.properties) { const hookArgPropsMinusClasses = []; let classesProp = null; hookArg.properties.forEach((hookProp) => { if (hookProp.key.name === 'classes') { classesProp = hookProp; } else { hookArgPropsMinusClasses.push(hookProp); } }); if (classesProp !== null) { if (hookArgPropsMinusClasses.length === 0) { hookCall.node.arguments[0] = j.identifier('undefined'); } else { hookArg.properties = hookArgPropsMinusClasses; } const secondArg = j.objectExpression([]); secondArg.properties.push( j.objectProperty( j.identifier('props'), j.objectExpression([ j.objectProperty(j.identifier('classes'), classesProp.value), ]), ), ); hookCall.node.arguments.push(secondArg); } } } }) .closest(j.VariableDeclarator) .forEach((path) => { let foundClsxOrClassnamesUsage = false; const classesName = path.node.id.name; const classesAssign = classesName === 'classes' ? 'classes' : `classes: ${classesName}`; if (clsxOrClassnamesName !== null) { j(path) .closestScope() .find(j.CallExpression, { callee: { name: clsxOrClassnamesName } }) .forEach((callPath) => { callPath.node.callee.name = 'cx'; foundClsxOrClassnamesUsage = true; }); } if (foundClsxOrClassnamesUsage) { path.node.id.name = `{ ${classesAssign}, cx }`; } else { path.node.id.name = `{ ${classesAssign} }`; } }); root.find(j.ExportDefaultDeclaration, { declaration: { name: hookName } }).forEach((path) => { const comments = [ j.commentLine( ` TODO jss-to-tss-react codemod: usages of this hook outside of this file will not be converted.`, true, ), ]; addCommentsToDeclaration(path, comments); }); }); } if (foundWithStyles) { /** * Convert withStyles syntax */ const styleVariables = []; root .find(j.CallExpression, { callee: { type: 'CallExpression', callee: { name: 'withStyles' } }, }) .replaceWith((path) => { const withStylesCall = path.node.callee; const styles = path.node.callee.arguments[0]; if (styles.type === 'Identifier') { styleVariables.push(styles.name); } else { const nestedKeys = []; const commentsToAdd = []; transformStylesExpression(j, commentsToAdd, styles, nestedKeys, (newStylesExpression) => { path.node.callee.arguments[0] = newStylesExpression; }); addCommentsToClosestDeclaration(j, path, commentsToAdd); } const component = path.node.arguments[0]; withStylesCall.arguments.unshift(component); return withStylesCall; }); styleVariables.forEach((styleVar) => { root.find(j.VariableDeclarator, { id: { name: styleVar } }).forEach((path) => { const nestedKeys = []; const commentsToAdd = []; transformStylesExpression( j, commentsToAdd, path.node.init, nestedKeys, (newStylesExpression) => { path.node.init = newStylesExpression; }, ); addCommentsToClosestDeclaration(j, path, commentsToAdd); }); }); } return root.toSource(printOptions); }
6,534
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/jss-to-tss-react.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshiftWithDefaultParser from 'jscodeshift'; import transform from './jss-to-tss-react'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } const jscodeshift = jscodeshiftWithDefaultParser.withParser('tsx'); describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('jss-to-tss-react', () => { it('transforms @material-ui/core/styles makeStyles to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-from-material-ui-core-styles.js'), path: require.resolve('./jss-to-tss-react.test/actual-from-material-ui-core-styles.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-from-material-ui-core-styles.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./jss-to-tss-react.test/expected-from-material-ui-core-styles.js'), path: require.resolve( './jss-to-tss-react.test/expected-from-material-ui-core-styles.js', ), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-from-material-ui-core-styles.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms @material-ui/core makeStyles to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-from-material-ui-core.js'), path: require.resolve('./jss-to-tss-react.test/actual-from-material-ui-core.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-from-material-ui-core.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('adds todo comments for scenarios that are not supported', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-todo-comments.js'), path: require.resolve('./jss-to-tss-react.test/actual-todo-comments.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-todo-comments.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms makeStyles with style rules returned by function to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-mixins-pattern.js'), path: require.resolve('./jss-to-tss-react.test/actual-mixins-pattern.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-mixins-pattern.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms @mui/styles makeStyles to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-from-mui-styles.js'), path: require.resolve('./jss-to-tss-react.test/actual-from-mui-styles.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-from-mui-styles.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms @mui/styles/makeStyles to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-from-mui-styles-makeStyles.js'), path: require.resolve('./jss-to-tss-react.test/actual-from-mui-styles-makeStyles.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-from-mui-styles-makeStyles.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms typescript makeStyles with nested selectors to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-typescript.tsx'), path: require.resolve('./jss-to-tss-react.test/actual-typescript.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-typescript.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms typescript makeStyles example in docs to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-typescript-docs-example.tsx'), path: require.resolve('./jss-to-tss-react.test/actual-typescript-docs-example.tsx'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-typescript-docs-example.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms typescript makeStyles advanced example in docs with params to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-typescript-docs-example-params.tsx'), path: require.resolve( './jss-to-tss-react.test/actual-typescript-docs-example-params.tsx', ), }, { jscodeshift }, {}, ); const expected = read( './jss-to-tss-react.test/expected-typescript-docs-example-params.tsx', ); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms withStyles to use tss-react', () => { const actual = transform( { source: read('./jss-to-tss-react.test/actual-withStyles.js'), path: require.resolve('./jss-to-tss-react.test/actual-withStyles.js'), }, { jscodeshift }, {}, ); const expected = read('./jss-to-tss-react.test/expected-withStyles.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,535
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/link-underline-hover.js
export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; const jsxLinkNames = []; /** * find Link import name */ root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^(@material-ui\/core|@mui\/material)\/Link/)) .forEach(({ node }) => { node.specifiers.forEach((s) => { if (s.type === 'ImportDefaultSpecifier') { jsxLinkNames.push(s.local.name); node.source.value = node.source.value.replace('@material-ui/core', '@mui/material'); } }); }); root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^(@material-ui\/core|@mui\/material)\/?$/)) .forEach(({ node }) => { node.specifiers.forEach((s) => { if (s.imported.name === 'Link') { jsxLinkNames.push(s.local.name); node.source.value = node.source.value.replace('@material-ui/core', '@mui/material'); } }); }); jsxLinkNames.forEach((name) => { root.findJSXElements(name).forEach(({ node }) => { const hasUnderlineProp = node.openingElement.attributes.find( (attr) => attr?.name?.name === 'underline', ); if (!hasUnderlineProp) { node.openingElement.attributes.push( j.jsxAttribute(j.jsxIdentifier('underline'), j.literal('hover')), ); } }); }); return root.toSource(printOptions); }
6,536
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/link-underline-hover.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './link-underline-hover'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('link-underline-hover', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./link-underline-hover.test/actual.js'), path: require.resolve('./link-underline-hover.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./link-underline-hover.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./link-underline-hover.test/expected.js'), path: require.resolve('./link-underline-hover.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./link-underline-hover.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,537
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/material-ui-styles.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const printOptions = options.printOptions || { quote: 'single' }; const j = api.jscodeshift; const root = j(file.source); const list = [ 'createGenerateClassName', 'createStyles', 'jssPreset', 'makeStyles', 'ServerStyleSheets', 'useThemeVariants', 'withStyles', 'withTheme', 'getStylesCreator', 'mergeClasses', 'StylesProvider', ]; const types = [ 'GenerateClassNameOptions', 'StyleRules', 'StyleRulesCallback', 'Styles', 'ClassNameMap', 'WithStylesOptions', 'WithStyles', 'StyledComponentProps', 'WithThemeCreatorOption', 'WithTheme', 'ThemedComponentProps', 'StylesCreator', 'Classes', 'MergeClassesOption', 'StylesOptions', 'StylesProviderProps', 'StylesContext', ]; const stylesPackage = '@material-ui/styles'; // https://github.com/facebook/jscodeshift/blob/master/recipes/retain-first-comment.md const getFirstNode = () => root.find(j.Program).get('body', 0).node; // Save the comments attached to the first node const firstNode = getFirstNode(); const { comments } = firstNode; root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/core\/?(styles)?$/)) .forEach((path) => { const importList = []; const typeList = []; const removedList = []; const specifiers = path.node.specifiers; specifiers.forEach(({ imported, local }, index) => { if (types.includes(imported.name)) { typeList.push({ imported, local }); removedList.push(index); } if (list.includes(imported.name)) { importList.push( j.importDeclaration( [j.importDefaultSpecifier(j.identifier(local.name))], j.literal(`${stylesPackage}/${imported.name}`), ), ); removedList.push(index); } }); /** * delete path.node.specifiers[index] cause empty item in array * use this approach until we find a better way */ path.node.specifiers = path.node.specifiers.filter( (_, index) => !removedList.includes(index), ); path.insertAfter(...importList); if (typeList.length) { const appendedSpecifiers = typeList.map(({ imported, local }) => j.importSpecifier(imported, local), ); const muiStyles = root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/styles\/?$/)); if (muiStyles.size()) { muiStyles.forEach(({ node }) => { node.specifiers = [...node.specifiers, ...appendedSpecifiers]; }); } else { path.insertAfter(j.importDeclaration(appendedSpecifiers, j.literal(stylesPackage))); } } }) .filter((path) => !path.node.specifiers.length) .remove(); // If the first node has been modified or deleted, reattach the comments const firstNode2 = getFirstNode(); if (firstNode2 !== firstNode) { firstNode2.comments = comments; } return root.toSource(printOptions); }
6,538
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/material-ui-styles.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './material-ui-styles'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('material-ui-styles', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./material-ui-styles.test/actual.js'), path: require.resolve('./material-ui-styles.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-styles.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./material-ui-styles.test/expected.js'), path: require.resolve('./material-ui-styles.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-styles.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('remove no variable import', () => { const actual = transform( { source: read('./material-ui-styles.test/single-import.actual.js'), path: require.resolve('./material-ui-styles.test/single-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-styles.test/single-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transform core import', () => { const actual = transform( { source: read('./material-ui-styles.test/core-import.actual.js'), path: require.resolve('./material-ui-styles.test/core-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-styles.test/core-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transform types import', () => { const actual = transform( { source: read('./material-ui-styles.test/types-import.actual.js'), path: require.resolve('./material-ui-styles.test/types-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-styles.test/types-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,539
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/material-ui-types.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', }; let importName = ''; root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/types\/?$/)) .forEach((path) => { let previousVarName; path.node.specifiers.forEach((node) => { if (!node.imported && node.local.name === 'Omit') { // default specifier previousVarName = node.local.name; node.local.name = 'DistributiveOmit'; } if (node.imported && node.imported.name === 'Omit') { previousVarName = node.local.name; node.local = null; node.imported.name = 'DistributiveOmit'; } }); if (previousVarName) { importName = previousVarName; } }); const source = root.toSource(printOptions); if (importName) { return source.replace(/([^a-zA-Z])Omit</gm, '$1DistributiveOmit<'); } return source; }
6,540
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/material-ui-types.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './material-ui-types'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('material-ui-types', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./material-ui-types.test/actual.js'), path: require.resolve('./material-ui-types.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-types.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./material-ui-types.test/expected.js'), path: require.resolve('./material-ui-types.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./material-ui-types.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,541
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/modal-props.js
import { EOL } from 'os'; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; let hasDisableBackdropClick = false; let handleOnEscapeKeyDown = false; let source = j(file.source) .findJSXElements('Modal') .forEach((path) => { const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { if (node.type === 'JSXAttribute') { if (node.name.name === 'disableBackdropClick') { hasDisableBackdropClick = true; delete attributes[index]; } if (node.name.name === 'onEscapeKeyDown') { handleOnEscapeKeyDown = true; delete attributes[index]; } } }); }) .toSource(printOptions); if (hasDisableBackdropClick) { source = source.replace( /(<Modal)([\s\S]*>)/gm, `$1// You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#modal)${EOL}$2`, ); } if (hasDisableBackdropClick) { source = source.replace( /(<Modal)([\s\S]*>)/gm, `$1// \`disableBackdropClick\` is removed by codemod.${EOL}$2`, ); } if (handleOnEscapeKeyDown) { source = source.replace( /(<Modal)([\s\S]*>)/gm, `$1${EOL}// \`handleOnEscapeKeyDown\` is removed by codemod.${EOL}$2`, ); } return source; }
6,542
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/modal-props.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './modal-props'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('modal-props', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./modal-props.test/actual.js'), path: require.resolve('./modal-props.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./modal-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./modal-props.test/expected.js'), path: require.resolve('./modal-props.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./modal-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,543
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/moved-lab-modules.js
const movedLabModules = [ 'Alert', 'AlertTitle', 'Autocomplete', 'AvatarGroup', 'Pagination', 'Rating', 'Skeleton', 'SpeedDial', 'SpeedDialAction', 'SpeedDialIcon', 'ToggleButton', 'ToggleButtonGroup', ]; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions || { quote: 'single' }; return j(file.source) .find(j.ImportDeclaration) .forEach((path) => { const importSource = path.node.source.value; const subPackageImportMatch = importSource.match(/@material-ui\/lab\/(.*)/); if (subPackageImportMatch !== null) { const componentName = subPackageImportMatch[1]; if (movedLabModules.includes(componentName)) { /** * @type {import('jscodeshift').ASTPath} */ const sourcePath = path.get('source'); sourcePath.replace(j.stringLiteral(`@material-ui/core/${componentName}`)); } } else if (importSource === '@material-ui/lab') { // Sieve import specifiers into /core and /lab const labImportSpecifiers = []; const coreImportSpecifiers = []; path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportSpecifier') { if (movedLabModules.includes(specifier.imported.name)) { coreImportSpecifiers.push(specifier); } else { labImportSpecifiers.push(specifier); } } else { // `import Lab from '@material-ui/lab'` // `import * as Lab from '@material-ui/lab'` // These imports would require scope analysis. console.warn(`Can't handle ${specifier.type}`); } }); if (coreImportSpecifiers.length > 0) { path.replace( j.importDeclaration(coreImportSpecifiers, j.stringLiteral('@material-ui/core')), j.importDeclaration(labImportSpecifiers, j.stringLiteral('@material-ui/lab')), ); } } }) .toSource(printOptions); }
6,544
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/moved-lab-modules.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './moved-lab-modules'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('moved-lab-modules', () => { it('transforms exports as needed', () => { const actual = transform( { source: read('./moved-lab-modules.test/actual.js'), path: require.resolve('./moved-lab-modules.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./moved-lab-modules.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./moved-lab-modules.test/expected.js'), path: require.resolve('./moved-lab-modules.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./moved-lab-modules.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,545
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/mui-replace.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source .replace(/@material-ui\/unstyled/gm, '@mui/base') .replace(/@material-ui\/core/gm, '@mui/material') .replace(/@material-ui\/icons/gm, '@mui/icons-material') .replace(/@material-ui\/(?!(pickers|data-grid|x-grid))/gm, '@mui/'); }
6,546
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/mui-replace.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './mui-replace'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@material-ui/codemod', () => { describe('v5.0.0', () => { describe('mui-replace', () => { it('replace material-ui with mui', () => { const actual = transform( { source: read('./mui-replace.test/actual.js'), path: require.resolve('./mui-replace.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./mui-replace.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./mui-replace.test/expected.js'), path: require.resolve('./mui-replace.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./mui-replace.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,547
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/optimal-imports.js
import { dirname } from 'path'; import addImports from 'jscodeshift-add-imports'; import getJSExports from '../util/getJSExports'; // istanbul ignore next if (process.env.NODE_ENV === 'test') { const resolve = require.resolve; require.resolve = (source) => resolve( source .replace(/^@material-ui\/core\/es/, '../../../mui-material/src') .replace(/^@material-ui\/core\/modern/, '../../../mui-material/src'), ); } export default function transformer(fileInfo, api, options) { const j = api.jscodeshift; const importModule = options.importModule || '@material-ui/core'; const targetModule = options.targetModule || '@material-ui/core'; const printOptions = options.printOptions || { quote: 'single', trailingComma: true, }; const root = j(fileInfo.source); const importRegExp = new RegExp(`^${importModule}/([^/]+/)+([^/]+)$`); const resultSpecifiers = new Map(); const addSpecifier = (source, specifier) => { if (!resultSpecifiers.has(source)) { resultSpecifiers.set(source, []); } resultSpecifiers.get(source).push(specifier); }; root.find(j.ImportDeclaration).forEach((path) => { if (path.value.importKind && path.value.importKind !== 'value') { return; } const importPath = path.value.source.value.replace(/(index)?(\.js)?$/, ''); const match = importPath.match(importRegExp); if (!match) { return; } const subpath = match[1].replace(/\/$/, ''); if (/^(internal)/.test(subpath)) { return; } const targetImportPath = `${targetModule}/${subpath}`; let loader; try { loader = require.resolve(`${importModule}/modern/${subpath}`, { paths: [dirname(fileInfo.path)], }); } catch (error) { loader = require.resolve(`${importModule}/es/${subpath}`, { paths: [dirname(fileInfo.path)], }); } const whitelist = getJSExports(loader); path.node.specifiers.forEach((specifier, index) => { if (!path.node.specifiers.length) { return; } if (specifier.importKind && specifier.importKind !== 'value') { return; } if (specifier.type === 'ImportNamespaceSpecifier') { return; } const localName = specifier.local.name; switch (specifier.type) { case 'ImportNamespaceSpecifier': return; case 'ImportDefaultSpecifier': { const moduleName = match[2]; if (!whitelist.has(moduleName) && moduleName !== 'withStyles') { return; } addSpecifier( targetImportPath, j.importSpecifier(j.identifier(moduleName), j.identifier(localName)), ); path.get('specifiers', index).prune(); break; } case 'ImportSpecifier': if (!whitelist.has(specifier.imported.name)) { return; } addSpecifier(targetImportPath, specifier); path.get('specifiers', index).prune(); break; default: break; } }); if (!path.node.specifiers.length) { path.prune(); } }); addImports( root, [...resultSpecifiers.keys()].map((source) => j.importDeclaration(resultSpecifiers.get(source), j.stringLiteral(source)), ), ); return root.toSource(printOptions); }
6,548
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/optimal-imports.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './optimal-imports'; import readFile from '../util/readFile'; function trim(str) { return str ? str.replace(/^\s+|\s+$/, '') : ''; } function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('optimal-imports', () => { it('convert path as needed', () => { const actual = transform( { source: read('./optimal-imports.test/actual.js'), path: require.resolve('./optimal-imports.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./optimal-imports.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./optimal-imports.test/expected.js'), path: require.resolve('./optimal-imports.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./optimal-imports.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,549
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/pagination-round-circular.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; const source = j(file.source) .find(j.JSXElement) .filter(({ node }) => node.openingElement.name.name?.match(/^(Pagination|PaginationItem)$/)) .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if ( node.type === 'JSXAttribute' && node.name.name === 'shape' && (node.value.value === 'round' || node.value.expression?.value === 'round') ) { node.value = j.literal('circular'); } if (node.type === 'JSXAttribute' && node.name.name === 'classes') { (node.value?.expression?.properties || []).forEach((subNode) => { if (subNode.key.name === 'round') { subNode.key.name = 'circular'; } }); } }); }) .toSource(printOptions); return source.replace(/\.(MuiPagination|MuiPaginationItem)-round/gm, '.$1-circular'); }
6,550
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/pagination-round-circular.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './pagination-round-circular'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('pagination-round-circular', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./pagination-round-circular.test/actual.js'), path: require.resolve('./pagination-round-circular.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./pagination-round-circular.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./pagination-round-circular.test/expected.js'), path: require.resolve('./pagination-round-circular.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./pagination-round-circular.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,551
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/preset-safe.js
import transformAdapterV4 from './adapter-v4'; import transformAutocompleteRenaming from './autocomplete-rename-closeicon'; import transformAutocompleteOption from './autocomplete-rename-option'; import transformAvatarCircular from './avatar-circle-circular'; import transformBadgeOverlap from './badge-overlap-value'; import transformBoxBorderRadius from './box-borderradius-values'; import transformBoxRenameGap from './box-rename-gap'; import transformBoxRenameCss from './box-rename-css'; import transformButtonColorProp from './button-color-prop'; import transformChipVariantProp from './chip-variant-prop'; import transformCircularProgressVariant from './circularprogress-variant'; import transformCollapsedHeight from './collapse-rename-collapsedheight'; import transformCoreStylesImport from './core-styles-import'; import transformCreateTheme from './create-theme'; import transformDialogProps from './dialog-props'; import transformDialogTitleProps from './dialog-title-props'; import transformEmotionPrependCache from './emotion-prepend-cache'; import transformExpansionPanelComponent from './expansion-panel-component'; import transformFabVariant from './fab-variant'; import transformFade from './fade-rename-alpha'; import transformGridJustify from './grid-justify-justifycontent'; import transformGridListComponent from './grid-list-component'; import transformHiddenDownProps from './hidden-down-props'; import transformIconButtonSize from './icon-button-size'; import transformMuiStyles from './material-ui-styles'; import transformTypes from './material-ui-types'; import transformModalProps from './modal-props'; import transformMovedLabModules from './moved-lab-modules'; import transformPaginationRoundCircular from './pagination-round-circular'; import transformPrivateImports from './optimal-imports'; import transformRootRef from './root-ref'; import transformSkeletonVariant from './skeleton-variant'; import transformStyledEngineProvider from './styled-engine-provider'; import transformTableProps from './table-props'; import transformTabsScrollButtons from './tabs-scroll-buttons'; import transformTextareaMinMaxRows from './textarea-minmax-rows'; import transformThemeAugment from './theme-augment'; import transformThemeBreakpoints from './theme-breakpoints'; import transformThemeBreakpointsWidth from './theme-breakpoints-width'; import transformThemeOptions from './theme-options'; import transformThemePaletteMode from './theme-palette-mode'; import transformThemeProvider from './theme-provider'; import transformThemeSpacing from './theme-spacing'; import transformThemeTypographyRound from './theme-typography-round'; import transformTransitions from './transitions'; import transformUseTransitionProps from './use-transitionprops'; import transformWithMobileDialog from './with-mobile-dialog'; import transformWithWidth from './with-width'; import transformUseAutocomplete from './use-autocomplete'; import transformMuiReplace from './mui-replace'; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { file.source = transformAdapterV4(file, api, options); file.source = transformAutocompleteRenaming(file, api, options); file.source = transformAutocompleteOption(file, api, options); file.source = transformAvatarCircular(file, api, options); file.source = transformBadgeOverlap(file, api, options); file.source = transformBoxBorderRadius(file, api, options); file.source = transformBoxRenameGap(file, api, options); file.source = transformBoxRenameCss(file, api, options); file.source = transformButtonColorProp(file, api, options); file.source = transformChipVariantProp(file, api, options); file.source = transformCircularProgressVariant(file, api, options); file.source = transformCollapsedHeight(file, api, options); file.source = transformCoreStylesImport(file, api, options); file.source = transformCreateTheme(file, api, options); file.source = transformDialogProps(file, api, options); file.source = transformDialogTitleProps(file, api, options); file.source = transformEmotionPrependCache(file, api, options); file.source = transformExpansionPanelComponent(file, api, options); file.source = transformFabVariant(file, api, options); file.source = transformFade(file, api, options); file.source = transformGridJustify(file, api, options); file.source = transformGridListComponent(file, api, options); file.source = transformHiddenDownProps(file, api, options); file.source = transformIconButtonSize(file, api, options); file.source = transformMuiStyles(file, api, options); file.source = transformModalProps(file, api, options); file.source = transformMovedLabModules(file, api, options); file.source = transformPaginationRoundCircular(file, api, options); file.source = transformPrivateImports(file, api, options); file.source = transformRootRef(file, api, options); file.source = transformSkeletonVariant(file, api, options); file.source = transformStyledEngineProvider(file, api, options); file.source = transformTableProps(file, api, options); file.source = transformTabsScrollButtons(file, api, options); file.source = transformTextareaMinMaxRows(file, api, options); file.source = transformThemeAugment(file, api, options); file.source = transformThemeBreakpoints(file, api, options); file.source = transformThemeBreakpointsWidth(file, api, options); file.source = transformThemeOptions(file, api, options); file.source = transformThemePaletteMode(file, api, options); file.source = transformThemeProvider(file, api, options); file.source = transformThemeSpacing(file, api, options); file.source = transformThemeTypographyRound(file, api, options); file.source = transformTransitions(file, api, options); file.source = transformTypes(file, api, options); file.source = transformUseTransitionProps(file, api, options); file.source = transformWithMobileDialog(file, api, options); file.source = transformWithWidth(file, api, options); file.source = transformUseAutocomplete(file, api, options); // mui-replace should be the last file.source = transformMuiReplace(file, api, options); return file.source; }
6,552
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/preset-safe.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './preset-safe'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('preset-safe', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./preset-safe.test/actual.js'), path: require.resolve('./preset-safe.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./preset-safe.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./preset-safe.test/expected.js'), path: require.resolve('./preset-safe.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./preset-safe.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,553
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/rename-css-variables.js
const capitalize = (str) => { return str.charAt(0).toUpperCase() + str.slice(1); }; const JoyComponents = [ 'Alert', 'AspectRatio', 'Autocomplete', 'AutocompleteListbox', 'AutocompleteOption', 'Avatar', 'AvatarGroup', 'Badge', 'Box', 'Breadcrumbs', 'Button', 'Card', 'CardContent', 'CardCover', 'CardOverflow', 'Checkbox', 'Chip', 'ChipDelete', 'CircularProgress', 'Container', 'CssBaseline', 'Divider', 'FormControl', 'FormHelperText', 'FormLabel', 'Grid', 'IconButton', 'Input', 'LinearProgress', 'Link', 'List', 'ListDivider', 'ListItem', 'ListItemButton', 'ListItemContent', 'ListItemDecorator', 'ListSubheader', 'Menu', 'MenuItem', 'MenuList', 'Modal', 'ModalClose', 'ModalDialog', 'Option', 'Radio', 'RadioGroup', 'ScopedCssBaseline', 'Select', 'Sheet', 'Slider', 'Stack', 'SvgIcon', 'Switch', 'Tab', 'Table', 'TableCell', 'TabList', 'TabPanel', 'Tabs', 'Textarea', 'TextField', 'Tooltip', 'Typography', ]; /** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return ( file.source // from `--<Component>-<slot>-<property>` to `--<Component>-<slot><Property>` .replace( /--([a-zA-Z]+)([-_])([a-zA-Z]+)-([a-zA-Z]+)/gm, (matched, capture1, capture2, capture3, capture4) => { if ( !JoyComponents.includes(capture1) && !['internal', 'unstable', 'private'].includes(capture1) ) { return matched; } // turn `--List-item-...` and `--List-divider-...` to `--ListItem-...` and `--ListDivider-...` if (capture1 === 'List' && ['divider', 'item'].includes(capture3)) { return `--${capture1}${capitalize(capture3)}-${capture4}`; } // turn `--List-decorator-...` to `--ListItemDecorator-...` if (capture1 === 'List' && ['decorator'].includes(capture3)) { return `--${capture1}Item${capitalize(capture3)}-${capture4}`; } if (!JoyComponents.includes(capture3)) { return `--${capture1}${capture2}${capture3}${capitalize(capture4)}`; } return matched; }, ) .replace(/--List-decoratorSize/gm, '--ListItemDecorator-size') .replace(/--List-decoratorColor/gm, '--ListItemDecorator-color') // from `--internal-...` to `--unstable_...` .replace(/--internal-/gm, '--unstable_') // from `--private_...` to `--unstable_...` .replace(/--private_/gm, '--unstable_') ); }
6,554
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/rename-css-variables.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './rename-css-variables'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('rename-css-variables', () => { it('renames css variables based on the new rules', () => { const actual = transform( { source: read('./rename-css-variables.test/actual.js'), path: require.resolve('./rename-css-variables.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./rename-css-variables.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); it('should be idempotent', () => { const actual = transform( { source: read('./rename-css-variables.test/expected.js'), path: require.resolve('./rename-css-variables.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./rename-css-variables.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); });
6,555
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/root-ref.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './root-ref'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('root-ref', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./root-ref.test/actual.js'), path: require.resolve('./root-ref.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./root-ref.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./root-ref.test/expected.js'), path: require.resolve('./root-ref.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./root-ref.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,556
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/skeleton-variant.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions; const source = j(file.source) .findJSXElements('Skeleton') .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if (node.type === 'JSXAttribute' && node.name.name === 'variant') { if (node.value.value === 'circle' || node.value.expression?.value === 'circle') { node.value = j.literal('circular'); } if (node.value.value === 'rect' || node.value.expression?.value === 'rect') { node.value = j.literal('rectangular'); } } if (node.type === 'JSXAttribute' && node.name.name === 'classes') { node.value?.expression?.properties?.forEach((subNode) => { if (subNode.key.name === 'circle') { subNode.key.name = 'circular'; } if (subNode.key.name === 'rect') { subNode.key.name = 'rectangular'; } }); } }); }) .toSource(printOptions); return source .replace(/\.MuiSkeleton-circle/gm, '.MuiSkeleton-circular') .replace(/\.MuiSkeleton-rect([^\w])/gm, '.MuiSkeleton-rectangular$1'); }
6,557
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/skeleton-variant.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './skeleton-variant'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('skeleton-variant', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./skeleton-variant.test/actual.js'), path: require.resolve('./skeleton-variant.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./skeleton-variant.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./skeleton-variant.test/expected.js'), path: require.resolve('./skeleton-variant.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./skeleton-variant.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,558
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/styled-engine-provider.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options = {}) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single' }; let isImported = false; /** * try to import `StyledEngineProvider` */ root .find(j.ImportSpecifier) .forEach(({ node }) => { if (node.imported.name === 'StyledEngineProvider') { isImported = true; } }) .filter( ({ node }) => node.imported.name === 'MuiThemeProvider' || node.imported.name === 'ThemeProvider', ) .at(0) .forEach((path) => { if (!isImported) { path.insertAfter(j.importSpecifier(j.identifier('StyledEngineProvider'))); } }); /** * wrapped with <StyledEngineProvider> */ let hasWrapped = false; function wrapJSX(name) { root.findJSXElements(name).forEach((element) => { const identifier = j.jsxIdentifier('StyledEngineProvider'); const parent = element.parent; if ( parent.node.type !== 'JSXElement' || (parent.node.type === 'JSXElement' && parent.node.openingElement.name.name !== 'StyledEngineProvider') ) { hasWrapped = true; element.replace( j.jsxElement( j.jsxOpeningElement(identifier, [j.jsxAttribute(j.jsxIdentifier('injectFirst'))]), j.jsxClosingElement(identifier), [j.jsxText('\n'), element.node, j.jsxText('\n')], ), ); } }); } wrapJSX('MuiThemeProvider'); if (!hasWrapped) { wrapJSX('ThemeProvider'); } return root.toSource(printOptions); }
6,559
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/styled-engine-provider.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './styled-engine-provider'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('new style-engine-provider import', () => { it('import StyleEngineProvider after MuiThemeProvider', () => { const actual = transform( { source: read('./styled-engine-provider.test/mui-theme-provider.actual.js'), path: require.resolve('./styled-engine-provider.test/mui-theme-provider.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./styled-engine-provider.test/mui-theme-provider.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./styled-engine-provider.test/mui-theme-provider.expected.js'), path: require.resolve('./styled-engine-provider.test/mui-theme-provider.expected.js'), }, { jscodeshift }, {}, ); const expected = read('./styled-engine-provider.test/mui-theme-provider.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('import StyleEngineProvider after ThemeProvider', () => { const actual = transform( { source: read('./styled-engine-provider.test/theme-provider.actual.js'), path: require.resolve('./styled-engine-provider.test/theme-provider.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./styled-engine-provider.test/theme-provider.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,560
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/table-props.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; root .find(j.JSXElement) .filter(({ node }) => node.openingElement.name.name?.match(/^(Table|TableCell)$/)) .forEach(({ node }) => { node.openingElement.attributes.forEach((attr) => { if ( attr.name?.name === 'padding' && (attr.value?.value === 'default' || attr.value?.expression?.value === 'default') ) { attr.value = j.literal('normal'); } }); }); root.findJSXElements('TablePagination').forEach(({ node }) => { node.openingElement.attributes.forEach((attr) => { if (attr.type === 'JSXAttribute' && attr.name.name === 'onChangeRowsPerPage') { attr.name.name = 'onRowsPerPageChange'; } if (attr.type === 'JSXAttribute' && attr.name?.name === 'onChangePage') { attr.name.name = 'onPageChange'; } if (attr.type === 'JSXAttribute' && attr.name?.name === 'classes') { (attr.value.expression.properties || []).forEach((subNode) => { if (subNode.key.name === 'input') { subNode.key.name = 'select'; } }); } }); }); return root .toSource(printOptions) .replace(/\.MuiTablePagination-input/gm, '.MuiTablePagination-select'); }
6,561
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/table-props.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './table-props'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('table-props', () => { it('transforms as needed', () => { const actual = transform( { source: read('./table-props.test/actual.js'), path: require.resolve('./table-props.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./table-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./table-props.test/expected.js'), path: require.resolve('./table-props.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./table-props.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,562
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/tabs-scroll-buttons.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; root.findJSXElements('Tabs').forEach(({ node }) => { let prevScrollButtonValue; node.openingElement.attributes.forEach((attr) => { if (attr.name && attr.name.name === 'scrollButtons') { if (attr.value) { prevScrollButtonValue = attr.value.value || attr.value.expression?.value; if (attr.value.value === 'on' || attr.value.expression?.value === 'on') { delete attr.value; } else if (attr.value.value === 'desktop' || attr.value.expression?.value === 'desktop') { delete attr.value; } else if (attr.value.value === 'off' || attr.value.expression?.value === 'off') { attr.value = j.jsxExpressionContainer(j.literal(false)); } } } }); if (prevScrollButtonValue === 'on') { node.openingElement.attributes.push( j.jsxAttribute(j.jsxIdentifier('allowScrollButtonsMobile')), ); } }); return root.toSource(printOptions); }
6,563
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/tabs-scroll-buttons.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './tabs-scroll-buttons'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('tabs-scroll-buttons', () => { it('transforms as needed', () => { const actual = transform( { source: read('./tabs-scroll-buttons.test/actual.js'), path: require.resolve('./tabs-scroll-buttons.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./tabs-scroll-buttons.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./tabs-scroll-buttons.test/expected.js'), path: require.resolve('./tabs-scroll-buttons.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./tabs-scroll-buttons.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,564
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/textarea-minmax-rows.js
import renameProps from '../util/renameProps'; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; renameProps({ root, componentName: 'TextareaAutosize', props: { rows: 'minRows', rowsMin: 'minRows', rowsMax: 'maxRows' }, }); renameProps({ root, componentName: 'TextField', props: { rowsMin: 'minRows', rowsMax: 'maxRows' }, }); return root.toSource(printOptions); }
6,565
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/textarea-minmax-rows.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './textarea-minmax-rows'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('textarea-minmax-rows', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./textarea-minmax-rows.test/actual.js'), path: require.resolve('./textarea-minmax-rows.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./textarea-minmax-rows.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./textarea-minmax-rows.test/expected.js'), path: require.resolve('./textarea-minmax-rows.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./textarea-minmax-rows.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,566
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-augment.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ const template = ` declare module '@material-ui/styles/defaultTheme' { // eslint-disable-next-line @typescript-eslint/no-empty-interface interface DefaultTheme extends Theme {} } `; export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', }; if (file.path.endsWith('.tsx')) { let hasTheme = false; let isRootFile = false; root.find(j.ImportSpecifier).forEach(({ node }) => { if (node.imported.name === 'Theme') { hasTheme = true; } if (node.imported.name === 'ThemeProvider' || node.imported.name === 'MuiThemeProvider') { isRootFile = true; } }); if (!hasTheme) { root .find(j.ImportSpecifier) .filter( ({ node }) => node.imported.name === 'ThemeProvider' || node.imported.name === 'MuiThemeProvider', ) .at(0) .forEach((path) => { path.insertAfter(j.importSpecifier(j.identifier('Theme'))); }); } if (!file.source.match(/declare module ['"]@material-ui\/styles\/defaultTheme['"]/gm)) { root .find(j.ImportDeclaration) .at(-1) .forEach((path) => { if (isRootFile) { path.insertAfter(template); } }); } return root.toSource(printOptions); } return file.source; }
6,567
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-breakpoints-width.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source.replace( /(theme\.breakpoints|breakpoints)\.width\(['"](.*)['"]\)/gm, '$1.values.$2', ); }
6,568
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-breakpoints-width.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-breakpoints-width'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-breakpoints-width', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./theme-breakpoints-width.test/actual.js'), path: require.resolve('./theme-breakpoints-width.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-breakpoints-width.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./theme-breakpoints-width.test/expected.js'), path: require.resolve('./theme-breakpoints-width.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-breakpoints-width.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,569
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-breakpoints.js
const map = { xs: 'sm', sm: 'md', md: 'lg', lg: 'xl', xl: 'xl' }; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', }; root .find(j.CallExpression, { callee: { type: 'MemberExpression', object: { property: { name: 'breakpoints' } }, property: { type: 'Identifier', name: 'down' }, }, }) .forEach((path) => { path.node.arguments.forEach((node) => { const replacementValue = map[node.value]; if (replacementValue !== undefined) { node.value = replacementValue; } }); }); root .find(j.CallExpression, { callee: { type: 'MemberExpression', object: { property: { name: 'breakpoints' } }, property: { type: 'Identifier', name: 'between' }, }, }) .forEach((path) => { const node = path.node.arguments[1]; const replacementValue = map[node.value]; if (replacementValue !== undefined) { node.value = replacementValue; } }); return root.toSource(printOptions); }
6,570
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-breakpoints.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-breakpoints'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-breakpoints', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./theme-breakpoints.test/actual.js'), path: require.resolve('./theme-breakpoints.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-breakpoints.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,571
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-options.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source.replace(/(\s|:|\{)ThemeOptions/gm, '$1DeprecatedThemeOptions'); }
6,572
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-options.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-options'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-options', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./theme-options.test/actual.js'), path: require.resolve('./theme-options.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-options.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./theme-options.test/expected.js'), path: require.resolve('./theme-options.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-options.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,573
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-palette-mode.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source .replace(/(theme\.palette|palette)\.type/gm, '$1.mode') .replace(/(palette:\s*{\r?\n?\s.*)type/gm, '$1mode'); }
6,574
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-palette-mode.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-palette-mode'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-palette-mode', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./theme-palette-mode.test/actual.js'), path: require.resolve('./theme-palette-mode.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-palette-mode.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./theme-palette-mode.test/expected.js'), path: require.resolve('./theme-palette-mode.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-palette-mode.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,575
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-provider.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', }; root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/core\/?(styles)?$/)) .forEach((path) => { let previousVarName; path.node.specifiers.forEach((node) => { if (!node.imported && node.local.name === 'MuiThemeProvider') { // default specifier previousVarName = node.local.name; node.local.name = 'ThemeProvider'; } if (node.imported && node.imported.name === 'MuiThemeProvider') { previousVarName = node.local.name; node.local = null; node.imported.name = 'ThemeProvider'; } }); if (previousVarName) { root.findJSXElements(previousVarName).forEach(({ node }) => { node.openingElement.name.name = 'ThemeProvider'; if (node.closingElement) { node.closingElement.name.name = 'ThemeProvider'; } }); } }); return root.toSource(printOptions); }
6,576
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-provider.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-provider'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-provider', () => { it('transforms MuiThemeProvider as needed', () => { const actual = transform( { source: read('./theme-provider.test/actual.js'), path: require.resolve('./theme-provider.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-provider.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./theme-provider.test/expected.js'), path: require.resolve('./theme-provider.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-provider.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms MuiThemeProvider in core import', () => { const actual = transform( { source: read('./theme-provider.test/core-import.actual.js'), path: require.resolve('./theme-provider.test/core-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-provider.test/core-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,577
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-spacing.js
/* eslint-disable no-template-curly-in-string */ /** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source .replace( // handle cases like: `-${theme.spacing(1)}px` /`(-?)\${(-?)(theme\.spacing|spacing)\(([^{}]*)\)}px`/gm, '$3($1$2$4)', ) .replace( // handle cases like: theme.spacing(gap) + 'px' /((theme\.spacing|spacing)\(.*\))\s*\+\s*'px'/gm, '$1', ) .replace( // handle cases like: theme.spacing(gap) + "px" /((theme\.spacing|spacing)\(.*\))\s*\+\s*"px"/gm, '$1', ) .replace( // handle cases like: `calc(${theme.spacing(2)} - 1px) 0` /\${(theme\.spacing|spacing)(\([^)]+\))\s*([+-])\s*([\d.]+)\s*}px/gm, 'calc(${$1$2} $3 $4px)', ) .replace( // handle cases like: calc(${theme.spacing(itemHorzPadding)} * 0.3) /\${(theme\.spacing|spacing)(\([^)]+\))\s*([*/])\s*([\d.]+)\s*}px/gm, 'calc(${$1$2} $3 $4)', ) .replace( // handle common cases like: // `${theme.spacing(2)}px` // `${theme.spacing(2)}px ${theme.spacing(1)}px ${theme.spacing(2)}px ${theme.spacing(2)}px` /(spacing\([^)]+\)\})px(.)/gm, '$1$2', ); }
6,578
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-spacing.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-spacing'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-spacing', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./theme-spacing.test/actual.js'), path: require.resolve('./theme-spacing.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-spacing.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./theme-spacing.test/expected.js'), path: require.resolve('./theme-spacing.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-spacing.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('large file - transforms props as needed', () => { const actual = transform( { source: read('./theme-spacing.test/large-actual.js'), path: require.resolve('./theme-spacing.test/large-actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-spacing.test/large-expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('large file - should be idempotent', () => { const actual = transform( { source: read('./theme-spacing.test/large-expected.js'), path: require.resolve('./theme-spacing.test/large-expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-spacing.test/large-expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,579
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-typography-round.js
/** * @param {import('jscodeshift').FileInfo} file */ export default function transformer(file) { return file.source.replace( /(theme\.typography|typography)\.round\((.*)\)/gm, 'Math.round($2 * 1e5) / 1e5', ); }
6,580
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/theme-typography-round.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-typography-round'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('theme-typography-round', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./theme-typography-round.test/actual.js'), path: require.resolve('./theme-typography-round.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-typography-round.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./theme-typography-round.test/expected.js'), path: require.resolve('./theme-typography-round.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./theme-typography-round.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,581
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/top-level-imports.js
import { dirname } from 'path'; import addImports from 'jscodeshift-add-imports'; import getJSExports from '../util/getJSExports'; // istanbul ignore next if (process.env.NODE_ENV === 'test') { const resolve = require.resolve; require.resolve = (source) => resolve(source.replace(/^@mui\/material\/modern/, '../../../mui-material/src')); } export default function transformer(fileInfo, api, options) { const j = api.jscodeshift; const importModule = options.importModule || '@mui/material'; const targetModule = options.targetModule || '@mui/material'; const whitelist = getJSExports( require.resolve(`${importModule}/modern`, { paths: [dirname(fileInfo.path)], }), ); const printOptions = options.printOptions || { quote: 'single', trailingComma: true, }; const root = j(fileInfo.source); const importRegExp = new RegExp(`^${importModule}/(?:[^/]+/)*([^/]+)$`); const resultSpecifiers = []; root.find(j.ImportDeclaration).forEach((path) => { if (!path.node.specifiers.length) { return; } if (path.value.importKind && path.value.importKind !== 'value') { return; } const importPath = path.value.source.value; const match = importPath.match(importRegExp); if (!match) { return; } if (importPath.includes('internal/')) { return; } path.node.specifiers.forEach((specifier, index) => { if (specifier.importKind && specifier.importKind !== 'value') { return; } if (specifier.type === 'ImportNamespaceSpecifier') { return; } switch (specifier.type) { case 'ImportDefaultSpecifier': { const localName = specifier.local.name; const moduleName = match[1]; if (!whitelist.has(moduleName)) { return; } resultSpecifiers.push( j.importSpecifier(j.identifier(moduleName), j.identifier(localName)), ); path.get('specifiers', index).prune(); break; } case 'ImportSpecifier': if ( !whitelist.has(specifier.imported.name) == null && specifier.imported.name !== 'withStyles' ) { return; } resultSpecifiers.push(specifier); path.get('specifiers', index).prune(); break; default: break; } }); if (!path.node.specifiers.length) { path.prune(); } }); if (resultSpecifiers.length) { addImports(root, j.importDeclaration(resultSpecifiers, j.stringLiteral(targetModule))); } return root.toSource(printOptions); }
6,582
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/top-level-imports.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './top-level-imports'; import readFile from '../util/readFile'; function trim(str) { return str ? str.replace(/^\s+|\s+$/, '') : ''; } function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('top-level-imports', () => { it('convert path as needed', () => { const actual = transform( { source: read('./top-level-imports.test/actual.js'), path: require.resolve('./top-level-imports.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./top-level-imports.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./top-level-imports.test/expected.js'), path: require.resolve('./top-level-imports.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./top-level-imports.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,583
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/transitions.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions || { quote: 'single' }; const root = j(file.source); let variableName; root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value === '@material-ui/core/styles/transitions') .forEach((path) => { const specifier = path.node.specifiers[0]; if (specifier) { if (specifier.type === 'ImportDefaultSpecifier') { variableName = specifier.local.name; } specifier.local = j.identifier('createTransitions'); } path.node.source = j.literal('@material-ui/core/styles/createTransitions'); }); if (variableName) { root .find(j.ImportDeclaration) .at(-1) .insertAfter(`const ${variableName} = createTransitions({});`); } return root.toSource(printOptions); }
6,584
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/transitions.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './transitions'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('transitions', () => { it('transforms transitions as needed', () => { const actual = transform( { source: read('./transitions.test/actual.js'), path: require.resolve('./transitions.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./transitions.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./transitions.test/expected.js'), path: require.resolve('./transitions.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./transitions.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,585
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/tree-view-moved-to-x.js
const exports = { TreeView: { default: 'TreeView', named: [ 'treeViewClasses', 'TreeViewClasses', 'TreeViewClassKey', 'getTreeViewUtilityClass', 'TreeViewPropsBase', 'TreeViewProps', 'SingleSelectTreeViewProps', 'MultiSelectTreeViewProps', ], }, TreeItem: { default: 'TreeItem', named: [ 'useTreeItem', 'treeItemClasses', 'TreeItemClasses', 'TreeItemClassKey', 'getTreeItemUtilityClass', 'TreeItemProps', 'TreeItemContentProps', ], }, }; const buildLookup = () => { return Object.fromEntries( Object.entries(exports).flatMap(([entryPoint, entryPointData]) => [entryPointData.default, ...entryPointData.named].map((exportName) => [ exportName, { entryPoint }, ]), ), ); }; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(fileInfo, api, options) { const j = api.jscodeshift; const printOptions = options.printOptions || { quote: 'single' }; const lookup = buildLookup(); const root = j(fileInfo.source); root .find(j.ImportDeclaration) .forEach((path) => { const importSource = path.node.source.value; const subPackageImportMatch = importSource.match(/@mui\/lab\/(.*)/); if (subPackageImportMatch !== null) { const subModule = subPackageImportMatch[1]; if (subModule.startsWith('internal')) { console.warn('Imports from `@mui/lab/internal` are not supported'); return; } if (exports[subModule]) { /** * @type {import('jscodeshift').ASTPath} */ const sourcePath = path.get('source'); const targetPackage = '@mui/x-tree-view'; const targetImportPath = `${targetPackage}/${subModule}`; sourcePath.replace(j.stringLiteral(targetImportPath)); const importDeclaration = path.value; importDeclaration.specifiers = importDeclaration.specifiers.map((specifier) => { if (specifier.type === 'ImportDefaultSpecifier') { const localName = specifier.local.name; return j.importSpecifier(j.identifier(subModule), j.identifier(localName)); } return specifier; }); } } else if (importSource === '@mui/lab') { // Sieve import specifiers into /core and /lab const xImportSpecifiers = []; const labImportSpecifiers = []; path.node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportSpecifier') { const lookupValue = lookup[specifier.imported.name]; if (lookupValue) { xImportSpecifiers.push(specifier); } else { labImportSpecifiers.push(specifier); } } else { // `import Lab from '@material-ui/lab'` // `import * as Lab from '@material-ui/lab'` // These imports would require scope analysis. console.warn(`Can't handle ${specifier.type}`); } }); if (xImportSpecifiers.length > 0) { const targetPackage = '@mui/x-tree-view'; path.replace( j.importDeclaration(xImportSpecifiers, j.stringLiteral(targetPackage)), j.importDeclaration(labImportSpecifiers, j.stringLiteral('@mui/lab')), ); } } }) .toSource(printOptions); return root.toSource(printOptions); }
6,586
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/tree-view-moved-to-x.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './tree-view-moved-to-x'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('tree-view-moved-to-x', () => { it('transforms exports as needed (lab sub module)', () => { const actual = transform( { source: read('./tree-view-moved-to-x.test/actual-sub-module.js'), path: require.resolve('./tree-view-moved-to-x.test/actual-sub-module.js'), }, { jscodeshift }, {}, ); const expected = read('./tree-view-moved-to-x.test/expected-sub-module.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent (lab sub module)', () => { const actual = transform( { source: read('./tree-view-moved-to-x.test/expected-sub-module.js'), path: require.resolve('./tree-view-moved-to-x.test/expected-sub-module.js'), }, { jscodeshift }, {}, ); const expected = read('./tree-view-moved-to-x.test/expected-sub-module.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms exports as needed (lab root)', () => { const actual = transform( { source: read('./tree-view-moved-to-x.test/actual-root.js'), path: require.resolve('./tree-view-moved-to-x.test/actual-root.js'), }, { jscodeshift }, {}, ); const expected = read('./tree-view-moved-to-x.test/expected-root.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent (lab root)', () => { const actual = transform( { source: read('./tree-view-moved-to-x.test/expected-root.js'), path: require.resolve('./tree-view-moved-to-x.test/expected-root.js'), }, { jscodeshift }, {}, ); const expected = read('./tree-view-moved-to-x.test/expected-root.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,587
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/use-autocomplete.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single' }; const list = [ 'FilterOptionsState', 'createFilterOptions', 'CreateFilterOptionsConfig', 'AutocompleteFreeSoloValueMapping', 'Value', 'UseAutocompleteProps', 'AutocompleteHighlightChangeReason', 'AutocompleteInputChangeReason', 'AutocompleteChangeReason', 'AutocompleteCloseReason', 'useAutocomplete', ]; let coreImport; root .find(j.ImportDeclaration) .filter((path) => path.node.source.value.match(/^@material-ui\/lab\/?(useAutocomplete)?$/)) .forEach((path) => { const specifiers = []; path.node.specifiers.forEach((s, index) => { if (list.includes(s.imported ? s.imported.name : s.local.name)) { if (s.local.name === 'useAutocomplete') { specifiers.push(j.importDefaultSpecifier(j.identifier('useAutocomplete'))); } else { specifiers.push(s); } delete path.node.specifiers[index]; } }); if (specifiers.length) { if (!coreImport) { coreImport = j.importDeclaration( specifiers, j.literal('@material-ui/core/useAutocomplete'), ); path.insertAfter(coreImport); } else { coreImport.specifiers.push(...specifiers); } } }) .filter((path) => !Object.keys(path.node.specifiers).length) .remove(); return root.toSource(printOptions); }
6,588
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/use-autocomplete.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './use-autocomplete'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('use-autocomplete', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./use-autocomplete.test/actual.js'), path: require.resolve('./use-autocomplete.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./use-autocomplete.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./use-autocomplete.test/expected.js'), path: require.resolve('./use-autocomplete.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./use-autocomplete.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,589
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/use-transitionprops.js
import propsToObject from '../util/propsToObject'; const components = ['Dialog', 'Menu', 'Popover', 'Snackbar']; const props = ['onEnter', 'onEntered', 'onEntering', 'onExit', 'onExited', 'onExiting']; /** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single', }; components.forEach((component) => { propsToObject({ j, root, componentName: component, propName: 'TransitionProps', props }); }); return root.toSource(printOptions); }
6,590
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/use-transitionprops.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './use-transitionprops'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('use-transitionprops', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./use-transitionprops.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./use-transitionprops.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./use-transitionprops.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./use-transitionprops.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,591
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/variant-prop.js
const TargetMuiComponents = ['TextField', 'Select', 'FormControl']; export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; function addExplicitStandardProp(path) { const attributes = path.node.openingElement.attributes; const variant = attributes.find( (node) => node.type === 'JSXAttribute' && node.name.name === 'variant', ); if (!variant) { attributes.unshift(j.jsxAttribute(j.jsxIdentifier('variant'), j.literal('standard'))); } } const AffectedComponents = []; root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match( /^(@material-ui\/core|@mui\/material)(\/TextField|\/Select|\/FormControl)?$/, ), ) .forEach(({ node }) => { node.specifiers.forEach(({ local, imported }) => { if (!imported || (imported && TargetMuiComponents.includes(imported.name))) { AffectedComponents.push(local.name); } }); }); return j(file.source) .find(j.JSXElement) .filter(({ value: node }) => { const elementName = node.openingElement.name.name; return AffectedComponents.includes(elementName); }) .forEach(addExplicitStandardProp) .toSource(printOptions); }
6,592
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/variant-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './variant-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('variant-prop', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./variant-prop.test/actual.js'), path: require.resolve('./variant-prop.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./variant-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./variant-prop.test/expected.js'), path: require.resolve('./variant-prop.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./variant-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,593
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/with-width.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single' }; const imports = root.find(j.ImportDeclaration).paths(); const lastImport = imports[imports.length - 1]; root .find(j.ImportDeclaration) .filter((path) => path.node.source.value === '@material-ui/core/withWidth') .forEach(() => { lastImport.insertAfter( '// FIXME checkout https://mui.com/components/use-media-query/#migrating-from-withwidth\nconst withWidth = () => (WrappedComponent) => (props) => <WrappedComponent {...props} width="xs" />;', ); }) .remove(); let shouldRemoveImport = false; const collection = root .find(j.ImportDeclaration) .filter((path) => path.node.source.value === '@material-ui/core') .forEach(({ node }) => { node.specifiers .filter((s) => s.imported.name === 'withWidth') .forEach((s) => { lastImport.insertAfter( '// FIXME checkout https://mui.com/components/use-media-query/#migrating-from-withwidth\nconst withWidth = () => (WrappedComponent) => (props) => <WrappedComponent {...props} width="xs" />;'.replace( /withWidth/g, s.local.name, ), ); }); node.specifiers = node.specifiers.filter((s) => s.imported.name !== 'withWidth'); if (!node.specifiers.length) { shouldRemoveImport = true; } }); if (shouldRemoveImport) { collection.remove(); } return root.toSource(printOptions); }
6,594
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/with-mobile-dialog.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ const template = `// FIXME checkout https://mui.com/components/use-media-query/#using-material-uis-breakpoint-helpers const withMobileDialog = () => (WrappedComponent) => (props) => <WrappedComponent {...props} width="lg" fullScreen={false} />;`; export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions || { quote: 'single' }; const imports = root.find(j.ImportDeclaration).paths(); const lastImport = imports[imports.length - 1]; root .find(j.ImportDeclaration) .filter((path) => path.node.source.value === '@material-ui/core/withMobileDialog') .forEach(() => { lastImport.insertAfter(template); }) .remove(); let shouldRemoveImport = false; const collection = root .find(j.ImportDeclaration) .filter((path) => path.node.source.value === '@material-ui/core') .forEach(({ node }) => { node.specifiers .filter((s) => s.imported.name === 'withMobileDialog') .forEach((s) => { lastImport.insertAfter(template.replace(/withMobileDialog/g, s.local.name)); }); node.specifiers = node.specifiers.filter((s) => s.imported.name !== 'withMobileDialog'); if (!node.specifiers.length) { shouldRemoveImport = true; } }); if (shouldRemoveImport) { collection.remove(); } return root.toSource(printOptions); }
6,595
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/with-mobile-dialog.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './with-mobile-dialog'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('with-mobile-dialog', () => { it('transforms as needed', () => { const actual = transform( { source: read('./with-mobile-dialog.test/actual.js'), path: require.resolve('./with-mobile-dialog.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./with-mobile-dialog.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./with-mobile-dialog.test/expected.js'), path: require.resolve('./with-mobile-dialog.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./with-mobile-dialog.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should not remove import from core', () => { const actual = transform( { source: read('./with-mobile-dialog.test/no-withwidth.actual.js'), path: require.resolve('./with-mobile-dialog.test/no-withwidth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./with-mobile-dialog.test/no-withwidth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,596
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/with-width.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './with-width'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('with-width', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./with-width.test/actual.js'), path: require.resolve('./with-width.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./with-width.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./with-width.test/expected.js'), path: require.resolve('./with-width.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./with-width.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should not remove import from core', () => { const actual = transform( { source: read('./with-width.test/no-withwidth.actual.js'), path: require.resolve('./with-width.test/no-withwidth.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./with-width.test/no-withwidth.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,597
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/adapter-v4.test/actual.js
import { createMuiTheme, createTheme } from '@material-ui/core/styles'; const theme1 = createMuiTheme(); const theme2 = createTheme(); const theme3 = createMuiTheme({ palette: { primary: { main: '#ff5252' } } }); const theme4 = createTheme({ palette: { primary: { main: '#ff5252' } } });
6,598
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/adapter-v4.test/core-import.actual.js
import { createMuiTheme, ThemeOptions } from '@material-ui/core'; export const muiTheme = createMuiTheme(); export const muiTheme2 = createMuiTheme({});
6,599