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-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/types.ts
import * as React from 'react'; export type EventHandlers = Record<string, React.EventHandler<any>>; export type WithOptionalOwnerState<Props extends { ownerState: unknown }> = Omit< Props, 'ownerState' > & Partial<Pick<Props, 'ownerState'>>; export type SlotComponentProps<TSlotComponent extends React.ElementType, TOverrides, TOwnerState> = | (Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides) | (( ownerState: TOwnerState, ) => Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides); export type SlotComponentPropsWithSlotState< TSlotComponent extends React.ElementType, TOverrides, TOwnerState, TSlotState, > = | (Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides) | (( ownerState: TOwnerState, slotState: TSlotState, ) => Partial<React.ComponentPropsWithRef<TSlotComponent>> & TOverrides);
6,400
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useControllableReducer.test.tsx
import { expect } from 'chai'; import * as React from 'react'; import { spy } from 'sinon'; import { createRenderer } from '@mui-internal/test-utils'; import { useControllableReducer } from './useControllableReducer'; import { ControllableReducerParameters } from './useControllableReducer.types'; interface TestState { make: string; model: string; productionYear: number; features?: string[]; } interface SetMakeAction { type: 'setMake'; value: string; } interface UpdateProductionYearAction { type: 'updateProductionYear'; value: number; event: null; } interface UpdateFeaturesAction { type: 'updateFeatures'; value: string[]; } describe('useControllableReducer', () => { const { render } = createRenderer(); describe('param: reducer', () => { it('calls the provided reducer', () => { const reducer = spy((state: TestState, action: SetMakeAction) => { return { ...state, make: action.value, }; }); const actionToDispatch: SetMakeAction = { type: 'setMake', value: 'BMW', }; const reducerParameters: ControllableReducerParameters<TestState, SetMakeAction> = { reducer, controlledProps: {}, initialState: { make: 'Mazda', model: '3', productionYear: 2022 }, }; function TestComponent() { const [state, dispatch] = useControllableReducer(reducerParameters); React.useEffect(() => dispatch(actionToDispatch), [dispatch]); return ( <p> {state.make} {state.model} ({state.productionYear}) </p> ); } const { container } = render(<TestComponent />); expect(reducer.getCalls()[0].args[1]).to.include({ ...actionToDispatch }); expect(container.firstChild).to.have.text('BMW 3 (2022)'); }); }); describe('param: initialProps', () => { it('sets the initial state', () => { const reducerParameters: ControllableReducerParameters<TestState, SetMakeAction> = { reducer: (state) => state, controlledProps: {}, initialState: { make: 'Mazda', model: '3', productionYear: 2022 }, }; function TestComponent() { const [state] = useControllableReducer(reducerParameters); return ( <p> {state.make} {state.model} ({state.productionYear}) </p> ); } const { container } = render(<TestComponent />); expect(container.firstChild).to.have.text('Mazda 3 (2022)'); }); }); describe('param: controlledProps', () => { it('overwrites the state field with the corresponding controlled prop value', () => { const reducer = (state: TestState, action: SetMakeAction) => { // Even though the initial state is set to 'Mazda', the controlled prop overwrites it. expect(state.make).to.equal('Tesla'); return { ...state, make: action.value, }; }; const actionToDispatch: SetMakeAction = { type: 'setMake', value: 'BMW', }; const reducerParameters: ControllableReducerParameters<TestState, SetMakeAction> = { reducer, initialState: { make: 'Mazda', model: '3', productionYear: 2022 }, }; function TestComponent(props: { make: string }) { const [state, dispatch] = useControllableReducer<TestState, SetMakeAction>({ ...reducerParameters, controlledProps: { make: props.make }, }); React.useEffect(() => dispatch(actionToDispatch), [dispatch]); return ( <p> {state.make} {state.model} ({state.productionYear}) </p> ); } const { container, setProps } = render(<TestComponent make="Tesla" />); expect(container.firstChild).to.have.text('Tesla 3 (2022)'); setProps({ make: 'Mazda' }); expect(container.firstChild).to.have.text('Mazda 3 (2022)'); }); }); describe('param: stateComparers', () => { it('uses the provided state comparers', () => { const reducer = (state: TestState, action: UpdateFeaturesAction) => { return { ...state, features: action.value, }; }; const actionToDispatch: UpdateFeaturesAction = { type: 'updateFeatures', value: ['ABS', 'Traction control'], }; const onStateChangeSpy = spy(); const reducerParameters: ControllableReducerParameters<TestState, UpdateFeaturesAction> = { reducer, controlledProps: {}, initialState: { make: 'Mazda', model: '3', productionYear: 2022, features: ['ABS', 'Traction control'], }, stateComparers: { // deep comparison of the features array features: (a, b) => a !== undefined && b !== undefined && a.length === b.length && a.every((v, i) => v === b[i]), }, onStateChange: onStateChangeSpy, }; function TestComponent() { const [, dispatch] = useControllableReducer(reducerParameters); // The features array is new, but it contents remain the same. React.useEffect(() => dispatch(actionToDispatch), [dispatch]); return null; } render(<TestComponent />); expect(onStateChangeSpy.callCount).to.equal(0); }); }); describe('param: onStateChange', () => { it('calls onStateChange when the reducer returns a modified selected value', () => { const reducer = spy((state: TestState, action: UpdateProductionYearAction) => { return { ...state, productionYear: action.value, }; }); const actionToDispatch = { type: 'updateProductionYear' as const, event: null, value: 2010, }; const handleChange = spy(); const reducerParameters: ControllableReducerParameters< TestState, UpdateProductionYearAction > = { reducer, controlledProps: {}, initialState: { make: 'Mazda', model: '3', productionYear: 2022 }, onStateChange: handleChange, }; function TestComponent() { const [, dispatch] = useControllableReducer(reducerParameters); React.useEffect(() => dispatch(actionToDispatch), [dispatch]); return null; } render(<TestComponent />); expect(handleChange.called).to.equal(true); expect(handleChange.getCalls()[0].args).to.deep.equal([ null, 'productionYear', 2010, 'updateProductionYear', { make: 'Mazda', model: '3', productionYear: 2010, }, ]); }); }); describe('param: actionContext', () => { it('augments actions with the object provided to the reducer', () => { const reducer = ( state: TestState, action: UpdateProductionYearAction & { context: { overrideProductionYear: number } }, ) => { return { ...state, productionYear: action.context.overrideProductionYear, }; }; const actionToDispatch: UpdateProductionYearAction = { type: 'updateProductionYear', event: null, value: 2010, }; const reducerParameters: ControllableReducerParameters< TestState, UpdateProductionYearAction, { overrideProductionYear: number } > = { reducer, controlledProps: {}, initialState: { make: 'Mazda', model: '3', productionYear: 2022 }, actionContext: { overrideProductionYear: 2016 }, }; function TestComponent() { const [state, dispatch] = useControllableReducer(reducerParameters); React.useEffect(() => dispatch(actionToDispatch), [dispatch]); return ( <p> {state.make} {state.model} ({state.productionYear}) </p> ); } const { container } = render(<TestComponent />); expect(container.firstChild).to.have.text('Mazda 3 (2016)'); }); }); });
6,401
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useControllableReducer.ts
'use client'; import * as React from 'react'; import { ActionWithContext, ControllableReducerAction, ControllableReducerParameters, StateChangeCallback, StateComparers, } from './useControllableReducer.types'; function areEqual(a: any, b: any): boolean { return a === b; } const EMPTY_OBJECT = {}; const NOOP = () => {}; /** * Gets the current state augmented with controlled values from the outside. * If a state item has a corresponding controlled value, it will be used instead of the internal state. */ function getControlledState<State>(internalState: State, controlledProps: Partial<State>) { const augmentedState = { ...internalState }; (Object.keys(controlledProps) as (keyof State)[]).forEach((key) => { if (controlledProps[key] !== undefined) { (augmentedState as Record<keyof State, any>)[key] = controlledProps[key]; } }); return augmentedState; } interface UseStateChangeDetectionParameters<State extends {}> { /** * The next state returned by the reducer. */ nextState: State; /** * The initial state. */ initialState: State; /** * Comparers for each state item. If a state item has a corresponding comparer, it will be used to determine if the state has changed. */ stateComparers: StateComparers<State>; /** * The function called when the state has changed. */ onStateChange: StateChangeCallback<State>; /** * The external props used to override the state items. */ controlledProps: Partial<State>; /** * The last action that was dispatched. */ lastActionRef: React.MutableRefObject<ControllableReducerAction | null>; } /** * Defines an effect that compares the next state with the previous state and calls * the `onStateChange` callback if the state has changed. * The comparison is done based on the `stateComparers` parameter. */ function useStateChangeDetection<State extends {}>( parameters: UseStateChangeDetectionParameters<State>, ) { const { nextState, initialState, stateComparers, onStateChange, controlledProps, lastActionRef } = parameters; const internalPreviousStateRef = React.useRef<State>(initialState); React.useEffect(() => { if (lastActionRef.current === null) { // Detect changes only if an action has been dispatched. return; } const previousState = getControlledState(internalPreviousStateRef.current, controlledProps); (Object.keys(nextState) as (keyof State)[]).forEach((key) => { // go through all state keys and compare them with the previous state const stateComparer = stateComparers[key] ?? areEqual; const nextStateItem = nextState[key]; const previousStateItem = previousState[key]; if ( (previousStateItem == null && nextStateItem != null) || (previousStateItem != null && nextStateItem == null) || (previousStateItem != null && nextStateItem != null && !stateComparer(nextStateItem, previousStateItem)) ) { onStateChange?.( lastActionRef.current!.event ?? null, key, nextStateItem, lastActionRef.current!.type ?? '', nextState, ); } }); internalPreviousStateRef.current = nextState; lastActionRef.current = null; }, [ internalPreviousStateRef, nextState, lastActionRef, onStateChange, stateComparers, controlledProps, ]); } /** * The alternative to `React.useReducer` that lets you control the state from the outside. * * It can be used in an uncontrolled mode, similar to `React.useReducer`, or in a controlled mode, when the state is controlled by the props. * It also supports partially controlled state, when some state items are controlled and some are not. * * The controlled state items are provided via the `controlledProps` parameter. * When a reducer action is dispatched, the internal state is updated with the new values. * A change event (`onStateChange`) is then triggered (for each changed state item) if the new state is different from the previous state. * This event can be used to update the controlled values. * * The comparison of the previous and next states is done using the `stateComparers` parameter. * If a state item has a corresponding comparer, it will be used to determine if the state has changed. * This is useful when the state item is an object and you want to compare only a subset of its properties or if it's an array and you want to compare its contents. * * An additional feature is the `actionContext` parameter. It allows you to add additional properties to every action object, * similarly to how React context is implicitly available to every component. * * @template State - The type of the state calculated by the reducer. * @template Action - The type of the actions that can be dispatched. * @template ActionContext - The type of the additional properties that will be added to every action object. * * @ignore - internal hook. */ export function useControllableReducer< State extends {}, Action extends ControllableReducerAction, ActionContext = undefined, >( parameters: ControllableReducerParameters<State, Action, ActionContext>, ): [State, (action: Action) => void] { const lastActionRef = React.useRef<Action | null>(null); const { reducer, initialState, controlledProps = EMPTY_OBJECT, stateComparers = EMPTY_OBJECT, onStateChange = NOOP, actionContext, } = parameters; // The reducer that is passed to React.useReducer is wrapped with a function that augments the state with controlled values. const reducerWithControlledState = React.useCallback( (state: State, action: ActionWithContext<Action, ActionContext>) => { lastActionRef.current = action; const controlledState = getControlledState(state, controlledProps); const newState = reducer(controlledState, action); return newState; }, [controlledProps, reducer], ); const [nextState, dispatch] = React.useReducer(reducerWithControlledState, initialState); // The action that is passed to dispatch is augmented with the actionContext. const dispatchWithContext = React.useCallback( (action: Action) => { dispatch({ ...action, context: actionContext, } as ActionWithContext<Action, ActionContext>); }, [actionContext], ); useStateChangeDetection<State>({ nextState, initialState, stateComparers: stateComparers ?? EMPTY_OBJECT, onStateChange: onStateChange ?? NOOP, controlledProps, lastActionRef, }); return [getControlledState(nextState, controlledProps), dispatchWithContext]; }
6,402
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useControllableReducer.types.ts
/** * Functions that compare fields of a given State object */ export type StateComparers<State> = { [key in keyof State]?: (value1: State[key], value2: State[key]) => boolean; }; export type StateChangeCallback<State> = <StateKey extends keyof State>( event: React.SyntheticEvent | null, field: StateKey, value: State[StateKey], reason: string, state: State, ) => void; export type ActionWithContext<Action, ContextValue> = Action & { context: ContextValue; }; /** * Parameters of the useControllableReducer hook. */ export interface ControllableReducerParameters< State, Action extends ControllableReducerAction, ActionContext = undefined, > { /** * The reducer function. * * @param state The previous state. If controlledProps are defined, the state will contain the values of the controlledProps. * @param action The action to dispatch. The action can be augmented with the `actionContext`. * @returns The updated state. */ reducer: (state: State, action: ActionWithContext<Action, ActionContext>) => State; /** * The controlled props that will override the state items. */ controlledProps?: Partial<State>; /** * The initial state. */ initialState: State; /** * Comparers for each state item. If a state item has a corresponding comparer, it will be used to determine if the state has changed. * This is taken into consideration when firing the `onStateChange` event. * If no comparer is defined, the default equality comparison will be used. */ stateComparers?: StateComparers<State>; /** * The event handler called whenever a field of the state changes. */ onStateChange?: StateChangeCallback<State>; /** * Additional properties that will be added to the action. */ actionContext?: ActionContext; } /* * The standard shape of the action accepted by the controllable reducer */ export type ControllableReducerAction = { /** * The type of the action. */ type?: string; /** * The event that triggered the action. */ event?: React.SyntheticEvent | null; };
6,403
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useForcedRerendering.ts
'use client'; import * as React from 'react'; /** * @ignore - internal hook. */ export function useForcedRerendering() { const [, setState] = React.useState({}); return React.useCallback(() => { setState({}); }, []); }
6,404
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useMessageBus.test.ts
import { spy } from 'sinon'; import { expect } from 'chai'; import { createMessageBus } from './useMessageBus'; describe('messageBus', () => { it('should be able to subscribe to a message', () => { const { subscribe, publish } = createMessageBus(); const testSubject = 'test'; const callback = spy(); subscribe(testSubject, callback); publish(testSubject, 'foo'); expect(callback.args[0][0]).to.equal('foo'); }); it('should be able to unsubscribe from a message', () => { const { subscribe, publish } = createMessageBus(); const testSubject = 'test'; const callback = spy(); const unsubscribe = subscribe(testSubject, callback); unsubscribe(); publish(testSubject, 'foo'); expect(callback.callCount).to.equal(0); }); it('should be able to publish multiple messages', () => { const { subscribe, publish } = createMessageBus(); const testSubject1 = 'test1'; const testSubject2 = 'test2'; const callback = spy(); subscribe(testSubject1, callback); subscribe(testSubject2, callback); publish(testSubject1, 'foo'); publish(testSubject2, 'foo'); expect(callback.callCount).to.equal(2); }); it('should be able to publish multiple messages with different arguments', () => { const { subscribe, publish } = createMessageBus(); const testSubject1 = 'test1'; const testSubject2 = 'test2'; const callback = spy(); subscribe(testSubject1, callback); subscribe(testSubject2, callback); publish(testSubject1, 'foo'); publish(testSubject2, 'bar'); expect(callback.args[0][0]).to.equal('foo'); expect(callback.args[1][0]).to.equal('bar'); }); });
6,405
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useMessageBus.ts
'use client'; import * as React from 'react'; export interface MessageBus { subscribe(topic: string, callback: Function): () => void; publish(topic: string, ...args: unknown[]): void; } export function createMessageBus(): MessageBus { const listeners = new Map<string, Set<Function>>(); function subscribe(topic: string, callback: Function) { let topicListeners = listeners.get(topic); if (!topicListeners) { topicListeners = new Set([callback]); listeners.set(topic, topicListeners); } else { topicListeners.add(callback); } return () => { topicListeners!.delete(callback); if (topicListeners!.size === 0) { listeners.delete(topic); } }; } function publish(topic: string, ...args: unknown[]) { const topicListeners = listeners.get(topic); if (topicListeners) { topicListeners.forEach((callback) => callback(...args)); } } return { subscribe, publish }; } /** * @ignore - internal hook. */ export function useMessageBus() { const bus = React.useRef<MessageBus>(); if (!bus.current) { bus.current = createMessageBus(); } return bus.current; }
6,406
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useSlotProps.test.tsx
import * as React from 'react'; import { expect } from 'chai'; import { spy } from 'sinon'; import { createRenderer } from '@mui-internal/test-utils'; import { EventHandlers } from '@mui/base'; import { useSlotProps, UseSlotPropsParameters, UseSlotPropsResult } from './useSlotProps'; const { render } = createRenderer(); function callUseSlotProps< ElementType extends React.ElementType, SlotProps, ExternalForwardedProps, ExternalSlotProps extends Record<string, unknown>, AdditionalProps, OwnerState, >( parameters: UseSlotPropsParameters< ElementType, SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps, OwnerState >, ) { const TestComponent = React.forwardRef( ( _: unknown, ref: React.Ref<UseSlotPropsResult<ElementType, SlotProps, AdditionalProps, OwnerState>>, ) => { const slotProps = useSlotProps(parameters); React.useImperativeHandle(ref, () => slotProps as any); return null; }, ); const ref = React.createRef<UseSlotPropsResult<ElementType, SlotProps, AdditionalProps, OwnerState>>(); render(<TestComponent ref={ref} />); return ref.current!; } describe('useSlotProps', () => { it('returns the provided slot props if no overrides are present', () => { const clickHandler = () => {}; const getSlotProps = (otherHandlers: EventHandlers) => { expect(otherHandlers).to.deep.equal({}); return { id: 'test', onClick: clickHandler, }; }; const result = callUseSlotProps({ elementType: 'div', getSlotProps, externalSlotProps: undefined, ownerState: undefined, }); expect(result).to.deep.equal({ id: 'test', onClick: clickHandler, ref: null, }); }); it('calls getSlotProps with the external event handlers', () => { const externalClickHandler = () => {}; const internalClickHandler = () => {}; const getSlotProps = (otherHandlers: EventHandlers) => { expect(otherHandlers).to.deep.equal({ onClick: externalClickHandler, }); return { id: 'internalId', onClick: internalClickHandler, }; }; const result = callUseSlotProps({ elementType: 'div', getSlotProps, externalSlotProps: { className: 'externalClassName', id: 'externalId', onClick: externalClickHandler, }, ownerState: undefined, }); expect(result).to.deep.equal({ className: 'externalClassName', id: 'externalId', onClick: internalClickHandler, ref: null, }); }); it('adds ownerState to props if the elementType is a component', () => { const getSlotProps = () => ({ id: 'test', }); function TestComponent(props: any) { return <div {...props} />; } const result = callUseSlotProps({ elementType: TestComponent, getSlotProps, externalSlotProps: undefined, ownerState: { foo: 'bar', }, }); expect(result).to.deep.equal({ id: 'test', ref: null, ownerState: { foo: 'bar', }, }); }); it('synchronizes refs provided by internal and external props', () => { const internalRef = React.createRef(); const externalRef = React.createRef(); const getSlotProps = () => ({ ref: internalRef, }); const result = callUseSlotProps({ elementType: 'div', getSlotProps, externalSlotProps: { ref: externalRef, }, ownerState: undefined, }); result.ref('test'); expect(internalRef.current).to.equal('test'); expect(externalRef.current).to.equal('test'); }); // The "everything but the kitchen sink" test it('constructs props from complex parameters', () => { const internalRef = React.createRef(); const externalRef = React.createRef(); const additionalRef = React.createRef(); const internalClickHandler = spy(); const externalClickHandler = spy(); const externalForwardedClickHandler = spy(); const createInternalClickHandler = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => { expect(otherHandlers).to.deep.equal({ onClick: externalClickHandler, }); otherHandlers.onClick(event); internalClickHandler(event); }; // usually provided by the hook: const getSlotProps = (otherHandlers: EventHandlers) => ({ id: 'internalId', onClick: createInternalClickHandler(otherHandlers), ref: internalRef, className: 'internal', }); const ownerState = { test: true, }; // provided by the user by appending additional props on the Base UI component: const forwardedProps = { 'data-test': 'externalForwarded', className: 'externalForwarded', onClick: externalForwardedClickHandler, }; // provided by the user via slotProps.*: const componentProps = (os: typeof ownerState) => ({ 'data-fromownerstate': os.test, 'data-test': 'externalComponentsProps', className: 'externalComponentsProps', onClick: externalClickHandler, ref: externalRef, id: 'external', ownerState: { foo: 'bar', }, }); // set in the Base UI component: const additionalProps = { className: 'additional', ref: additionalRef, }; function TestComponent(props: any) { return <div {...props} />; } const result = callUseSlotProps({ elementType: TestComponent, getSlotProps, externalForwardedProps: forwardedProps, externalSlotProps: componentProps, additionalProps, ownerState, className: ['another-class', 'yet-another-class'], }); // `id` from componentProps overrides the one from getSlotProps expect(result).to.haveOwnProperty('id', 'external'); // `slotProps` is called with the ownerState expect(result).to.haveOwnProperty('data-fromownerstate', true); // class names are concatenated expect(result).to.haveOwnProperty( 'className', 'internal additional another-class yet-another-class externalForwarded externalComponentsProps', ); // `data-test` from componentProps overrides the one from forwardedProps expect(result).to.haveOwnProperty('data-test', 'externalComponentsProps'); // all refs should be synced result.ref('test'); expect(internalRef.current).to.equal('test'); expect(externalRef.current).to.equal('test'); expect(additionalRef.current).to.equal('test'); // event handler provided in slotProps is called result.onClick({} as React.MouseEvent); expect(externalClickHandler.calledOnce).to.equal(true); // event handler provided in forwardedProps is not called (was overridden by slotProps) expect(externalForwardedClickHandler.notCalled).to.equal(true); // internal event handler is called expect(internalClickHandler.calledOnce).to.equal(true); // internal ownerState is merged with the one provided by slotProps expect(result.ownerState).to.deep.equal({ test: true, foo: 'bar', }); }); it('should call externalSlotProps with ownerState if skipResolvingSlotProps is not provided', () => { const externalSlotProps = spy(); const ownerState = { foo: 'bar' }; const getSlotProps = () => ({ skipResolvingSlotProps: true, }); callUseSlotProps({ elementType: 'div', getSlotProps, externalSlotProps, ownerState, }); expect(externalSlotProps.callCount).to.not.equal(0); expect(externalSlotProps.args[0][0]).to.deep.equal(ownerState); }); it('should not call externalSlotProps if skipResolvingSlotProps is true', () => { const externalSlotProps = spy(); const getSlotProps = () => ({ skipResolvingSlotProps: true, }); callUseSlotProps({ elementType: 'div', getSlotProps, externalSlotProps, skipResolvingSlotProps: true, ownerState: undefined, }); expect(externalSlotProps.callCount).to.equal(0); }); });
6,407
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useSlotProps.ts
'use client'; import * as React from 'react'; import { unstable_useForkRef as useForkRef } from '@mui/utils'; import { appendOwnerState, AppendOwnerStateReturnType } from './appendOwnerState'; import { mergeSlotProps, MergeSlotPropsParameters, MergeSlotPropsResult, WithCommonProps, } from './mergeSlotProps'; import { resolveComponentProps } from './resolveComponentProps'; export type UseSlotPropsParameters< ElementType extends React.ElementType, SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps, OwnerState, > = Omit< MergeSlotPropsParameters<SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps>, 'externalSlotProps' > & { /** * The type of the component used in the slot. */ elementType: ElementType | undefined; /** * The `slotProps.*` of the Base UI component. */ externalSlotProps: | ExternalSlotProps | ((ownerState: OwnerState) => ExternalSlotProps) | undefined; /** * The ownerState of the Base UI component. */ ownerState: OwnerState; /** * Set to true if the slotProps callback should receive more props. */ skipResolvingSlotProps?: boolean; }; export type UseSlotPropsResult< ElementType extends React.ElementType, SlotProps, AdditionalProps, OwnerState, > = AppendOwnerStateReturnType< ElementType, MergeSlotPropsResult<SlotProps, object, object, AdditionalProps>['props'] & { ref: ((instance: any | null) => void) | null; }, OwnerState >; /** * @ignore - do not document. * Builds the props to be passed into the slot of an unstyled component. * It merges the internal props of the component with the ones supplied by the user, allowing to customize the behavior. * If the slot component is not a host component, it also merges in the `ownerState`. * * @param parameters.getSlotProps - A function that returns the props to be passed to the slot component. */ export function useSlotProps< ElementType extends React.ElementType, SlotProps, AdditionalProps, OwnerState, >( parameters: UseSlotPropsParameters< ElementType, SlotProps, object, WithCommonProps<Record<string, any>>, AdditionalProps, OwnerState >, ) { const { elementType, externalSlotProps, ownerState, skipResolvingSlotProps = false, ...rest } = parameters; const resolvedComponentsProps = skipResolvingSlotProps ? {} : resolveComponentProps(externalSlotProps, ownerState); const { props: mergedProps, internalRef } = mergeSlotProps({ ...rest, externalSlotProps: resolvedComponentsProps, }); const ref = useForkRef( internalRef, resolvedComponentsProps?.ref, parameters.additionalProps?.ref, ) as ((instance: any | null) => void) | null; const props: UseSlotPropsResult<ElementType, SlotProps, AdditionalProps, OwnerState> = appendOwnerState( elementType, { ...mergedProps, ref, }, ownerState, ); return props; }
6,408
0
petrpan-code/mui/material-ui/packages/mui-base/src
petrpan-code/mui/material-ui/packages/mui-base/src/utils/useTextNavigation.ts
'use client'; import * as React from 'react'; const TEXT_NAVIGATION_RESET_TIMEOUT = 500; // milliseconds /** * @ignore - internal hook. * * Provides a handler for text navigation. * It's used to navigate a list by typing the first letters of the options. * * @param callback A function to be called when the navigation should be performed. * @returns A function to be used in a keydown event handler. */ export function useTextNavigation( callback: (searchString: string, event: React.KeyboardEvent) => void, ) { const textCriteriaRef = React.useRef<{ searchString: string; lastTime: number | null; }>({ searchString: '', lastTime: null, }); return React.useCallback( (event: React.KeyboardEvent) => { if (event.key.length === 1 && event.key !== ' ') { const textCriteria = textCriteriaRef.current; const lowerKey = event.key.toLowerCase(); const currentTime = performance.now(); if ( textCriteria.searchString.length > 0 && textCriteria.lastTime && currentTime - textCriteria.lastTime > TEXT_NAVIGATION_RESET_TIMEOUT ) { textCriteria.searchString = lowerKey; } else if ( textCriteria.searchString.length !== 1 || lowerKey !== textCriteria.searchString ) { // If there is just one character in the buffer and the key is the same, do not append textCriteria.searchString += lowerKey; } textCriteria.lastTime = currentTime; callback(textCriteria.searchString, event); } }, [callback], ); }
6,409
0
petrpan-code/mui/material-ui/packages/mui-base/test/typescript
petrpan-code/mui/material-ui/packages/mui-base/test/typescript/moduleAugmentation/selectComponentsProps.spec.tsx
import * as React from 'react'; import { Select } from '@mui/base'; declare module '@mui/base' { interface SelectRootSlotPropsOverrides { variant?: 'one' | 'two'; } } <Select slotProps={{ root: { variant: 'one' } }} />; // @ts-expect-error unknown variant <Select slotProps={{ root: { variant: 'three' } }} />;
6,410
0
petrpan-code/mui/material-ui/packages/mui-base/test/typescript
petrpan-code/mui/material-ui/packages/mui-base/test/typescript/moduleAugmentation/selectComponentsProps.tsconfig.json
{ "extends": "../../../../../tsconfig.json", "files": ["selectComponentsProps.spec.tsx"] }
6,411
0
petrpan-code/mui/material-ui/packages/mui-base/test/typescript
petrpan-code/mui/material-ui/packages/mui-base/test/typescript/moduleAugmentation/sliderComponentsProps.spec.tsx
import * as React from 'react'; import { Slider } from '@mui/base'; declare module '@mui/base' { interface SliderRootSlotPropsOverrides { variant?: 'one' | 'two'; } } <Slider slotProps={{ root: { variant: 'one' } }} />; // @ts-expect-error unknown color <Slider slotProps={{ root: { variant: 'three' } }} />;
6,412
0
petrpan-code/mui/material-ui/packages/mui-base/test/typescript
petrpan-code/mui/material-ui/packages/mui-base/test/typescript/moduleAugmentation/sliderComponentsProps.tsconfig.json
{ "extends": "../../../../../tsconfig.json", "files": ["sliderComponentsProps.spec.tsx"] }
6,413
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-codemod/.npmignore
/* !/src/*.js !/lib/*.js *.test.js
6,414
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-codemod/README.md
# @mui/codemod > Codemod scripts for MUI [![npm version](https://img.shields.io/npm/v/@mui/codemod.svg?style=flat-square)](https://www.npmjs.com/package/@mui/codemod) [![npm downloads](https://img.shields.io/npm/dm/@mui/codemod.svg?style=flat-square)](https://www.npmjs.com/package/@mui/codemod) This repository contains a collection of codemod scripts based for use with [jscodeshift](https://github.com/facebook/jscodeshift) that help update MUI APIs. ## Setup & run <!-- #default-branch-switch --> ```bash npx @mui/codemod <codemod> <paths...> Applies a `@mui/codemod` to the specified paths Positionals: codemod The name of the codemod [string] paths Paths forwarded to `jscodeshift` [string] Options: --version Show version number [boolean] --help Show help [boolean] --dry dry run (no changes are made to files) [boolean] [default: false] --parser which parser for jscodeshift to use. [string] [default: 'tsx'] --print print transformed files to stdout, useful for development [boolean] [default: false] --jscodeshift [string] [default: false] Examples: npx @mui/codemod v4.0.0/theme-spacing-api src npx @mui/codemod v5.0.0/component-rename-prop src -- --component=Grid --from=prop --to=newProp npx @mui/codemod v5.0.0/preset-safe src --parser=flow ``` ### jscodeshift options To pass more options directly to jscodeshift, use `--jscodeshift="..."`. For example: ```bash npx @mui/codemod --jscodeshift="--run-in-band --verbose=2" ``` See all available options [here](https://github.com/facebook/jscodeshift#usage-cli). ### Recast Options Options to [recast](https://github.com/benjamn/recast)'s printer can be provided through jscodeshift's `printOptions` command line argument ```bash npx @mui/codemod <transform> <path> --jscodeshift="--printOptions='{\"quote\":\"double\"}'" ``` ## Included scripts ### v5.0.0 ### `base-use-named-exports` Base UI default exports were changed to named ones. Previously we had a mix of default and named ones. This was changed to improve consistency and avoid problems some bundlers have with default exports. See https://github.com/mui/material-ui/issues/21862 for more context. This codemod updates the import and re-export statements. ```diff - import BaseButton from '@mui/base/Button'; + import { Button as BaseButton } from '@mui/base/Button'; - export { default as BaseSlider } from '@mui/base/Slider'; + export { Slider as BaseSlider } from '@mui/base/Slider'; ``` ```bash npx @mui/codemod v5.0.0/base-use-named-exports <path> ``` ### `base-remove-unstyled-suffix` The `Unstyled` suffix has been removed from all Base UI component names, including names of types and other related identifiers. ```diff - <Input component='a' href='url' />; + <Input slots={{ root: 'a' }} href='url' />; ``` ```bash npx @mui/codemod v5.0.0/base-remove-unstyled-suffix <path> ``` #### `base-remove-component-prop` Remove `component` prop from all Base UI components by transferring its value into `slots.root`. This change only affects Base UI components. ```diff - <Input component={CustomRoot} /> + <Input slots={{ root: CustomRoot }} /> ``` ```bash npx @mui/codemod v5.0.0/base-remove-component-prop <path> ``` #### `rename-css-variables` Updates the names of the CSS variables of the Joy UI components to adapt to the new naming standards of the CSS variables for components. ```diff - <List sx={{ py: 'var(--List-divider-gap)' }}> + <List sx={{ py: 'var(--ListDivider-gap)' }}> - <Switch sx={{ '--Switch-track-width': '40px' }}> + <Switch sx={{ '--Switch-trackWidth': '40px' }}> ``` ```bash npx @mui/codemod v5.0.0/rename-css-variables <path> ``` #### `base-hook-imports` Updates the sources of the imports of the Base UI hooks to adapt to the new directories of the hooks. ```diff - import { useBadge } from '@mui/base/BadgeUnstyled'; + import useBadge from '@mui/base/useBadge'; ``` ```bash npx @mui/codemod v5.0.0/base-hook-imports <path> ``` #### `joy-rename-classname-prefix` Renames the classname prefix from `'Joy'` to `'Mui'` for Joy UI components. ```diff <Button - sx={{ '& .JoyButton-root': { '& .JoyButton-button': {} } }} + sx={{ '& .MuiButton-root': { '& .MuiButton-button': {} } }} />; ``` ```bash npx @mui/codemod v5.0.0/joy-rename-classname-prefix <path> ``` #### `joy-rename-row-prop` Transforms `row` prop to `orientation` prop across `Card`, `List` and `RadioGroup` components. ```diff <Card - row + orientation={"horizontal"} />; ``` ```bash npx @mui/codemod v5.0.0/joy-rename-row-prop <path> ``` #### `joy-avatar-remove-imgProps` Remove `imgProps` prop by transferring its value into `slotProps.img` This change only affects Joy UI Avatar component. ```diff <Avatar - imgProps={{ ['data-id']: 'imageId' }} - slotProps={{ root: { ['data-id']: 'rootId' }}} + slotProps={{ root: { ['data-id']: 'rootId' }, img: { ['data-id']: 'imageId' } }} />; ``` ```bash npx @mui/codemod v5.0.0/joy-avatar-remove-imgProps <path> ``` #### `joy-text-field-to-input` Replace `<TextField>` with composition of `Input` This change only affects Joy UI components. ```diff -import TextField from '@mui/joy/TextField'; +import FormControl from '@mui/joy/FormControl'; +import FormLabel from '@mui/joy/FormLabel'; +import FormHelperText from '@mui/joy/FormHelperText'; +import Input from '@mui/joy/Input'; -<TextField - id="Id" - label="Label" - placeholder="Placeholder" - helperText="Help!" - name="Name" - type="tel" - autoComplete="on" - autoFocus - error - required - fullWidth - defaultValue="DefaultValue" - size="sm" - color="primary" - variant="outlined" -/> +<FormControl + id="Id" + required + size="sm" + color="primary"> + <FormLabel> + Label + </FormLabel> + <JoyInput + placeholder="Placeholder" + name="Name" + type="tel" + autoComplete="on" + autoFocus + error + fullWidth + defaultValue="DefaultValue" + variant="outlined" /> + <FormHelperText id="Id-helper-text"> + Help! + </FormHelperText> +</FormControl> ``` ```bash npx @mui/codemod v5.0.0/joy-text-field-to-input <path> ``` #### `joy-rename-components-to-slots` Renames the `components` and `componentsProps` props to `slots` and `slotProps`, respectively. This change only affects Joy UI components. ```diff <Autocomplete - components={{ listbox: CustomListbox }} + slots={{ listbox: CustomListbox }} - componentsProps={{ root: { className: 'root' }, listbox: { 'data-testid': 'listbox' } }} + slotProps={{ root: { className: 'root' }, listbox: { 'data-testid': 'listbox' } }} />; ``` ```bash npx @mui/codemod v5.0.0/joy-rename-components-to-slots <path> ``` The associated breaking change was done in [#34997](https://github.com/mui/material-ui/pull/34997). #### `date-pickers-moved-to-x` Rename the imports of Date and Time Pickers from `@mui/lab` to `@mui/x-date-pickers` and `@mui/x-date-pickers-pro`. ```bash npx @mui/codemod v5.0.0/date-pickers-moved-to-x <path> ``` #### `tree-view-moved-to-x` Rename the imports of Tree View from `@mui/lab` to `@mui/x-tree-view`. ```bash npx @mui/codemod v5.0.0/tree-view-moved-to-x <path> ``` #### 🚀 `preset-safe` A combination of all important transformers for migrating v4 to v5. ⚠️ This codemod should be run only once. ```bash npx @mui/codemod v5.0.0/preset-safe <path|folder> ``` The list includes these transformers - [`adapter-v4`](#adapter-v4) - [`autocomplete-rename-closeicon`](#autocomplete-rename-closeicon) - [`autocomplete-rename-option`](#autocomplete-rename-option) - [`avatar-circle-circular`](#avatar-circle-circular) - [`badge-overlap-value`](#badge-overlap-value) - [`box-borderradius-values`](#box-borderradius-values) - [`box-rename-css`](#box-rename-css) - [`box-rename-gap`](#box-rename-gap) - [`button-color-prop`](#button-color-prop) - [`chip-variant-prop`](#chip-variant-prop) - [`circularprogress-variant`](#circularprogress-variant) - [`collapse-rename-collapsedheight`](#collapse-rename-collapsedheight) - [`core-styles-import`](#core-styles-import) - [`create-theme`](#create-theme) - [`dialog-props`](#dialog-props) - [`dialog-title-props`](#dialog-title-props) - [`emotion-prepend-cache`](#emotion-prepend-cache) - [`expansion-panel-component`](#expansion-panel-component) - [`fab-variant`](#fab-variant) - [`fade-rename-alpha`](#fade-rename-alpha) - [`grid-justify-justifycontent`](#grid-justify-justifycontent) - [`grid-list-component`](#grid-list-component) - [`icon-button-size`](#icon-button-size) - [`material-ui-styles`](#material-ui-styles) - [`material-ui-types`](#material-ui-types) - [`modal-props`](#modal-props) - [`moved-lab-modules`](#moved-lab-modules) - [`pagination-round-circular`](#pagination-round-circular) - [`optimal-imports`](#optimal-imports) - [`root-ref`](#root-ref) - [`skeleton-variant`](#skeleton-variant) - [`styled-engine-provider`](#styled-engine-provider) - [`table-props`](#table-props) - [`tabs-scroll-buttons`](#tabs-scroll-buttons) - [`textarea-minmax-rows`](#textarea-minmax-rows) - [`theme-augment`](#theme-augment) - [`theme-breakpoints`](#theme-breakpoints) - [`theme-breakpoints-width`](#theme-breakpoints-width) - [`theme-options`](#theme-options) - [`theme-palette-mode`](#theme-palette-mode) - [`theme-provider`](#theme-provider) - [`theme-spacing`](#theme-spacing) - [`theme-typography-round`](#theme-typography-round) - [`transitions`](#transitions) - [`use-autocomplete`](#use-autocomplete) - [`use-transitionprops`](#use-transitionprops) - [`with-mobile-dialog`](#with-mobile-dialog) - [`with-width`](#with-width) - [`mui-replace`](#mui-replace) #### `adapter-v4` Imports and inserts `adaptV4Theme` into `createTheme` (or `createMuiTheme`) ```diff +import { adaptV4Theme } from '@material-ui/core/styles'; -createTheme({ palette: { ... }}) +createTheme(adaptV4Theme({ palette: { ... }})) ``` ```bash npx @mui/codemod v5.0.0/adapter-v4 <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#theme). #### `autocomplete-rename-closeicon` Renames `Autocomplete`'s `closeIcon` prop to `clearIcon`. ```diff -<Autocomplete closeIcon={defaultClearIcon} /> +<Autocomplete clearIcon={defaultClearIcon} /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/autocomplete-rename-closeicon <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#autocomplete). #### `autocomplete-rename-option` Renames `Autocomplete`'s `getOptionSelected` to `isOptionEqualToValue`. ```diff <Autocomplete - getOptionSelected={(option, value) => option.title === value.title} + isOptionEqualToValue={(option, value) => option.title === value.title} /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/autocomplete-rename-option <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#autocomplete). #### `avatar-circle-circular` Updates the `Avatar`'s `variant` value and `classes` key from 'circle' to 'circular'. ```diff -<Avatar variant="circle" /> -<Avatar classes={{ circle: 'className' }} /> +<Avatar variant="circular" /> +<Avatar classes={{ circular: 'className' }} /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/avatar-circle-circular <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#avatar). #### `badge-overlap-value` Renames the badge's props. ```diff -<Badge overlap="circle"> -<Badge overlap="rectangle"> +<Badge overlap="circular"> +<Badge overlap="rectangular"> <Badge classes={{ - anchorOriginTopRightRectangle: 'className', - anchorOriginBottomRightRectangle: 'className', - anchorOriginTopLeftRectangle: 'className', - anchorOriginBottomLeftRectangle: 'className', - anchorOriginTopRightCircle: 'className', - anchorOriginBottomRightCircle: 'className', - anchorOriginTopLeftCircle: 'className', + anchorOriginTopRightRectangular: 'className', + anchorOriginBottomRightRectangular: 'className', + anchorOriginTopLeftRectangular: 'className', + anchorOriginBottomLeftRectangular: 'className', + anchorOriginTopRightCircular: 'className', + anchorOriginBottomRightCircular: 'className', + anchorOriginTopLeftCircular: 'className', }}> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/badge-overlap-value <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#badge). #### `base-rename-components-to-slots` Renames the `components` and `componentsProps` props to `slots` and `slotProps`, respectively. Also, changes `slots`' fields names to camelCase. This change only affects Base UI components. ```diff <BadgeUnstyled - components={{ Root, Badge: CustomBadge }} + slots={{ root: Root, badge: CustomBadge }} - componentsProps={{ root: { className: 'root' }, badge: { 'data-testid': 'badge' } }} + slotProps={{ root: { className: 'root' }, badge: { 'data-testid': 'badge' } }} />; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/base-rename-components-to-slots <path> ``` The associated breaking change was done in [#34693](https://github.com/mui/material-ui/pull/34693). #### `box-borderradius-values` Updates the Box API from separate system props to `sx`. ```diff -<Box borderRadius="borderRadius"> -<Box borderRadius={16}> +<Box borderRadius={1}> +<Box borderRadius="16px"> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/box-borderradius-values <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#box). #### `box-rename-css` Renames the Box `css` prop to `sx` ```diff -<Box css={{ m: 2 }}> +<Box sx={{ m: 2 }}> ``` ```bash npx @mui/codemod v5.0.0/box-rename-css <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#box). #### `box-rename-gap` Renames the Box `grid*Gap` props. ```diff -<Box gridGap={2}>Item 3</Box> -<Box gridColumnGap={3}>Item 4</Box> -<Box gridRowGap={4}>Item 5</Box> +<Box gap={2}>Item 3</Box> +<Box columnGap={3}>Item 4</Box> +<Box rowGap={4}>Item 5</Box> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/box-rename-gap <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#box). #### `button-color-prop` Removes the outdated `color` prop values. ```diff -<Button color="default"> +<Button> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/button-color-prop <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#button). #### `chip-variant-prop` Removes the Chip `variant` prop if the value is `"default"`. ```diff -<Chip variant="default"> +<Chip> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/chip-variant-prop <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#chip). #### `circularprogress-variant` Renames the CircularProgress `static` variant to `determinate`. ```diff -<CircularProgress variant="static" classes={{ static: 'className' }} /> +<CircularProgress variant="determinate" classes={{ determinate: 'className' }} /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/circularprogress-variant <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#circularprogress). #### `collapse-rename-collapsedheight` Renames `Collapse`'s `collapsedHeight` prop to `collapsedSize`. ```diff -<Collapse collapsedHeight={40} /> -<Collapse classes={{ container: 'collapse' }} /> +<Collapse collapsedSize={40} /> +<Collapse classes={{ root: 'collapse' }} /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/collapse-rename-collapsedheight <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#collapse). #### `component-rename-prop` A generic codemod to rename any component prop. ```diff -<Component prop="value" /> -<Component prop /> +<Component newProp="value" /> +<Component newProp /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/component-rename-prop <path> -- --component=Grid --from=prop --to=newProp ``` #### `core-styles-import` Renames private import from `core/styles/*` to `core/styles` ```diff -import { darken, lighten } from '@material-ui/core/styles/colorManipulator'; +import { darken, lighten } from '@material-ui/core/styles'; ``` ```bash npx @mui/codemod v5.0.0/core-styles-import <path> ``` #### `create-theme` Renames the function `createMuiTheme` to `createTheme` ```diff -import { createMuiTheme } from '@material-ui/core/styles'; +import { createTheme } from '@material-ui/core/styles'; ``` ```bash npx @mui/codemod v5.0.0/create-theme <path> ``` #### `dialog-props` Remove `disableBackdropClick` prop from `<Dialog>` ```diff -<Dialog disableBackdropClick /> +<Dialog /> ``` ```bash npx @mui/codemod v5.0.0/dialog-props <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#dialog). #### `dialog-title-props` Remove `disableTypography` prop from `<DialogTitle>` ```diff -<DialogTitle disableTypography /> +<DialogTitle /> ``` ```bash npx @mui/codemod v5.0.0/dialog-title-props <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#dialog). #### `emotion-prepend-cache` Adds `prepend: true` to Emotion `createCache` ```diff const cache = emotionCreateCache({ key: 'css', + prepend: true, }); ``` ```bash npx @mui/codemod v5.0.0/create-theme <path> ``` #### `expansion-panel-component` Renames `ExpansionPanel*` to `Accordion*` ```bash npx @mui/codemod v5.0.0/expansion-panel-component <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#expansionpanel). #### `fab-variant` ```diff -<Fab variant="round" /> +<Fab variant="circular" /> ``` ```bash npx @mui/codemod v5.0.0/fab-variant <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#fab). #### `fade-rename-alpha` Renames the `fade` style utility import and calls to `alpha`. ```diff -import { fade, lighten } from '@material-ui/core/styles'; +import { alpha, lighten } from '@material-ui/core/styles'; -const foo = fade('#aaa'); +const foo = alpha('#aaa'); ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/fade-rename-alpha <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#styles). #### `grid-justify-justifycontent` Renames `Grid`'s `justify` prop to `justifyContent`. ```diff -<Grid justify="left">Item</Grid> +<Grid item justifyContent="left">Item</Grid> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/grid-justify-justifycontent <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#grid). #### `grid-list-component` Renames `GridList*` to `ImageList*` ```bash npx @mui/codemod v5.0.0/grid-list-component <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#gridlist). #### `icon-button-size` Adds `size="large"` if `size` is not defined to get the same appearance as v4. ```diff -<IconButton size="medium" /> -<IconButton /> +<IconButton size="medium" /> +<IconButton size="large" /> ``` ```bash npx @mui/codemod v5.0.0/icon-button-size <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#iconbutton). #### `jss-to-styled` Replace JSS styling with `makeStyles` or `withStyles` to `styled` API. ```diff import Typography from '@material-ui/core/Typography'; -import makeStyles from '@material-ui/styles/makeStyles'; +import { styled } from '@material-ui/core/styles'; -const useStyles = makeStyles((theme) => ({ - root: { - display: 'flex', - alignItems: 'center', - backgroundColor: theme.palette.primary.main - }, - cta: { - borderRadius: theme.shape.radius - }, - content: { - color: theme.palette.common.white, - fontSize: 16, - lineHeight: 1.7 - }, -})) +const PREFIX = 'MyCard'; +const classes = { + root: `${PREFIX}-root`, + cta: `${PREFIX}-cta`, + content: `${PREFIX}-content`, +} +const Root = styled('div')((theme) => ({ + [`&.${classes.root}`]: { + display: 'flex', + alignItems: 'center', + backgroundColor: theme.palette.primary.main + }, + [`& .${classes.cta}`]: { + borderRadius: theme.shape.radius + }, + [`& .${classes.content}`]: { + color: theme.palette.common.white, + fontSize: 16, + lineHeight: 1.7 + }, +})) export const MyCard = () => { const classes = useStyles(); return ( - <div className={classes.root}> + <Root className={classes.root}> <Typography className={classes.content}>...</Typography> <Button className={classes.cta}>Go</Button> - </div> + </Root> ) } ``` ```bash npx @mui/codemod v5.0.0/jss-to-styled <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#1-use-styled-or-sx-api). > **Note:** This approach converts the first element in the return statement into styled component but also increases CSS specificity to override nested children. > This codemod should be adopted after handling all breaking changes, [check out the migration documentation](https://mui.com/material-ui/migration/migration-v4/). #### `jss-to-tss-react` Migrate JSS styling with `makeStyles` or `withStyles` to the corresponding `tss-react` API. ```diff -import clsx from 'clsx'; -import {makeStyles, createStyles} from '@material-ui/core/styles'; +import { makeStyles } from 'tss-react/mui'; -const useStyles = makeStyles((theme) => createStyles< - 'root' | 'small' | 'child', {color: 'primary' | 'secondary', padding: number} -> -({ - root: ({color, padding}) => ({ +const useStyles = makeStyles<{color: 'primary' | 'secondary', padding: number}, 'child' | 'small'>({name: 'App'})((theme, { color, padding }, classes) => ({ + root: { padding: padding, - '&:hover $child': { + [`&:hover .${classes.child}`]: { backgroundColor: theme.palette[color].main, } - }), + }, small: {}, child: { border: '1px solid black', height: 50, - '&$small': { + [`&.${classes.small}`]: { height: 30 } } -}), {name: 'App'}); +})); function App({classes: classesProp}: {classes?: any}) { - const classes = useStyles({color: 'primary', padding: 30, classes: classesProp}); + const { classes, cx } = useStyles({ + color: 'primary', + padding: 30 + }, { + props: { + classes: classesProp + } + }); return ( <div className={classes.root}> <div className={classes.child}> The Background take the primary theme color when the mouse hovers the parent. </div> - <div className={clsx(classes.child, classes.small)}> + <div className={cx(classes.child, classes.small)}> The Background take the primary theme color when the mouse hovers the parent. I am smaller than the other child. </div> </div> ); } export default App; ``` ```bash npx @mui/codemod v5.0.0/jss-to-tss-react <path> ``` The following scenarios are not currently handled by this codemod and will be marked with a "TODO jss-to-tss-react codemod" comment: - If the hook returned by `makeStyles` (e.g. `useStyles`) is exported and used in another file, the usages in other files will not be converted. - Arrow functions as the value for a CSS prop will not be converted. Arrow functions **are** supported at the rule level, though with some caveats listed below. - In order for arrow functions at the rule level to be converted, the parameter must use object destructuring (e.g. `root: ({color, padding}) => (...)`). If the parameter is not destructured (e.g. `root: (props) => (...)`), it will not be converted. - If an arrow function at the rule level contains a code block (i.e. contains an explicit `return` statement) rather than just an object expression, it will not be converted. You can find more details about migrating from JSS to tss-react in [the migration guide](https://mui.com/material-ui/migration/migrating-from-jss/#2-use-tss-react). #### `link-underline-hover` Apply `underline="hover"` to `<Link />` that does not define `underline` prop (to get the same behavior as in v4). ```diff -<Link /> +<Link underline="hover" /> ``` ```bash npx @mui/codemod v5.0.0/link-underline-hover <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#link). #### `material-ui-styles` Moves JSS imports to `@material-ui/styles` ```diff -import { - createGenerateClassName, - createStyles, - jssPreset, - makeStyles, - ServerStyleSheets, - useThemeVariants, - withStyles, - withTheme, - ThemeProvider, - styled, - getStylesCreator, - mergeClasses, -} from '@material-ui/core/styles'; +import { ThemeProvider, styled } from '@material-ui/core/styles'; +import createGenerateClassName from '@material-ui/styles/createGenerateClassName'; +import createStyles from '@material-ui/styles/createStyles'; +import jssPreset from '@material-ui/styles/jssPreset'; +import makeStyles from '@material-ui/styles/makeStyles'; +import ServerStyleSheets from '@material-ui/styles/ServerStyleSheets'; +import useThemeVariants from '@material-ui/styles/useThemeVariants'; +import withStyles from '@material-ui/styles/withStyles'; +import withTheme from '@material-ui/styles/withTheme'; +import getStylesCreator from '@material-ui/styles/getStylesCreator'; import mergeClasses from '@material-ui/styles/mergeClasses'; ``` ```bash npx @mui/codemod v5.0.0/material-ui-styles <path> ``` #### `material-ui-types` Renames `Omit` import from `@material-ui/types` to `DistributiveOmit` ```diff -import { Omit } from '@material-ui/types'; +import { DistributiveOmit } from '@material-ui/types'; ``` ```bash npx @mui/codemod v5.0.0/material-ui-types <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#material-ui-types). #### `modal-props` Removes `disableBackdropClick` and `onEscapeKeyDown` from `<Modal>` ```diff <Modal - disableBackdropClick - onEscapeKeyDown={handleEscapeKeyDown} /> ``` ```bash npx @mui/codemod v5.0.0/modal-props <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#modal). #### `moved-lab-modules` Updates all imports for `@material-ui/lab` components that have moved to `@material-ui/core`. ```diff -import Skeleton from '@material-ui/lab/Skeleton'; +import Skeleton from '@material-ui/core/Skeleton'; ``` or ```diff -import { SpeedDial } from '@material-ui/lab'; +import { SpeedDial } from '@material-ui/core'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/moved-lab-modules <path> ``` You can find more details about this breaking change in the migration guide. - [Alert](https://mui.com/material-ui/migration/v5-component-changes/#alert) - [Autocomplete](https://mui.com/material-ui/migration/v5-component-changes/#autocomplete) - [AvatarGroup](https://mui.com/material-ui/migration/v5-component-changes/#avatar) - [Pagination](https://mui.com/material-ui/migration/v5-component-changes/#pagination) - [Skeleton](https://mui.com/material-ui/migration/v5-component-changes/#skeleton) - [SpeedDial](https://mui.com/material-ui/migration/v5-component-changes/#speeddial) - [ToggleButton](https://mui.com/material-ui/migration/v5-component-changes/#togglebutton) #### `pagination-round-circular` Renames `Pagination*`'s `shape` values from 'round' to 'circular'. ```diff -<Pagination shape="round" /> -<PaginationItem shape="round" /> +<Pagination shape="circular" /> +<PaginationItem shape="circular" /> ``` ```bash npx @mui/codemod v5.0.0/pagination-round-circular <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#pagination). #### `optimal-imports` Fix private import paths. ```diff -import red from '@material-ui/core/colors/red'; -import createTheme from '@material-ui/core/styles/createTheme'; +import { red } from '@material-ui/core/colors'; +import { createTheme } from '@material-ui/core/styles'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/optimal-imports <path> ``` #### `root-ref` Removes `RootRef` from the codebase. ```bash npx @mui/codemod v5.0.0/root-ref <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#rootref). #### `skeleton-variant` ```diff -<Skeleton variant="circle" /> -<Skeleton variant="rect" /> +<Skeleton variant="circular" /> +<Skeleton variant="rectangular" /> ``` ```bash npx @mui/codemod v5.0.0/skeleton-variant <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#skeleton). #### `styled-engine-provider` Applies `StyledEngineProvider` to the files that contains `ThemeProvider`. ```bash npx @mui/codemod v5.0.0/styled-engine-provider <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-style-changes/#style-library). #### `table-props` Renames props in `Table*` components. ```diff -<> - <TablePagination onChangeRowsPerPage={() => {}} onChangePage={() => {}} /> - <TablePagination classes={{ input: 'foo' }} /> - <Table padding="default" /> - <TableCell padding="default" /> -</> +<> + <TablePagination onRowsPerPageChange={() => {}} onPageChange={() => {}} /> + <TablePagination classes={{ select: 'foo' }} /> + <Table padding="normal" /> + <TableCell padding="normal" /> +</> ``` ```bash npx @mui/codemod v5.0.0/table-props <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#table). #### `tabs-scroll-buttons` Renames the `Tabs`'s `scrollButtons` prop values. ```diff -<Tabs scrollButtons="on" /> -<Tabs scrollButtons="desktop" /> -<Tabs scrollButtons="off" /> +<Tabs scrollButtons allowScrollButtonsMobile /> +<Tabs scrollButtons /> +<Tabs scrollButtons={false} /> ``` ```bash npx @mui/codemod v5.0.0/tabs-scroll-buttons <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#tabs). #### `textarea-minmax-rows` Renames `TextField`'s rows props. ```diff -<TextField rowsMin={3} rowsMax={6} /> -<TextareaAutosize rows={2} /> -<TextareaAutosize rowsMin={3} rowsMax={6} /> +<TextField minRows={3} maxRows={6} /> +<TextareaAutosize minRows={2} /> +<TextareaAutosize minRows={3} maxRows={6} /> ``` ```bash npx @mui/codemod v5.0.0/textarea-minmax-rows <path> ``` You can find more details about this breaking change in the migration guide. - [TextareaAutosize](https://mui.com/material-ui/migration/v5-component-changes/#textareaautoresize) - [TextField](https://mui.com/material-ui/migration/v5-component-changes/#textfield) #### `theme-augment` Adds `DefaultTheme` module augmentation to typescript projects. ```bash npx @mui/codemod v5.0.0/theme-augment <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#material-ui-styles). #### `theme-breakpoints` Updates breakpoint values to match new logic. ⚠️ This mod is not idempotent, it should be run only once. ```diff -theme.breakpoints.down('sm') -theme.breakpoints.between('sm', 'md') +theme.breakpoints.down('md') +theme.breakpoints.between('sm', 'lg') ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/theme-breakpoints <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#theme). #### `theme-breakpoints-width` Renames `theme.breakpoints.width('md')` to `theme.breakpoints.values.md`. ```bash npx @mui/codemod v5.0.0/theme-breakpoints-width <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#theme). #### `theme-options` ```diff -import { ThemeOptions } from '@material-ui/core'; +import { DeprecatedThemeOptions } from '@material-ui/core'; ``` ```bash npx @mui/codemod v5.0.0/theme-options <path> ``` #### `theme-palette-mode` Renames `type` to `mode`. ```diff { palette: { - type: 'dark', + mode: 'dark', }, } ``` ```diff -theme.palette.type === 'dark' +theme.palette.mode === 'dark' ``` ```bash npx @mui/codemod v5.0.0/theme-palette-mode <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#theme). #### `theme-provider` Renames `MuiThemeProvider` to `ThemeProvider`. ```bash npx @mui/codemod v5.0.0/theme-provider <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#material-ui-core-styles). #### `theme-spacing` Removes the 'px' suffix from some template strings. ```diff -`${theme.spacing(2)}px` -`${theme.spacing(2)}px ${theme.spacing(4)}px` +`${theme.spacing(2)}` +`${theme.spacing(2)} ${theme.spacing(4)}` ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/theme-spacing <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#theme). #### `theme-typography-round` Renames `theme.typography.round($number)` to `Math.round($number * 1e5) / 1e5`. ```diff -`${theme.typography.round($number)}` +`${Math.round($number * 1e5) / 1e5}` ``` ```bash npx @mui/codemod v5.0.0/theme-typography-round <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#theme). #### `top-level-imports` Converts all `@mui/material` submodule imports to the root module: ```diff -import List from '@mui/material/List'; -import Grid from '@mui/material/Grid'; +import { List, Grid } from '@mui/material'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/top-level-imports <path> ``` Head to https://mui.com/guides/minimizing-bundle-size/ to understand when it's useful. #### `transitions` Renames import `transitions` to `createTransitions` ```bash npx @mui/codemod v5.0.0/transitions <path> ``` #### `use-autocomplete` Renames `useAutocomplete` related import from lab to core ```diff -import useAutocomplete from '@material-ui/lab/useAutocomplete'; +import useAutocomplete from '@material-ui/core/useAutocomplete'; ``` ```bash npx @mui/codemod v5.0.0/use-autocomplete <path> ``` #### `use-transitionprops` Updates Dialog, Menu, Popover, and Snackbar to use the `TransitionProps` prop to replace the `onEnter*` and `onExit*` props. ```diff <Dialog - onEnter={onEnter} - onEntered={onEntered} - onEntering={onEntering} - onExit={onExit} - onExited={onExited} - onExiting={onExiting} + TransitionProps={{ + onEnter, + onEntered, + onEntering, + onExit, + onExited, + onExiting, + }} /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/use-transitionprops <path> ``` You can find more details about this breaking change in [the migration guide](/material-ui/migration/v5-component-changes/#dialog). #### `variant-prop` > Don't run this codemod if you already set `variant` to `outlined` or `filled` in theme default props. Adds the TextField, Select, and FormControl's `variant="standard"` prop when `variant` is undefined. The diff should look like this: ```diff -<TextField value="Standard" /> +<TextField value="Standard" variant="standard" /> ``` ```diff -<Select value="Standard" /> +<Select value="Standard" variant="standard" /> ``` ```diff -<FormControl value="Standard" /> +<FormControl value="Standard" variant="standard" /> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v5.0.0/variant-prop <path> ``` #### `with-mobile-dialog` Removes imported `withMobileDialog`, and inserts hardcoded version to prevent application crash. ```diff -import withMobileDialog from '@material-ui/core/withMobileDialog'; +// FIXME checkout https://mui.com/material-ui/migration/v5-component-changes/#dialog +const withMobileDialog = () => (WrappedComponent) => (props) => <WrappedComponent {...props} width="lg" fullScreen={false} />; ``` ```bash npx @mui/codemod v5.0.0/with-mobile-dialog <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-component-changes/#dialog). #### `with-width` Removes `withWidth` import, and inserts hardcoded version to prevent application crash. ```diff -import withWidth from '@material-ui/core/withWidth'; +// FIXME checkout https://mui.com/components/use-media-query/#migrating-from-withwidth +const withWidth = () => (WrappedComponent) => (props) => <WrappedComponent {...props} width="xs" />; ``` ```bash npx @mui/codemod v5.0.0/with-width <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/v5-style-changes/#material-ui-core-styles). #### `mui-replace` Replace every occurrence of `material-ui` related package with the new package names (listed below) except these packages (`@material-ui/pickers`, `@material-ui/data-grid`, `@material-ui/x-grid` & `@material-ui/x-grid-data-generator`). [More details about why package names are changed](https://github.com/mui/material-ui/issues/27666) **Material Design components** ```diff -import Alert from '@material-ui/core/Alert'; +import Alert from '@mui/material/Alert'; ``` **JSS styles package** ```diff -import { makeStyles } from '@material-ui/styles'; +import { makeStyles } from '@mui/styles'; ``` **System package** ```diff -import { SxProps } from '@material-ui/system'; +import { SxProps } from '@mui/system'; ``` **Utilities package** ```diff -import { deepmerge } from '@material-ui/utils'; +import { deepmerge } from '@mui/utils'; ``` **Lab** ```diff -import Mansory from '@material-ui/lab/Mansory'; +import Mansory from '@mui/lab/Mansory'; ``` **Dependencies** ```diff // package.json -"@material-ui/core": "next", -"@material-ui/icons": "next", -"@material-ui/lab": "next", -"@material-ui/unstyled": "next", -"@material-ui/styled-engine-sc": "next", +"@mui/material": "next", +"@mui/icons-material": "next", +"@mui/lab": "next", +"@mui/base": "next", +"@mui/styled-engine-sc": "next", ``` ```bash npx @mui/codemod v5.0.0/mui-replace <path> ``` You can find more details about this breaking change in [the migration guide](https://mui.com/material-ui/migration/migration-v4/#update-material-ui-version). ### v4.0.0 #### `theme-spacing-api` Updates the `theme-spacing-api` from `theme.spacing.unit x` to `theme.spacing(x)`. The diff should look like this: ```diff -const spacing = theme.spacing.unit; +const spacing = theme.spacing(1); ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v4.0.0/theme-spacing-api <path> ``` This codemod tries to perform a basic expression simplification which can be improved for expressions that use more than one operation. ```diff -const spacing = theme.spacing.unit / 5; +const spacing = theme.spacing(0.2); // Limitation -const spacing = theme.spacing.unit * 5 * 5; +const spacing = theme.spacing(5) * 5; ``` #### `optimal-imports` Converts all `@material-ui/core` imports more than 1 level deep to the optimal form for tree shaking: ```diff -import withStyles from '@material-ui/core/styles/withStyles'; -import createTheme from '@material-ui/core/styles/createTheme'; +import { withStyles, createTheme } from '@material-ui/core/styles'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v4.0.0/optimal-imports <path> ``` Head to https://mui.com/guides/minimizing-bundle-size/ to understand when it's useful. #### `top-level-imports` Converts all `@material-ui/core` submodule imports to the root module: ```diff -import List from '@material-ui/core/List'; -import { withStyles } from '@material-ui/core/styles'; +import { List, withStyles } from '@material-ui/core'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v4.0.0/top-level-imports <path> ``` Head to https://mui.com/guides/minimizing-bundle-size/ to understand when it's useful. ### v1.0.0 #### `import-path` Updates the `import-paths` for the new location of the components. MUI v1.0.0 flatten the import paths. The diff should look like this: ```diff -import { MenuItem } from '@material-ui/core/Menu'; +import MenuItem from '@material-ui/core/MenuItem'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v1.0.0/import-path <path> ``` **Notice**: if you are migrating from pre-v1.0, and your imports use `material-ui`, you will need to manually find and replace all references to `material-ui` in your code to `@material-ui/core`. E.g.: ```diff -import Typography from 'material-ui/Typography'; +import Typography from '@material-ui/core/Typography'; ``` Subsequently, you can run the above `find ...` command to flatten your imports. #### `color-imports` Updates the `color-imports` for the new location of MUI color palettes. The diff should look like this: ```diff -import { blue, teal500 } from 'material-ui/styles/colors'; +import blue from '@material-ui/core/colors/blue'; +import teal from '@material-ui/core/colors/teal'; +const teal500 = teal['500']; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v1.0.0/color-imports <path> ``` **additional options** <!-- #default-branch-switch --> ```bash npx @mui/codemod v1.0.0/color-imports <path> -- --importPath='mui/styles/colors' --targetPath='mui/colors' ``` #### `svg-icon-imports` Updates the `svg-icons` import paths from `material-ui/svg-icons/<category>/<icon-name>` to `@material-ui/icons/<IconName>`, to use the new `@material-ui/icons` package. The diff should look like this: ```diff -import AccessAlarmIcon from 'material-ui/svg-icons/device/AccessAlarm'; -import ThreeDRotation from 'material-ui/svg-icons/action/ThreeDRotation'; +import AccessAlarmIcon from '@material-ui/icons/AccessAlarm'; +import ThreeDRotation from '@material-ui/icons/ThreeDRotation'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v1.0.0/svg-icon-imports <path> ``` #### `menu-item-primary-text` Updates `MenuItem` with `primaryText` property making its value tag's child. The diff should look like this: ```diff -<MenuItem primaryText="Profile" /> -<MenuItem primaryText={"Profile" + "!"} /> +<MenuItem>Profile</MenuItem> +<MenuItem>{"Profile" + "!"}</MenuItem> ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v1.0.0/menu-item-primary-text <path> ``` ### v0.15.0 #### `import-path` Updates the `import-paths` for the new location of the components. MUI v0.15.0 is reorganizing the folder distribution of the project. The diff should look like this: ```diff // From the source -import FlatButton from 'material-ui/src/flat-button'; +import FlatButton from 'material-ui/src/FlatButton'; // From npm -import RaisedButton from 'material-ui/lib/raised-button'; +import RaisedButton from 'material-ui/RaisedButton'; ``` <!-- #default-branch-switch --> ```bash npx @mui/codemod v0.15.0/import-path <path> ```
6,415
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-codemod/codemod.js
#!/usr/bin/env node const childProcess = require('child_process'); const { promises: fs } = require('fs'); const path = require('path'); const yargs = require('yargs'); const jscodeshiftPackage = require('jscodeshift/package.json'); const jscodeshiftDirectory = path.dirname(require.resolve('jscodeshift')); const jscodeshiftExecutable = path.join(jscodeshiftDirectory, jscodeshiftPackage.bin.jscodeshift); async function runTransform(transform, files, flags, codemodFlags) { const transformerSrcPath = path.resolve(__dirname, './src', `${transform}.js`); const transformerBuildPath = path.resolve(__dirname, './node', `${transform}.js`); let transformerPath; try { await fs.stat(transformerSrcPath); transformerPath = transformerSrcPath; } catch (srcPathError) { try { await fs.stat(transformerBuildPath); transformerPath = transformerBuildPath; } catch (buildPathError) { if (buildPathError.code === 'ENOENT') { throw new Error( `Transform '${transform}' not found. Check out ${path.resolve( __dirname, './README.md for a list of available codemods.', )}`, ); } throw buildPathError; } } const args = [ // can't directly spawn `jscodeshiftExecutable` due to https://github.com/facebook/jscodeshift/issues/424 jscodeshiftExecutable, '--transform', transformerPath, ...codemodFlags, '--extensions', 'js,ts,jsx,tsx', '--parser', flags.parser || 'tsx', '--ignore-pattern', '**/node_modules/**', ]; if (flags.dry) { args.push('--dry'); } if (flags.print) { args.push('--print'); } if (flags.jscodeshift) { args.push(flags.jscodeshift); } args.push(...files); // eslint-disable-next-line no-console -- debug information console.log(`Executing command: jscodeshift ${args.join(' ')}`); const jscodeshiftProcess = childProcess.spawnSync('node', args, { stdio: 'inherit' }); if (jscodeshiftProcess.error) { throw jscodeshiftProcess.error; } } function run(argv) { const { codemod, paths, ...flags } = argv; return runTransform( codemod, paths.map((filePath) => path.resolve(filePath)), flags, argv._, ); } yargs .command({ command: '$0 <codemod> <paths...>', describe: 'Applies a `@mui/codemod` to the specified paths', builder: (command) => { return command .positional('codemod', { description: 'The name of the codemod', type: 'string', }) .positional('paths', { array: true, description: 'Paths forwarded to `jscodeshift`', type: 'string', }) .option('dry', { description: 'dry run (no changes are made to files)', default: false, type: 'boolean', }) .option('parser', { description: 'which parser for jscodeshift to use', default: 'tsx', type: 'string', }) .option('print', { description: 'print transformed files to stdout, useful for development', default: false, type: 'boolean', }) .option('jscodeshift', { description: '(Advanced) Pass options directly to jscodeshift', default: false, type: 'string', }); }, handler: run, }) .scriptName('npx @mui/codemod') .example('$0 v4.0.0/theme-spacing-api src') .example('$0 v5.0.0/component-rename-prop src -- --component=Grid --from=prop --to=newProp') .help() .parse();
6,416
0
petrpan-code/mui/material-ui/packages
petrpan-code/mui/material-ui/packages/mui-codemod/package.json
{ "name": "@mui/codemod", "version": "5.14.18", "bin": "./codemod.js", "private": false, "author": "MUI Team", "description": "Codemod scripts for MUI.", "keywords": [ "react", "react-component", "mui", "codemod", "jscodeshift" ], "scripts": { "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-codemod/**/*.test.js'", "prebuild": "rimraf build", "build": "node ../../scripts/build.mjs node --out-dir ./build && cpy README.md build && cpy package.json build && cpy codemod.js build", "release": "yarn build && npm publish" }, "repository": { "type": "git", "url": "https://github.com/mui/material-ui.git", "directory": "packages/mui-codemod" }, "license": "MIT", "homepage": "https://github.com/mui/material-ui/tree/master/packages/mui-codemod", "funding": { "type": "opencollective", "url": "https://opencollective.com/mui-org" }, "dependencies": { "@babel/core": "^7.23.3", "@babel/runtime": "^7.23.2", "@babel/traverse": "^7.23.3", "jscodeshift": "^0.13.1", "jscodeshift-add-imports": "^1.0.10", "yargs": "^17.7.2" }, "devDependencies": { "@types/chai": "^4.3.10", "@types/jscodeshift": "0.11.5", "chai": "^4.3.10" }, "sideEffects": false, "publishConfig": { "access": "public" }, "engines": { "node": ">=12.0.0" } }
6,417
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/util/getJSExports.js
import { readFileSync } from 'fs'; import { parseSync } from '@babel/core'; import traverse from '@babel/traverse'; import memoize from './memoize'; const getJSExports = memoize((file) => { const result = new Set(); const ast = parseSync(readFileSync(file, 'utf8'), { filename: file, }); traverse(ast, { ExportSpecifier: ({ node: { exported } }) => { result.add(exported.name); }, }); return result; }); export default getJSExports;
6,418
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/util/memoize.js
const memoize = (func, resolver = (a) => a) => { const cache = new Map(); return (...args) => { const key = resolver(...args); if (cache.has(key)) { return cache.get(key); } const value = func(...args); cache.set(key, value); return value; }; }; export default memoize;
6,419
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/util/propsToObject.js
export default function propsToObject({ j, root, componentName, aliasName, propName, props }) { function buildObject(node, value) { const shorthand = node.value.expression && node.value.expression.name === node.name.name; const property = j.objectProperty( j.identifier(node.name.name), node.value.expression ? node.value.expression : node.value, ); property.shorthand = shorthand; value.push(property); return value; } const result = aliasName ? root.find(j.JSXElement, { openingElement: { name: { property: { name: componentName } } } }) : root.findJSXElements(componentName); return result.forEach((path) => { if (!aliasName || (aliasName && path.node.openingElement.name.object.name === aliasName)) { let propValue = []; const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { // Only transform whitelisted props if (node.type === 'JSXAttribute' && props.includes(node.name.name)) { propValue = buildObject(node, propValue); delete attributes[index]; } }); if (propValue.length > 0) { const propNameAttr = attributes.find((attr) => attr?.name?.name === propName); if (propNameAttr) { (propNameAttr.value.expression?.properties || []).push( ...j.objectExpression(propValue).properties, ); } else { attributes.push( j.jsxAttribute( j.jsxIdentifier(propName), j.jsxExpressionContainer(j.objectExpression(propValue)), ), ); } } } }); }
6,420
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/util/readFile.js
import fs from 'fs'; import { EOL } from 'os'; export default function readFile(filePath) { const fileContents = fs.readFileSync(filePath, 'utf8').toString(); if (EOL !== '\n') { return fileContents.replace(/\n/g, EOL); } return fileContents; }
6,421
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/util/renameClassKey.js
export default function renameClassKey({ root, componentName, classes, printOptions }) { const source = root .findJSXElements(componentName) .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if (node.type === 'JSXAttribute' && node.name.name === 'classes') { node.value?.expression?.properties?.forEach((subNode) => { if (Object.keys(classes).includes(subNode.key.name)) { subNode.key.name = classes[subNode.key.name]; } }); } }); }) .toSource(printOptions); return Object.entries(classes).reduce((result, [currentKey, newKey]) => { const regex = new RegExp(`.Mui${componentName}-${currentKey}`, 'gm'); return result.replace(regex, `.Mui${componentName}-${newKey}`); }, source); }
6,422
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/util/renameProps.js
export default function renameProps({ root, componentName, props }) { return root.findJSXElements(componentName).forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if (node.type === 'JSXAttribute' && Object.keys(props).includes(node.name.name)) { node.name.name = props[node.name.name]; } }); }); }
6,423
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v0.15.0/import-path.js
const pathConversion = { 'app-bar': 'AppBar', 'auto-complete': 'AutoComplete', avatar: 'Avatar', badge: 'Badge', 'flat-button': 'FlatButton', 'raised-button': 'RaisedButton', 'floating-action-button': 'FloatingActionButton', 'icon-button': 'IconButton', 'card/card': 'Card/Card', 'card/card-actions': 'Card/CardActions', 'card/card-header': 'Card/CardHeader', 'card/card-media': 'Card/CardMedia', 'card/card-title': 'Card/CardTitle', 'card/card-text': 'Card/CardText', 'date-picker/date-picker': 'DatePicker', dialog: 'Dialog', divider: 'Divider', 'grid-list/grid-list': 'GridList/GridList', 'grid-list/grid-tile': 'GridList/GridTile', 'font-icon': 'FontIcon', 'svg-icon': 'SvgIcon', 'left-nav': 'Drawer', 'lists/list': 'List/List', 'lists/list-item': 'List/ListItem', 'menus/menu': 'Menu', 'menus/menu-item': 'MenuItem', 'menus/icon-menu': 'IconMenu', paper: 'Paper', 'popover/popover': 'Popover', 'circular-progress': 'CircularProgress', 'linear-progress': 'LinearProgress', 'refresh-indicator': 'RefreshIndicator', 'select-field': 'SelectField', slider: 'Slider', checkbox: 'Checkbox', 'radio-button': 'RadioButton', 'radio-button-group': 'RadioButton/RadioButtonGroup', toggle: 'Toggle', snackbar: 'Snackbar', 'table/table': 'Table/Table', 'table/table-header-column': 'Table/TableHeaderColumn', 'table/table-row': 'Table/TableRow', 'table/table-header': 'Table/TableHeader', 'table/table-row-column': 'Table/TableRowColumn', 'table/table-body': 'Table/TableBody', 'table/table-footer': 'Table/TableFooter', 'tabs/tab': 'Tabs/Tab', 'tabs/tabs': 'Tabs/Tabs', 'text-field': 'TextField', 'time-picker/time-picker': 'TimePicker', 'toolbar/toolbar': 'Toolbar/Toolbar', 'toolbar/toolbar-group': 'Toolbar/ToolbarGroup', 'toolbar/toolbar-separator': 'Toolbar/ToolbarSeparator', 'toolbar/toolbar-title': 'Toolbar/ToolbarTitle', MuiThemeProvider: 'styles/MuiThemeProvider', }; const pathBaseSource = ['material-ui/src/', 'material-ui/src/']; const pathBasePackage = ['material-ui/lib/', 'material-ui/']; function getPathsBase(path) { if (path.indexOf(pathBaseSource[0]) === 0) { return pathBaseSource; } if (path.indexOf(pathBasePackage[0]) === 0) { return pathBasePackage; } return new Error('Wrong path'); } export default function transformer(fileInfo, api) { const j = api.jscodeshift; return j(fileInfo.source) .find(j.ImportDeclaration) .filter((path) => path.value.source.value.indexOf('material-ui/') === 0) .replaceWith((path) => { const pathOld = path.value.source.value; const pathsBase = getPathsBase(pathOld); const pathSuffix = pathOld.substring(pathsBase[0].length); let pathNew; if (pathConversion[pathSuffix]) { pathNew = pathsBase[1] + pathConversion[pathSuffix]; } else { pathNew = pathsBase[1] + pathSuffix; } return j.importDeclaration(path.node.specifiers, j.literal(pathNew)); }) .toSource({ quote: 'single', }); }
6,424
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v0.15.0/import-path.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './import-path'; import readFile from '../util/readFile'; function trim(str) { return str.replace(/^\s+|\s+$/, ''); } function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v0.15.0', () => { describe('import-path', () => { it('convert path as needed', () => { const actual = transform({ source: read('./import-path.test/actual.js') }, { jscodeshift }); const expected = read('./import-path.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,425
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v0.15.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v0.15.0/import-path.test/actual.js
import FlatButton from 'material-ui/src/flat-button'; import RaisedButton from 'material-ui/lib/raised-button'; import SvgIcon from 'material-ui/lib/svg-icon'; import Colors from 'material-ui/lib/styles/colors'; import NavigationExpandMoreIcon from 'material-ui/lib/svg-icons/navigation/expand-more';
6,426
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v0.15.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v0.15.0/import-path.test/expected.js
import FlatButton from 'material-ui/src/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import SvgIcon from 'material-ui/SvgIcon'; import Colors from 'material-ui/styles/colors'; import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more';
6,427
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/color-imports.js
// This codemod attempts to fix the color imports breaking change introduced in // https://github.com/mui/material-ui/releases/tag/v1.0.0-alpha.21 // List of colors that are in the `common` module const commonColors = [ 'black', 'white', 'transparent', 'fullBlack', 'darkBlack', 'lightBlack', 'minBlack', 'faintBlack', 'fullWhite', 'darkWhite', 'lightWhite', ]; /** * Break down `colorIdentifier` into its `palette` and `hue` * e.g. lightBlue600 -> [lightBlue, 600] * @param {string} colorIdentifier */ function colorAccent(colorIdentifier) { const [, palette, hue] = colorIdentifier.match(/([A-Za-z]+?)(A?\d+)?$/); return { palette, hue }; } /** * Return color module path * @param {string} colorPalette */ function colorImportPath(colorPalette) { return commonColors.indexOf(colorPalette) !== -1 ? 'common' : colorPalette; } /** * Replace all expressions that use identifier to access color palettes. * e.g. colors.amber100 -> colors.amber['100'] * @param {sting} identifier * @param {jscodeshift_api_object} j * @param {jscodeshift_ast_object} root */ function transformMemberExpressions(identifier, j, root) { // replace all expressions using `identifier` to access color palettes root.find(j.MemberExpression).forEach((path) => { if (path.node.object.name !== identifier) { return; } const colorProperty = path.node.property.name; const { palette, hue } = colorAccent(colorProperty); const colorModuleName = colorImportPath(palette); const property = hue || palette; path.node.property = hue || colorModuleName === 'common' ? j.memberExpression( j.identifier(colorModuleName), /^[_|a-z]/i.test(property) ? j.identifier(property) : j.literal(property), ) : j.identifier(colorModuleName); }); } /** * Replace all member imports. * e.g. import { red, blue } from 'material-ui/styles/colors' * @param {jscodeshift_api_object} j * @param {jscodeshift_ast_object} root * @param {string} importPath * @param {string} targetPath */ function transformMemberImports(j, root, importPath, targetPath) { // find member imports root.find(j.ImportDeclaration, { source: { value: importPath } }).forEach((importDeclaration) => { const memberImportSpecifiers = importDeclaration.node.specifiers.filter( (specifier) => specifier.type === 'ImportSpecifier', ); if (memberImportSpecifiers.length) { j(importDeclaration).replaceWith(() => { const importDeclarations = []; const assignmentExpressions = []; memberImportSpecifiers.forEach((memberSpecifier) => { const { palette, hue } = colorAccent(memberSpecifier.imported.name); const colorModuleName = colorImportPath(palette); const modulePath = `${targetPath}/${colorModuleName}`; const colorIdentifier = j.identifier(colorModuleName); // import color module (if not already imported) if (importDeclarations.map((p) => p.source.value).indexOf(modulePath) === -1) { importDeclarations.push( j.importDeclaration( [j.importDefaultSpecifier(colorIdentifier)], j.literal(modulePath), ), ); } // conditional assignment expression if (hue || colorModuleName === 'common') { const property = hue || palette; assignmentExpressions.push( j.variableDeclaration('const', [ j.variableDeclarator( j.identifier(memberSpecifier.local.name), j.memberExpression( colorIdentifier, /^[_|a-z]/i.test(property) ? j.identifier(property) : j.literal(property), ), ), ]), ); } }); return importDeclarations.concat(assignmentExpressions); }); } }); } /** * Replace all namespace imports. * e.g. import * as colors from 'material-ui/styles/colors' * @param {jscodeshift_api_object} j * @param {jscodeshift_ast_object} root * @param {string} importPath * @param {string} targetPath */ function transformNamespaceImports(j, root, importPath, targetPath) { // find namespace imports root.find(j.ImportDeclaration, { source: { value: importPath } }).forEach((importDeclaration) => { const namespaceImportSpecifier = importDeclaration.node.specifiers.find( (specifier) => specifier.type === 'ImportNamespaceSpecifier', ); if (namespaceImportSpecifier) { j(importDeclaration).replaceWith( j.importDeclaration( [j.importNamespaceSpecifier(j.identifier(namespaceImportSpecifier.local.name))], j.literal(targetPath), ), ); transformMemberExpressions(namespaceImportSpecifier.local.name, j, root); } }); } module.exports = function transformer(fileInfo, api, options = {}) { const j = api.jscodeshift; const root = j(fileInfo.source); const importPath = options.importPath || 'material-ui/styles/colors'; const targetPath = options.targetPath || '@material-ui/core/colors'; // transforms transformMemberImports(j, root, importPath, targetPath); transformNamespaceImports(j, root, importPath, targetPath); return root.toSource({ quote: 'single' }); };
6,428
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/color-imports.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './color-imports'; import readFile from '../util/readFile'; function trim(str) { return str.replace(/^\s+|\s+$/, ''); } function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v1.0.0', () => { describe('color-imports', () => { it('update color module imports', () => { const actual = transform( { source: read('./color-imports.test/actual.js') }, { jscodeshift }, ); const expected = read('./color-imports.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,429
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/import-path.js
const entryModuleToFlatten = [ 'BottomNavigation', 'BottomNavigationAction', 'Card', 'CardActions', 'CardContent', 'CardHeader', 'CardMedia', 'CircularProgress', 'ClickAwayListener', 'Collapse', 'Dialog', 'DialogActions', 'DialogContent', 'DialogContentText', 'DialogTitle', 'ExpansionPanel', 'ExpansionPanelActions', 'ExpansionPanelDetails', 'ExpansionPanelSummary', 'Fade', 'Form', 'FormControl', 'FormControlLabel', 'FormGroup', 'FormHelperText', 'FormLabel', 'GridList', 'GridListTile', 'Grow', 'Input', 'InputLabel', 'LinearProgress', 'List', 'ListItem', 'ListItemAvatar', 'ListItemIcon', 'ListItemSecondaryAction', 'ListItemText', 'ListSubheader', 'Menu', 'MenuItem', 'Progress', 'Radio', 'RadioGroup', 'Slide', 'Step', 'StepButton', 'StepContent', 'Stepper', 'Stepper', 'Tab', 'Table', 'TableBody', 'TableCell', 'TableFooter', 'TableHead', 'TablePagination', 'TableRow', 'Tabs', 'withWidth', 'Zoom', ]; const keepSpecifiers = ['withWidth']; export default function transformer(fileInfo, api, options) { const j = api.jscodeshift; let hasModifications = false; const printOptions = options.printOptions || { quote: 'single', trailingComma: true, }; const importModule = options.importModule || '@material-ui/core'; const targetModule = options.targetModule || '@material-ui/core'; const root = j(fileInfo.source); const importRegExp = new RegExp(`^${importModule}/(.+)$`); root.find(j.ImportDeclaration).forEach((path) => { const importPath = path.value.source.value; let entryModule = importPath.match(importRegExp); // Remove non-MUI imports if (!entryModule) { return; } entryModule = entryModule[1].split('/'); entryModule = entryModule[entryModule.length - 1]; // No need to flatten if (!entryModuleToFlatten.includes(entryModule)) { return; } hasModifications = true; if (keepSpecifiers.includes(entryModule)) { path.value.source.value = `${targetModule}/${entryModule}`; return; } path.node.specifiers.forEach((specifier) => { const localName = specifier.local.name; const importedName = specifier.imported ? specifier.imported.name : null; if (!importedName) { const importStatement = j.importDeclaration( [j.importDefaultSpecifier(j.identifier(localName))], j.literal(`${targetModule}/${entryModule}`), ); j(path).insertBefore(importStatement); } else { const importStatement = j.importDeclaration( [j.importDefaultSpecifier(j.identifier(localName))], j.literal(`${targetModule}/${importedName}`), ); j(path).insertBefore(importStatement); } }); path.prune(); }); return hasModifications ? root.toSource(printOptions) : null; }
6,430
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/import-path.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './import-path'; 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('v1.0.0', () => { describe('import-path', () => { it('convert path as needed', () => { const actual = transform( { source: read('./import-path.test/actual.js') }, { jscodeshift }, {}, ); const expected = read('./import-path.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('./import-path.test/expected.js') }, { jscodeshift }, {}, ); const expected = read('./import-path.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,431
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/menu-item-primary-text.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('MenuItem') .forEach((path) => { if (!path.node.openingElement.selfClosing) { return; } const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { if (node.type === 'JSXAttribute' && node.name.name === 'primaryText') { delete attributes[index]; path.node.openingElement.selfClosing = false; path.node.children = [node.value]; path.node.closingElement = j.jsxClosingElement(path.node.openingElement.name); } }); }) .toSource(printOptions); }
6,432
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/menu-item-primary-text.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './menu-item-primary-text'; 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('v1.0.0', () => { describe('menu-item-primary-text', () => { it('convert property as needed', () => { const actual = transform( { source: read('./menu-item-primary-text.test/actual.js') }, { jscodeshift }, {}, ); const expected = read('./menu-item-primary-text.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('./menu-item-primary-text.test/expected.js') }, { jscodeshift }, {}, ); const expected = read('./menu-item-primary-text.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,433
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/svg-icon-imports.js
/** * Capitalize a string * @param {string} string */ function capitalize(string) { return string ? `${string[0].toUpperCase()}${string.slice(1)}` : string; } /** * Transform kebab-case icon name to PascalCase * e.g. access-alarm => AccessAlarm * @param {string} iconName */ function pascalize(iconName) { return iconName.split('-').map(capitalize).join(''); } /** * Update all `svg-icons` import references to use `@material-ui/icons` package. * Find and replace string literal AST nodes to ensure all svg-icon paths get updated, regardless * of being in an import declaration, or a require() call, etc. * @param {jscodeshift_api_object} j * @param {jscodeshift_ast_object} root */ function transformSVGIconImports(j, root) { const pathMatchRegex = /^material-ui\/svg-icons\/.+\/(.+)$/; root .find(j.Literal) .filter((path) => pathMatchRegex.test(path.node.value)) .forEach((path) => { const [, iconName] = path.node.value.match(pathMatchRegex); // update to new path path.node.value = `@material-ui/icons/${pascalize(iconName)}`; }); } module.exports = function transformer(fileInfo, api) { const j = api.jscodeshift; const root = j(fileInfo.source); // transforms transformSVGIconImports(j, root); return root.toSource({ quote: 'single' }); };
6,434
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/svg-icon-imports.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './svg-icon-imports'; import readFile from '../util/readFile'; function trim(str) { return str.replace(/^\s+|\s+$/, ''); } function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v1.0.0', () => { describe('svg-icon-imports', () => { it('update svg-icon imports', () => { const actual = transform( { source: read('./svg-icon-imports.test/actual.js') }, { jscodeshift }, ); const expected = read('./svg-icon-imports.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,435
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/color-imports.test/actual.js
import { blue, teal500, fullWhite, fullBlack } from 'material-ui/styles/colors'; import { lightBlue600 as primaryColor, orangeA200 } from 'material-ui/styles/colors'; import * as muiColors from 'material-ui/styles/colors'; let randomColorUsedFromCollection = muiColors.amber100; console.log(muiColors.transparent);
6,436
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/color-imports.test/expected.js
import blue from '@material-ui/core/colors/blue'; import teal from '@material-ui/core/colors/teal'; import common from '@material-ui/core/colors/common'; const teal500 = teal['500']; const fullWhite = common.fullWhite; const fullBlack = common.fullBlack; import lightBlue from '@material-ui/core/colors/lightBlue'; import orange from '@material-ui/core/colors/orange'; const primaryColor = lightBlue['600']; const orangeA200 = orange.A200; import * as muiColors from '@material-ui/core/colors'; let randomColorUsedFromCollection = muiColors.amber['100']; console.log(muiColors.common.transparent);
6,437
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/import-path.test/actual.js
import * as React from 'react'; import { withStyles } from '@material-ui/core/styles'; import { MenuItem } from '@material-ui/core/Menu'; import MuiTabs, { Tab } from '@material-ui/core/Tabs'; import BottomNavigation, { BottomNavigationAction } from '@material-ui/core/BottomNavigation'; import Card, { CardActions, CardContent } from '@material-ui/core/Card'; import { CardHeader, CardMedia } from '@material-ui/core/Card'; import MuiCollapse from '@material-ui/core/transitions/Collapse'; import List, { ListItemIcon, ListItem, ListItemAvatar, ListItemText, ListItemSecondaryAction, } from '@material-ui/core/List'; import Dialog, { DialogTitle } from '@material-ui/core/Dialog'; import { DialogActions, DialogContent, DialogContentText } from '@material-ui/core/Dialog'; import Slide from '@material-ui/core/transitions/Slide'; import Radio, { RadioGroup } from '@material-ui/core/Radio'; import { FormControlLabel } from '@material-ui/core/Form'; import ExpansionPanel, { ExpansionPanelSummary, ExpansionPanelDetails, ExpansionPanelActions, } from '@material-ui/core/ExpansionPanel'; import GridList, { GridListTile } from '@material-ui/core/GridList'; import { CircularProgress } from '@material-ui/core/Progress'; import { LinearProgress as MuiLinearProgress } from '@material-ui/core/Progress'; import { FormLabel, FormControl, FormGroup, FormHelperText } from '@material-ui/core/Form'; import Fade from '@material-ui/core/transitions/Fade'; import Stepper, { Step, StepButton, StepContent } from '@material-ui/core/Stepper'; import Table, { TableBody, TableCell, TablePagination, TableRow } from '@material-ui/core/Table'; import TableHead from '@material-ui/core/Table/TableHead'; import Input, { InputLabel } from '@material-ui/core/Input'; import Grow from '@material-ui/core/transitions/Grow'; import TableFooter from '@material-ui/core/Table/TableFooter'; import withWidth, { isWidthUp } from '@material-ui/core/utils/withWidth'; import Zoom from '@material-ui/core/transitions/Zoom'; import ClickAwayListener from '@material-ui/core/utils/ClickAwayListener'; import ListSubheader from '@material-ui/core/List/ListSubheader';
6,438
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/import-path.test/expected.js
import * as React from 'react'; import { withStyles } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import Tab from '@material-ui/core/Tab'; import MuiTabs from '@material-ui/core/Tabs'; import BottomNavigationAction from '@material-ui/core/BottomNavigationAction'; import BottomNavigation from '@material-ui/core/BottomNavigation'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Card from '@material-ui/core/Card'; import CardMedia from '@material-ui/core/CardMedia'; import CardHeader from '@material-ui/core/CardHeader'; import MuiCollapse from '@material-ui/core/Collapse'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import List from '@material-ui/core/List'; import DialogTitle from '@material-ui/core/DialogTitle'; import Dialog from '@material-ui/core/Dialog'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogContent from '@material-ui/core/DialogContent'; import DialogActions from '@material-ui/core/DialogActions'; import Slide from '@material-ui/core/Slide'; import RadioGroup from '@material-ui/core/RadioGroup'; import Radio from '@material-ui/core/Radio'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import ExpansionPanelActions from '@material-ui/core/ExpansionPanelActions'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import GridListTile from '@material-ui/core/GridListTile'; import GridList from '@material-ui/core/GridList'; import CircularProgress from '@material-ui/core/CircularProgress'; import MuiLinearProgress from '@material-ui/core/LinearProgress'; import FormHelperText from '@material-ui/core/FormHelperText'; import FormGroup from '@material-ui/core/FormGroup'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; import Fade from '@material-ui/core/Fade'; import StepContent from '@material-ui/core/StepContent'; import StepButton from '@material-ui/core/StepButton'; import Step from '@material-ui/core/Step'; import Stepper from '@material-ui/core/Stepper'; import TableRow from '@material-ui/core/TableRow'; import TablePagination from '@material-ui/core/TablePagination'; import TableCell from '@material-ui/core/TableCell'; import TableBody from '@material-ui/core/TableBody'; import Table from '@material-ui/core/Table'; import TableHead from '@material-ui/core/TableHead'; import InputLabel from '@material-ui/core/InputLabel'; import Input from '@material-ui/core/Input'; import Grow from '@material-ui/core/Grow'; import TableFooter from '@material-ui/core/TableFooter'; import withWidth, { isWidthUp } from '@material-ui/core/withWidth'; import Zoom from '@material-ui/core/Zoom'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import ListSubheader from '@material-ui/core/ListSubheader';
6,439
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/menu-item-primary-text.test/actual.js
<div> <MenuItem onClick={() => { analytics('Clicked Menu > Progress'); }} primaryText="My Progress" rightIcon={<ProgressIcon />} /> <MenuItem onClick={() => { analytics('Clicked Menu > Progress2'); }} primaryText={true ? "My Progress" : "Not progress"} rightIcon={<ProgressIcon />} /> <MenuItem onClick={() => { analytics('Clicked Menu > Progress2'); }} primaryText={getText('progress')} rightIcon={<ProgressIcon />} /> <MenuItem onClick={() => { analytics('Clicked Menu > Progress'); }} rightIcon={<ProgressIcon />} > Already changed </MenuItem> </div>
6,440
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/menu-item-primary-text.test/expected.js
<div> <MenuItem onClick={() => { analytics('Clicked Menu > Progress'); }} rightIcon={<ProgressIcon />}>My Progress</MenuItem> <MenuItem onClick={() => { analytics('Clicked Menu > Progress2'); }} rightIcon={<ProgressIcon />}>{true ? "My Progress" : "Not progress"}</MenuItem> <MenuItem onClick={() => { analytics('Clicked Menu > Progress2'); }} rightIcon={<ProgressIcon />}>{getText('progress')}</MenuItem> <MenuItem onClick={() => { analytics('Clicked Menu > Progress'); }} rightIcon={<ProgressIcon />} > Already changed </MenuItem> </div>
6,441
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/svg-icon-imports.test/actual.js
import CheckCircle from 'material-ui/svg-icons/action/check-circle'; import Rotation3D from 'material-ui/svg-icons/action/three-d-rotation'; import Comment from 'material-ui/svg-icons/communication/comment'; const TransferWithinAStation = require('material-ui/svg-icons/maps/transfer-within-a-station');
6,442
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v1.0.0/svg-icon-imports.test/expected.js
import CheckCircle from '@material-ui/icons/CheckCircle'; import Rotation3D from '@material-ui/icons/ThreeDRotation'; import Comment from '@material-ui/icons/Comment'; const TransferWithinAStation = require('@material-ui/icons/TransferWithinAStation');
6,443
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.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')); } 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}`; const whitelist = getJSExports( require.resolve(`${importModule}/es/${subpath}`, { paths: [dirname(fileInfo.path)], }), ); 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()] .sort() .map((source) => j.importDeclaration(resultSpecifiers.get(source).sort(), j.stringLiteral(source)), ), ); return root.toSource(printOptions); }
6,444
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.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('@material-ui/codemod', () => { describe('v4.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,445
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/theme-spacing-api.js
/* eslint-disable no-eval */ /** * Update all `theme.spacing.unit` usages to use `theme.spacing()`. * Find and replace string literal AST nodes to ensure all spacing API usages get updated, regardless * of any calculation being performed. * @param {jscodeshift_api_object} j * @param {jscodeshift_ast_object} root */ function transformThemeSpacingApi(j, root) { const mightContainApi = (path) => { return ( j(path) .find(j.MemberExpression, { object: { property: { name: 'spacing', }, }, property: { name: 'unit', }, }) .size() > 0 ); }; const replaceApi = (pathArg) => { pathArg .find(j.MemberExpression, { object: { property: { name: 'spacing', }, }, property: { name: 'unit', }, }) .replaceWith((path) => { let param = null; const themeParam = path.node.object.object.name; if (j.BinaryExpression.check(path.parent.node)) { const expression = path.parent.node; const operation = expression.operator; // check if it's a variable if (j.Identifier.check(expression.right)) { param = expression.right; } else if (j.Literal.check(expression.right)) { const value = expression.right.value; if (operation === '*' || operation === '/') { param = j.literal(eval(`1 ${operation} ${value}`)); } } } if (param) { path.parent.replace( j.callExpression( j.memberExpression(j.identifier(themeParam), j.identifier('spacing')), [param], ), ); return path.node; } return j.callExpression( j.memberExpression(j.identifier(themeParam), j.identifier('spacing')), [j.literal(1)], ); }); }; const arrowFunctions = root.find(j.ArrowFunctionExpression).filter(mightContainApi); const functionDeclarations = root.find(j.FunctionDeclaration).filter(mightContainApi); replaceApi(arrowFunctions); replaceApi(functionDeclarations); } /** * Update all `spacing.unit` usages to use `spacing()`. * Find and replace string literal AST nodes to ensure all spacing API usages get updated, regardless * of any calculation being performed. * @param {jscodeshift_api_object} j * @param {jscodeshift_ast_object} root */ function transformThemeSpacingApiDestructured(j, root) { const mightContainApi = (path) => { return ( j(path) .find(j.MemberExpression, { object: { name: 'spacing', }, property: { name: 'unit', }, }) .size() > 0 ); }; const replaceApi = (pathArg) => { pathArg .find(j.MemberExpression, { object: { name: 'spacing', }, property: { name: 'unit', }, }) .replaceWith((path) => { let param = null; const spacingParam = path.node.object.name; if (j.BinaryExpression.check(path.parent.node)) { const expression = path.parent.node; const operation = expression.operator; // check if it's a variable if (j.Identifier.check(expression.right)) { param = expression.right; } else if (j.Literal.check(expression.right)) { const value = expression.right.value; if (operation === '*' || operation === '/') { param = j.literal(eval(`1 ${operation} ${value}`)); } } } if (param) { path.parent.replace(j.callExpression(j.identifier(spacingParam), [param])); return path.node; } return j.callExpression(j.identifier(spacingParam), [j.literal(1)]); }); }; const arrowFunctions = root.find(j.ArrowFunctionExpression).filter(mightContainApi); const functionDeclarations = root.find(j.FunctionDeclaration).filter(mightContainApi); replaceApi(arrowFunctions); replaceApi(functionDeclarations); } module.exports = function transformer(fileInfo, api) { const j = api.jscodeshift; const root = j(fileInfo.source); // transforms transformThemeSpacingApi(j, root); transformThemeSpacingApiDestructured(j, root); return root.toSource({ quote: 'single' }); };
6,446
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/theme-spacing-api.test.js
import path from 'path'; import { EOL } from 'os'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './theme-spacing-api'; import readFile from '../util/readFile'; function trim(str) { return str.replace(/^\s+|\s+$/, '').replace(/\r*\n/g, EOL); } function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v4.0.0', () => { describe('theme-spacing', () => { it('update theme spacing API', () => { const actual = transform( { source: read('./theme-spacing-api.test/actual.js') }, { jscodeshift }, ); const expected = read('./theme-spacing-api.test/expected.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); it('update theme spacing API for destructured', () => { const actual = transform( { source: read('./theme-spacing-api.test/actual_destructured.js') }, { jscodeshift }, ); const expected = read('./theme-spacing-api.test/expected_destructured.js'); expect(trim(actual)).to.equal(trim(expected), 'The transformed version should be correct'); }); }); }); });
6,447
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/top-level-imports.js
import addImports from 'jscodeshift-add-imports'; 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'; let requirePath = importModule; if (process.env.NODE_ENV === 'test') { requirePath = requirePath.replace(/^@material-ui\/core/, '../../../mui-material/src'); } // eslint-disable-next-line global-require, import/no-dynamic-require const whitelist = require(requirePath); 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[moduleName] == null) { return; } resultSpecifiers.push( j.importSpecifier(j.identifier(moduleName), j.identifier(localName)), ); path.get('specifiers', index).prune(); break; } case 'ImportSpecifier': if ( whitelist[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,448
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.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('v4.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,449
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/optimal-imports.test/actual.js
import * as React from 'react'; import { withTheme } from '@material-ui/core/styles'; import withStyles from '@material-ui/core/styles/withStyles'; import createTheme from '@material-ui/core/styles/createTheme'; import MenuItem from '@material-ui/core/MenuItem'; import Tab from '@material-ui/core/Tab'; import MuiTabs from '@material-ui/core/Tabs'; import BottomNavigationAction from '@material-ui/core/BottomNavigationAction'; import BottomNavigation from '@material-ui/core/BottomNavigation'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Card from '@material-ui/core/Card'; import CardMedia from '@material-ui/core/CardMedia'; import CardHeader from '@material-ui/core/CardHeader'; import MuiCollapse from '@material-ui/core/Collapse'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import List from '@material-ui/core/List'; import DialogTitle from '@material-ui/core/DialogTitle'; import Dialog from '@material-ui/core/Dialog'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogContent from '@material-ui/core/DialogContent'; import DialogActions from '@material-ui/core/DialogActions'; import Slide from '@material-ui/core/Slide'; import RadioGroup from '@material-ui/core/RadioGroup'; import Radio from '@material-ui/core/Radio'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import ExpansionPanelActions from '@material-ui/core/ExpansionPanelActions'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import CircularProgress from '@material-ui/core/CircularProgress'; import MuiLinearProgress from '@material-ui/core/LinearProgress'; import FormHelperText from '@material-ui/core/FormHelperText'; import FormGroup from '@material-ui/core/FormGroup'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; import Fade from '@material-ui/core/Fade'; import StepContent from '@material-ui/core/StepContent'; import StepButton from '@material-ui/core/StepButton'; import Step from '@material-ui/core/Step'; import Stepper from '@material-ui/core/Stepper'; import TableRow from '@material-ui/core/TableRow'; import TablePagination from '@material-ui/core/TablePagination'; import TableCell from '@material-ui/core/TableCell'; import TableBody from '@material-ui/core/TableBody'; import Table from '@material-ui/core/Table'; import TableHead from '@material-ui/core/TableHead'; import InputLabel from '@material-ui/core/InputLabel'; import Input from '@material-ui/core/Input'; import Grow from '@material-ui/core/Grow'; import TableFooter from '@material-ui/core/TableFooter'; import withWidth, { isWidthUp } from '@material-ui/core/withWidth'; import Zoom from '@material-ui/core/Zoom'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import ListSubheader from '@material-ui/core/ListSubheader'; // just testing that these get ignored import TableContext from '@material-ui/core/Table/TableContext'; import TabScrollButton from '@material-ui/core/Tabs/TabScrollButton'; import SwitchBase from '@material-ui/core/internal/SwitchBase';
6,450
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/optimal-imports.test/expected.js
import * as React from 'react'; import { withTheme, withStyles, createTheme } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import Tab from '@material-ui/core/Tab'; import MuiTabs from '@material-ui/core/Tabs'; import BottomNavigationAction from '@material-ui/core/BottomNavigationAction'; import BottomNavigation from '@material-ui/core/BottomNavigation'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Card from '@material-ui/core/Card'; import CardMedia from '@material-ui/core/CardMedia'; import CardHeader from '@material-ui/core/CardHeader'; import MuiCollapse from '@material-ui/core/Collapse'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import List from '@material-ui/core/List'; import DialogTitle from '@material-ui/core/DialogTitle'; import Dialog from '@material-ui/core/Dialog'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogContent from '@material-ui/core/DialogContent'; import DialogActions from '@material-ui/core/DialogActions'; import Slide from '@material-ui/core/Slide'; import RadioGroup from '@material-ui/core/RadioGroup'; import Radio from '@material-ui/core/Radio'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import ExpansionPanelActions from '@material-ui/core/ExpansionPanelActions'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import CircularProgress from '@material-ui/core/CircularProgress'; import MuiLinearProgress from '@material-ui/core/LinearProgress'; import FormHelperText from '@material-ui/core/FormHelperText'; import FormGroup from '@material-ui/core/FormGroup'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; import Fade from '@material-ui/core/Fade'; import StepContent from '@material-ui/core/StepContent'; import StepButton from '@material-ui/core/StepButton'; import Step from '@material-ui/core/Step'; import Stepper from '@material-ui/core/Stepper'; import TableRow from '@material-ui/core/TableRow'; import TablePagination from '@material-ui/core/TablePagination'; import TableCell from '@material-ui/core/TableCell'; import TableBody from '@material-ui/core/TableBody'; import Table from '@material-ui/core/Table'; import TableHead from '@material-ui/core/TableHead'; import InputLabel from '@material-ui/core/InputLabel'; import Input from '@material-ui/core/Input'; import Grow from '@material-ui/core/Grow'; import TableFooter from '@material-ui/core/TableFooter'; import withWidth, { isWidthUp } from '@material-ui/core/withWidth'; import Zoom from '@material-ui/core/Zoom'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import ListSubheader from '@material-ui/core/ListSubheader'; // just testing that these get ignored import TableContext from '@material-ui/core/Table/TableContext'; import TabScrollButton from '@material-ui/core/Tabs/TabScrollButton'; import SwitchBase from '@material-ui/core/internal/SwitchBase';
6,451
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/theme-spacing-api.test/actual.js
const spacingAlone = theme => ({ spacing: theme.spacing.unit, }); const spacingMultiply = theme => ({ spacing: theme.spacing.unit * 5, }); const spacingDivide = theme => ({ spacing: theme.spacing.unit / 5, }); const spacingAdd = theme => ({ spacing: theme.spacing.unit + 5, }); const spacingSubtract = theme => ({ spacing: theme.spacing.unit - 5, }); const variable = 3; const spacingVariable = theme => ({ spacing: theme.spacing.unit * variable, }); const spacingParamNameChange = muiTheme => ({ spacing: muiTheme.spacing.unit, }); function styleFunction(theme) { return { spacing: theme.spacing.unit, }; } const theme = {}; const shouldntTouch = theme.spacing.unit; const styles = muiTheme => ({ root: { spacing: muiTheme.spacing.unit } }); const longChain = theme => ({ spacing: theme.spacing.unit * 5 * 5, });
6,452
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/theme-spacing-api.test/actual_destructured.js
const spacingAlone = ({spacing}) => ({ spacing: spacing.unit, }); const spacingMultiply = ({spacing}) => ({ spacing: spacing.unit * 5, }); const spacingDivide = ({spacing}) => ({ spacing: spacing.unit / 5, }); const spacingAdd = ({spacing}) => ({ spacing: spacing.unit + 5, }); const spacingSubtract = ({spacing}) => ({ spacing: spacing.unit - 5, }); const variable = 3; const spacingVariable = ({spacing}) => ({ spacing: spacing.unit * variable, }); const spacingParamNameChange = muiTheme => ({ spacing: muiTheme.spacing.unit, }); function styleFunction({spacing}) { return { spacing: spacing.unit, }; } const longChain = ({spacing}) => ({ spacing: spacing.unit * 5 * 5, });
6,453
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/theme-spacing-api.test/expected.js
const spacingAlone = theme => ({ spacing: theme.spacing(1), }); const spacingMultiply = theme => ({ spacing: theme.spacing(5), }); const spacingDivide = theme => ({ spacing: theme.spacing(0.2), }); const spacingAdd = theme => ({ spacing: theme.spacing(1) + 5, }); const spacingSubtract = theme => ({ spacing: theme.spacing(1) - 5, }); const variable = 3; const spacingVariable = theme => ({ spacing: theme.spacing(variable), }); const spacingParamNameChange = muiTheme => ({ spacing: muiTheme.spacing(1), }); function styleFunction(theme) { return { spacing: theme.spacing(1), }; } const theme = {}; const shouldntTouch = theme.spacing.unit; const styles = muiTheme => ({ root: { spacing: muiTheme.spacing(1) } }); const longChain = theme => ({ spacing: theme.spacing(5) * 5, });
6,454
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/theme-spacing-api.test/expected_destructured.js
const spacingAlone = ({spacing}) => ({ spacing: spacing(1), }); const spacingMultiply = ({spacing}) => ({ spacing: spacing(5), }); const spacingDivide = ({spacing}) => ({ spacing: spacing(0.2), }); const spacingAdd = ({spacing}) => ({ spacing: spacing(1) + 5, }); const spacingSubtract = ({spacing}) => ({ spacing: spacing(1) - 5, }); const variable = 3; const spacingVariable = ({spacing}) => ({ spacing: spacing(variable), }); const spacingParamNameChange = muiTheme => ({ spacing: muiTheme.spacing(1), }); function styleFunction({spacing}) { return { spacing: spacing(1), }; } const longChain = ({spacing}) => ({ spacing: spacing(5) * 5, });
6,455
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/top-level-imports.test/actual.js
import * as React from 'react'; import { withStyles } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import Tab from '@material-ui/core/Tab'; import MuiTabs from '@material-ui/core/Tabs'; import BottomNavigationAction from '@material-ui/core/BottomNavigationAction'; import BottomNavigation from '@material-ui/core/BottomNavigation'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Card from '@material-ui/core/Card'; import CardMedia from '@material-ui/core/CardMedia'; import CardHeader from '@material-ui/core/CardHeader'; import MuiCollapse from '@material-ui/core/Collapse'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import List from '@material-ui/core/List'; import DialogTitle from '@material-ui/core/DialogTitle'; import Dialog from '@material-ui/core/Dialog'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogContent from '@material-ui/core/DialogContent'; import DialogActions from '@material-ui/core/DialogActions'; import Slide from '@material-ui/core/Slide'; import RadioGroup from '@material-ui/core/RadioGroup'; import Radio from '@material-ui/core/Radio'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import AccordionActions from '@material-ui/core/AccordionActions'; import AccordionDetails from '@material-ui/core/AccordionDetails'; import AccordionSummary from '@material-ui/core/AccordionSummary'; import Accordion from '@material-ui/core/Accordion'; import CircularProgress from '@material-ui/core/CircularProgress'; import MuiLinearProgress from '@material-ui/core/LinearProgress'; import FormHelperText from '@material-ui/core/FormHelperText'; import FormGroup from '@material-ui/core/FormGroup'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; import Fade from '@material-ui/core/Fade'; import StepContent from '@material-ui/core/StepContent'; import StepButton from '@material-ui/core/StepButton'; import Step from '@material-ui/core/Step'; import Stepper from '@material-ui/core/Stepper'; import TableRow from '@material-ui/core/TableRow'; import TablePagination from '@material-ui/core/TablePagination'; import TableCell from '@material-ui/core/TableCell'; import TableBody from '@material-ui/core/TableBody'; import Table from '@material-ui/core/Table'; import TableHead from '@material-ui/core/TableHead'; import InputLabel from '@material-ui/core/InputLabel'; import Input from '@material-ui/core/Input'; import Grow from '@material-ui/core/Grow'; import TableFooter from '@material-ui/core/TableFooter'; import Zoom from '@material-ui/core/Zoom'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import ListSubheader from '@material-ui/core/ListSubheader';
6,456
0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0
petrpan-code/mui/material-ui/packages/mui-codemod/src/v4.0.0/top-level-imports.test/expected.js
import * as React from 'react'; import { withStyles, MenuItem, Tab, Tabs as MuiTabs, BottomNavigationAction, BottomNavigation, CardContent, CardActions, Card, CardMedia, CardHeader, Collapse as MuiCollapse, ListItemSecondaryAction, ListItemText, ListItemAvatar, ListItem, ListItemIcon, List, DialogTitle, Dialog, DialogContentText, DialogContent, DialogActions, Slide, RadioGroup, Radio, FormControlLabel, AccordionActions, AccordionDetails, AccordionSummary, Accordion, CircularProgress, LinearProgress as MuiLinearProgress, FormHelperText, FormGroup, FormControl, FormLabel, Fade, StepContent, StepButton, Step, Stepper, TableRow, TablePagination, TableCell, TableBody, Table, TableHead, InputLabel, Input, Grow, TableFooter, Zoom, ClickAwayListener, ListSubheader, } from '@material-ui/core';
6,457
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/adapter-v4.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 adaptV4Called = false; function isNotadaptV4ThemeArg(node) { return ( node.arguments.length && (node.arguments[0].type !== 'CallExpression' || (node.arguments[0].type === 'CallExpression' && node.arguments[0].callee.name !== 'adaptV4Theme')) ); } function hasAdaptV4(node) { return ( node.arguments.length && node.arguments[0].type === 'CallExpression' && node.arguments[0].callee.name === 'adaptV4Theme' ); } /** * add adapterV4 inside createMuiTheme */ root.find(j.CallExpression, { callee: { name: 'createMuiTheme' } }).forEach(({ node }) => { if (hasAdaptV4(node)) { adaptV4Called = true; } if (isNotadaptV4ThemeArg(node)) { node.arguments = [j.callExpression(j.identifier('adaptV4Theme'), node.arguments)]; adaptV4Called = true; } }); /** * add adapterV4 inside createTheme */ root.find(j.CallExpression, { callee: { name: 'createTheme' } }).forEach(({ node }) => { if (hasAdaptV4(node)) { adaptV4Called = true; } if (isNotadaptV4ThemeArg(node)) { node.arguments = [j.callExpression(j.identifier('adaptV4Theme'), node.arguments)]; adaptV4Called = true; } }); /** * Add `adaptV4Theme` if called from above and not existed */ if (adaptV4Called) { const size = root .find(j.ImportDeclaration) .filter( ({ node }) => node.source.value.match(/^@material-ui\/core\/?(styles)?$/) || node.source.value.match(/^@mui\/material\/?(styles)$/), ) .at(0) .forEach(({ node }) => { if (!node.specifiers.find(({ imported }) => imported.name === 'adaptV4Theme')) { node.specifiers = [...node.specifiers, j.importSpecifier(j.identifier('adaptV4Theme'))]; } }) .size(); if (!size) { // create import root .find(j.ImportDeclaration) .at(0) .forEach((path) => { path.insertAfter( j.importDeclaration( [j.importSpecifier(j.identifier('adaptV4Theme'))], j.literal('@material-ui/core/styles'), ), ); }); } } return root.toSource(printOptions); }
6,458
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/adapter-v4.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './adapter-v4'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('adapter-v4', () => { it('add adaptV4Theme as needed', () => { const actual = transform( { source: read('./adapter-v4.test/actual.js'), path: require.resolve('./adapter-v4.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./adapter-v4.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./adapter-v4.test/expected.js'), path: require.resolve('./adapter-v4.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./adapter-v4.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('works with core import', () => { const actual = transform( { source: read('./adapter-v4.test/core-import.actual.js'), path: require.resolve('./adapter-v4.test/core-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./adapter-v4.test/core-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('works with other path import', () => { const actual = transform( { source: read('./adapter-v4.test/no-styles-import.actual.js'), path: require.resolve('./adapter-v4.test/no-styles-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./adapter-v4.test/no-styles-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,459
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/autocomplete-rename-closeicon.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: 'Autocomplete', props: { closeIcon: 'clearIcon' }, }).toSource(printOptions); }
6,460
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/autocomplete-rename-closeicon.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './autocomplete-rename-closeicon'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('autocomplete-rename-closeicon', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./autocomplete-rename-closeicon.test/actual.js'), path: require.resolve('./autocomplete-rename-closeicon.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./autocomplete-rename-closeicon.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./autocomplete-rename-closeicon.test/expected.js'), path: require.resolve('./autocomplete-rename-closeicon.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./autocomplete-rename-closeicon.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,461
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/autocomplete-rename-option.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: 'Autocomplete', props: { getOptionSelected: 'isOptionEqualToValue' }, }).toSource(printOptions); }
6,462
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/autocomplete-rename-option.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './autocomplete-rename-option'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('autocomplete-rename-option', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./autocomplete-rename-option.test/actual.js'), path: require.resolve('./autocomplete-rename-option.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./autocomplete-rename-option.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./autocomplete-rename-option.test/expected.js'), path: require.resolve('./autocomplete-rename-option.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./autocomplete-rename-option.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,463
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/avatar-circle-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) .findJSXElements('Avatar') .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if ( node.type === 'JSXAttribute' && node.name.name === 'variant' && (node.value.value === 'circle' || node.value.expression?.value === 'circle') ) { node.value = j.literal('circular'); } if (node.type === 'JSXAttribute' && node.name.name === 'classes') { node.value?.expression?.properties?.forEach((subNode) => { if (subNode.key.name === 'circle') { subNode.key.name = 'circular'; } }); } }); }) .toSource(printOptions); return source.replace(/\.MuiAvatar-circle/gm, '.MuiAvatar-circular'); }
6,464
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/avatar-circle-circular.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './avatar-circle-circular'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('avatar-circle-circular', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./avatar-circle-circular.test/actual.js'), path: require.resolve('./avatar-circle-circular.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./avatar-circle-circular.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./avatar-circle-circular.test/expected.js'), path: require.resolve('./avatar-circle-circular.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./avatar-circle-circular.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,465
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/badge-overlap-value.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('Badge') .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if (node.type === 'JSXAttribute' && node.name.name === 'overlap') { if (node.value.value === 'circle' || node.value.expression?.value === 'circle') { node.value = j.literal('circular'); } else if ( node.value.value === 'rectangle' || node.value.expression?.value === 'rectangle' ) { node.value = j.literal('rectangular'); } } if ( node.type === 'JSXAttribute' && node.name.name === 'classes' && Array.isArray(node.value?.expression?.properties) ) { node.value?.expression?.properties?.forEach((subNode) => { if (subNode.key) { if (subNode.key.name.endsWith('Circle')) { subNode.key.name = subNode.key.name.replace('Circle', 'Circular'); } if (subNode.key.name.endsWith('Rectangle')) { subNode.key.name = subNode.key.name.replace('Rectangle', 'Rectangular'); } } }); } }); }) .toSource(printOptions); return source .replace(/(\.MuiBadge-.*)ircle/gm, '$1ircular') .replace(/(\.MuiBadge-.*)ectangle/gm, '$1ectangular'); }
6,466
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/badge-overlap-value.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './badge-overlap-value'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('badge-overlap-value', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./badge-overlap-value.test/actual.js'), path: require.resolve('./badge-overlap-value.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./badge-overlap-value.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./badge-overlap-value.test/expected.js'), path: require.resolve('./badge-overlap-value.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./badge-overlap-value.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,467
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-hook-imports.js
const capitalize = (str) => { return str.charAt(0).toUpperCase() + str.slice(1); }; const movedTypeExports = [ // Slider 'Mark', // Select 'SelectOption', 'SelectChild', 'isOptionGroup', 'SelectOptionGroup', 'SelectChangeEventType', // Listbox 'OptionState', 'UseListboxPropsWithDefaults', 'FocusManagementType', 'ListboxState', 'ListboxAction', 'ListboxReducer', 'ListboxReducerAction', // Autocomplete 'createFilterOptions', 'FilterOptionsState', 'AutocompleteFreeSoloValueMapping', 'AutocompleteValue', 'UseAutocompleteProps', 'AutocompleteGroupedOption', 'CreateFilterOptionsConfig', 'FilterOptionsState', 'AutocompleteInputChangeReason', 'AutocompleteCloseReason', 'AutocompleteGetTagProps', ]; /** * @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((path) => { const sourceVal = path.node.source.value; return sourceVal.startsWith('@mui/base/') && sourceVal.match('Unstyled'); }) // Process only Base components .forEach((path) => { // scenario 1: `@mui/base/<Component>Unstyled/use<Component>` // e.g., `@mui/base/SelectUnstyled/useSelect` const sourceVal = path.node.source.value; // replace `@mui/base/SelectUnstyled/useSelect` with `@mui/base/useSelect` if (sourceVal.replace(/@mui\/base\/([a-zA-Z]+)Unstyled/, '') !== '') { path.node.source.value = sourceVal.replace( /@mui\/base\/([a-zA-Z]+)Unstyled\/([a-zA-Z]+)/, '@mui/base/$2', ); return; } // scenario 2: @mui/base/<Component>Unstyled const specifiersForHook = []; const filteredSpecifiers = []; const hookName = sourceVal.replace(/@mui\/base\/([a-zA-Z]+)Unstyled/, 'use$1'); path.node.specifiers.forEach((elementNode) => { if (elementNode.type !== 'ImportSpecifier' || !elementNode.imported?.name) { filteredSpecifiers.push(elementNode); return; } const importName = elementNode.imported.name; const localName = elementNode.local.name; if (hookName === importName) { // hook specifiersForHook.push(j.importDefaultSpecifier(j.identifier(localName))); } else if ( // types that no longer exist in `...Unstyled` movedTypeExports.includes(importName) || (importName.startsWith(capitalize(hookName)) && (importName.endsWith('SlotProps') || importName.endsWith('Parameters') || importName.endsWith('ReturnValue'))) ) { specifiersForHook.push(j.importSpecifier(j.identifier(importName), elementNode.local)); } else { filteredSpecifiers.push(elementNode); } }); path.node.specifiers = filteredSpecifiers; if (specifiersForHook.length === 0) { return; } const hookImportDeclaration = j.importDeclaration( specifiersForHook, j.literal(`@mui/base/${hookName}`), ); if (filteredSpecifiers.length > 0) { path.insertAfter(hookImportDeclaration); } else { path.replace(hookImportDeclaration); } }); return root.toSource(printOptions); }
6,468
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-hook-imports.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './base-hook-imports'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('base-hook-imports', () => { it('transforms the imports of Base hooks to default imports', () => { const actual = transform( { source: read('./base-hook-imports.test/actual.js'), path: require.resolve('./base-hook-imports.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./base-hook-imports.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,469
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-remove-component-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; const transformed = root .find(j.ImportDeclaration) // Process only Base UI components .filter(({ node }) => node.source.value.startsWith('@mui/base')) .forEach((path) => { path.node.specifiers.forEach((elementNode) => { root.findJSXElements(elementNode.local.name).forEach((elementPath) => { if (elementPath.node.type !== 'JSXElement') { return; } const attributeNodes = []; let slotPropNodeInserted = false; let slotsPropNode; elementPath.node.openingElement.attributes.forEach((attributeNode) => { if ( attributeNode.type !== 'JSXAttribute' && attributeNode.type !== 'JSXSpreadAttribute' ) { return; } if (attributeNode.type === 'JSXSpreadAttribute') { attributeNodes.push(attributeNode); return; } const attributeName = attributeNode.name.name; if (attributeName !== 'component' && attributeName !== 'slots') { attributeNodes.push(attributeNode); return; } if (attributeName === 'component') { const valueNode = attributeNode.value.expression || attributeNode.value; const rootObject = j.objectProperty(j.identifier('root'), valueNode); if (slotsPropNode && slotsPropNode.value.expression) { slotsPropNode.value.expression.properties.push(rootObject); } else { slotsPropNode = j.jsxAttribute( j.jsxIdentifier('slots'), j.jsxExpressionContainer(j.objectExpression([rootObject])), ); if (!slotPropNodeInserted) { slotPropNodeInserted = true; attributeNodes.push(slotsPropNode); } } if (file.path.endsWith('.ts') || file.path.endsWith('.tsx')) { if (valueNode.type === 'Literal' && valueNode.value && valueNode.raw) { elementPath.node.openingElement.name.name += `<${valueNode.raw}>`; } else if (valueNode.type === 'Identifier' && valueNode.name) { elementPath.node.openingElement.name.name += `<typeof ${valueNode.name}>`; } } } if (attributeName === 'slots') { if ( slotsPropNode && slotsPropNode.value.expression && attributeNode.value.expression ) { slotsPropNode.value.expression.properties = [ ...slotsPropNode.value.expression.properties, ...attributeNode.value.expression.properties, ]; } else { slotsPropNode = attributeNode; } if (!slotPropNodeInserted) { slotPropNodeInserted = true; attributeNodes.push(slotsPropNode); } } }); elementPath.node.openingElement.attributes = attributeNodes; }); }); }); return transformed.toSource(printOptions); }
6,470
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-remove-component-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './base-remove-component-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('base-remove-component-prop', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./base-remove-component-prop.test/actual.tsx'), path: require.resolve('./base-remove-component-prop.test/actual.tsx'), }, { jscodeshift }, {}, ); const expected = read('./base-remove-component-prop.test/expected.tsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); it('does not add generics if js is used', () => { const actual = transform( { source: read('./base-remove-component-prop.test/actual.jsx'), path: require.resolve('./base-remove-component-prop.test/actual.jsx'), }, { jscodeshift }, {}, ); const expected = read('./base-remove-component-prop.test/expected.jsx'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); });
6,471
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-remove-unstyled-suffix.js
/** * @param {import('jscodeshift').FileInfo} file * @param {import('jscodeshift').API} api */ export default function transformer(file, api) { const j = api.jscodeshift; const root = j(file.source); const transformed = root .find(j.ImportDeclaration) .filter(({ node }) => { const sourceVal = node.source.value; if (sourceVal.startsWith('@mui/base')) { node.source.value = sourceVal.replace(/unstyled/im, ''); node.source.raw = sourceVal.replace(/unstyled/im, ''); } return sourceVal.startsWith('@mui/base'); }) .forEach((path) => { const specifiers = []; path.node.specifiers.forEach((elementNode) => { const importedName = elementNode.imported?.name || ''; if (elementNode.type === 'ImportSpecifier' && importedName.match(/unstyled/im)) { elementNode.imported.name = importedName.replace(/unstyled/im, ''); if (elementNode.local.name === importedName) { // specifier must be newly created to add "as"; // e.g., import { SwitchUnstyled } to import { Switch as SwitchUnstyled} specifiers.push(j.importSpecifier(elementNode.imported, elementNode.local)); return; } } specifiers.push(elementNode); }); path.node.specifiers = specifiers; }) .toSource(); return transformed; }
6,472
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-remove-unstyled-suffix.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './base-remove-unstyled-suffix'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('base-remove-unstyled-suffix', () => { it('removes `Unstyled` suffix from Base UI components except default import declarations', () => { const actual = transform( { source: read('./base-remove-unstyled-suffix.test/actual.js'), path: require.resolve('./base-remove-unstyled-suffix.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./base-remove-unstyled-suffix.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,473
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-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; const transformed = root.findJSXElements().forEach((path) => { // Process only unstyled components if (!path.node.openingElement.name.name.endsWith('Unstyled')) { return; } path.node.openingElement.attributes.forEach((node) => { if (node.type !== 'JSXAttribute') { return; } switch (node.name.name) { case 'components': transformComponentsProp(node); break; case 'componentsProps': transformComponentsPropsProp(node); break; default: } }); }); return transformed.toSource(printOptions); }
6,474
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-rename-components-to-slots.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './base-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('base-rename-components-to-slots', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./base-rename-components-to-slots.test/actual.js'), path: require.resolve('./base-rename-components-to-slots.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./base-rename-components-to-slots.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,475
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-use-named-exports.js
// certain exports don't match the directory they are in: const nameMapping = { className: 'Unstable_ClassNameGenerator', composeClasses: 'unstable_composeClasses', generateUtilityClass: 'unstable_generateUtilityClass', generateUtilityClasses: 'unstable_generateUtilityClasses', NumberInput: 'Unstable_NumberInput', }; // renamed directories to match the export: const pathMapping = { '@mui/base/className': '@mui/base/ClassNameGenerator', }; function getExportedIdentifier(importPath) { return nameMapping[importPath] ?? importPath; } function getTransformedPath(originalPath) { return pathMapping[originalPath] ?? originalPath; } /** * Finds the last segment of the path starting with @mui/base. * * @example '@mui/base/Menu' ➔ 'Menu' * @example '@mui/base' ➔ null */ function getBaseImportIdentifier(path, filePath) { const source = path?.node?.source?.value; if (!source) { return null; } const baseImportPathMatch = source.match(/@mui\/base\/(.+)/); if (baseImportPathMatch == null) { return null; } if (baseImportPathMatch[1]?.includes('/')) { console.warn( `WARNING: ${filePath}: "${source}" is more than one level deep. This is not supported.`, ); return null; } return baseImportPathMatch[1] ?? null; } /** * @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 withTransformedImports = j(file.source) .find(j.ImportDeclaration) .forEach((path) => { const baseImportPath = getBaseImportIdentifier(path, file.path); if (baseImportPath === null) { return; } path.node.specifiers = path.node.specifiers.map((specifier) => { if (specifier.type !== 'ImportDefaultSpecifier') { return specifier; } // import Y from @mui/base/X ➔ import { X as Y } from @mui/base/X return j.importSpecifier( j.identifier(getExportedIdentifier(baseImportPath)), specifier.local, ); }); path.node.source = j.stringLiteral(getTransformedPath(path.node.source.value)); }) .toSource(printOptions); return j(withTransformedImports) .find(j.ExportNamedDeclaration) .forEach((path) => { const baseImportPath = getBaseImportIdentifier(path); if (baseImportPath === null) { return; } path.node.specifiers = path.node.specifiers.map((specifier) => { if (specifier.local.name !== 'default') { return specifier; } if (specifier.exported.name === 'default') { // export { default } from @mui/base/X ➔ export { X as default } from @mui/base/X return j.exportSpecifier.from({ exported: j.identifier('default'), local: j.identifier(baseImportPath), }); } // export { default as Y } from @mui/base/X ➔ export { X as Y } from @mui/base/X return j.exportSpecifier.from({ exported: j.identifier(specifier.exported.name), local: j.identifier(getExportedIdentifier(baseImportPath)), }); }); path.node.source = j.stringLiteral(getTransformedPath(path.node.source.value)); }) .toSource(printOptions); }
6,476
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/base-use-named-exports.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './base-use-named-exports'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('base-use-named-exports', () => { it('transforms exports as needed', () => { const actual = transform( { source: read('./base-use-named-exports.test/actual.js'), path: require.resolve('./base-use-named-exports.test/actual.js'), }, { jscodeshift }, { printOptions: { quote: 'single' } }, ); const expected = read('./base-use-named-exports.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./base-use-named-exports.test/expected.js'), path: require.resolve('./base-use-named-exports.test/expected.js'), }, { jscodeshift }, { printOptions: { quote: 'single' } }, ); const expected = read('./base-use-named-exports.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('warns when deep import is found but transforms all the valid ones', () => { let actual; const filePath = require.resolve('./base-use-named-exports.test/actual-with-warning.js'); expect(() => { actual = transform( { source: read('./base-use-named-exports.test/actual-with-warning.js'), path: filePath, }, { jscodeshift }, { printOptions: { quote: 'single' } }, ); }).toWarnDev( `WARNING: ${filePath}: "@mui/base/utils/ClassNameConfigurator" is more than one level deep. This is not supported.`, ); const expected = read('./base-use-named-exports.test/expected-with-warning.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); expect(actual); }); }); }); });
6,477
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-borderradius-values.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('Box') .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if (node.type === 'JSXAttribute' && node.name.name === 'borderRadius') { // borderRadius={16} => borderRadius="16px" if (node.value.type === 'JSXExpressionContainer') { node.value = j.stringLiteral(`${node.value.expression.value}px`); // borderRadius="borderRadius" => borderRadius={1} } else if (node.value.value === 'borderRadius') { node.value = j.jsxExpressionContainer(j.numericLiteral(1)); } } }); }) .toSource(printOptions); }
6,478
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-borderradius-values.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './box-borderradius-values'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('box-borderradius-values', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./box-borderradius-values.test/actual.js'), path: require.resolve('./box-borderradius-values.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./box-borderradius-values.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,479
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-rename-css.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 || { quote: 'single', }; return renameProps({ root, componentName: 'Box', props: { css: 'sx' }, }).toSource(printOptions); }
6,480
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-rename-css.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './box-rename-css'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('box-rename-css', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./box-rename-css.test/actual.js'), path: require.resolve('./box-rename-css.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./box-rename-css.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./box-rename-css.test/expected.js'), path: require.resolve('./box-rename-css.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./box-rename-css.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,481
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-rename-gap.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: 'Box', props: { gridGap: 'gap', gridColumnGap: 'columnGap', gridRowGap: 'rowGap' }, }).toSource(printOptions); }
6,482
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-rename-gap.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './box-rename-gap'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('box-rename-gap', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./box-rename-gap.test/actual.js'), path: require.resolve('./box-rename-gap.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./box-rename-gap.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./box-rename-gap.test/expected.js'), path: require.resolve('./box-rename-gap.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./box-rename-gap.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,483
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-sx-prop.js
import propsToObject from '../util/propsToObject'; const props = [ 'border', 'borderTop', 'borderRight', 'borderBottom', 'borderLeft', 'borderColor', 'borderRadius', 'displayPrint', 'display', 'overflow', 'textOverflow', 'visibility', 'whiteSpace', 'flexDirection', 'flexWrap', 'justifyContent', 'alignItems', 'alignContent', 'order', 'flex', 'flexGrow', 'flexShrink', 'alignSelf', 'color', 'bgcolor', 'position', 'zIndex', 'top', 'right', 'bottom', 'left', 'boxShadow', 'width', 'maxWidth', 'minWidth', 'height', 'maxHeight', 'minHeight', 'boxSizing', 'm', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'letterSpacing', 'lineHeight', 'textAlign', ]; /** * @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 aliasName; root.find(j.ImportDeclaration).forEach((path) => { if (path.node.source.value.match(/^(@mui\/material|@material-ui\/core)$/)) { if (path.node.specifiers[0]?.type === 'ImportNamespaceSpecifier') { aliasName = path.node.specifiers[0].local.name; } } }); return propsToObject({ j, root, aliasName, componentName: 'Box', propName: 'sx', props, }).toSource(printOptions); }
6,484
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/box-sx-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './box-sx-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('box-sx-prop', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./box-sx-prop.test/actual.js'), path: require.resolve('./box-sx-prop.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./box-sx-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./box-sx-prop.test/expected.js'), path: require.resolve('./box-sx-prop.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./box-sx-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('alias, transforms props as needed', () => { const actual = transform( { source: read('./box-sx-prop.test/alias-actual.js'), path: require.resolve('./box-sx-prop.test/alias-actual.js'), }, { jscodeshift }, {}, ); const expected = read('./box-sx-prop.test/alias-expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('alias, should be idempotent', () => { const actual = transform( { source: read('./box-sx-prop.test/alias-expected.js'), path: require.resolve('./box-sx-prop.test/alias-expected.js'), }, { jscodeshift }, {}, ); const expected = read('./box-sx-prop.test/alias-expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,485
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/button-color-prop.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('Button') .forEach((path) => { const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { if ( node.type === 'JSXAttribute' && node.name.name === 'color' && (node.value.value === 'default' || node.value.expression?.value === 'default') ) { delete attributes[index]; } }); }) .toSource(printOptions); }
6,486
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/button-color-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './button-color-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('button-color-prop', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./button-color-prop.test/actual.js'), path: require.resolve('./button-color-prop.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./button-color-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./button-color-prop.test/expected.js'), path: require.resolve('./button-color-prop.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./button-color-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,487
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/chip-variant-prop.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('Chip') .forEach((path) => { const attributes = path.node.openingElement.attributes; attributes.forEach((node, index) => { if ( node.type === 'JSXAttribute' && node.name.name === 'variant' && (node.value.value === 'default' || node.value.expression?.value === 'default') ) { delete attributes[index]; } }); }) .toSource(printOptions); }
6,488
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/chip-variant-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './chip-variant-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('chip-variant-prop', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./chip-variant-prop.test/actual.js'), path: require.resolve('./chip-variant-prop.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./chip-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('./chip-variant-prop.test/expected.js'), path: require.resolve('./chip-variant-prop.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./chip-variant-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,489
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/circularprogress-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; return j(file.source) .findJSXElements('CircularProgress') .forEach((path) => { path.node.openingElement.attributes.forEach((node) => { if ( node.type === 'JSXAttribute' && node.name.name === 'variant' && (node.value.value === 'static' || node.value.expression?.value === 'static') ) { node.value = j.literal('determinate'); } if (node.type === 'JSXAttribute' && node.name.name === 'classes') { node.value?.expression?.properties?.forEach((subNode) => { if (subNode.key.name === 'static') { subNode.key.name = 'determinate'; } }); } }); }) .toSource(printOptions); }
6,490
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/circularprogress-variant.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './circularprogress-variant'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('circularprogress-variant', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./circularprogress-variant.test/actual.js'), path: require.resolve('./circularprogress-variant.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./circularprogress-variant.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./circularprogress-variant.test/expected.js'), path: require.resolve('./circularprogress-variant.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./circularprogress-variant.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,491
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/collapse-rename-collapsedheight.js
import renameProps from '../util/renameProps'; import renameClassKey from '../util/renameClassKey'; export default function transformer(file, api, options) { const j = api.jscodeshift; const root = j(file.source); const printOptions = options.printOptions; renameProps({ root, componentName: 'Collapse', props: { collapsedHeight: 'collapsedSize' }, }); return renameClassKey({ root, componentName: 'Collapse', classes: { container: 'root' }, printOptions, }); }
6,492
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/collapse-rename-collapsedheight.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './collapse-rename-collapsedheight'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('collapse-rename-collapsedheight', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./collapse-rename-collapsedheight.test/actual.js'), path: require.resolve('./collapse-rename-collapsedheight.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./collapse-rename-collapsedheight.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./collapse-rename-collapsedheight.test/expected.js'), path: require.resolve('./collapse-rename-collapsedheight.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./collapse-rename-collapsedheight.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,493
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/component-rename-prop.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: options.component, props: { [options.from]: options.to }, }).toSource(printOptions); }
6,494
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/component-rename-prop.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './component-rename-prop'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('component-rename-prop', () => { it('transforms props as needed', () => { const actual = transform( { source: read('./component-rename-prop.test/actual.js'), }, { jscodeshift }, { component: 'Component', from: 'prop', to: 'newProp' }, ); const expected = read('./component-rename-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./component-rename-prop.test/expected.js'), }, { jscodeshift }, { component: 'Component', from: 'prop', to: 'newProp' }, ); const expected = read('./component-rename-prop.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,495
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/core-styles-import.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 importStyles = root .find(j.ImportDeclaration) .filter((path) => path.node.source.value === '@material-ui/core/styles') .nodes()[0]; root .find(j.ImportDeclaration) .filter((path) => path.node.source.value.match(/^@material-ui\/core\/styles\/.+$/)) .forEach((path) => { const specifiers = path.node.specifiers.map((s) => { if (s.type === 'ImportDefaultSpecifier') { return j.importSpecifier(j.identifier(s.local.name)); } return s; }); if (!importStyles) { importStyles = j.importDeclaration(specifiers, j.literal('@material-ui/core/styles')); path.insertBefore(importStyles); } else { importStyles.specifiers.push(...specifiers); } }) .remove(); return root.toSource(printOptions); }
6,496
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/core-styles-import.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './core-styles-import'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('core-styles-import', () => { it('transforms as needed', () => { const actual = transform( { source: read('./core-styles-import.test/actual.js'), path: require.resolve('./core-styles-import.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./core-styles-import.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./core-styles-import.test/expected.js'), path: require.resolve('./core-styles-import.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./core-styles-import.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,497
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/create-theme.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', }; if (file.source.match(/(function\s*createTheme|const\s*createTheme)/g)) { root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/core\/?(styles)?$/)) .forEach(({ node }) => { let localName; node.specifiers.forEach((specifier, index) => { if (specifier.imported.name === 'createMuiTheme') { localName = specifier.local.name; delete node.specifiers[index]; } }); if (localName) { node.specifiers.push( j.importSpecifier(j.identifier('createTheme'), j.identifier(localName)), ); } }); } else { let previousVarName; root .find(j.ImportDeclaration) .filter(({ node }) => node.source.value.match(/^@material-ui\/core\/?(styles)?$/)) .forEach(({ node }) => { node.specifiers.forEach((specifier) => { if (!specifier.imported && specifier.local.name === 'createMuiTheme') { // default specifier previousVarName = specifier.local.name; specifier.local.name = 'createTheme'; } if (specifier.imported && specifier.imported.name === 'createMuiTheme') { previousVarName = specifier.local.name; specifier.local = null; specifier.imported.name = 'createTheme'; } }); }); root.find(j.CallExpression, { callee: { name: previousVarName } }).forEach(({ node }) => { node.callee.name = 'createTheme'; }); } return root.toSource(printOptions); }
6,498
0
petrpan-code/mui/material-ui/packages/mui-codemod/src
petrpan-code/mui/material-ui/packages/mui-codemod/src/v5.0.0/create-theme.test.js
import path from 'path'; import { expect } from 'chai'; import jscodeshift from 'jscodeshift'; import transform from './create-theme'; import readFile from '../util/readFile'; function read(fileName) { return readFile(path.join(__dirname, fileName)); } describe('@mui/codemod', () => { describe('v5.0.0', () => { describe('create-theme', () => { it('transforms createMuiTheme as needed', () => { const actual = transform( { source: read('./create-theme.test/actual.js'), path: require.resolve('./create-theme.test/actual.js'), }, { jscodeshift }, {}, ); const expected = read('./create-theme.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('should be idempotent', () => { const actual = transform( { source: read('./create-theme.test/expected.js'), path: require.resolve('./create-theme.test/expected.js'), }, { jscodeshift }, {}, ); const expected = read('./create-theme.test/expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('transforms with core import', () => { const actual = transform( { source: read('./create-theme.test/core-import.actual.js'), path: require.resolve('./create-theme.test/core-import.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./create-theme.test/core-import.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); it('existing custom createTheme', () => { const actual = transform( { source: read('./create-theme.test/custom-fn.actual.js'), path: require.resolve('./create-theme.test/custom-fn.actual.js'), }, { jscodeshift }, {}, ); const expected = read('./create-theme.test/custom-fn.expected.js'); expect(actual).to.equal(expected, 'The transformed version should be correct'); }); }); }); });
6,499