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 | petrpan-code/mui/material-ui/packages/mui-base/tsconfig.build.json | {
// This config is for emitting declarations (.d.ts) only
// Actual .ts source files are transpiled via babel
"extends": "./tsconfig.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"noEmit": false,
"emitDeclarationOnly": true,
"outDir": "build",
"rootDir": "./src"
},
"include": ["src/**/*.ts*"],
"exclude": ["src/**/*.spec.ts*", "src/**/*.test.ts*"],
"references": [{ "path": "../mui-utils/tsconfig.build.json" }]
}
| 6,100 |
0 | petrpan-code/mui/material-ui/packages | petrpan-code/mui/material-ui/packages/mui-base/tsconfig.json | {
"extends": "../../tsconfig.json",
"include": ["src/**/*", "test/**/*"]
}
| 6,101 |
0 | petrpan-code/mui/material-ui/packages/mui-base | petrpan-code/mui/material-ui/packages/mui-base/scripts/testModuleAugmentation.js | const childProcess = require('child_process');
const path = require('path');
const { chunk } = require('lodash');
const glob = require('fast-glob');
const { promisify } = require('util');
const exec = promisify(childProcess.exec);
const packageRoot = path.resolve(__dirname, '../');
async function test(tsconfigPath) {
try {
await exec(['yarn', 'tsc', '--project', tsconfigPath].join(' '), { cwd: packageRoot });
} catch (error) {
if (error.stdout !== undefined) {
// `exec` error
throw new Error(`exit code ${error.code}: ${error.stdout}`);
}
// Unknown error
throw error;
}
}
/**
* Tests various module augmentation scenarios.
* We can't run them with a single `tsc` run since these apply globally.
* Running them all would mean they're not isolated.
* Each test case represents a section in our docs.
*
* We're not using mocha since mocha is used for runtime tests.
* This script also allows us to test in parallel which we can't do with our mocha tests.
*/
async function main() {
const tsconfigPaths = await glob('test/typescript/moduleAugmentation/*.tsconfig.json', {
absolute: true,
cwd: packageRoot,
});
// Need to process in chunks or we might run out-of-memory
// approximate yarn lerna --concurrency 7
const tsconfigPathsChunks = chunk(tsconfigPaths, 7);
// eslint-disable-next-line no-restricted-syntax
for await (const tsconfigPathsChunk of tsconfigPathsChunks) {
await Promise.all(
tsconfigPathsChunk.map(async (tsconfigPath) => {
await test(tsconfigPath).then(
() => {
// eslint-disable-next-line no-console -- test runner feedback
console.log(`PASS ${path.relative(process.cwd(), tsconfigPath)}`);
},
(error) => {
// don't bail but log the error
console.error(`FAIL ${path.relative(process.cwd(), tsconfigPath)}\n ${error}`);
// and mark the test as failed
process.exitCode = 1;
},
);
}),
);
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
| 6,102 |
0 | petrpan-code/mui/material-ui/packages/mui-base | petrpan-code/mui/material-ui/packages/mui-base/src/index.d.ts | export * from './utils';
export * from './Badge';
export * from './Button';
export * from './ClickAwayListener';
export * from './composeClasses';
export * from './Dropdown';
export * from './FocusTrap';
export * from './FormControl';
export * from './Input';
export * from './Menu';
export * from './MenuButton';
export * from './MenuItem';
export * from './Modal';
export { NoSsr } from './NoSsr';
export * from './Unstable_NumberInput';
export * from './OptionGroup';
export * from './Option';
export * from './Popper';
export * from './Unstable_Popup';
export * from './Portal';
export * from './Select';
export * from './Slider';
export * from './Snackbar';
export * from './Switch';
export * from './TablePagination';
export * from './TabPanel';
export * from './TabsList';
export * from './Tabs';
export * from './Tab';
export * from './TextareaAutosize';
export * from './useAutocomplete';
export * from './useBadge';
export * from './useButton';
export * from './useDropdown';
export * from './useInput';
export * from './useMenu';
export * from './useMenuButton';
export * from './useMenuItem';
export * from './unstable_useNumberInput';
export * from './useOption';
export * from './useSelect';
export * from './useSlider';
export * from './useSnackbar';
export * from './useSwitch';
export * from './useTab';
export * from './useTabPanel';
export * from './useTabs';
export * from './useTabsList';
export * from './unstable_useModal';
| 6,103 |
0 | petrpan-code/mui/material-ui/packages/mui-base | petrpan-code/mui/material-ui/packages/mui-base/src/index.js | 'use client';
export * from './utils';
export * from './Badge';
export * from './Button';
export { ClickAwayListener } from './ClickAwayListener';
export * from './composeClasses';
export { Dropdown } from './Dropdown';
export { FocusTrap } from './FocusTrap';
export * from './FormControl';
export * from './Input';
export * from './Menu';
export * from './MenuButton';
export * from './MenuItem';
export * from './Modal';
export { NoSsr } from './NoSsr';
export * from './Unstable_NumberInput';
export * from './OptionGroup';
export * from './Option';
export { Popper } from './Popper';
export * from './Unstable_Popup';
export { Portal } from './Portal';
export * from './Select';
export * from './Slider';
export * from './Snackbar';
export * from './Switch';
export * from './TablePagination';
export * from './TabPanel';
export * from './TabsList';
export * from './Tabs';
export * from './Tab';
export { TextareaAutosize } from './TextareaAutosize';
export * from './useAutocomplete';
export * from './useBadge';
export * from './useButton';
export * from './useDropdown';
export * from './useInput';
export * from './useMenu';
export * from './useMenuButton';
export * from './useMenuItem';
export * from './unstable_useNumberInput';
export * from './useOption';
export * from './useSelect';
export * from './useSlider';
export * from './useSnackbar';
export * from './useSwitch';
export * from './useTab';
export * from './useTabPanel';
export * from './useTabs';
export * from './useTabsList';
export * from './unstable_useModal';
| 6,104 |
0 | petrpan-code/mui/material-ui/packages/mui-base | petrpan-code/mui/material-ui/packages/mui-base/src/index.test.js | /* eslint import/namespace: ['error', { allowComputed: true }] */
/**
* Important: This test also serves as a point to
* import the entire lib for coverage reporting
*/
import { expect } from 'chai';
import * as MaterialUI from './index';
describe('@mui/base', () => {
it('should have exports', () => {
expect(typeof MaterialUI).to.equal('object');
});
it('should not have undefined exports', () => {
Object.keys(MaterialUI).forEach((exportKey) =>
expect(Boolean(MaterialUI[exportKey])).to.equal(true),
);
});
});
| 6,105 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Badge/Badge.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Badge, BadgeBadgeSlotProps, BadgeRootSlotProps } from '@mui/base/Badge';
const Root = React.forwardRef(function Root(
props: BadgeRootSlotProps,
ref: React.ForwardedRef<HTMLSpanElement>,
) {
const { ownerState, ...other } = props;
return <span data-showzero={ownerState.showZero} {...other} ref={ref} />;
});
const CustomBadge = React.forwardRef(function CustomBadge(
props: BadgeBadgeSlotProps,
ref: React.ForwardedRef<HTMLSpanElement>,
) {
const { ownerState, ...other } = props;
return <span data-showzero={ownerState.showZero} {...other} ref={ref} />;
});
const styledBadge = <Badge slots={{ root: Root, badge: Badge }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
const CustomRoot = function CustomRoot() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Badge invalidProp={0} />
<Badge<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<Badge<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error required props not specified */}
<Badge<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<Badge
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Badge<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onClick={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
<Badge<'svg'> viewBox="" />
</div>
);
};
| 6,106 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Badge/Badge.test.tsx | import * as React from 'react';
import { createRenderer, createMount, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { Badge, badgeClasses as classes } from '@mui/base/Badge';
describe('<Badge />', () => {
const { render } = createRenderer();
const mount = createMount();
describeConformanceUnstyled(
<Badge>
<div />
</Badge>,
() => ({
classes,
inheritComponent: 'span',
render,
mount,
refInstanceof: window.HTMLSpanElement,
testComponentPropWith: 'div',
muiName: 'BaseBadge',
slots: {
root: {
expectedClassName: classes.root,
},
badge: {
expectedClassName: classes.badge,
},
},
skip: ['componentProp'],
}),
);
});
| 6,107 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Badge/Badge.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { useBadge } from '../useBadge';
import { getBadgeUtilityClass } from './badgeClasses';
import {
BadgeProps,
BadgeOwnerState,
BadgeTypeMap,
BadgeRootSlotProps,
BadgeBadgeSlotProps,
} from './Badge.types';
import { WithOptionalOwnerState, useSlotProps } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: BadgeOwnerState) => {
const { invisible } = ownerState;
const slots = {
root: ['root'],
badge: ['badge', invisible && 'invisible'],
};
return composeClasses(slots, useClassNamesOverride(getBadgeUtilityClass));
};
/**
*
* Demos:
*
* - [Badge](https://mui.com/base-ui/react-badge/)
*
* API:
*
* - [Badge API](https://mui.com/base-ui/react-badge/components-api/#badge)
*/
const Badge = React.forwardRef(function Badge<RootComponentType extends React.ElementType>(
props: BadgeProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
badgeContent: badgeContentProp,
children,
invisible: invisibleProp,
max: maxProp = 99,
slotProps = {},
slots = {},
showZero = false,
...other
} = props;
const { badgeContent, max, displayValue, invisible } = useBadge({
...props,
max: maxProp,
});
const ownerState: BadgeOwnerState = {
...props,
badgeContent,
invisible,
max,
showZero,
};
const classes = useUtilityClasses(ownerState);
const Root = slots.root ?? 'span';
const rootProps: WithOptionalOwnerState<BadgeRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
const BadgeComponent = slots.badge ?? 'span';
const badgeProps: WithOptionalOwnerState<BadgeBadgeSlotProps> = useSlotProps({
elementType: BadgeComponent,
externalSlotProps: slotProps.badge,
ownerState,
className: classes.badge,
});
return (
<Root {...rootProps}>
{children}
<BadgeComponent {...badgeProps}>{displayValue}</BadgeComponent>
</Root>
);
}) as PolymorphicComponent<BadgeTypeMap>;
Badge.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content rendered within the badge.
*/
badgeContent: PropTypes.node,
/**
* The badge will be added relative to this node.
*/
children: PropTypes.node,
/**
* If `true`, the badge is invisible.
* @default false
*/
invisible: PropTypes.bool,
/**
* Max count to show.
* @default 99
*/
max: PropTypes.number,
/**
* Controls whether the badge is hidden when `badgeContent` is zero.
* @default false
*/
showZero: PropTypes.bool,
/**
* The props used for each slot inside the Badge.
* @default {}
*/
slotProps: PropTypes.shape({
badge: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Badge.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
badge: PropTypes.elementType,
root: PropTypes.elementType,
}),
} as any;
export { Badge };
| 6,108 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Badge/Badge.types.ts | import * as React from 'react';
import { OverrideProps, Simplify } from '@mui/types';
import { SlotComponentProps } from '../utils';
export interface BadgeRootSlotPropsOverrides {}
export interface BadgeBadgeSlotPropsOverrides {}
export type BadgeOwnerState = Simplify<
BadgeOwnProps & {
badgeContent: React.ReactNode;
invisible: boolean;
max: number;
showZero: boolean;
}
>;
export interface BadgeOwnProps {
/**
* The content rendered within the badge.
*/
badgeContent?: React.ReactNode;
/**
* The badge will be added relative to this node.
*/
children?: React.ReactNode;
/**
* If `true`, the badge is invisible.
* @default false
*/
invisible?: boolean;
/**
* Max count to show.
* @default 99
*/
max?: number;
/**
* The props used for each slot inside the Badge.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'span', BadgeRootSlotPropsOverrides, BadgeOwnerState>;
badge?: SlotComponentProps<'span', BadgeBadgeSlotPropsOverrides, BadgeOwnerState>;
};
/**
* The components used for each slot inside the Badge.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: BadgeSlots;
/**
* Controls whether the badge is hidden when `badgeContent` is zero.
* @default false
*/
showZero?: boolean;
}
export interface BadgeSlots {
/**
* The component that renders the root.
* @default 'span'
*/
root?: React.ElementType;
/**
* The component that renders the badge.
* @default 'span'
*/
badge?: React.ElementType;
}
export interface BadgeTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'span',
> {
props: BadgeOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type BadgeProps<
RootComponentType extends React.ElementType = BadgeTypeMap['defaultComponent'],
> = OverrideProps<BadgeTypeMap<{}, RootComponentType>, RootComponentType>;
export type BadgeRootSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: BadgeOwnerState;
ref: React.Ref<HTMLSpanElement>;
};
export type BadgeBadgeSlotProps = {
className?: string;
children?: React.ReactNode;
ownerState: BadgeOwnerState;
};
| 6,109 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Badge/badgeClasses.ts | import { generateUtilityClasses } from '../generateUtilityClasses';
import { generateUtilityClass } from '../generateUtilityClass';
export interface BadgeClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the badge `span` element. */
badge: string;
/** State class applied to the badge `span` element if `invisible={true}`. */
invisible: string;
}
export type BadgeClassKey = keyof BadgeClasses;
export function getBadgeUtilityClass(slot: string): string {
return generateUtilityClass('MuiBadge', slot);
}
export const badgeClasses: BadgeClasses = generateUtilityClasses('MuiBadge', [
'root',
'badge',
'invisible',
]);
| 6,110 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Badge/index.ts | 'use client';
export { Badge } from './Badge';
export * from './Badge.types';
export * from './badgeClasses';
| 6,111 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Button/Button.spec.tsx | import * as React from 'react';
import clsx from 'clsx';
import { expectType } from '@mui/types';
import { Button, ButtonProps, ButtonRootSlotProps } from '@mui/base/Button';
const CustomButtonRoot = React.forwardRef(function CustomButtonRoot(props: ButtonRootSlotProps) {
const { ownerState, ...other } = props;
const classes = clsx(
other.className,
ownerState.active && 'active',
ownerState.focusVisible && 'focusVisible',
);
return <button type="button" {...other} className={classes} />;
});
function ButtonWithCustomRoot(props: ButtonProps) {
return <Button {...props} slots={{ root: CustomButtonRoot }} />;
}
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
const Root = function Root() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Button invalidProp={0} />
<Button slots={{ root: 'a' }} href="#" />
<Button
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onClick={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
}}
type="submit"
/>
<Button<typeof CustomComponent>
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error onClick must be specified in the custom root component */}
<Button<typeof Root> slots={{ root: Root }} onClick={() => {}} />
{/* @ts-expect-error required props not specified */}
<Button<typeof CustomComponent> slots={{ root: CustomComponent }} />
<Button<'svg'> viewBox="" />
<Button
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Button<'div'>
slotProps={{ root: 'div' }}
ref={(elem) => {
expectType<HTMLDivElement | null, typeof elem>(elem);
}}
onClick={(e) => {
expectType<React.MouseEvent<HTMLDivElement, MouseEvent>, typeof e>(e);
}}
/>
</div>
);
};
| 6,112 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Button/Button.test.tsx | import * as React from 'react';
import {
act,
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
} from '@mui-internal/test-utils';
import { expect } from 'chai';
import { spy } from 'sinon';
import { Button, buttonClasses } from '@mui/base/Button';
describe('<Button />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<Button />, () => ({
inheritComponent: 'button',
render,
mount,
refInstanceof: window.HTMLButtonElement,
testComponentPropWith: 'span',
muiName: 'MuiButton',
slots: {
root: {
expectedClassName: buttonClasses.root,
},
},
skip: ['componentProp'],
}));
describe('role attribute', () => {
it('is set when the root component is an HTML element other than a button', () => {
const { getByRole } = render(<Button slots={{ root: 'span' }} />);
expect(getByRole('button')).not.to.equal(null);
});
it('is set when the root component is a component that renders an HTML component other than a button', () => {
const WrappedSpan = React.forwardRef(
(
props: React.HTMLAttributes<HTMLSpanElement>,
ref: React.ForwardedRef<HTMLSpanElement>,
) => <span role={props.role} ref={ref} />,
);
const { getByRole } = render(<Button slots={{ root: WrappedSpan }} />);
expect(getByRole('button')).not.to.equal(null);
});
it('is not set when the root component is a component that renders an HTML button component', () => {
const WrappedButton = React.forwardRef(
(
props: React.HTMLAttributes<HTMLButtonElement>,
ref: React.ForwardedRef<HTMLButtonElement>,
) => <button role={props.role} ref={ref} />,
);
const { getByRole } = render(<Button slots={{ root: WrappedButton }} />);
expect(getByRole('button')).not.to.have.attribute('role');
});
});
describe('prop: focusableWhenDisabled', () => {
describe('as native button', () => {
it('has the aria-disabled instead of disabled attribute when disabled', () => {
const { getByRole } = render(<Button focusableWhenDisabled disabled />);
const button = getByRole('button');
expect(button).to.have.attribute('aria-disabled');
expect(button).not.to.have.attribute('disabled');
});
it('can receive focus when focusableWhenDisabled is set', () => {
const { getByRole } = render(<Button focusableWhenDisabled disabled />);
const button = getByRole('button');
act(() => {
button.focus();
});
expect(document.activeElement).to.equal(button);
});
it('does not respond to user actions when disabled and focused', () => {
const handleClick = spy();
const { getByRole } = render(
<Button focusableWhenDisabled disabled onClick={handleClick} />,
);
const button = getByRole('button');
act(() => {
button.focus();
});
act(() => {
button.click();
fireEvent.keyDown(button, { key: 'Enter' });
fireEvent.keyUp(button, { key: ' ' });
});
expect(handleClick.callCount).to.equal(0);
});
});
describe('as non-button element', () => {
it('can receive focus when focusableWhenDisabled is set', () => {
const { getByRole } = render(
<Button slots={{ root: 'span' }} focusableWhenDisabled disabled />,
);
const button = getByRole('button');
act(() => {
button.focus();
});
expect(document.activeElement).to.equal(button);
});
it('has aria-disabled and tabIndex attributes set', () => {
const { getByRole } = render(
<Button slots={{ root: 'span' }} focusableWhenDisabled disabled />,
);
const button = getByRole('button');
expect(button).to.have.attribute('aria-disabled', 'true');
expect(button).to.have.attribute('tabindex', '0');
});
it('does not respond to user actions when disabled and focused', () => {
const handleClick = spy();
const { getByRole } = render(
<Button slots={{ root: 'span' }} focusableWhenDisabled disabled onClick={handleClick} />,
);
const button = getByRole('button');
act(() => {
button.focus();
});
act(() => {
button.click();
fireEvent.keyDown(button, { key: 'Enter' });
fireEvent.keyUp(button, { key: ' ' });
});
expect(handleClick.callCount).to.equal(0);
});
});
});
describe('prop: href', () => {
it('renders as a link when the "href" prop is provided', () => {
const { getByRole } = render(<Button href="#" />);
expect(getByRole('link')).not.to.equal(null);
});
it('renders as the element provided in the "component" prop, even with a "href" prop', () => {
const { getByRole } = render(<Button slots={{ root: 'h1' }} href="#" />);
expect(getByRole('heading')).not.to.equal(null);
});
it('renders as the element provided in the "components.Root" prop, even with a "href" prop', () => {
const { getByRole } = render(<Button slots={{ root: 'h1' }} href="#" />);
expect(getByRole('heading')).not.to.equal(null);
});
});
describe('prop: to', () => {
it('renders as a link when the "to" prop is provided', () => {
const { container } = render(<Button to="#" />);
expect(container.querySelector('a')).not.to.equal(null);
});
it('renders as the element provided in the "component" prop, even with a "to" prop', () => {
const { getByRole } = render(<Button slots={{ root: 'h1' }} to="#" />);
expect(getByRole('heading')).not.to.equal(null);
});
it('renders as the element provided in the "components.Root" prop, even with a "to" prop', () => {
const { getByRole } = render(<Button slots={{ root: 'h1' }} to="#" />);
expect(getByRole('heading')).not.to.equal(null);
});
});
});
| 6,113 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Button/Button.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getButtonUtilityClass } from './buttonClasses';
import { ButtonProps, ButtonTypeMap, ButtonRootSlotProps, ButtonOwnerState } from './Button.types';
import { useButton } from '../useButton';
import { WithOptionalOwnerState } from '../utils/types';
import { useSlotProps } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: ButtonOwnerState) => {
const { active, disabled, focusVisible } = ownerState;
const slots = {
root: ['root', disabled && 'disabled', focusVisible && 'focusVisible', active && 'active'],
};
return composeClasses(slots, useClassNamesOverride(getButtonUtilityClass));
};
/**
* The foundation for building custom-styled buttons.
*
* Demos:
*
* - [Button](https://mui.com/base-ui/react-button/)
*
* API:
*
* - [Button API](https://mui.com/base-ui/react-button/components-api/#button)
*/
const Button = React.forwardRef(function Button<RootComponentType extends React.ElementType>(
props: ButtonProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
action,
children,
disabled,
focusableWhenDisabled = false,
onFocusVisible,
slotProps = {},
slots = {},
...other
} = props;
const buttonRef = React.useRef<HTMLButtonElement | HTMLAnchorElement | HTMLElement>();
const { active, focusVisible, setFocusVisible, getRootProps } = useButton({
...props,
focusableWhenDisabled,
});
React.useImperativeHandle(
action,
() => ({
focusVisible: () => {
setFocusVisible(true);
buttonRef.current!.focus();
},
}),
[setFocusVisible],
);
const ownerState: ButtonOwnerState = {
...props,
active,
focusableWhenDisabled,
focusVisible,
};
const classes = useUtilityClasses(ownerState);
const defaultElement = other.href || other.to ? 'a' : 'button';
const Root: React.ElementType = slots.root ?? defaultElement;
const rootProps: WithOptionalOwnerState<ButtonRootSlotProps> = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalForwardedProps: other,
externalSlotProps: slotProps.root,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
return <Root {...rootProps}>{children}</Root>;
}) as PolymorphicComponent<ButtonTypeMap>;
Button.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A ref for imperative actions. It currently only supports `focusVisible()` action.
*/
action: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({
current: PropTypes.shape({
focusVisible: PropTypes.func.isRequired,
}),
}),
]),
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, allows a disabled button to receive focus.
* @default false
*/
focusableWhenDisabled: PropTypes.bool,
/**
* @ignore
*/
href: PropTypes.string,
/**
* @ignore
*/
onFocusVisible: PropTypes.func,
/**
* The props used for each slot inside the Button.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Button.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* @ignore
*/
to: PropTypes.string,
} as any;
export { Button };
| 6,114 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Button/Button.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { UseButtonParameters, UseButtonRootSlotProps } from '../useButton';
import { SlotComponentProps } from '../utils';
import { PolymorphicProps } from '../utils/PolymorphicComponent';
export interface ButtonActions {
focusVisible(): void;
}
export interface ButtonRootSlotPropsOverrides {}
export interface ButtonOwnProps extends Omit<UseButtonParameters, 'rootRef'> {
/**
* A ref for imperative actions. It currently only supports `focusVisible()` action.
*/
action?: React.Ref<ButtonActions>;
children?: React.ReactNode;
className?: string;
/**
* The props used for each slot inside the Button.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'button', ButtonRootSlotPropsOverrides, ButtonOwnerState>;
};
/**
* The components used for each slot inside the Button.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: ButtonSlots;
}
export interface ButtonSlots {
/**
* The component that renders the root.
* @default props.href || props.to ? 'a' : 'button'
*/
root?: React.ElementType;
}
export type ButtonProps<
RootComponentType extends React.ElementType = ButtonTypeMap['defaultComponent'],
> = PolymorphicProps<ButtonTypeMap<{}, RootComponentType>, RootComponentType>;
export interface ButtonTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'button',
> {
props: ButtonOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type ButtonOwnerState = Simplify<
ButtonOwnProps & {
active: boolean;
focusVisible: boolean;
}
>;
export type ButtonRootSlotProps = Simplify<
UseButtonRootSlotProps & {
ownerState: ButtonOwnerState;
className?: string;
children?: React.ReactNode;
}
>;
| 6,115 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Button/buttonClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface ButtonClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root `button` element if `active={true}`. */
active: string;
/** State class applied to the root `button` element if `disabled={true}`. */
disabled: string;
/** State class applied to the root `button` element if `focusVisible={true}`. */
focusVisible: string;
}
export type ButtonClassKey = keyof ButtonClasses;
export function getButtonUtilityClass(slot: string): string {
return generateUtilityClass('MuiButton', slot);
}
export const buttonClasses: ButtonClasses = generateUtilityClasses('MuiButton', [
'root',
'active',
'disabled',
'focusVisible',
]);
| 6,116 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Button/index.ts | 'use client';
export { Button } from './Button';
export * from './buttonClasses';
export * from './Button.types';
| 6,117 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/ClassNameGenerator/index.ts | export { unstable_ClassNameGenerator } from '@mui/utils';
| 6,118 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/ClickAwayListener/ClickAwayListener.test.js | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
act,
createRenderer,
fireEvent,
fireDiscreteEvent,
screen,
} from '@mui-internal/test-utils';
import { Portal } from '@mui/base/Portal';
import { ClickAwayListener } from '@mui/base/ClickAwayListener';
describe('<ClickAwayListener />', () => {
const { render: clientRender, clock } = createRenderer({ clock: 'fake' });
/**
* @type {typeof plainRender extends (...args: infer T) => any ? T : never} args
*
* @remarks
* This is for all intents and purposes the same as our client render method.
* `plainRender` is already wrapped in act().
* However, React has a bug that flushes effects in a portal synchronously.
* We have to defer the effect manually like `useEffect` would so we have to flush the effect manually instead of relying on `act()`.
* React bug: https://github.com/facebook/react/issues/20074
*/
function render(...args) {
const result = clientRender(...args);
clock.tick(0);
return result;
}
it('should render the children', () => {
const children = <span />;
const { container } = render(
<ClickAwayListener onClickAway={() => {}}>{children}</ClickAwayListener>,
);
expect(container.querySelectorAll('span').length).to.equal(1);
});
describe('prop: onClickAway', () => {
it('should be called when clicking away', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway}>
<span />
</ClickAwayListener>,
);
fireEvent.click(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
it('should not be called when clicking inside', () => {
const handleClickAway = spy();
const { container } = render(
<ClickAwayListener onClickAway={handleClickAway}>
<span />
</ClickAwayListener>,
);
fireEvent.click(container.querySelector('span'));
expect(handleClickAway.callCount).to.equal(0);
});
it('should be called when preventDefault is `true`', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway}>
<span />
</ClickAwayListener>,
);
const preventDefault = (event) => event.preventDefault();
document.body.addEventListener('click', preventDefault);
fireEvent.click(document.body);
expect(handleClickAway.callCount).to.equal(1);
document.body.removeEventListener('click', preventDefault);
});
it('should not be called when clicking inside a portaled element', () => {
const handleClickAway = spy();
const { getByText } = render(
<ClickAwayListener onClickAway={handleClickAway}>
<div>
<Portal>
<span>Inside a portal</span>
</Portal>
</div>
</ClickAwayListener>,
);
fireEvent.click(getByText('Inside a portal'));
expect(handleClickAway.callCount).to.equal(0);
});
it('should be called when clicking inside a portaled element and `disableReactTree` is `true`', () => {
const handleClickAway = spy();
const { getByText } = render(
<ClickAwayListener onClickAway={handleClickAway} disableReactTree>
<div>
<Portal>
<span>Inside a portal</span>
</Portal>
</div>
</ClickAwayListener>,
);
fireEvent.click(getByText('Inside a portal'));
expect(handleClickAway.callCount).to.equal(1);
});
it('should not be called even if the event propagation is stopped', () => {
const handleClickAway = spy();
const { getByText } = render(
<ClickAwayListener onClickAway={handleClickAway} disableReactTree>
<div>
<div
onClick={(event) => {
event.stopPropagation();
}}
>
Outside a portal
</div>
<Portal>
<span
onClick={(event) => {
event.stopPropagation();
}}
>
Stop inside a portal
</span>
</Portal>
<Portal>
<span
onClick={(event) => {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
}}
>
Stop all inside a portal
</span>
</Portal>
</div>
</ClickAwayListener>,
);
fireEvent.click(getByText('Outside a portal'));
expect(handleClickAway.callCount).to.equal(0);
fireEvent.click(getByText('Stop all inside a portal'));
expect(handleClickAway.callCount).to.equal(0);
fireEvent.click(getByText('Stop inside a portal'));
// undesired behavior in React 16
expect(handleClickAway.callCount).to.equal(React.version.startsWith('16') ? 1 : 0);
});
['onClick', 'onClickCapture'].forEach((eventListenerName) => {
it(`should not be called when ${eventListenerName} mounted the listener`, () => {
function Test() {
const [open, setOpen] = React.useState(false);
return (
<React.Fragment>
<button data-testid="trigger" {...{ [eventListenerName]: () => setOpen(true) }} />
{open &&
ReactDOM.createPortal(
<ClickAwayListener onClickAway={() => setOpen(false)}>
<div data-testid="child" />
</ClickAwayListener>,
// Needs to be an element between the react root we render into and the element where CAL attaches its native listener (now: `document`).
document.body,
)}
</React.Fragment>
);
}
render(<Test />);
fireDiscreteEvent.click(screen.getByTestId('trigger'));
expect(screen.getByTestId('child')).not.to.equal(null);
});
});
it('should be called if an element is interleaved between mousedown and mouseup', () => {
/**
* @param {Element} element
* @returns {Element[]}
*/
function ancestorElements(element) {
const ancestors = [];
let ancestor = element;
while (ancestor !== null) {
ancestors.unshift(ancestor);
ancestor = ancestor.parentElement;
}
return ancestors;
}
/**
* @param {Element} elementA
* @param {Element} elementB
* @returns {Element}
*/
function findNearestCommonAncestor(elementA, elementB) {
const ancestorsA = ancestorElements(elementA);
const ancestorsB = ancestorElements(elementB);
if (ancestorsA[0] !== ancestorsB[0]) {
throw new Error('A and B share no common ancestor');
}
for (let index = 1; index < ancestorsA.length; index += 1) {
if (ancestorsA[index] !== ancestorsB[index]) {
return ancestorsA[index - 1];
}
}
throw new Error('Unreachable reached. This is a bug in findNearestCommonAncestor');
}
const onClickAway = spy();
function ClickAwayListenerMouseDownPortal() {
const [open, toggleOpen] = React.useReducer((flag) => !flag, false);
return (
<ClickAwayListener onClickAway={onClickAway}>
<div data-testid="trigger" onMouseDown={toggleOpen}>
{open &&
// interleave an element during mousedown so that the following mouseup would not be targetted at the mousedown target.
// This results in the click event being targetted at the nearest common ancestor.
ReactDOM.createPortal(
<div data-testid="interleaved-element">Portaled Div</div>,
document.body,
)}
</div>
</ClickAwayListener>
);
}
render(<ClickAwayListenerMouseDownPortal />);
const mouseDownTarget = screen.getByTestId('trigger');
fireDiscreteEvent.mouseDown(mouseDownTarget);
const mouseUpTarget = screen.getByTestId('interleaved-element');
// https://w3c.github.io/uievents/#events-mouseevent-event-order
const clickTarget = findNearestCommonAncestor(mouseDownTarget, mouseUpTarget);
fireDiscreteEvent.mouseUp(mouseUpTarget);
fireDiscreteEvent.click(clickTarget);
expect(onClickAway.callCount).to.equal(1);
});
});
describe('prop: mouseEvent', () => {
it('should not call `props.onClickAway` when `props.mouseEvent` is `false`', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} mouseEvent={false}>
<span />
</ClickAwayListener>,
);
fireEvent.click(document.body);
expect(handleClickAway.callCount).to.equal(0);
});
it('should call `props.onClickAway` when mouse down is triggered', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} mouseEvent="onMouseDown">
<span />
</ClickAwayListener>,
);
fireEvent.mouseUp(document.body);
expect(handleClickAway.callCount).to.equal(0);
fireEvent.mouseDown(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
it('should call `props.onClickAway` when mouse up is triggered', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} mouseEvent="onMouseUp">
<span />
</ClickAwayListener>,
);
fireEvent.mouseDown(document.body);
expect(handleClickAway.callCount).to.equal(0);
fireEvent.mouseUp(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
it('should call `props.onClickAway` when pointer down is triggered', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} mouseEvent="onPointerDown">
<span />
</ClickAwayListener>,
);
fireEvent.pointerUp(document.body);
expect(handleClickAway.callCount).to.equal(0);
fireEvent.pointerDown(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
it('should call `props.onClickAway` when pointer up is triggered', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} mouseEvent="onPointerUp">
<span />
</ClickAwayListener>,
);
fireEvent.pointerDown(document.body);
expect(handleClickAway.callCount).to.equal(0);
fireEvent.pointerUp(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
});
describe('prop: touchEvent', () => {
it('should not call `props.onClickAway` when `props.touchEvent` is `false`', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} touchEvent={false}>
<span />
</ClickAwayListener>,
);
fireEvent.touchEnd(document.body);
expect(handleClickAway.callCount).to.equal(0);
});
it('should call `props.onClickAway` when the appropriate touch event is triggered', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} touchEvent="onTouchStart">
<span />
</ClickAwayListener>,
);
fireEvent.touchEnd(document.body);
expect(handleClickAway.callCount).to.equal(0);
fireEvent.touchStart(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
it('should ignore `touchend` when preceded by `touchmove` event', () => {
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway} touchEvent="onTouchEnd">
<span />
</ClickAwayListener>,
);
fireEvent.touchStart(document.body);
fireEvent.touchMove(document.body);
fireEvent.touchEnd(document.body);
expect(handleClickAway.callCount).to.equal(0);
fireEvent.touchEnd(document.body);
expect(handleClickAway.callCount).to.equal(1);
expect(handleClickAway.args[0].length).to.equal(1);
});
});
it('should handle null child', () => {
const Child = React.forwardRef(() => null);
const handleClickAway = spy();
render(
<ClickAwayListener onClickAway={handleClickAway}>
<Child />
</ClickAwayListener>,
);
fireEvent.click(document.body);
expect(handleClickAway.callCount).to.equal(0);
});
[
['onClick', false],
['onClick', true],
['onClickCapture', false],
['onClickCapture', true],
].forEach(([eventName, disableReactTree]) => {
it(`when 'disableRectTree=${disableReactTree}' ${eventName} triggers onClickAway if an outside target is removed`, function test() {
if (!new Event('click').composedPath) {
this.skip();
}
const handleClickAway = spy();
function Test() {
const [buttonShown, hideButton] = React.useReducer(() => false, true);
return (
<React.Fragment>
{buttonShown && <button {...{ [eventName]: hideButton }} type="button" />}
<ClickAwayListener onClickAway={handleClickAway} disableReactTree={disableReactTree}>
<div />
</ClickAwayListener>
</React.Fragment>
);
}
render(<Test />);
act(() => {
screen.getByRole('button').click();
});
expect(handleClickAway.callCount).to.equal(1);
});
it(`when 'disableRectTree=${disableReactTree}' ${eventName} does not trigger onClickAway if an inside target is removed`, function test() {
if (!new Event('click').composedPath) {
this.skip();
}
const handleClickAway = spy();
function Test() {
const [buttonShown, hideButton] = React.useReducer(() => false, true);
return (
<ClickAwayListener onClickAway={handleClickAway} disableReactTree={disableReactTree}>
<div>{buttonShown && <button {...{ [eventName]: hideButton }} type="button" />}</div>
</ClickAwayListener>
);
}
render(<Test />);
act(() => {
screen.getByRole('button').click();
});
expect(handleClickAway.callCount).to.equal(0);
});
});
});
| 6,119 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/ClickAwayListener/ClickAwayListener.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import {
elementAcceptingRef,
exactProp,
unstable_ownerDocument as ownerDocument,
unstable_useForkRef as useForkRef,
unstable_useEventCallback as useEventCallback,
} from '@mui/utils';
// TODO: return `EventHandlerName extends `on${infer EventName}` ? Lowercase<EventName> : never` once generatePropTypes runs with TS 4.1
function mapEventPropToEvent(
eventProp: ClickAwayMouseEventHandler | ClickAwayTouchEventHandler,
): 'click' | 'mousedown' | 'mouseup' | 'touchstart' | 'touchend' | 'pointerdown' | 'pointerup' {
return eventProp.substring(2).toLowerCase() as any;
}
function clickedRootScrollbar(event: MouseEvent, doc: Document) {
return (
doc.documentElement.clientWidth < event.clientX ||
doc.documentElement.clientHeight < event.clientY
);
}
type ClickAwayMouseEventHandler =
| 'onClick'
| 'onMouseDown'
| 'onMouseUp'
| 'onPointerDown'
| 'onPointerUp';
type ClickAwayTouchEventHandler = 'onTouchStart' | 'onTouchEnd';
export interface ClickAwayListenerProps {
/**
* The wrapped element.
*/
children: React.ReactElement;
/**
* If `true`, the React tree is ignored and only the DOM tree is considered.
* This prop changes how portaled elements are handled.
* @default false
*/
disableReactTree?: boolean;
/**
* The mouse event to listen to. You can disable the listener by providing `false`.
* @default 'onClick'
*/
mouseEvent?: ClickAwayMouseEventHandler | false;
/**
* Callback fired when a "click away" event is detected.
*/
onClickAway: (event: MouseEvent | TouchEvent) => void;
/**
* The touch event to listen to. You can disable the listener by providing `false`.
* @default 'onTouchEnd'
*/
touchEvent?: ClickAwayTouchEventHandler | false;
}
/**
* Listen for click events that occur somewhere in the document, outside of the element itself.
* For instance, if you need to hide a menu when people click anywhere else on your page.
*
* Demos:
*
* - [Click-Away Listener](https://mui.com/base-ui/react-click-away-listener/)
*
* API:
*
* - [ClickAwayListener API](https://mui.com/base-ui/react-click-away-listener/components-api/#click-away-listener)
*/
function ClickAwayListener(props: ClickAwayListenerProps): JSX.Element {
const {
children,
disableReactTree = false,
mouseEvent = 'onClick',
onClickAway,
touchEvent = 'onTouchEnd',
} = props;
const movedRef = React.useRef(false);
const nodeRef = React.useRef<Element>(null);
const activatedRef = React.useRef(false);
const syntheticEventRef = React.useRef(false);
React.useEffect(() => {
// Ensure that this component is not "activated" synchronously.
// https://github.com/facebook/react/issues/20074
setTimeout(() => {
activatedRef.current = true;
}, 0);
return () => {
activatedRef.current = false;
};
}, []);
const handleRef = useForkRef(
// @ts-expect-error TODO upstream fix
children.ref,
nodeRef,
);
// The handler doesn't take event.defaultPrevented into account:
//
// event.preventDefault() is meant to stop default behaviors like
// clicking a checkbox to check it, hitting a button to submit a form,
// and hitting left arrow to move the cursor in a text input etc.
// Only special HTML elements have these default behaviors.
const handleClickAway = useEventCallback((event: MouseEvent | TouchEvent) => {
// Given developers can stop the propagation of the synthetic event,
// we can only be confident with a positive value.
const insideReactTree = syntheticEventRef.current;
syntheticEventRef.current = false;
const doc = ownerDocument(nodeRef.current);
// 1. IE11 support, which trigger the handleClickAway even after the unbind
// 2. The child might render null.
// 3. Behave like a blur listener.
if (
!activatedRef.current ||
!nodeRef.current ||
('clientX' in event && clickedRootScrollbar(event, doc))
) {
return;
}
// Do not act if user performed touchmove
if (movedRef.current) {
movedRef.current = false;
return;
}
let insideDOM;
// If not enough, can use https://github.com/DieterHolvoet/event-propagation-path/blob/master/propagationPath.js
if (event.composedPath) {
insideDOM = event.composedPath().indexOf(nodeRef.current) > -1;
} else {
insideDOM =
!doc.documentElement.contains(
// @ts-expect-error returns `false` as intended when not dispatched from a Node
event.target,
) ||
nodeRef.current.contains(
// @ts-expect-error returns `false` as intended when not dispatched from a Node
event.target,
);
}
if (!insideDOM && (disableReactTree || !insideReactTree)) {
onClickAway(event);
}
});
// Keep track of mouse/touch events that bubbled up through the portal.
const createHandleSynthetic = (handlerName: string) => (event: React.SyntheticEvent) => {
syntheticEventRef.current = true;
const childrenPropsHandler = children.props[handlerName];
if (childrenPropsHandler) {
childrenPropsHandler(event);
}
};
const childrenProps: { ref: React.Ref<Element> } & Pick<
React.DOMAttributes<Element>,
ClickAwayMouseEventHandler | ClickAwayTouchEventHandler
> = { ref: handleRef };
if (touchEvent !== false) {
childrenProps[touchEvent] = createHandleSynthetic(touchEvent);
}
React.useEffect(() => {
if (touchEvent !== false) {
const mappedTouchEvent = mapEventPropToEvent(touchEvent);
const doc = ownerDocument(nodeRef.current);
const handleTouchMove = () => {
movedRef.current = true;
};
doc.addEventListener(mappedTouchEvent, handleClickAway);
doc.addEventListener('touchmove', handleTouchMove);
return () => {
doc.removeEventListener(mappedTouchEvent, handleClickAway);
doc.removeEventListener('touchmove', handleTouchMove);
};
}
return undefined;
}, [handleClickAway, touchEvent]);
if (mouseEvent !== false) {
childrenProps[mouseEvent] = createHandleSynthetic(mouseEvent);
}
React.useEffect(() => {
if (mouseEvent !== false) {
const mappedMouseEvent = mapEventPropToEvent(mouseEvent);
const doc = ownerDocument(nodeRef.current);
doc.addEventListener(mappedMouseEvent, handleClickAway);
return () => {
doc.removeEventListener(mappedMouseEvent, handleClickAway);
};
}
return undefined;
}, [handleClickAway, mouseEvent]);
return <React.Fragment>{React.cloneElement(children, childrenProps)}</React.Fragment>;
}
ClickAwayListener.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The wrapped element.
*/
children: elementAcceptingRef.isRequired,
/**
* If `true`, the React tree is ignored and only the DOM tree is considered.
* This prop changes how portaled elements are handled.
* @default false
*/
disableReactTree: PropTypes.bool,
/**
* The mouse event to listen to. You can disable the listener by providing `false`.
* @default 'onClick'
*/
mouseEvent: PropTypes.oneOf([
'onClick',
'onMouseDown',
'onMouseUp',
'onPointerDown',
'onPointerUp',
false,
]),
/**
* Callback fired when a "click away" event is detected.
*/
onClickAway: PropTypes.func.isRequired,
/**
* The touch event to listen to. You can disable the listener by providing `false`.
* @default 'onTouchEnd'
*/
touchEvent: PropTypes.oneOf(['onTouchEnd', 'onTouchStart', false]),
} as any;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
(ClickAwayListener as any)['propTypes' + ''] = exactProp(ClickAwayListener.propTypes);
}
export { ClickAwayListener };
| 6,120 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/ClickAwayListener/index.ts | export * from './ClickAwayListener';
| 6,121 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Dropdown/Dropdown.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { act, createRenderer } from '@mui-internal/test-utils';
import { Dropdown } from '@mui/base/Dropdown';
import { DropdownContext } from '@mui/base/useDropdown';
import { MenuButton } from '@mui/base/MenuButton';
import { MenuItem } from '@mui/base/MenuItem';
import { Menu } from '@mui/base/Menu';
describe('<Dropdown />', () => {
const { render } = createRenderer();
it('registers a popup id correctly', () => {
function TestComponent() {
const { registerPopup, popupId } = React.useContext(DropdownContext)!;
expect(context).not.to.equal(null);
React.useEffect(() => {
registerPopup('test-popup');
}, [registerPopup]);
return <p>{popupId}</p>;
}
const { container } = render(
<Dropdown>
<TestComponent />
</Dropdown>,
);
expect(container.innerHTML).to.equal('<p>test-popup</p>');
});
it('registers a trigger element correctly', () => {
const trigger = document.createElement('button');
trigger.setAttribute('data-testid', 'test-button');
function TestComponent() {
const { registerTrigger, triggerElement } = React.useContext(DropdownContext)!;
expect(context).not.to.equal(null);
React.useEffect(() => {
registerTrigger(trigger);
}, [registerTrigger]);
return <p>{triggerElement?.getAttribute('data-testid')}</p>;
}
const { container } = render(
<Dropdown>
<TestComponent />
</Dropdown>,
);
expect(container.innerHTML).to.equal('<p>test-button</p>');
});
it('focuses the first item after the menu is opened', () => {
const { getByRole, getAllByRole } = render(
<div>
<Dropdown>
<MenuButton>Toggle</MenuButton>
<Menu>
<MenuItem>One</MenuItem>
<MenuItem>Two</MenuItem>
<MenuItem>Three</MenuItem>
</Menu>
</Dropdown>
</div>,
);
const button = getByRole('button');
act(() => {
button.click();
});
const menuItems = getAllByRole('menuitem');
expect(menuItems[0]).toHaveFocus();
});
it('focuses the trigger after the menu is closed', () => {
const { getByRole } = render(
<div>
<input type="text" />
<Dropdown>
<MenuButton>Toggle</MenuButton>
<Menu>
<MenuItem>Close</MenuItem>
</Menu>
</Dropdown>
<input type="text" />
</div>,
);
const button = getByRole('button');
act(() => {
button.click();
});
const menuItem = getByRole('menuitem');
act(() => {
menuItem.click();
});
expect(button).toHaveFocus();
});
});
| 6,122 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Dropdown/Dropdown.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { exactProp } from '@mui/utils';
import { DropdownProps } from './Dropdown.types';
import { DropdownContext } from '../useDropdown/DropdownContext';
import { useDropdown } from '../useDropdown/useDropdown';
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/)
*
* API:
*
* - [Dropdown API](https://mui.com/base-ui/react-menu/components-api/#dropdown)
*/
function Dropdown(props: DropdownProps) {
const { children, open, defaultOpen, onOpenChange } = props;
const { contextValue } = useDropdown({
defaultOpen,
onOpenChange,
open,
});
return <DropdownContext.Provider value={contextValue}>{children}</DropdownContext.Provider>;
}
Dropdown.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
children: PropTypes.node,
/**
* If `true`, the dropdown is initially open.
*/
defaultOpen: PropTypes.bool,
/**
* Callback fired when the component requests to be opened or closed.
*/
onOpenChange: PropTypes.func,
/**
* Allows to control whether the dropdown is open.
* This is a controlled counterpart of `defaultOpen`.
*/
open: PropTypes.bool,
} as any;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
(Dropdown as any)['propTypes' + ''] = exactProp(Dropdown.propTypes);
}
export { Dropdown };
| 6,123 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Dropdown/Dropdown.types.ts | export interface DropdownProps {
children: React.ReactNode;
/**
* If `true`, the dropdown is initially open.
*/
defaultOpen?: boolean;
/**
* Callback fired when the component requests to be opened or closed.
*/
onOpenChange?: (
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
open: boolean,
) => void;
/**
* Allows to control whether the dropdown is open.
* This is a controlled counterpart of `defaultOpen`.
*/
open?: boolean;
}
| 6,124 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Dropdown/index.ts | export * from './Dropdown';
export * from './Dropdown.types';
| 6,125 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FocusTrap/FocusTrap.test.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { expect } from 'chai';
import { act, createRenderer, screen } from '@mui-internal/test-utils';
import { FocusTrap } from '@mui/base/FocusTrap';
import { Portal } from '@mui/base/Portal';
interface GenericProps {
[index: string]: any;
}
describe('<FocusTrap />', () => {
const { clock, render } = createRenderer();
let initialFocus: HTMLElement | null = null;
beforeEach(() => {
initialFocus = document.createElement('button');
initialFocus.tabIndex = 0;
document.body.appendChild(initialFocus);
act(() => {
initialFocus!.focus();
});
});
afterEach(() => {
document.body.removeChild(initialFocus!);
});
it('should return focus to the root', () => {
const { getByTestId } = render(
<FocusTrap open>
<div tabIndex={-1} data-testid="root">
<input autoFocus data-testid="auto-focus" />
</div>
</FocusTrap>,
// TODO: https://github.com/reactwg/react-18/discussions/18#discussioncomment-893076
{ strictEffects: false },
);
expect(getByTestId('auto-focus')).toHaveFocus();
act(() => {
initialFocus!.focus();
});
expect(getByTestId('root')).toHaveFocus();
});
it('should not return focus to the children when disableEnforceFocus is true', () => {
const { getByTestId } = render(
<FocusTrap open disableEnforceFocus>
<div tabIndex={-1}>
<input autoFocus data-testid="auto-focus" />
</div>
</FocusTrap>,
// TODO: https://github.com/reactwg/react-18/discussions/18#discussioncomment-893076s
{ strictEffects: false },
);
expect(getByTestId('auto-focus')).toHaveFocus();
act(() => {
initialFocus!.focus();
});
expect(initialFocus).toHaveFocus();
});
it('should focus first focusable child in portal', () => {
const { getByTestId } = render(
<FocusTrap open>
<div tabIndex={-1}>
<Portal>
<input autoFocus data-testid="auto-focus" />
</Portal>
</div>
</FocusTrap>,
);
expect(getByTestId('auto-focus')).toHaveFocus();
});
it('should warn if the root content is not focusable', () => {
const UnfocusableDialog = React.forwardRef<HTMLDivElement>((_, ref) => <div ref={ref} />);
expect(() => {
render(
<FocusTrap open>
<UnfocusableDialog />
</FocusTrap>,
);
}).toErrorDev('MUI: The modal content node does not accept focus');
});
it('should not attempt to focus nonexistent children', () => {
const EmptyDialog = React.forwardRef(() => null);
render(
<FocusTrap open>
<EmptyDialog />
</FocusTrap>,
);
});
it('should focus rootRef if no tabbable children are rendered', () => {
render(
<FocusTrap open>
<div tabIndex={-1} data-testid="root">
<div>Title</div>
</div>
</FocusTrap>,
);
expect(screen.getByTestId('root')).toHaveFocus();
});
it('does not steal focus from a portaled element if any prop but open changes', () => {
function Test(props: GenericProps) {
return (
<FocusTrap disableAutoFocus open {...props}>
<div data-testid="focus-root" tabIndex={-1}>
{ReactDOM.createPortal(<input data-testid="portal-input" />, document.body)}
</div>
</FocusTrap>
);
}
const { setProps } = render(<Test />);
const portaledTextbox = screen.getByTestId('portal-input');
act(() => {
portaledTextbox.focus();
});
// sanity check
expect(portaledTextbox).toHaveFocus();
setProps({ disableAutoFocus: false });
expect(portaledTextbox).toHaveFocus();
setProps({ disableEnforceFocus: true });
expect(portaledTextbox).toHaveFocus();
setProps({ disableRestoreFocus: true });
expect(portaledTextbox).toHaveFocus();
// same behavior, just referential equality changes
setProps({ isEnabled: () => true });
expect(portaledTextbox).toHaveFocus();
});
it('undesired: lazy root does not get autofocus', () => {
let mountDeferredComponent: React.DispatchWithoutAction;
const DeferredComponent = React.forwardRef<HTMLDivElement>(function DeferredComponent(
props,
ref,
) {
const [mounted, setMounted] = React.useReducer(() => true, false);
mountDeferredComponent = setMounted;
if (mounted) {
return <div ref={ref} {...props} />;
}
return null;
});
render(
<FocusTrap open>
<DeferredComponent data-testid="deferred-component" />
</FocusTrap>,
);
expect(initialFocus).toHaveFocus();
act(() => {
mountDeferredComponent();
});
// desired
// expect(screen.getByTestId('deferred-component')).toHaveFocus();
// undesired
expect(initialFocus).toHaveFocus();
});
it('does not bounce focus around due to sync focus-restore + focus-contain', () => {
const eventLog: string[] = [];
function Test(props: GenericProps) {
return (
<div onBlur={() => eventLog.push('blur')}>
<FocusTrap open {...props}>
<div data-testid="root" tabIndex={-1}>
<input data-testid="focus-input" />
</div>
</FocusTrap>
</div>
);
}
const { setProps } = render(<Test />, {
// Strict Effects interferes with the premise of the test.
// It would trigger a focus restore (i.e. a blur event)
strictEffects: false,
});
// same behavior, just referential equality changes
setProps({ isEnabled: () => true });
expect(screen.getByTestId('root')).toHaveFocus();
expect(eventLog).to.deep.equal([]);
});
it('does not focus if isEnabled returns false', () => {
function Test(props: GenericProps) {
return (
<div>
<input />
<FocusTrap open {...props}>
<div tabIndex={-1} data-testid="root" />
</FocusTrap>
</div>
);
}
const { setProps, getByRole } = render(<Test />);
expect(screen.getByTestId('root')).toHaveFocus();
act(() => {
getByRole('textbox').focus();
});
expect(getByRole('textbox')).not.toHaveFocus();
setProps({ isEnabled: () => false });
act(() => {
getByRole('textbox').focus();
});
expect(getByRole('textbox')).toHaveFocus();
});
it('restores focus when closed', () => {
function Test(props: GenericProps) {
return (
<FocusTrap open {...props}>
<div data-testid="focus-root" tabIndex={-1}>
<input />
</div>
</FocusTrap>
);
}
const { setProps } = render(<Test />);
setProps({ open: false });
expect(initialFocus).toHaveFocus();
});
it('undesired: enabling restore-focus logic when closing has no effect', () => {
function Test(props: GenericProps) {
return (
<FocusTrap open disableRestoreFocus {...props}>
<div data-testid="root" tabIndex={-1}>
<input data-testid="focus-input" />
</div>
</FocusTrap>
);
}
const { setProps } = render(<Test />);
setProps({ open: false, disableRestoreFocus: false });
// undesired: should be expect(initialFocus).toHaveFocus();
expect(screen.getByTestId('root')).toHaveFocus();
});
it('undesired: setting `disableRestoreFocus` to false before closing has no effect', () => {
function Test(props: GenericProps) {
return (
<FocusTrap open disableRestoreFocus {...props}>
<div data-testid="root" tabIndex={-1}>
<input data-testid="focus-input" />
</div>
</FocusTrap>
);
}
const { setProps } = render(<Test />);
setProps({ disableRestoreFocus: false });
setProps({ open: false });
// undesired: should be expect(initialFocus).toHaveFocus();
expect(screen.getByTestId('root')).toHaveFocus();
});
describe('interval', () => {
clock.withFakeTimers();
it('contains the focus if the active element is removed', () => {
function WithRemovableElement({ hideButton = false }) {
return (
<FocusTrap open>
<div tabIndex={-1} data-testid="root">
{!hideButton && (
<button type="button" data-testid="hide-button">
I am going to disappear
</button>
)}
</div>
</FocusTrap>
);
}
const { setProps } = render(<WithRemovableElement />);
expect(screen.getByTestId('root')).toHaveFocus();
act(() => {
screen.getByTestId('hide-button').focus();
});
expect(screen.getByTestId('hide-button')).toHaveFocus();
setProps({ hideButton: true });
expect(screen.getByTestId('root')).not.toHaveFocus();
clock.tick(500); // wait for the interval check to kick in.
expect(screen.getByTestId('root')).toHaveFocus();
});
describe('prop: disableAutoFocus', () => {
it('should not trap', () => {
const { getByRole } = render(
<div>
<input />
<FocusTrap open disableAutoFocus>
<div tabIndex={-1} data-testid="root" />
</FocusTrap>
</div>,
);
clock.tick(500); // trigger an interval call
expect(initialFocus).toHaveFocus();
act(() => {
getByRole('textbox').focus();
});
expect(getByRole('textbox')).toHaveFocus();
});
it('should trap once the focus moves inside', () => {
render(
<div>
<input data-testid="outside-input" />
<FocusTrap open disableAutoFocus>
<div tabIndex={-1} data-testid="root">
<button type="button" data-testid="focus-input" />
</div>
</FocusTrap>
</div>,
);
expect(initialFocus).toHaveFocus();
act(() => {
screen.getByTestId('outside-input').focus();
});
expect(screen.getByTestId('outside-input')).toHaveFocus();
// the trap activates
act(() => {
screen.getByTestId('focus-input').focus();
});
expect(screen.getByTestId('focus-input')).toHaveFocus();
// the trap prevent to escape
act(() => {
screen.getByTestId('outside-input').focus();
});
expect(screen.getByTestId('root')).toHaveFocus();
});
it('should restore the focus', () => {
function Test(props: GenericProps) {
return (
<div>
<input data-testid="outside-input" />
<FocusTrap open disableAutoFocus {...props}>
<div tabIndex={-1} data-testid="root">
<input data-testid="focus-input" />
</div>
</FocusTrap>
</div>
);
}
const { setProps } = render(<Test />);
// set the expected focus restore location
act(() => {
screen.getByTestId('outside-input').focus();
});
expect(screen.getByTestId('outside-input')).toHaveFocus();
// the trap activates
act(() => {
screen.getByTestId('root').focus();
});
expect(screen.getByTestId('root')).toHaveFocus();
// restore the focus to the first element before triggering the trap
setProps({ open: false });
expect(screen.getByTestId('outside-input')).toHaveFocus();
});
});
});
});
| 6,126 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FocusTrap/FocusTrap.tsx | 'use client';
/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */
import * as React from 'react';
import PropTypes from 'prop-types';
import {
exactProp,
elementAcceptingRef,
unstable_useForkRef as useForkRef,
unstable_ownerDocument as ownerDocument,
} from '@mui/utils';
import { FocusTrapProps } from './FocusTrap.types';
// Inspired by https://github.com/focus-trap/tabbable
const candidatesSelector = [
'input',
'select',
'textarea',
'a[href]',
'button',
'[tabindex]',
'audio[controls]',
'video[controls]',
'[contenteditable]:not([contenteditable="false"])',
].join(',');
interface OrderedTabNode {
documentOrder: number;
tabIndex: number;
node: HTMLElement;
}
function getTabIndex(node: HTMLElement): number {
const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10);
if (!Number.isNaN(tabindexAttr)) {
return tabindexAttr;
}
// Browsers do not return `tabIndex` correctly for contentEditable nodes;
// https://bugs.chromium.org/p/chromium/issues/detail?id=661108&q=contenteditable%20tabindex&can=2
// so if they don't have a tabindex attribute specifically set, assume it's 0.
// in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default
// `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
// yet they are still part of the regular tab order; in FF, they get a default
// `tabIndex` of 0; since Chrome still puts those elements in the regular tab
// order, consider their tab index to be 0.
if (
node.contentEditable === 'true' ||
((node.nodeName === 'AUDIO' || node.nodeName === 'VIDEO' || node.nodeName === 'DETAILS') &&
node.getAttribute('tabindex') === null)
) {
return 0;
}
return node.tabIndex;
}
function isNonTabbableRadio(node: HTMLInputElement): boolean {
if (node.tagName !== 'INPUT' || node.type !== 'radio') {
return false;
}
if (!node.name) {
return false;
}
const getRadio = (selector: string) =>
node.ownerDocument.querySelector(`input[type="radio"]${selector}`);
let roving = getRadio(`[name="${node.name}"]:checked`);
if (!roving) {
roving = getRadio(`[name="${node.name}"]`);
}
return roving !== node;
}
function isNodeMatchingSelectorFocusable(node: HTMLInputElement): boolean {
if (
node.disabled ||
(node.tagName === 'INPUT' && node.type === 'hidden') ||
isNonTabbableRadio(node)
) {
return false;
}
return true;
}
function defaultGetTabbable(root: HTMLElement): HTMLElement[] {
const regularTabNodes: HTMLElement[] = [];
const orderedTabNodes: OrderedTabNode[] = [];
Array.from(root.querySelectorAll(candidatesSelector)).forEach((node, i) => {
const nodeTabIndex = getTabIndex(node as HTMLElement);
if (nodeTabIndex === -1 || !isNodeMatchingSelectorFocusable(node as HTMLInputElement)) {
return;
}
if (nodeTabIndex === 0) {
regularTabNodes.push(node as HTMLElement);
} else {
orderedTabNodes.push({
documentOrder: i,
tabIndex: nodeTabIndex,
node: node as HTMLElement,
});
}
});
return orderedTabNodes
.sort((a, b) =>
a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex,
)
.map((a) => a.node)
.concat(regularTabNodes);
}
function defaultIsEnabled(): boolean {
return true;
}
/**
* Utility component that locks focus inside the component.
*
* Demos:
*
* - [Focus Trap](https://mui.com/base-ui/react-focus-trap/)
*
* API:
*
* - [FocusTrap API](https://mui.com/base-ui/react-focus-trap/components-api/#focus-trap)
*/
function FocusTrap(props: FocusTrapProps): JSX.Element {
const {
children,
disableAutoFocus = false,
disableEnforceFocus = false,
disableRestoreFocus = false,
getTabbable = defaultGetTabbable,
isEnabled = defaultIsEnabled,
open,
} = props;
const ignoreNextEnforceFocus = React.useRef(false);
const sentinelStart = React.useRef<HTMLDivElement>(null);
const sentinelEnd = React.useRef<HTMLDivElement>(null);
const nodeToRestore = React.useRef<EventTarget | null>(null);
const reactFocusEventTarget = React.useRef<EventTarget | null>(null);
// This variable is useful when disableAutoFocus is true.
// It waits for the active element to move into the component to activate.
const activated = React.useRef(false);
const rootRef = React.useRef<HTMLElement>(null);
// @ts-expect-error TODO upstream fix
const handleRef = useForkRef(children.ref, rootRef);
const lastKeydown = React.useRef<KeyboardEvent | null>(null);
React.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
activated.current = !disableAutoFocus;
}, [disableAutoFocus, open]);
React.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
const doc = ownerDocument(rootRef.current);
if (!rootRef.current.contains(doc.activeElement)) {
if (!rootRef.current.hasAttribute('tabIndex')) {
if (process.env.NODE_ENV !== 'production') {
console.error(
[
'MUI: The modal content node does not accept focus.',
'For the benefit of assistive technologies, ' +
'the tabIndex of the node is being set to "-1".',
].join('\n'),
);
}
rootRef.current.setAttribute('tabIndex', '-1');
}
if (activated.current) {
rootRef.current.focus();
}
}
return () => {
// restoreLastFocus()
if (!disableRestoreFocus) {
// In IE11 it is possible for document.activeElement to be null resulting
// in nodeToRestore.current being null.
// Not all elements in IE11 have a focus method.
// Once IE11 support is dropped the focus() call can be unconditional.
if (nodeToRestore.current && (nodeToRestore.current as HTMLElement).focus) {
ignoreNextEnforceFocus.current = true;
(nodeToRestore.current as HTMLElement).focus();
}
nodeToRestore.current = null;
}
};
// Missing `disableRestoreFocus` which is fine.
// We don't support changing that prop on an open FocusTrap
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
React.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
const doc = ownerDocument(rootRef.current);
const loopFocus = (nativeEvent: KeyboardEvent) => {
lastKeydown.current = nativeEvent;
if (disableEnforceFocus || !isEnabled() || nativeEvent.key !== 'Tab') {
return;
}
// Make sure the next tab starts from the right place.
// doc.activeElement refers to the origin.
if (doc.activeElement === rootRef.current && nativeEvent.shiftKey) {
// We need to ignore the next contain as
// it will try to move the focus back to the rootRef element.
ignoreNextEnforceFocus.current = true;
if (sentinelEnd.current) {
sentinelEnd.current.focus();
}
}
};
const contain = () => {
const rootElement = rootRef.current;
// Cleanup functions are executed lazily in React 17.
// Contain can be called between the component being unmounted and its cleanup function being run.
if (rootElement === null) {
return;
}
if (!doc.hasFocus() || !isEnabled() || ignoreNextEnforceFocus.current) {
ignoreNextEnforceFocus.current = false;
return;
}
// The focus is already inside
if (rootElement.contains(doc.activeElement)) {
return;
}
// The disableEnforceFocus is set and the focus is outside of the focus trap (and sentinel nodes)
if (
disableEnforceFocus &&
doc.activeElement !== sentinelStart.current &&
doc.activeElement !== sentinelEnd.current
) {
return;
}
// if the focus event is not coming from inside the children's react tree, reset the refs
if (doc.activeElement !== reactFocusEventTarget.current) {
reactFocusEventTarget.current = null;
} else if (reactFocusEventTarget.current !== null) {
return;
}
if (!activated.current) {
return;
}
let tabbable: string[] | HTMLElement[] = [];
if (
doc.activeElement === sentinelStart.current ||
doc.activeElement === sentinelEnd.current
) {
tabbable = getTabbable(rootRef.current!);
}
// one of the sentinel nodes was focused, so move the focus
// to the first/last tabbable element inside the focus trap
if (tabbable.length > 0) {
const isShiftTab = Boolean(
lastKeydown.current?.shiftKey && lastKeydown.current?.key === 'Tab',
);
const focusNext = tabbable[0];
const focusPrevious = tabbable[tabbable.length - 1];
if (typeof focusNext !== 'string' && typeof focusPrevious !== 'string') {
if (isShiftTab) {
focusPrevious.focus();
} else {
focusNext.focus();
}
}
// no tabbable elements in the trap focus or the focus was outside of the focus trap
} else {
rootElement.focus();
}
};
doc.addEventListener('focusin', contain);
doc.addEventListener('keydown', loopFocus, true);
// With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area.
// e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.
// Instead, we can look if the active element was restored on the BODY element.
//
// The whatwg spec defines how the browser should behave but does not explicitly mention any events:
// https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.
const interval = setInterval(() => {
if (doc.activeElement && doc.activeElement.tagName === 'BODY') {
contain();
}
}, 50);
return () => {
clearInterval(interval);
doc.removeEventListener('focusin', contain);
doc.removeEventListener('keydown', loopFocus, true);
};
}, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open, getTabbable]);
const onFocus = (event: FocusEvent) => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
reactFocusEventTarget.current = event.target;
const childrenPropsHandler = children.props.onFocus;
if (childrenPropsHandler) {
childrenPropsHandler(event);
}
};
const handleFocusSentinel = (event: React.FocusEvent<HTMLDivElement>) => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
};
return (
<React.Fragment>
<div
tabIndex={open ? 0 : -1}
onFocus={handleFocusSentinel}
ref={sentinelStart}
data-testid="sentinelStart"
/>
{React.cloneElement(children, { ref: handleRef, onFocus })}
<div
tabIndex={open ? 0 : -1}
onFocus={handleFocusSentinel}
ref={sentinelEnd}
data-testid="sentinelEnd"
/>
</React.Fragment>
);
}
FocusTrap.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A single child content element.
*/
children: elementAcceptingRef,
/**
* If `true`, the focus trap will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any focus trap children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the focus trap less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, the focus trap will not prevent focus from leaving the focus trap while open.
*
* Generally this should never be set to `true` as it makes the focus trap less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, the focus trap will not restore focus to previously focused element once
* focus trap is hidden or unmounted.
* @default false
*/
disableRestoreFocus: PropTypes.bool,
/**
* Returns an array of ordered tabbable nodes (i.e. in tab order) within the root.
* For instance, you can provide the "tabbable" npm dependency.
* @param {HTMLElement} root
*/
getTabbable: PropTypes.func,
/**
* This prop extends the `open` prop.
* It allows to toggle the open state without having to wait for a rerender when changing the `open` prop.
* This prop should be memoized.
* It can be used to support multiple focus trap mounted at the same time.
* @default function defaultIsEnabled(): boolean {
* return true;
* }
*/
isEnabled: PropTypes.func,
/**
* If `true`, focus is locked.
*/
open: PropTypes.bool.isRequired,
} as any;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
(FocusTrap as any)['propTypes' + ''] = exactProp(FocusTrap.propTypes);
}
export { FocusTrap };
| 6,127 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FocusTrap/FocusTrap.types.ts | import * as React from 'react';
export interface FocusTrapProps {
/**
* If `true`, focus is locked.
*/
open: boolean;
/**
* Returns an array of ordered tabbable nodes (i.e. in tab order) within the root.
* For instance, you can provide the "tabbable" npm dependency.
* @param {HTMLElement} root
*/
getTabbable?: (root: HTMLElement) => string[];
/**
* This prop extends the `open` prop.
* It allows to toggle the open state without having to wait for a rerender when changing the `open` prop.
* This prop should be memoized.
* It can be used to support multiple focus trap mounted at the same time.
* @default function defaultIsEnabled(): boolean {
* return true;
* }
*/
isEnabled?: () => boolean;
/**
* A single child content element.
*/
children: React.ReactElement;
/**
* If `true`, the focus trap will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any focus trap children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the focus trap less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableAutoFocus?: boolean;
/**
* If `true`, the focus trap will not prevent focus from leaving the focus trap while open.
*
* Generally this should never be set to `true` as it makes the focus trap less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableEnforceFocus?: boolean;
/**
* If `true`, the focus trap will not restore focus to previously focused element once
* focus trap is hidden or unmounted.
* @default false
*/
disableRestoreFocus?: boolean;
}
| 6,128 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FocusTrap/index.ts | export { FocusTrap } from './FocusTrap';
export * from './FocusTrap.types';
| 6,129 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/FormControl.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { FormControl } from '@mui/base/FormControl';
import { FormControlRootSlotProps } from './FormControl.types';
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
function FormControlTest() {
return (
<div>
<FormControl required />
{/* @ts-expect-error */}
<FormControl invalidProp={0} />
<FormControl<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<FormControl<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<FormControl<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<FormControl<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<FormControl<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onClick={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
}
function Root(props: FormControlRootSlotProps) {
const { ownerState, children, ...other } = props;
return (
<div data-filled={ownerState.filled} {...other}>
{children as React.ReactNode}
</div>
);
}
const StyledFormControl = <FormControl slots={{ root: Root }} />;
| 6,130 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/FormControl.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
} from '@mui-internal/test-utils';
import { FormControl, formControlClasses, useFormControlContext } from '@mui/base/FormControl';
describe('<FormControl />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<FormControl />, () => ({
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'div',
muiName: 'BaseFormControl',
slots: {
root: {
expectedClassName: formControlClasses.root,
},
},
skip: ['componentProp'],
}));
describe('initial state', () => {
it('has undefined value', () => {
function TestComponent() {
const context = useFormControlContext();
return <input value={context!.value as string} onChange={context!.onChange} />;
}
const { getByRole } = render(
<FormControl>
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox')).to.have.property('value', '');
});
it('has disabled, filled, focused, and required set to false', () => {
function TestComponent() {
const context = useFormControlContext();
return (
<input
data-filled={context!.filled}
data-focused={context!.focused}
disabled={context!.disabled}
required={context!.required}
/>
);
}
const { getByRole } = render(
<FormControl>
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox')).to.include({
disabled: false,
required: false,
});
expect(getByRole('textbox').dataset).to.include({
filled: 'false',
focused: 'false',
});
});
});
describe('prop: value', () => {
it('propagates the value via the context', () => {
function TestComponent() {
const context = useFormControlContext();
return <input value={context!.value as string} onChange={context!.onChange} />;
}
const { getByRole } = render(
<FormControl value="42">
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox')).to.have.property('value', '42');
});
});
describe('prop: disabled', () => {
it('propagates the value via the context', () => {
function TestComponent() {
const context = useFormControlContext();
return <input disabled={context?.disabled} />;
}
const { getByRole } = render(
<FormControl disabled>
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox')).to.have.property('disabled', true);
});
});
describe('prop: defaultValue', () => {
it('propagates the value via the context', () => {
function TestComponent() {
const context = useFormControlContext();
return <input value={context!.value as string} onChange={context!.onChange} />;
}
const { getByRole } = render(
<FormControl defaultValue="foo">
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox')).to.have.property('value', 'foo');
});
});
describe('prop: required', () => {
it('propagates the value via the context', () => {
function TestComponent() {
const context = useFormControlContext();
return <input required={context!.required} />;
}
const { getByRole } = render(
<FormControl required>
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox')).to.have.property('required', true);
});
});
describe('prop: filled', () => {
it('should be set if value is provided', () => {
function TestComponent() {
const context = useFormControlContext();
return <input data-filled={context!.filled} />;
}
const { getByRole } = render(
<FormControl value="foo">
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox').dataset).to.have.property('filled', 'true');
});
it('should be set if defaultValue is provided', () => {
function TestComponent() {
const context = useFormControlContext();
return <input data-filled={context!.filled} />;
}
const { getByRole } = render(
<FormControl defaultValue="foo">
<TestComponent />
</FormControl>,
);
expect(getByRole('textbox').dataset).to.have.property('filled', 'true');
});
it('should be set if a controlled inner input sets its value', () => {
function TestComponent() {
const context = useFormControlContext();
return (
<input
data-filled={context!.filled}
value={context!.value as string}
onChange={context!.onChange}
/>
);
}
const { getByRole } = render(
<FormControl>
<TestComponent />
</FormControl>,
);
const input = getByRole('textbox');
fireEvent.change(input, { target: { value: 'a' } });
expect(input.dataset).to.have.property('filled', 'true');
});
});
describe('prop: onChange', () => {
it("propagates the inner input's onChange to FormControl's onChange", () => {
function TestComponent() {
const context = useFormControlContext();
return <input value={context!.value as string} onChange={context!.onChange} />;
}
const handleChange = spy();
const { getByRole } = render(
<FormControl onChange={handleChange}>
<TestComponent />
</FormControl>,
);
const input = getByRole('textbox');
fireEvent.change(input, { target: { value: 'test' } });
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][0]).to.have.property('target');
expect(handleChange.args[0][0].target).to.have.property('value', 'test');
});
});
});
| 6,131 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/FormControl.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import useControlled from '@mui/utils/useControlled';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { FormControlContext } from './FormControlContext';
import { getFormControlUtilityClass } from './formControlClasses';
import {
FormControlProps,
NativeFormControlElement,
FormControlTypeMap,
FormControlOwnerState,
FormControlState,
FormControlRootSlotProps,
} from './FormControl.types';
import { useSlotProps, WithOptionalOwnerState } from '../utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
function hasValue(value: unknown) {
return value != null && !(Array.isArray(value) && value.length === 0) && value !== '';
}
function useUtilityClasses(ownerState: FormControlOwnerState) {
const { disabled, error, filled, focused, required } = ownerState;
const slots = {
root: [
'root',
disabled && 'disabled',
focused && 'focused',
error && 'error',
filled && 'filled',
required && 'required',
],
};
return composeClasses(slots, useClassNamesOverride(getFormControlUtilityClass));
}
/**
* Provides context such as filled/focused/error/required for form inputs.
* Relying on the context provides high flexibility and ensures that the state always stays
* consistent across the children of the `FormControl`.
* This context is used by the following components:
*
* * FormLabel
* * FormHelperText
* * Input
* * InputLabel
*
* You can find one composition example below and more going to [the demos](https://mui.com/material-ui/react-text-field/#components).
*
* ```jsx
* <FormControl>
* <InputLabel htmlFor="my-input">Email address</InputLabel>
* <Input id="my-input" aria-describedby="my-helper-text" />
* <FormHelperText id="my-helper-text">We'll never share your email.</FormHelperText>
* </FormControl>
* ```
*
* ⚠️ Only one `Input` can be used within a FormControl because it create visual inconsistencies.
* For instance, only one input can be focused at the same time, the state shouldn't be shared.
*
* Demos:
*
* - [Form Control](https://mui.com/base-ui/react-form-control/)
* - [Input](https://mui.com/joy-ui/react-input/)
* - [Checkbox](https://mui.com/material-ui/react-checkbox/)
* - [Radio Group](https://mui.com/material-ui/react-radio-button/)
* - [Switch](https://mui.com/material-ui/react-switch/)
* - [Text Field](https://mui.com/material-ui/react-text-field/)
*
* API:
*
* - [FormControl API](https://mui.com/base-ui/react-form-control/components-api/#form-control)
*/
const FormControl = React.forwardRef(function FormControl<
RootComponentType extends React.ElementType,
>(props: FormControlProps<RootComponentType>, forwardedRef: React.ForwardedRef<Element>) {
const {
defaultValue,
children,
disabled = false,
error = false,
onChange,
required = false,
slotProps = {},
slots = {},
value: incomingValue,
...other
} = props;
const [value, setValue] = useControlled({
controlled: incomingValue,
default: defaultValue,
name: 'FormControl',
state: 'value',
});
const filled = hasValue(value);
const [focusedState, setFocused] = React.useState(false);
const focused = focusedState && !disabled;
React.useEffect(() => setFocused((isFocused) => (disabled ? false : isFocused)), [disabled]);
const ownerState: FormControlOwnerState = {
...props,
disabled,
error,
filled,
focused,
required,
};
const childContext: FormControlState = React.useMemo(() => {
return {
disabled,
error,
filled,
focused,
onBlur: () => {
setFocused(false);
},
onChange: (event: React.ChangeEvent<NativeFormControlElement>) => {
setValue(event.target.value);
onChange?.(event);
},
onFocus: () => {
setFocused(true);
},
required,
value: value ?? '',
};
}, [disabled, error, filled, focused, onChange, required, setValue, value]);
const classes = useUtilityClasses(ownerState);
const renderChildren = () => {
if (typeof children === 'function') {
return children(childContext);
}
return children;
};
const Root = slots.root ?? 'div';
const rootProps: WithOptionalOwnerState<FormControlRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
children: renderChildren(),
},
ownerState,
className: classes.root,
});
return (
<FormControlContext.Provider value={childContext}>
<Root {...rootProps} />
</FormControlContext.Provider>
);
}) as PolymorphicComponent<FormControlTypeMap>;
FormControl.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.node,
PropTypes.func,
]),
/**
* Class name applied to the root element.
*/
className: PropTypes.string,
/**
* @ignore
*/
defaultValue: PropTypes.any,
/**
* If `true`, the label, input and helper text should be displayed in a disabled state.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, the label is displayed in an error state.
* @default false
*/
error: PropTypes.bool,
/**
* Callback fired when the form element's value is modified.
*/
onChange: PropTypes.func,
/**
* If `true`, the label will indicate that the `input` is required.
* @default false
*/
required: PropTypes.bool,
/**
* The props used for each slot inside the FormControl.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the FormControl.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* The value of the form element.
*/
value: PropTypes.any,
} as any;
export { FormControl };
| 6,132 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/FormControl.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export type NativeFormControlElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
export interface FormControlRootSlotPropsOverrides {}
export interface FormControlOwnProps {
/**
* The content of the component.
*/
children?: React.ReactNode | ((state: FormControlState) => React.ReactNode);
/**
* Class name applied to the root element.
*/
className?: string;
defaultValue?: unknown;
/**
* If `true`, the label, input and helper text should be displayed in a disabled state.
* @default false
*/
disabled?: boolean;
/**
* If `true`, the label is displayed in an error state.
* @default false
*/
error?: boolean;
/**
* Callback fired when the form element's value is modified.
*/
onChange?: React.ChangeEventHandler<NativeFormControlElement>;
/**
* If `true`, the label will indicate that the `input` is required.
* @default false
*/
required?: boolean;
/**
* The props used for each slot inside the FormControl.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', FormControlRootSlotPropsOverrides, FormControlOwnerState>;
};
/**
* The components used for each slot inside the FormControl.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: FormControlSlots;
/**
* The value of the form element.
*/
value?: unknown;
}
export interface FormControlSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export interface FormControlTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: FormControlOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type FormControlProps<
RootComponentType extends React.ElementType = FormControlTypeMap['defaultComponent'],
> = PolymorphicProps<FormControlTypeMap<{}, RootComponentType>, RootComponentType>;
type NonOptionalOwnerState = 'disabled' | 'error' | 'required';
export type FormControlOwnerState = Simplify<
Omit<FormControlOwnProps, NonOptionalOwnerState> &
Required<Pick<FormControlProps, NonOptionalOwnerState>> & {
filled: boolean;
focused: boolean;
}
>;
export type FormControlState = {
/**
* If `true`, the label, input and helper text should be displayed in a disabled state.
*/
disabled: boolean;
/**
* If `true`, the label is displayed in an error state.
*/
error: boolean;
/**
* If `true`, the form element has some value.
*/
filled: boolean;
/**
* If `true`, the form element is focused and not disabled.
*/
focused: boolean;
/**
* Callback fired when the form element has lost focus.
*/
onBlur: () => void;
/**
* Callback fired when the form element's value is modified.
*/
onChange: React.ChangeEventHandler<NativeFormControlElement>;
/**
* Callback fired when the form element receives focus.
*/
onFocus: () => void;
/**
* If `true`, the label will indicate that the `input` is required.
*/
required: boolean;
/**
* The value of the form element.
*/
value: unknown;
};
export type FormControlRootSlotProps = {
children: React.ReactNode | ((state: FormControlState) => React.ReactNode);
className?: string;
ownerState: FormControlOwnerState;
};
export interface UseFormControlContextReturnValue extends FormControlState {}
| 6,133 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/FormControlContext.ts | import * as React from 'react';
import { FormControlState } from './FormControl.types';
/**
* @ignore - internal component.
*/
const FormControlContext = React.createContext<FormControlState | undefined>(undefined);
if (process.env.NODE_ENV !== 'production') {
FormControlContext.displayName = 'FormControlContext';
}
export { FormControlContext };
| 6,134 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/formControlClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface FormControlClasses {
/** Class applied to the root element. */
root: string;
/** State class applied to the root element if `disabled={true}`. */
disabled: string;
/** State class applied to the root element if `error={true}`. */
error: string;
/** State class applied to the root element if the inner input has value. */
filled: string;
/** State class applied to the root element if the inner input is focused. */
focused: string;
/** State class applied to the root element if `required={true}`. */
required: string;
}
export type FormControlClassKey = keyof FormControlClasses;
export function getFormControlUtilityClass(slot: string): string {
return generateUtilityClass('MuiFormControl', slot);
}
export const formControlClasses: FormControlClasses = generateUtilityClasses('MuiFormControl', [
'root',
'disabled',
'error',
'filled',
'focused',
'required',
]);
| 6,135 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/index.ts | export { FormControl } from './FormControl';
export { FormControlContext } from './FormControlContext';
export type {
FormControlProps,
FormControlRootSlotPropsOverrides,
FormControlState,
UseFormControlContextReturnValue,
FormControlOwnProps,
} from './FormControl.types';
export * from './formControlClasses';
export { useFormControlContext } from './useFormControlContext';
| 6,136 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/FormControl/useFormControlContext.ts | 'use client';
import * as React from 'react';
import { UseFormControlContextReturnValue } from './FormControl.types';
import { FormControlContext } from './FormControlContext';
/**
*
* Demos:
*
* - [Form Control](https://mui.com/base-ui/react-form-control/#hook)
*
* API:
*
* - [useFormControlContext API](https://mui.com/base-ui/react-form-control/hooks-api/#use-form-control-context)
*/
export function useFormControlContext(): UseFormControlContextReturnValue | undefined {
return React.useContext(FormControlContext);
}
| 6,137 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Input/Input.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Input, InputInputSlotProps, InputRootSlotProps } from '@mui/base/Input';
const InputRoot = React.forwardRef(function InputRoot(
props: InputRootSlotProps,
ref: React.Ref<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-focused={ownerState.focused} {...other} ref={ref} />;
});
const InputInput = React.forwardRef(function InputInput(
props: InputInputSlotProps,
ref: React.Ref<HTMLInputElement>,
) {
const { ownerState, ...other } = props;
return <input data-focused={ownerState.focused} {...other} ref={ref} />;
});
const styledInput = <Input slots={{ root: InputRoot, input: InputInput }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Input invalidProp={0} />
<Input<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<Input<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Input<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<Input<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Input<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,138 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Input/Input.test.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import {
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
screen,
act,
} from '@mui-internal/test-utils';
import { expect } from 'chai';
import { spy } from 'sinon';
import { Input, inputClasses, InputOwnerState } from '@mui/base/Input';
describe('<Input />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<Input />, () => ({
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'div',
muiName: 'MuiInput',
slots: {
root: {
expectedClassName: inputClasses.root,
},
input: {
expectedClassName: inputClasses.input,
testWithElement: 'input',
},
},
skip: ['componentProp'],
}));
it('should render textarea without any console errors when multiline=true', () => {
render(<Input multiline />);
expect(screen.getByRole('textbox')).to.have.tagName('textarea');
});
describe('prop: inputRef', () => {
it('should be able to attach input ref passed through slotProps', () => {
const inputRef = React.createRef<HTMLInputElement>();
const { getByRole } = render(<Input slotProps={{ input: { ref: inputRef } }} />);
expect(inputRef.current).to.deep.equal(getByRole('textbox'));
});
it('should be able to access the native textarea of a multiline input', () => {
const inputRef = React.createRef<HTMLInputElement>();
const { container } = render(<Input multiline slotProps={{ input: { ref: inputRef } }} />);
expect(inputRef.current).to.equal(container.querySelector('textarea'));
});
});
describe('event handlers', () => {
it('should call event handlers passed in slotProps', () => {
const handleChange = spy();
const handleFocus = spy();
const handleBlur = spy();
const handleKeyDown = spy();
const handleKeyUp = spy();
const { getByRole } = render(
<Input
slotProps={{
input: {
onChange: handleChange,
onFocus: handleFocus,
onBlur: handleBlur,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
},
}}
/>,
);
const input = getByRole('textbox');
// simulating user input: gain focus, key input (keydown, (input), change, keyup), blur
act(() => {
input.focus();
});
expect(handleFocus.callCount).to.equal(1);
fireEvent.keyDown(input, { key: 'a' });
expect(handleKeyDown.callCount).to.equal(1);
fireEvent.change(input, { target: { value: 'a' } });
expect(handleChange.callCount).to.equal(1);
fireEvent.keyUp(input, { key: 'a' });
expect(handleKeyUp.callCount).to.equal(1);
act(() => {
input.blur();
});
expect(handleBlur.callCount).to.equal(1);
});
it('should call event handlers passed to component', () => {
const handleChange = spy();
const handleFocus = spy();
const handleBlur = spy();
const handleKeyDown = spy();
const handleKeyUp = spy();
const { getByRole } = render(
<Input
onChange={handleChange}
onFocus={handleFocus}
onBlur={handleBlur}
onKeyUp={handleKeyUp}
onKeyDown={handleKeyDown}
/>,
);
const input = getByRole('textbox');
// simulating user input: gain focus, key input (keydown, (input), change, keyup), blur
act(() => {
input.focus();
});
expect(handleFocus.callCount).to.equal(1);
fireEvent.keyDown(input, { key: 'a' });
expect(handleKeyDown.callCount).to.equal(1);
fireEvent.change(input, { target: { value: 'a' } });
expect(handleChange.callCount).to.equal(1);
fireEvent.keyUp(input, { key: 'a' });
expect(handleKeyUp.callCount).to.equal(1);
act(() => {
input.blur();
});
expect(handleBlur.callCount).to.equal(1);
});
it('should call slotProps.input.onChange callback with all params sent from custom Input component', () => {
const INPUT_VALUE = 'base';
const OUTPUT_VALUE = 'test';
/**
* This component simulates the integration of react-select with Input
* react-select has a custom onChange that is essentially "(string, string) => void"
* https://github.com/mui/material-ui/issues/18130
*/
const CustomInput = React.forwardRef(function CustomInput(
props: {
onChange: (...args: string[]) => void;
ownerState: InputOwnerState;
},
ref: React.ForwardedRef<HTMLInputElement>,
) {
const { onChange, ownerState, ...other } = props;
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange(e.target.value, OUTPUT_VALUE);
};
return <input ref={ref} onChange={handleChange} {...other} />;
});
CustomInput.propTypes = {
onChange: PropTypes.func.isRequired,
};
let outputArguments: string[] = [];
function parentHandleChange(...args: string[]) {
outputArguments = args;
}
const { getByRole } = render(
<Input
slots={{
input: CustomInput,
}}
slotProps={{
input: {
onChange: parentHandleChange as unknown as React.ChangeEventHandler<HTMLInputElement>,
},
}}
/>,
);
const textbox = getByRole('textbox');
fireEvent.change(textbox, { target: { value: INPUT_VALUE } });
expect(outputArguments.length).to.equal(2);
expect(outputArguments[0]).to.equal(INPUT_VALUE);
expect(outputArguments[1]).to.equal(OUTPUT_VALUE);
});
});
describe('prop: multiline', () => {
it('should pass the rows prop to the underlying textarea when multiline=true', () => {
const { getByRole } = render(<Input multiline rows={5} />);
expect(getByRole('textbox')).to.have.attribute('rows', '5');
});
it('should not pass the minRows or maxRows prop to the underlying textarea slot when default host component is used', () => {
const { getByRole } = render(<Input multiline minRows={5} maxRows={10} />);
expect(getByRole('textbox')).not.to.have.attribute('minRows');
expect(getByRole('textbox')).not.to.have.attribute('maxRows');
});
it('should pass the minRows or maxRows prop to the underlying textarea slot if a custom component is used', () => {
const CustomTextarea = React.forwardRef(
({ minRows, maxRows, ownerState, ...other }: any, ref) => {
expect(minRows).to.equal(5);
expect(maxRows).to.equal(10);
return <textarea {...other} ref={ref} />;
},
);
render(<Input multiline minRows={5} maxRows={10} slots={{ textarea: CustomTextarea }} />);
});
it('should forward the value to the textarea', () => {
render(<Input multiline maxRows={4} value="Hello" />);
const textarea = screen.getByRole('textbox', { hidden: false });
expect(textarea).to.have.value('Hello');
});
it('should preserve state when changing rows', () => {
const { setProps } = render(<Input multiline />);
const textarea = screen.getByRole('textbox', { hidden: false });
act(() => {
textarea.focus();
});
setProps({ rows: 4 });
expect(textarea).toHaveFocus();
});
});
describe('controlled', () => {
it('should considered [] as controlled', () => {
const { getByRole } = render(<Input value={[]} />);
const input = getByRole('textbox');
expect(input).to.have.property('value', '');
fireEvent.change(input, { target: { value: 'do not work' } });
expect(input).to.have.property('value', '');
});
});
describe('errors', () => {
it("throws on change if the target isn't mocked", () => {
/**
* This component simulates a custom input component that hides the inner
* input value for security reasons e.g. react-stripe-element.
*
* A ref is exposed to trigger a change event instead of using fireEvent.change
*/
const BadInputComponent = React.forwardRef(function BadInputComponent(
props: {
onChange: (arg: Record<string, unknown>) => void;
},
ref,
) {
const { onChange } = props;
// simulates const handleChange = () => onChange({}) and passing that
// handler to the onChange prop of `input`
React.useImperativeHandle(ref, () => () => onChange({}));
return <input />;
});
BadInputComponent.propTypes = {
onChange: PropTypes.func.isRequired,
};
const triggerChangeRef = React.createRef<HTMLInputElement>();
expect(() => {
render(
<Input
slots={{ input: BadInputComponent }}
slotProps={{
input: {
ref: triggerChangeRef,
},
}}
/>,
);
}).toErrorDev([
'MUI: You have provided a `slots.input` to the input component\nthat does not correctly handle the `ref` prop.\nMake sure the `ref` prop is called with a HTMLInputElement.',
// React 18 Strict Effects run mount effects twice
React.version.startsWith('18') &&
'MUI: You have provided a `slots.input` to the input component\nthat does not correctly handle the `ref` prop.\nMake sure the `ref` prop is called with a HTMLInputElement.',
]);
});
});
});
| 6,139 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Input/Input.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { isHostComponent } from '../utils/isHostComponent';
import { getInputUtilityClass } from './inputClasses';
import {
InputInputSlotProps,
InputOwnerState,
InputProps,
InputRootSlotProps,
InputTypeMap,
} from './Input.types';
import { useInput } from '../useInput';
import { EventHandlers, useSlotProps, WithOptionalOwnerState } from '../utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: InputOwnerState) => {
const { disabled, error, focused, formControlContext, multiline, startAdornment, endAdornment } =
ownerState;
const slots = {
root: [
'root',
disabled && 'disabled',
error && 'error',
focused && 'focused',
Boolean(formControlContext) && 'formControl',
multiline && 'multiline',
Boolean(startAdornment) && 'adornedStart',
Boolean(endAdornment) && 'adornedEnd',
],
input: ['input', disabled && 'disabled', multiline && 'multiline'],
};
return composeClasses(slots, useClassNamesOverride(getInputUtilityClass));
};
/**
*
* Demos:
*
* - [Input](https://mui.com/base-ui/react-input/)
*
* API:
*
* - [Input API](https://mui.com/base-ui/react-input/components-api/#input)
*/
const Input = React.forwardRef(function Input<RootComponentType extends React.ElementType>(
props: InputProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
'aria-describedby': ariaDescribedby,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledby,
autoComplete,
autoFocus,
className,
defaultValue,
disabled,
endAdornment,
error,
id,
multiline = false,
name,
onClick,
onChange,
onKeyDown,
onKeyUp,
onFocus,
onBlur,
placeholder,
readOnly,
required,
startAdornment,
value,
type: typeProp,
rows,
slotProps = {},
slots = {},
minRows,
maxRows,
...other
} = props;
const {
getRootProps,
getInputProps,
focused,
formControlContext,
error: errorState,
disabled: disabledState,
} = useInput({
disabled,
defaultValue,
error,
onBlur,
onClick,
onChange,
onFocus,
required,
value,
});
const type = !multiline ? typeProp ?? 'text' : undefined;
const ownerState: InputOwnerState = {
...props,
disabled: disabledState,
error: errorState,
focused,
formControlContext,
multiline,
type,
};
const classes = useUtilityClasses(ownerState);
const propsToForward = {
'aria-describedby': ariaDescribedby,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledby,
autoComplete,
autoFocus,
id,
onKeyDown,
onKeyUp,
name,
placeholder,
readOnly,
type,
};
const Root = slots.root ?? 'div';
const rootProps: WithOptionalOwnerState<InputRootSlotProps> = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: [classes.root, className],
});
const InputComponent = multiline ? slots.textarea ?? 'textarea' : slots.input ?? 'input';
const inputProps: WithOptionalOwnerState<InputInputSlotProps> = useSlotProps({
elementType: InputComponent,
getSlotProps: (otherHandlers: EventHandlers) => {
return getInputProps({
...propsToForward,
...otherHandlers,
});
},
externalSlotProps: slotProps.input,
additionalProps: {
rows: multiline ? rows : undefined,
...(multiline &&
!isHostComponent(InputComponent) && {
minRows: rows || minRows,
maxRows: rows || maxRows,
}),
},
ownerState,
className: classes.input,
});
if (process.env.NODE_ENV !== 'production') {
if (multiline) {
if (rows) {
if (minRows || maxRows) {
console.warn(
'MUI: You can not use the `minRows` or `maxRows` props when the input `rows` prop is set.',
);
}
}
}
}
return (
<Root {...rootProps}>
{startAdornment}
<InputComponent {...inputProps} />
{endAdornment}
</Root>
);
}) as PolymorphicComponent<InputTypeMap>;
Input.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
'aria-describedby': PropTypes.string,
/**
* @ignore
*/
'aria-label': PropTypes.string,
/**
* @ignore
*/
'aria-labelledby': PropTypes.string,
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element is focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Class name applied to the root element.
*/
className: PropTypes.string,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the component is disabled.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
disabled: PropTypes.bool,
/**
* Trailing adornment for this input.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the `input` will indicate an error by setting the `aria-invalid` attribute on the input and the `Mui-error` class on the root element.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* @ignore
*/
inputRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({
current: PropTypes.object,
}),
]),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows: PropTypes.number,
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows: PropTypes.number,
/**
* If `true`, a `textarea` element is rendered.
* @default false
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onClick: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* @ignore
*/
onKeyUp: PropTypes.func,
/**
* The short hint displayed in the `input` before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element is required.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.number,
/**
* The props used for each slot inside the Input.
* @default {}
*/
slotProps: PropTypes.shape({
input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the InputBase.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
input: PropTypes.elementType,
root: PropTypes.elementType,
textarea: PropTypes.elementType,
}),
/**
* Leading adornment for this input.
*/
startAdornment: PropTypes.node,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type: PropTypes /* @typescript-to-proptypes-ignore */.oneOf([
'button',
'checkbox',
'color',
'date',
'datetime-local',
'email',
'file',
'hidden',
'image',
'month',
'number',
'password',
'radio',
'range',
'reset',
'search',
'submit',
'tel',
'text',
'time',
'url',
'week',
]),
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any,
} as any;
export { Input };
| 6,140 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Input/Input.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { FormControlState } from '../FormControl';
import { UseInputParameters, UseInputRootSlotProps } from '../useInput';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface InputRootSlotPropsOverrides {}
export interface InputInputSlotPropsOverrides {}
export interface SingleLineInputProps {
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows?: undefined;
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows?: undefined;
/**
* If `true`, a `textarea` element is rendered.
* @default false
*/
multiline?: false;
/**
* Number of rows to display when multiline option is set to true.
*/
rows?: undefined;
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type?: React.HTMLInputTypeAttribute;
}
export interface MultiLineInputProps {
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows?: number;
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows?: number;
/**
* If `true`, a `textarea` element is rendered.
* @default false
*/
multiline: true;
/**
* Number of rows to display when multiline option is set to true.
*/
rows?: number;
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
* @default 'text'
*/
type?: undefined;
}
export type InputOwnProps = (SingleLineInputProps | MultiLineInputProps) &
Omit<UseInputParameters, 'error'> & {
'aria-describedby'?: string;
'aria-label'?: string;
'aria-labelledby'?: string;
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete?: string;
/**
* If `true`, the `input` element is focused during the first mount.
*/
autoFocus?: boolean;
/**
* Class name applied to the root element.
*/
className?: string;
/**
* Trailing adornment for this input.
*/
endAdornment?: React.ReactNode;
/**
* If `true`, the `input` will indicate an error by setting the `aria-invalid` attribute on the input and the `Mui-error` class on the root element.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error?: boolean;
/**
* The id of the `input` element.
*/
id?: string;
/**
* Name attribute of the `input` element.
*/
name?: string;
onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;
onKeyUp?: React.KeyboardEventHandler<HTMLInputElement>;
/**
* The short hint displayed in the `input` before the user enters a value.
*/
placeholder?: string;
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly?: boolean;
/**
* The props used for each slot inside the Input.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', InputRootSlotPropsOverrides, InputOwnerState>;
input?: SlotComponentProps<'input', InputInputSlotPropsOverrides, InputOwnerState>;
};
/**
* The components used for each slot inside the InputBase.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: InputSlots;
/**
* Leading adornment for this input.
*/
startAdornment?: React.ReactNode;
/**
* The value of the `input` element, required for a controlled component.
*/
value?: unknown;
};
export interface InputSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
/**
* The component that renders the input.
* @default 'input'
*/
input?: React.ElementType;
/**
* The component that renders the textarea.
* @default 'textarea'
*/
textarea?: React.ElementType;
}
export interface InputTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: InputOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type InputProps<
RootComponentType extends React.ElementType = InputTypeMap['defaultComponent'],
> = PolymorphicProps<InputTypeMap<{}, RootComponentType>, RootComponentType>;
export type InputOwnerState = Simplify<
InputOwnProps & {
formControlContext: FormControlState | undefined;
focused: boolean;
type: React.InputHTMLAttributes<HTMLInputElement>['type'] | undefined;
}
>;
export type InputRootSlotProps = Simplify<
UseInputRootSlotProps & {
ownerState: InputOwnerState;
className?: string;
children?: React.ReactNode;
ref?: React.Ref<HTMLDivElement>;
}
>;
export type InputInputSlotProps = Simplify<
Omit<UseInputRootSlotProps, 'onClick'> & {
'aria-describedby': React.AriaAttributes['aria-describedby'];
'aria-label': React.AriaAttributes['aria-label'];
'aria-labelledby': React.AriaAttributes['aria-labelledby'];
autoComplete: string | undefined;
autoFocus: boolean | undefined;
className?: string;
id: string | undefined;
name: string | undefined;
onKeyDown: React.KeyboardEventHandler<HTMLInputElement> | undefined;
onKeyUp: React.KeyboardEventHandler<HTMLInputElement> | undefined;
ownerState: InputOwnerState;
placeholder: string | undefined;
readOnly: boolean | undefined;
ref: React.Ref<HTMLInputElement>;
type: React.HTMLInputTypeAttribute | undefined;
}
>;
| 6,141 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Input/index.ts | 'use client';
export { Input } from './Input';
export * from './Input.types';
export * from './inputClasses';
| 6,142 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Input/inputClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface InputClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the root element if the component is a descendant of `FormControl`. */
formControl: string;
/** Class name applied to the root element if `startAdornment` is provided. */
adornedStart: string;
/** Class name applied to the root element if `endAdornment` is provided. */
adornedEnd: string;
/** State class applied to the root element if the component is focused. */
focused: string;
/** State class applied to the root element if `disabled={true}`. */
disabled: string;
/** State class applied to the root element if `error={true}`. */
error: string;
/** Class name applied to the root element if `multiline={true}`. */
multiline: string;
/** Class name applied to the input element. */
input: string;
/** Class name applied to the input element if `multiline={true}`. */
inputMultiline: string;
/** Class name applied to the input element if `type="search"`. */
inputTypeSearch: string;
}
export type InputClassKey = keyof InputClasses;
export function getInputUtilityClass(slot: string): string {
return generateUtilityClass('MuiInput', slot);
}
export const inputClasses: InputClasses = generateUtilityClasses('MuiInput', [
'root',
'formControl',
'focused',
'disabled',
'error',
'multiline',
'input',
'inputMultiline',
'inputTypeSearch',
'adornedStart',
'adornedEnd',
]);
| 6,143 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Menu/Menu.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Menu } from '@mui/base/Menu';
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Menu invalidProp={0} />
<Menu<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<Menu<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error required props not specified */}
<Menu<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<Menu<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Menu<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,144 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Menu/Menu.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
act,
} from '@mui-internal/test-utils';
import { Menu, menuClasses } from '@mui/base/Menu';
import { MenuItem, MenuItemRootSlotProps } from '@mui/base/MenuItem';
import { DropdownContext, DropdownContextValue } from '@mui/base/useDropdown';
const testContext: DropdownContextValue = {
dispatch: () => {},
popupId: 'menu-popup',
registerPopup: () => {},
registerTrigger: () => {},
state: { open: true },
triggerElement: null,
};
describe('<Menu />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<Menu />, () => ({
inheritComponent: 'div',
render: (node) => {
return render(
<DropdownContext.Provider value={testContext}>{node}</DropdownContext.Provider>,
);
},
mount: (node: React.ReactNode) => {
const wrapper = mount(
<DropdownContext.Provider value={testContext}>{node}</DropdownContext.Provider>,
);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLDivElement,
muiName: 'MuiMenu',
slots: {
root: {
expectedClassName: menuClasses.root,
},
listbox: {
expectedClassName: menuClasses.listbox,
},
},
skip: ['reactTestRenderer', 'componentProp', 'slotsProp'],
}));
describe('after initialization', () => {
function Test() {
return (
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem>1</MenuItem>
<MenuItem>2</MenuItem>
<MenuItem>3</MenuItem>
</Menu>
</DropdownContext.Provider>
);
}
it('highlights the first item when the menu is opened', () => {
const { getAllByRole } = render(<Test />);
const [firstItem, ...otherItems] = getAllByRole('menuitem');
expect(firstItem.tabIndex).to.equal(0);
otherItems.forEach((item) => {
expect(item.tabIndex).to.equal(-1);
});
});
});
describe('keyboard navigation', () => {
it('changes the highlighted item using the arrow keys', () => {
const { getByTestId } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem data-testid="item-1">1</MenuItem>
<MenuItem data-testid="item-2">2</MenuItem>
<MenuItem data-testid="item-3">3</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const item1 = getByTestId('item-1');
const item2 = getByTestId('item-2');
const item3 = getByTestId('item-3');
act(() => {
item1.focus();
});
fireEvent.keyDown(item1, { key: 'ArrowDown' });
expect(document.activeElement).to.equal(item2);
fireEvent.keyDown(item2, { key: 'ArrowDown' });
expect(document.activeElement).to.equal(item3);
fireEvent.keyDown(item3, { key: 'ArrowUp' });
expect(document.activeElement).to.equal(item2);
});
it('changes the highlighted item using the Home and End keys', () => {
const { getByTestId } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem data-testid="item-1">1</MenuItem>
<MenuItem data-testid="item-2">2</MenuItem>
<MenuItem data-testid="item-3">3</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const item1 = getByTestId('item-1');
const item3 = getByTestId('item-3');
act(() => {
item1.focus();
});
fireEvent.keyDown(item1, { key: 'End' });
expect(document.activeElement).to.equal(getByTestId('item-3'));
fireEvent.keyDown(item3, { key: 'Home' });
expect(document.activeElement).to.equal(getByTestId('item-1'));
});
it('includes disabled items during keyboard navigation', () => {
const { getByTestId } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem data-testid="item-1">1</MenuItem>
<MenuItem disabled data-testid="item-2">
2
</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const item1 = getByTestId('item-1');
const item2 = getByTestId('item-2');
act(() => {
item1.focus();
});
fireEvent.keyDown(item1, { key: 'ArrowDown' });
expect(document.activeElement).to.equal(item2);
expect(item2).to.have.attribute('aria-disabled', 'true');
});
describe('text navigation', () => {
it('changes the highlighted item', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// useMenu Text navigation match menu items using HTMLElement.innerText
// innerText is not supported by JsDom
this.skip();
}
const { getByText, getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem>Aa</MenuItem>
<MenuItem>Ba</MenuItem>
<MenuItem>Bb</MenuItem>
<MenuItem>Ca</MenuItem>
<MenuItem>Cb</MenuItem>
<MenuItem>Cd</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const items = getAllByRole('menuitem');
act(() => {
items[0].focus();
});
fireEvent.keyDown(items[0], { key: 'c' });
expect(document.activeElement).to.equal(getByText('Ca'));
expect(getByText('Ca')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[3], { key: 'd' });
expect(document.activeElement).to.equal(getByText('Cd'));
expect(getByText('Cd')).to.have.attribute('tabindex', '0');
});
it('repeated keys circulate all items starting with that letter', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// useMenu Text navigation match menu items using HTMLElement.innerText
// innerText is not supported by JsDom
this.skip();
}
const { getByText, getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem>Aa</MenuItem>
<MenuItem>Ba</MenuItem>
<MenuItem>Bb</MenuItem>
<MenuItem>Ca</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const items = getAllByRole('menuitem');
act(() => {
items[0].focus();
});
fireEvent.keyDown(items[0], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Ba'));
expect(getByText('Ba')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[1], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Bb'));
expect(getByText('Bb')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[2], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Ba'));
expect(getByText('Ba')).to.have.attribute('tabindex', '0');
});
it('changes the highlighted item using text navigation on label prop', () => {
const { getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem label="Aa">1</MenuItem>
<MenuItem label="Ba">2</MenuItem>
<MenuItem label="Bb">3</MenuItem>
<MenuItem label="Ca">4</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const items = getAllByRole('menuitem');
act(() => {
items[0].focus();
});
fireEvent.keyDown(items[0], { key: 'b' });
expect(document.activeElement).to.equal(items[1]);
expect(items[1]).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[1], { key: 'b' });
expect(document.activeElement).to.equal(items[2]);
expect(items[2]).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[2], { key: 'b' });
expect(document.activeElement).to.equal(items[1]);
expect(items[1]).to.have.attribute('tabindex', '0');
});
it('skips the non-stringifiable items', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// useMenu Text navigation match menu items using HTMLElement.innerText
// innerText is not supported by JsDom
this.skip();
}
const { getByText, getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem>Aa</MenuItem>
<MenuItem>Ba</MenuItem>
<MenuItem />
<MenuItem>
<div>Nested Content</div>
</MenuItem>
<MenuItem>{undefined}</MenuItem>
<MenuItem>{null}</MenuItem>
<MenuItem>Bc</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const items = getAllByRole('menuitem');
act(() => {
items[0].focus();
});
fireEvent.keyDown(items[0], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Ba'));
expect(getByText('Ba')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[1], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Bc'));
expect(getByText('Bc')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[6], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Ba'));
expect(getByText('Ba')).to.have.attribute('tabindex', '0');
});
it('navigate to options with diacritic characters', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// useMenu Text navigation match menu items using HTMLElement.innerText
// innerText is not supported by JsDom
this.skip();
}
const { getByText, getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem>Aa</MenuItem>
<MenuItem>Ba</MenuItem>
<MenuItem>Bb</MenuItem>
<MenuItem>Bą</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const items = getAllByRole('menuitem');
act(() => {
items[0].focus();
});
fireEvent.keyDown(items[0], { key: 'b' });
expect(document.activeElement).to.equal(getByText('Ba'));
expect(getByText('Ba')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[1], { key: 'Control' });
fireEvent.keyDown(items[1], { key: 'Alt' });
fireEvent.keyDown(items[1], { key: 'ą' });
expect(document.activeElement).to.equal(getByText('Bą'));
expect(getByText('Bą')).to.have.attribute('tabindex', '0');
});
it('navigate to next options with beginning diacritic characters', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// useMenu Text navigation match menu items using HTMLElement.innerText
// innerText is not supported by JsDom
this.skip();
}
const { getByText, getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem>Aa</MenuItem>
<MenuItem>ąa</MenuItem>
<MenuItem>ąb</MenuItem>
<MenuItem>ąc</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const items = getAllByRole('menuitem');
act(() => {
items[0].focus();
});
fireEvent.keyDown(items[0], { key: 'Control' });
fireEvent.keyDown(items[0], { key: 'Alt' });
fireEvent.keyDown(items[0], { key: 'ą' });
expect(document.activeElement).to.equal(getByText('ąa'));
expect(getByText('ąa')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[1], { key: 'Alt' });
fireEvent.keyDown(items[1], { key: 'Control' });
fireEvent.keyDown(items[1], { key: 'ą' });
expect(document.activeElement).to.equal(getByText('ąb'));
expect(getByText('ąb')).to.have.attribute('tabindex', '0');
fireEvent.keyDown(items[2], { key: 'Control' });
fireEvent.keyDown(items[2], { key: 'AltGraph' });
fireEvent.keyDown(items[2], { key: 'ą' });
expect(document.activeElement).to.equal(getByText('ąc'));
expect(getByText('ąc')).to.have.attribute('tabindex', '0');
});
});
});
describe('prop: onItemsChange', () => {
it('should be called when the menu items change', () => {
const handleItemsChange = spy();
const { setProps } = render(
<DropdownContext.Provider value={testContext}>
<Menu onItemsChange={handleItemsChange}>
<MenuItem key="1">1</MenuItem>
<MenuItem key="2">2</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
// The first call is the initial render.
expect(handleItemsChange.callCount).to.equal(1);
setProps({
children: (
<Menu onItemsChange={handleItemsChange}>
<MenuItem key="1">1</MenuItem>
<MenuItem key="3">3</MenuItem>
</Menu>
),
});
expect(handleItemsChange.callCount).to.equal(2);
});
});
describe('prop: anchor', () => {
it('should be placed near the specified element', async () => {
function TestComponent() {
const [anchor, setAnchor] = React.useState<HTMLElement | null>(null);
return (
<div>
<DropdownContext.Provider value={testContext}>
<Menu
anchor={anchor}
slotProps={{ root: { 'data-testid': 'popup', placement: 'bottom-start' } }}
>
<MenuItem>1</MenuItem>
<MenuItem>2</MenuItem>
</Menu>
</DropdownContext.Provider>
<div data-testid="anchor" style={{ marginTop: '100px' }} ref={setAnchor} />
</div>
);
}
const { getByTestId } = render(<TestComponent />);
const popup = getByTestId('popup');
const anchor = getByTestId('anchor');
const anchorPosition = anchor.getBoundingClientRect();
expect(popup.style.getPropertyValue('transform')).to.equal(
`translate(${anchorPosition.left}px, ${anchorPosition.bottom}px)`,
);
});
it('should be placed at the specified position', async () => {
const boundingRect = {
x: 200,
y: 100,
top: 100,
left: 200,
bottom: 100,
right: 200,
height: 0,
width: 0,
toJSON: () => {},
};
const virtualElement = { getBoundingClientRect: () => boundingRect };
const { getByTestId } = render(
<DropdownContext.Provider value={testContext}>
<Menu
anchor={virtualElement}
slotProps={{ root: { 'data-testid': 'popup', placement: 'bottom-start' } }}
>
<MenuItem>1</MenuItem>
<MenuItem>2</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const popup = getByTestId('popup');
expect(popup.style.getPropertyValue('transform')).to.equal(`translate(200px, 100px)`);
});
});
it('perf: does not rerender menu items unnecessarily', () => {
const renderItem1Spy = spy();
const renderItem2Spy = spy();
const renderItem3Spy = spy();
const renderItem4Spy = spy();
const LoggingRoot = React.forwardRef(function LoggingRoot(
props: MenuItemRootSlotProps & { renderSpy: () => void },
ref: React.ForwardedRef<HTMLLIElement>,
) {
const { renderSpy, ownerState, ...other } = props;
renderSpy();
return <li {...other} ref={ref} />;
});
const { getAllByRole } = render(
<DropdownContext.Provider value={testContext}>
<Menu>
<MenuItem
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderItem1Spy } as any }}
id="item-1"
>
1
</MenuItem>
<MenuItem
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderItem2Spy } as any }}
id="item-2"
>
2
</MenuItem>
<MenuItem
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderItem3Spy } as any }}
id="item-3"
>
3
</MenuItem>
<MenuItem
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderItem4Spy } as any }}
id="item-4"
>
4
</MenuItem>
</Menu>
</DropdownContext.Provider>,
);
const menuItems = getAllByRole('menuitem');
act(() => {
menuItems[0].focus();
});
renderItem1Spy.resetHistory();
renderItem2Spy.resetHistory();
renderItem3Spy.resetHistory();
renderItem4Spy.resetHistory();
expect(renderItem1Spy.callCount).to.equal(0);
fireEvent.keyDown(menuItems[0], { key: 'ArrowDown' }); // highlights '2'
// React renders twice in strict mode, so we expect twice the number of spy calls
// Also, useButton's focusVisible polyfill causes an extra render when focus is gained/lost.
expect(renderItem1Spy.callCount).to.equal(4); // '1' rerenders as it loses highlight
expect(renderItem2Spy.callCount).to.equal(4); // '2' rerenders as it receives highlight
// neither the highlighted nor the selected state of these options changed,
// so they don't need to rerender:
expect(renderItem3Spy.callCount).to.equal(0);
expect(renderItem4Spy.callCount).to.equal(0);
});
});
| 6,145 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Menu/Menu.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { HTMLElementType, refType } from '@mui/utils';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { MenuOwnerState, MenuProps, MenuRootSlotProps, MenuTypeMap } from './Menu.types';
import { getMenuUtilityClass } from './menuClasses';
import { useMenu } from '../useMenu';
import { MenuProvider } from '../useMenu/MenuProvider';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { Popper } from '../Popper';
import { useSlotProps } from '../utils/useSlotProps';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { WithOptionalOwnerState } from '../utils';
import { ListActionTypes } from '../useList';
function useUtilityClasses(ownerState: MenuOwnerState) {
const { open } = ownerState;
const slots = {
root: ['root', open && 'expanded'],
listbox: ['listbox', open && 'expanded'],
};
return composeClasses(slots, useClassNamesOverride(getMenuUtilityClass));
}
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/)
*
* API:
*
* - [Menu API](https://mui.com/base-ui/react-menu/components-api/#menu)
*/
const Menu = React.forwardRef(function Menu<RootComponentType extends React.ElementType>(
props: MenuProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
actions,
anchor: anchorProp,
children,
onItemsChange,
slotProps = {},
slots = {},
...other
} = props;
const { contextValue, getListboxProps, dispatch, open, triggerElement } = useMenu({
onItemsChange,
});
const anchor = anchorProp ?? triggerElement;
React.useImperativeHandle(
actions,
() => ({
dispatch,
resetHighlight: () => dispatch({ type: ListActionTypes.resetHighlight, event: null }),
}),
[dispatch],
);
const ownerState: MenuOwnerState = { ...props, open };
const classes = useUtilityClasses(ownerState);
const Root = slots.root ?? 'div';
const rootProps = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
role: undefined,
},
className: classes.root,
ownerState,
});
const Listbox = slots.listbox ?? 'ul';
const listboxProps: WithOptionalOwnerState<MenuRootSlotProps> = useSlotProps({
elementType: Listbox,
getSlotProps: getListboxProps,
externalSlotProps: slotProps.listbox,
className: classes.listbox,
ownerState,
});
if (open === true && anchor == null) {
return (
<Root {...rootProps}>
<Listbox {...listboxProps}>
<MenuProvider value={contextValue}>{children}</MenuProvider>
</Listbox>
</Root>
);
}
return (
<Popper {...rootProps} open={open} anchorEl={anchor} slots={{ root: Root }}>
<Listbox {...listboxProps}>
<MenuProvider value={contextValue}>{children}</MenuProvider>
</Listbox>
</Popper>
);
}) as PolymorphicComponent<MenuTypeMap>;
Menu.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A ref with imperative actions that can be performed on the menu.
*/
actions: refType,
/**
* The element based on which the menu is positioned.
*/
anchor: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
HTMLElementType,
PropTypes.object,
PropTypes.func,
]),
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Function called when the items displayed in the menu change.
*/
onItemsChange: PropTypes.func,
/**
* The props used for each slot inside the Menu.
* @default {}
*/
slotProps: PropTypes.shape({
listbox: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Menu.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
listbox: PropTypes.elementType,
root: PropTypes.elementType,
}),
} as any;
export { Menu };
| 6,146 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Menu/Menu.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { PolymorphicProps, SlotComponentProps } from '../utils';
import { UseMenuListboxSlotProps } from '../useMenu';
import { ListAction } from '../useList';
import { Popper, PopperProps } from '../Popper';
export interface MenuRootSlotPropsOverrides {}
export interface MenuListboxSlotPropsOverrides {}
export interface MenuActions {
/**
* Dispatches an action that can cause a change to the menu's internal state.
*/
dispatch: (action: ListAction<string>) => void;
/**
* Resets the highlighted item.
*/
resetHighlight: () => void;
}
export interface MenuOwnProps {
/**
* A ref with imperative actions that can be performed on the menu.
*/
actions?: React.Ref<MenuActions>;
/**
* The element based on which the menu is positioned.
*/
anchor?: PopperProps['anchorEl'];
children?: React.ReactNode;
className?: string;
/**
* Function called when the items displayed in the menu change.
*/
onItemsChange?: (items: string[]) => void;
/**
* The props used for each slot inside the Menu.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', MenuRootSlotPropsOverrides, MenuOwnerState> &
Partial<React.ComponentPropsWithoutRef<typeof Popper>>;
listbox?: SlotComponentProps<'ul', MenuListboxSlotPropsOverrides, MenuOwnerState>;
};
/**
* The components used for each slot inside the Menu.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: MenuSlots;
}
export interface MenuSlots {
/**
* The component that renders the popup element.
* @default 'div'
*/
root?: React.ElementType;
/**
* The component that renders the listbox.
* @default 'ul'
*/
listbox?: React.ElementType;
}
export interface MenuTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: MenuOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type MenuProps<
RootComponentType extends React.ElementType = MenuTypeMap['defaultComponent'],
> = PolymorphicProps<MenuTypeMap<{}, RootComponentType>, RootComponentType>;
export type MenuOwnerState = Simplify<
MenuOwnProps & {
open: boolean;
}
>;
export type MenuRootSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: MenuOwnerState;
ref: React.Ref<any>;
};
export type MenuPopupSlotProps = UseMenuListboxSlotProps & {
children?: React.ReactNode;
className?: string;
ownerState: MenuOwnerState;
};
| 6,147 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Menu/index.tsx | export { Menu } from './Menu';
export * from './menuClasses';
export * from './Menu.types';
| 6,148 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Menu/menuClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface MenuClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the listbox element. */
listbox: string;
/** State class applied to the root element if `open={true}`. */
expanded: string;
}
export type MenuClassKey = keyof MenuClasses;
export function getMenuUtilityClass(slot: string): string {
return generateUtilityClass('MuiMenu', slot);
}
export const menuClasses: MenuClasses = generateUtilityClasses('MuiMenu', [
'root',
'listbox',
'expanded',
]);
| 6,149 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuButton/MenuButton.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
act,
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
} from '@mui-internal/test-utils';
import { MenuButton, menuButtonClasses } from '@mui/base/MenuButton';
import { DropdownContext, DropdownContextValue, DropdownActionTypes } from '@mui/base/useDropdown';
const testContext: DropdownContextValue = {
dispatch: () => {},
popupId: 'menu-popup',
registerPopup: () => {},
registerTrigger: () => {},
state: { open: true },
triggerElement: null,
};
describe('<MenuButton />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<MenuButton />, () => ({
inheritComponent: 'button',
render: (node) => {
return render(
<DropdownContext.Provider value={testContext}>{node}</DropdownContext.Provider>,
);
},
mount: (node: React.ReactNode) => {
const wrapper = mount(
<DropdownContext.Provider value={testContext}>{node}</DropdownContext.Provider>,
);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLButtonElement,
muiName: 'MuiMenuButton',
slots: {
root: {
expectedClassName: menuButtonClasses.root,
testWithElement: null,
},
},
skip: ['componentProp', 'reactTestRenderer'],
}));
describe('prop: disabled', () => {
it('should render a disabled button', () => {
const { getByRole } = render(
<DropdownContext.Provider value={testContext}>
<MenuButton disabled />
</DropdownContext.Provider>,
);
const button = getByRole('button');
expect(button).to.have.property('disabled', true);
});
it('should not open the menu when clicked', () => {
const dispatchSpy = spy();
const context = {
...testContext,
state: { open: false },
dispatch: dispatchSpy,
};
const { getByRole } = render(
<DropdownContext.Provider value={context}>
<MenuButton disabled />
</DropdownContext.Provider>,
);
const button = getByRole('button');
button.click();
expect(dispatchSpy.called).to.equal(false);
});
});
describe('prop: focusableWhenDisabled', () => {
it('has the aria-disabled instead of disabled attribute when disabled', () => {
const { getByRole } = render(
<DropdownContext.Provider value={testContext}>
<MenuButton disabled focusableWhenDisabled />
</DropdownContext.Provider>,
);
const button = getByRole('button');
expect(button).to.have.attribute('aria-disabled');
expect(button).not.to.have.attribute('disabled');
});
it('can receive focus when focusableWhenDisabled is set', () => {
const { getByRole } = render(
<DropdownContext.Provider value={testContext}>
<MenuButton disabled focusableWhenDisabled />
</DropdownContext.Provider>,
);
const button = getByRole('button');
act(() => {
button.focus();
});
expect(document.activeElement).to.equal(button);
});
});
it('toggles the menu state when clicked', () => {
const dispatchSpy = spy();
const context = {
...testContext,
state: { open: false },
dispatch: dispatchSpy,
};
const { getByRole } = render(
<DropdownContext.Provider value={context}>
<MenuButton />
</DropdownContext.Provider>,
);
const button = getByRole('button');
button.click();
expect(dispatchSpy.calledOnce).to.equal(true);
expect(dispatchSpy.args[0][0]).to.contain({ type: DropdownActionTypes.toggle });
});
describe('keyboard navigation', () => {
['ArrowUp', 'ArrowDown'].forEach((key) =>
it(`opens the menu when pressing ${key}`, () => {
const dispatchSpy = spy();
const context = {
...testContext,
state: { open: false },
dispatch: dispatchSpy,
};
const { getByRole } = render(
<DropdownContext.Provider value={context}>
<MenuButton />
</DropdownContext.Provider>,
);
const button = getByRole('button');
act(() => {
button.focus();
});
fireEvent.keyDown(button, { key });
expect(dispatchSpy.calledOnce).to.equal(true);
expect(dispatchSpy.args[0][0]).to.contain({ type: DropdownActionTypes.open });
}),
);
});
describe('accessibility attributes', () => {
it('has the aria-haspopup attribute', () => {
const { getByRole } = render(
<DropdownContext.Provider value={testContext}>
<MenuButton />
</DropdownContext.Provider>,
);
const button = getByRole('button');
expect(button).to.have.attribute('aria-haspopup');
});
it('has the aria-expanded=false attribute when closed', () => {
const context = {
...testContext,
state: { open: false },
};
const { getByRole } = render(
<DropdownContext.Provider value={context}>
<MenuButton />
</DropdownContext.Provider>,
);
const button = getByRole('button');
expect(button).to.have.attribute('aria-expanded', 'false');
});
it('has the aria-expanded=true attribute when open', () => {
const context = {
...testContext,
state: { open: true },
};
const { getByRole } = render(
<DropdownContext.Provider value={context}>
<MenuButton />
</DropdownContext.Provider>,
);
const button = getByRole('button');
expect(button).to.have.attribute('aria-expanded', 'true');
});
it('has the aria-controls attribute', () => {
const { getByRole } = render(
<DropdownContext.Provider value={testContext}>
<MenuButton />
</DropdownContext.Provider>,
);
const button = getByRole('button');
expect(button).to.have.attribute('aria-controls', 'menu-popup');
});
});
});
| 6,150 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuButton/MenuButton.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { MenuButtonOwnerState, MenuButtonProps } from './MenuButton.types';
import { useSlotProps } from '../utils';
import { useMenuButton } from '../useMenuButton';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { getMenuButtonUtilityClass } from './menuButtonClasses';
const useUtilityClasses = (ownerState: MenuButtonOwnerState) => {
const { active, disabled, open } = ownerState;
const slots = {
root: ['root', disabled && 'disabled', active && 'active', open && 'expanded'],
};
return composeClasses(slots, useClassNamesOverride(getMenuButtonUtilityClass));
};
/**
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/)
*
* API:
*
* - [MenuButton API](https://mui.com/base-ui/react-menu/components-api/#menu-button)
*/
const MenuButton = React.forwardRef(function MenuButton(
props: MenuButtonProps,
forwardedRef: React.ForwardedRef<HTMLElement>,
) {
const {
children,
disabled = false,
label,
slots = {},
slotProps = {},
focusableWhenDisabled = false,
...other
} = props;
const { getRootProps, open, active } = useMenuButton({
disabled,
focusableWhenDisabled,
rootRef: forwardedRef,
});
const ownerState: MenuButtonOwnerState = {
...props,
open,
active,
disabled,
focusableWhenDisabled,
};
const classes = useUtilityClasses(ownerState);
const Root = slots.root || 'button';
const rootProps = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalForwardedProps: other,
externalSlotProps: slotProps.root,
additionalProps: {
ref: forwardedRef,
type: 'button',
},
ownerState,
className: classes.root,
});
return <Root {...rootProps}>{children}</Root>;
});
MenuButton.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
children: PropTypes.node,
/**
* Class name applied to the root element.
*/
className: PropTypes.string,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, allows a disabled button to receive focus.
* @default false
*/
focusableWhenDisabled: PropTypes.bool,
/**
* Label of the button
*/
label: PropTypes.string,
/**
* The components used for each slot inside the MenuButton.
* Either a string to use a HTML element or a component.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The props used for each slot inside the MenuButton.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
} as any;
export { MenuButton };
| 6,151 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuButton/MenuButton.types.ts | import { SlotComponentProps } from '../utils/types';
export interface MenuButtonRootSlotPropsOverrides {}
export interface MenuButtonProps {
children?: React.ReactNode;
/**
* Class name applied to the root element.
*/
className?: string;
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
/**
* If `true`, allows a disabled button to receive focus.
* @default false
*/
focusableWhenDisabled?: boolean;
/**
* Label of the button
*/
label?: string;
/**
* The props used for each slot inside the MenuButton.
* @default {}
*/
slots?: MenuButtonSlots;
/**
* The components used for each slot inside the MenuButton.
* Either a string to use a HTML element or a component.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'button', MenuButtonRootSlotPropsOverrides, MenuButtonOwnerState>;
};
}
export interface MenuButtonSlots {
/**
* The component that renders the root.
* @default 'button'
*/
root?: React.ElementType;
}
export type MenuButtonOwnerState = MenuButtonProps & {
active: boolean;
focusableWhenDisabled: boolean;
open: boolean;
};
| 6,152 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuButton/index.ts | 'use client';
export { MenuButton } from './MenuButton';
export * from './MenuButton.types';
export * from './menuButtonClasses';
| 6,153 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuButton/menuButtonClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface MenuButtonClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root element if `active={true}`. */
active: string;
/** State class applied to the root element if `disabled={true}`. */
disabled: string;
/** State class applied to the root element if the associated menu is open. */
expanded: string;
}
export type MenuButtonClassKey = keyof MenuButtonClasses;
export function getMenuButtonUtilityClass(slot: string): string {
return generateUtilityClass('MuiMenuButton', slot);
}
export const menuButtonClasses: MenuButtonClasses = generateUtilityClasses('MuiMenuButton', [
'root',
'active',
'disabled',
'expanded',
]);
| 6,154 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuItem/MenuItem.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { MenuItem } from '@mui/base/MenuItem';
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<MenuItem invalidProp={0} />
<MenuItem<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<MenuItem<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error required props not specified */}
<MenuItem<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<MenuItem<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<MenuItem<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,155 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuItem/MenuItem.test.tsx | import * as React from 'react';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { MenuItem, menuItemClasses } from '@mui/base/MenuItem';
import { MenuProvider } from '@mui/base/useMenu';
const dummyGetItemState = () => ({
disabled: false,
highlighted: false,
selected: false,
index: 0,
focusable: true,
});
const testContext = {
dispatch: () => {},
getItemIndex: () => 0,
getItemProps: () => ({}),
getItemState: dummyGetItemState,
open: false,
registerItem: () => ({ id: '', deregister: () => {} }),
totalSubitemCount: 0,
};
describe('<MenuItem />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<MenuItem />, () => ({
inheritComponent: 'li',
render: (node) => {
return render(<MenuProvider value={testContext}>{node}</MenuProvider>);
},
mount: (node: React.ReactNode) => {
const wrapper = mount(<MenuProvider value={testContext}>{node}</MenuProvider>);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLLIElement,
testComponentPropWith: 'span',
muiName: 'MuiMenuItem',
slots: {
root: {
expectedClassName: menuItemClasses.root,
},
},
skip: [
'componentProp',
'reactTestRenderer', // Need to be wrapped in MenuContext
],
}));
});
| 6,156 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuItem/MenuItem.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import {
MenuItemOwnerState,
MenuItemProps,
MenuItemRootSlotProps,
MenuItemTypeMap,
} from './MenuItem.types';
import { getMenuItemUtilityClass } from './menuItemClasses';
import { useMenuItem, useMenuItemContextStabilizer } from '../useMenuItem';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { useSlotProps } from '../utils/useSlotProps';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { WithOptionalOwnerState } from '../utils';
import { ListContext } from '../useList';
function useUtilityClasses(ownerState: MenuItemOwnerState) {
const { disabled, focusVisible } = ownerState;
const slots = {
root: ['root', disabled && 'disabled', focusVisible && 'focusVisible'],
};
return composeClasses(slots, useClassNamesOverride(getMenuItemUtilityClass));
}
const InnerMenuItem = React.memo(
React.forwardRef(function MenuItem<RootComponentType extends React.ElementType>(
props: MenuItemProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
children,
disabled: disabledProp = false,
label,
id,
slotProps = {},
slots = {},
...other
} = props;
const { getRootProps, disabled, focusVisible, highlighted } = useMenuItem({
id,
disabled: disabledProp,
rootRef: forwardedRef,
label,
});
const ownerState: MenuItemOwnerState = { ...props, disabled, focusVisible, highlighted };
const classes = useUtilityClasses(ownerState);
const Root = slots.root ?? 'li';
const rootProps: WithOptionalOwnerState<MenuItemRootSlotProps> = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
className: classes.root,
ownerState,
});
return <Root {...rootProps}>{children}</Root>;
}),
);
/**
* An unstyled menu item to be used within a Menu.
*
* Demos:
*
* - [Menu](https://mui.com/base-ui/react-menu/)
*
* API:
*
* - [MenuItem API](https://mui.com/base-ui/react-menu/components-api/#menu-item)
*/
const MenuItem = React.forwardRef(function MenuItem(
props: MenuItemProps,
ref: React.ForwardedRef<Element>,
) {
const { id: idProp } = props;
// This wrapper component is used as a performance optimization.
// `useMenuItemContextStabilizer` ensures that the context value
// is stable across renders, so that the actual MenuItem re-renders
// only when it needs to.
const { contextValue, id } = useMenuItemContextStabilizer(idProp);
return (
<ListContext.Provider value={contextValue}>
<InnerMenuItem {...props} id={id} ref={ref} />
</ListContext.Provider>
);
}) as PolymorphicComponent<MenuItemTypeMap>;
MenuItem.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the menu item will be disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* A text representation of the menu item's content.
* Used for keyboard text navigation matching.
*/
label: PropTypes.string,
/**
* @ignore
*/
onClick: PropTypes.func,
/**
* The props used for each slot inside the MenuItem.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the MenuItem.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
} as any;
export { MenuItem };
| 6,157 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuItem/MenuItem.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { PolymorphicProps, SlotComponentProps } from '../utils';
import { UseMenuItemRootSlotProps } from '../useMenuItem';
export interface MenuItemRootSlotPropsOverrides {}
export type MenuItemOwnerState = Simplify<
MenuItemOwnProps & {
disabled: boolean;
focusVisible: boolean;
highlighted: boolean;
}
>;
export interface MenuItemOwnProps {
children?: React.ReactNode;
className?: string;
onClick?: React.MouseEventHandler<HTMLElement>;
/**
* If `true`, the menu item will be disabled.
* @default false
*/
disabled?: boolean;
/**
* The components used for each slot inside the MenuItem.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: MenuItemSlots;
/**
* The props used for each slot inside the MenuItem.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'li', MenuItemRootSlotPropsOverrides, MenuItemOwnerState>;
};
/**
* A text representation of the menu item's content.
* Used for keyboard text navigation matching.
*/
label?: string;
}
export interface MenuItemSlots {
/**
* The component that renders the root.
* @default 'li'
*/
root?: React.ElementType;
}
export interface MenuItemTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'li',
> {
props: MenuItemOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type MenuItemProps<
RootComponentType extends React.ElementType = MenuItemTypeMap['defaultComponent'],
> = PolymorphicProps<MenuItemTypeMap<{}, RootComponentType>, RootComponentType>;
export interface MenuItemState {
disabled: boolean;
highlighted: boolean;
}
export type MenuItemRootSlotProps = Simplify<
UseMenuItemRootSlotProps & {
children?: React.ReactNode;
className: string;
ref: React.Ref<HTMLElement>;
ownerState: MenuItemOwnerState;
}
>;
| 6,158 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuItem/index.ts | 'use client';
export * from './MenuItem';
export * from './MenuItem.types';
export * from './menuItemClasses';
| 6,159 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MenuItem/menuItemClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface MenuItemClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root `button` element if `disabled={true}`. */
disabled: string;
/** State class applied to the root `button` element if `focusVisible={true}`. */
focusVisible: string;
}
export type MenuItemClassKey = keyof MenuItemClasses;
export function getMenuItemUtilityClass(slot: string): string {
return generateUtilityClass('MuiMenuItem', slot);
}
export const menuItemClasses: MenuItemClasses = generateUtilityClasses('MuiMenuItem', [
'root',
'disabled',
'focusVisible',
]);
| 6,160 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Modal/Modal.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Modal, ModalBackdropSlotProps, ModalRootSlotProps } from '@mui/base/Modal';
function Root(props: ModalRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-keepmounted={ownerState.keepMounted} {...other} />;
}
function Backdrop(props: ModalBackdropSlotProps) {
const { ownerState, ...other } = props;
return <div data-keepmounted={ownerState.keepMounted} {...other} />;
}
const styledModal = (
<Modal open slots={{ root: Root, backdrop: Backdrop }}>
<div />
</Modal>
);
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Modal invalidProp={0} />
<Modal<'a'>
slots={{
root: 'a',
}}
href="#"
open
>
<div />
</Modal>
<Modal<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
open
>
<div />
</Modal>
{/* @ts-expect-error */}
<Modal<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
open
>
<div />
</Modal>
<Modal<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
open
>
<div />
</Modal>
<Modal<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
open
>
<div />
</Modal>
</div>
);
};
| 6,161 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Modal/Modal.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { Modal, modalClasses as classes, ModalRootSlotProps } from '@mui/base/Modal';
describe('<Modal />', () => {
const mount = createMount();
const { render } = createRenderer();
let savedBodyStyle: CSSStyleDeclaration;
before(() => {
savedBodyStyle = document.body.style;
});
beforeEach(() => {
document.body.setAttribute('style', savedBodyStyle.cssText);
});
describeConformanceUnstyled(
<Modal open>
<div />
</Modal>,
() => ({
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
slots: {
root: {
expectedClassName: classes.root,
},
},
skip: [
'componentProp',
'reactTestRenderer', // portal https://github.com/facebook/react/issues/11565
],
}),
);
it('default exited state is opposite of open prop', () => {
let exited = null;
const Root = React.forwardRef<HTMLSpanElement, ModalRootSlotProps>(
({ ownerState: ownerStateProp, ...other }, ref) => {
exited = ownerStateProp.exited;
return <span ref={ref} {...other} />;
},
);
render(
<Modal open slots={{ root: Root }}>
<div />
</Modal>,
);
expect(exited).to.equal(false);
});
it('does not forward style props as DOM attributes if component slot is primitive', () => {
const elementRef = React.createRef<HTMLDivElement>();
render(
<Modal
open
slots={{
root: 'span',
}}
ref={elementRef}
>
<div />
</Modal>,
);
const { current: element } = elementRef;
expect(element!.getAttribute('ownerState')).to.equal(null);
expect(element!.getAttribute('theme')).to.equal(null);
});
it('should set the ariaHidden attr when open and not specified', () => {
const elementRef = React.createRef<HTMLDivElement>();
// by default, aria-hidden == (open ? null : true)
// so test that
render(
<Modal open ref={elementRef} keepMounted data-testid="modal">
<div />
</Modal>,
);
const { current: element } = elementRef;
expect(element!.getAttribute('aria-hidden'), 'null when modal open').to.equal(null);
});
it('should set the ariaHidden attr when closed and not specified', () => {
const elementRef = React.createRef<HTMLDivElement>();
// by default, aria-hidden == (open ? null : true)
// so test that
render(
<Modal open={false} ref={elementRef} keepMounted data-testid="modal">
<div />
</Modal>,
);
const { current: element } = elementRef;
expect(element!.getAttribute('aria-hidden'), 'true when modal open').to.equal('true');
});
it('should pass the ariaHidden prop when open', () => {
const elementRef = React.createRef<HTMLDivElement>();
// by default, aria-hidden == (open ? null : true)
// so test the inverses of that
render(
<Modal open aria-hidden ref={elementRef} keepMounted data-testid="modal">
<div />
</Modal>,
);
const { current: element } = elementRef;
expect(element!.getAttribute('aria-hidden'), 'true when modal open').to.equal('true');
});
it('should pass the ariaHidden prop when closed', () => {
const elementRef = React.createRef<HTMLDivElement>();
// by default, aria-hidden == (open ? null : true)
// so test the inverses of that
render(
<Modal open={false} aria-hidden={false} ref={elementRef} keepMounted data-testid="modal">
<div />
</Modal>,
);
const { current: element } = elementRef;
expect(element!.getAttribute('aria-hidden'), 'null when modal closed').to.equal(null);
});
});
| 6,162 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Modal/Modal.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { elementAcceptingRef, HTMLElementType } from '@mui/utils';
import { EventHandlers, useSlotProps } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { ModalOwnerState, ModalProps, ModalTypeMap } from './Modal.types';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { Portal } from '../Portal';
import { unstable_useModal as useModal } from '../unstable_useModal';
import { FocusTrap } from '../FocusTrap';
import { getModalUtilityClass } from './modalClasses';
const useUtilityClasses = (ownerState: ModalOwnerState) => {
const { open, exited } = ownerState;
const slots = {
root: ['root', !open && exited && 'hidden'],
backdrop: ['backdrop'],
};
return composeClasses(slots, useClassNamesOverride(getModalUtilityClass));
};
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* * [Dialog](https://mui.com/material-ui/api/dialog/)
* * [Drawer](https://mui.com/material-ui/api/drawer/)
* * [Menu](https://mui.com/material-ui/api/menu/)
* * [Popover](https://mui.com/material-ui/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](https://mui.com/material-ui/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*
* Demos:
*
* - [Modal](https://mui.com/base-ui/react-modal/)
*
* API:
*
* - [Modal API](https://mui.com/base-ui/react-modal/components-api/#modal)
*/
const Modal = React.forwardRef(function Modal<RootComponentType extends React.ElementType>(
props: ModalProps<RootComponentType>,
forwardedRef: React.ForwardedRef<HTMLElement>,
) {
const {
children,
closeAfterTransition = false,
container,
disableAutoFocus = false,
disableEnforceFocus = false,
disableEscapeKeyDown = false,
disablePortal = false,
disableRestoreFocus = false,
disableScrollLock = false,
hideBackdrop = false,
keepMounted = false,
onBackdropClick,
onClose,
onKeyDown,
open,
onTransitionEnter,
onTransitionExited,
slotProps = {},
slots = {},
...other
} = props;
const propsWithDefaults: Omit<ModalOwnerState, 'exited' | 'hasTransition'> = {
...props,
closeAfterTransition,
disableAutoFocus,
disableEnforceFocus,
disableEscapeKeyDown,
disablePortal,
disableRestoreFocus,
disableScrollLock,
hideBackdrop,
keepMounted,
};
const {
getRootProps,
getBackdropProps,
getTransitionProps,
portalRef,
isTopModal,
exited,
hasTransition,
} = useModal({
...propsWithDefaults,
rootRef: forwardedRef,
});
const ownerState = {
...propsWithDefaults,
exited,
hasTransition,
};
const classes = useUtilityClasses(ownerState);
const childProps: {
onEnter?: () => void;
onExited?: () => void;
tabIndex?: string;
} = {};
if (children.props.tabIndex === undefined) {
childProps.tabIndex = '-1';
}
// It's a Transition like component
if (hasTransition) {
const { onEnter, onExited } = getTransitionProps();
childProps.onEnter = onEnter;
childProps.onExited = onExited;
}
const Root = slots.root ?? 'div';
const rootProps = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
getSlotProps: getRootProps,
className: classes.root,
ownerState,
});
const BackdropComponent = slots.backdrop;
const backdropProps = useSlotProps({
elementType: BackdropComponent,
externalSlotProps: slotProps.backdrop,
getSlotProps: (otherHandlers: EventHandlers) => {
return getBackdropProps({
...otherHandlers,
onClick: (e: React.MouseEvent) => {
if (onBackdropClick) {
onBackdropClick(e);
}
if (otherHandlers?.onClick) {
otherHandlers.onClick(e);
}
},
});
},
className: classes.backdrop,
ownerState,
});
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
return (
<Portal ref={portalRef} container={container} disablePortal={disablePortal}>
{/*
* Marking an element with the role presentation indicates to assistive technology
* that this element should be ignored; it exists to support the web application and
* is not meant for humans to interact with directly.
* https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-static-element-interactions.md
*/}
<Root {...rootProps}>
{!hideBackdrop && BackdropComponent ? <BackdropComponent {...backdropProps} /> : null}
<FocusTrap
disableEnforceFocus={disableEnforceFocus}
disableAutoFocus={disableAutoFocus}
disableRestoreFocus={disableRestoreFocus}
isEnabled={isTopModal}
open={open}
>
{React.cloneElement(children, childProps)}
</FocusTrap>
</Root>
</Portal>
);
}) as PolymorphicComponent<ModalTypeMap>;
Modal.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A single child content element.
*/
children: elementAcceptingRef.isRequired,
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
* @default false
*/
closeAfterTransition: PropTypes.bool,
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
HTMLElementType,
PropTypes.func,
]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, hitting escape will not fire the `onClose` callback.
* @default false
*/
disableEscapeKeyDown: PropTypes.bool,
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal: PropTypes.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden or unmounted.
* @default false
*/
disableRestoreFocus: PropTypes.bool,
/**
* Disable the scroll lock behavior.
* @default false
*/
disableScrollLock: PropTypes.bool,
/**
* If `true`, the backdrop is not rendered.
* @default false
*/
hideBackdrop: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
* @default false
*/
keepMounted: PropTypes.bool,
/**
* Callback fired when the backdrop is clicked.
* @deprecated Use the `onClose` prop with the `reason` argument to handle the `backdropClick` events.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: PropTypes.func,
/**
* A function called when a transition enters.
*/
onTransitionEnter: PropTypes.func,
/**
* A function called when a transition has exited.
*/
onTransitionExited: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool.isRequired,
/**
* The props used for each slot inside the Modal.
* @default {}
*/
slotProps: PropTypes.shape({
backdrop: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Modal.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
backdrop: PropTypes.elementType,
root: PropTypes.elementType,
}),
} as any;
export { Modal };
| 6,163 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Modal/Modal.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { PortalProps } from '../Portal';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface ModalRootSlotPropsOverrides {}
export interface ModalBackdropSlotPropsOverrides {}
export interface ModalOwnProps {
/**
* A single child content element.
*/
children: React.ReactElement;
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
* @default false
*/
closeAfterTransition?: boolean;
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container?: PortalProps['container'];
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableAutoFocus?: boolean;
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableEnforceFocus?: boolean;
/**
* If `true`, hitting escape will not fire the `onClose` callback.
* @default false
*/
disableEscapeKeyDown?: boolean;
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal?: PortalProps['disablePortal'];
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden or unmounted.
* @default false
*/
disableRestoreFocus?: boolean;
/**
* Disable the scroll lock behavior.
* @default false
*/
disableScrollLock?: boolean;
/**
* If `true`, the backdrop is not rendered.
* @default false
*/
hideBackdrop?: boolean;
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
* @default false
*/
keepMounted?: boolean;
/**
* Callback fired when the backdrop is clicked.
* @deprecated Use the `onClose` prop with the `reason` argument to handle the `backdropClick` events.
*/
onBackdropClick?: React.ReactEventHandler<{}>;
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose?: {
bivarianceHack(event: {}, reason: 'backdropClick' | 'escapeKeyDown'): void;
}['bivarianceHack'];
/**
* A function called when a transition enters.
*/
onTransitionEnter?: () => void;
/**
* A function called when a transition has exited.
*/
onTransitionExited?: () => void;
/**
* If `true`, the component is shown.
*/
open: boolean;
/**
* The props used for each slot inside the Modal.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', ModalRootSlotPropsOverrides, ModalOwnerState>;
backdrop?: SlotComponentProps<'div', ModalBackdropSlotPropsOverrides, ModalOwnerState>;
};
/**
* The components used for each slot inside the Modal.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: ModalSlots;
}
export interface ModalSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
/**
* The component that renders the backdrop.
*/
backdrop?: React.ElementType;
}
export interface ModalTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: ModalOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type ModalProps<
RootComponentType extends React.ElementType = ModalTypeMap['defaultComponent'],
> = PolymorphicProps<ModalTypeMap<{}, RootComponentType>, RootComponentType>;
export type ModalOwnerState = Simplify<
ModalOwnProps & {
closeAfterTransition: boolean;
disableAutoFocus: boolean;
disableEnforceFocus: boolean;
disableEscapeKeyDown: boolean;
disablePortal: boolean;
disableRestoreFocus: boolean;
disableScrollLock: boolean;
exited: boolean;
hideBackdrop: boolean;
keepMounted: boolean;
}
>;
export interface ModalRootSlotProps {
children: React.ReactNode;
className?: string;
onKeyDown: React.KeyboardEventHandler;
ownerState: ModalOwnerState;
role: React.AriaRole;
}
export interface ModalBackdropSlotProps {
'aria-hidden': React.AriaAttributes['aria-hidden'];
children?: React.ReactNode;
onClick: React.MouseEventHandler;
open: boolean;
ownerState: ModalOwnerState;
}
| 6,164 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Modal/index.ts | export { Modal } from './Modal';
export * from './Modal.types';
export * from './modalClasses';
| 6,165 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Modal/modalClasses.ts | import { generateUtilityClasses } from '../generateUtilityClasses';
import { generateUtilityClass } from '../generateUtilityClass';
export interface ModalClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the root element if the `Modal` has exited. */
hidden: string;
/** Class name applied to the backdrop element. */
backdrop: string;
}
export type ModalClassKey = keyof ModalClasses;
export function getModalUtilityClass(slot: string): string {
return generateUtilityClass('MuiModal', slot);
}
export const modalClasses: ModalClasses = generateUtilityClasses('MuiModal', [
'root',
'hidden',
'backdrop',
]);
| 6,166 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MultiSelect/MultiSelect.tsx | 'use client';
let warnedOnce = false;
const warn = () => {
if (!warnedOnce) {
console.error(
[
'Base UI: The MultiSelect component was removed from the library.',
'',
'The multi-select functionality is now available in the Select component.',
'Replace <MultiSelect> with <Select multiple /> in your code to remove this error.',
].join('\n'),
);
warnedOnce = true;
}
};
/**
* The foundation for building custom-styled multi-selection select components.
*
* @deprecated The multi-select functionality is now available in the Select component. Replace <MultiSelect> with <Select multiple /> in your code.
* @ignore - do not document.
*/
export function MultiSelect() {
warn();
return null;
}
| 6,167 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/MultiSelect/index.ts | 'use client';
export { MultiSelect } from './MultiSelect';
| 6,168 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/NoSsr/NoSsr.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { createRenderer } from '@mui-internal/test-utils';
import { NoSsr } from '@mui/base/NoSsr';
describe('<NoSsr />', () => {
const { render, renderToString } = createRenderer();
describe('server-side rendering', () => {
it('should not render the children as the width is unknown', () => {
const { container } = renderToString(
<NoSsr>
<span>Hello</span>
</NoSsr>,
);
expect(container.firstChild).to.equal(null);
});
});
describe('mounted', () => {
it('should render the children', () => {
render(
<NoSsr>
<span id="client-only" />
</NoSsr>,
);
expect(document.querySelector('#client-only')).not.to.equal(null);
});
});
describe('prop: fallback', () => {
it('should render the fallback', () => {
const { container } = renderToString(
<div>
<NoSsr fallback="fallback">
<span>Hello</span>
</NoSsr>
</div>,
);
expect(container.firstChild).to.have.text('fallback');
});
});
describe('prop: defer', () => {
it('should defer the rendering', () => {
render(
<NoSsr defer>
<span id="client-only">Hello</span>
</NoSsr>,
);
expect(document.querySelector('#client-only')).not.to.equal(null);
});
});
});
| 6,169 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/NoSsr/NoSsr.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { exactProp, unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
import { NoSsrProps } from './NoSsr.types';
/**
* NoSsr purposely removes components from the subject of Server Side Rendering (SSR).
*
* This component can be useful in a variety of situations:
*
* * Escape hatch for broken dependencies not supporting SSR.
* * Improve the time-to-first paint on the client by only rendering above the fold.
* * Reduce the rendering time on the server.
* * Under too heavy server load, you can turn on service degradation.
*
* Demos:
*
* - [No SSR](https://mui.com/base-ui/react-no-ssr/)
*
* API:
*
* - [NoSsr API](https://mui.com/base-ui/react-no-ssr/components-api/#no-ssr)
*/
function NoSsr(props: NoSsrProps): JSX.Element {
const { children, defer = false, fallback = null } = props;
const [mountedState, setMountedState] = React.useState(false);
useEnhancedEffect(() => {
if (!defer) {
setMountedState(true);
}
}, [defer]);
React.useEffect(() => {
if (defer) {
setMountedState(true);
}
}, [defer]);
// We need the Fragment here to force react-docgen to recognise NoSsr as a component.
return <React.Fragment>{mountedState ? children : fallback}</React.Fragment>;
}
NoSsr.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* You can wrap a node.
*/
children: PropTypes.node,
/**
* If `true`, the component will not only prevent server-side rendering.
* It will also defer the rendering of the children into a different screen frame.
* @default false
*/
defer: PropTypes.bool,
/**
* The fallback content to display.
* @default null
*/
fallback: PropTypes.node,
} as any;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
(NoSsr as any)['propTypes' + ''] = exactProp(NoSsr.propTypes);
}
export { NoSsr };
| 6,170 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/NoSsr/NoSsr.types.ts | import * as React from 'react';
export interface NoSsrProps {
/**
* You can wrap a node.
*/
children?: React.ReactNode;
/**
* If `true`, the component will not only prevent server-side rendering.
* It will also defer the rendering of the children into a different screen frame.
* @default false
*/
defer?: boolean;
/**
* The fallback content to display.
* @default null
*/
fallback?: React.ReactNode;
}
| 6,171 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/NoSsr/index.ts | 'use client';
export { NoSsr } from './NoSsr';
export * from './NoSsr.types';
| 6,172 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Option/Option.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Option, OptionRootSlotProps } from '@mui/base/Option';
const Root = React.forwardRef(function Root<OptionValue>(
props: OptionRootSlotProps<OptionValue>,
ref: React.ForwardedRef<HTMLLIElement>,
) {
const { ownerState, ...other } = props;
return <li data-selected={ownerState.selected} {...other} ref={ref} />;
});
const option = <Option value={null} slots={{ root: Root }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Option invalidProp={0} />
<Option<number, 'a'>
value={1}
slots={{
root: 'a',
}}
href="#"
/>
<Option<number, typeof CustomComponent>
value={1}
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Option<number, typeof CustomComponent>
value={1}
slots={{
root: CustomComponent,
}}
/>
<Option<number, 'button'>
value={1}
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Option<number, 'button'>
value={1}
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,173 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Option/Option.test.tsx | import * as React from 'react';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { Option, optionClasses } from '@mui/base/Option';
import { SelectProvider } from '../useSelect/SelectProvider';
const dummyGetItemState = () => ({
highlighted: false,
selected: false,
index: 0,
focusable: false,
});
describe('<Option />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<Option value={42} />, () => ({
inheritComponent: 'li',
render: (node) => {
return render(
<SelectProvider
value={{
dispatch: () => {},
getItemIndex: () => 0,
getItemState: dummyGetItemState,
registerItem: () => ({ id: 0, deregister: () => {} }),
totalSubitemCount: 0,
}}
>
{node}
</SelectProvider>,
);
},
mount: (node: React.ReactNode) => {
const wrapper = mount(
<SelectProvider
value={{
dispatch: () => {},
getItemIndex: () => 0,
getItemState: dummyGetItemState,
registerItem: () => ({ id: 0, deregister: () => {} }),
totalSubitemCount: 0,
}}
>
{node}
</SelectProvider>,
);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLLIElement,
testComponentPropWith: 'span',
muiName: 'MuiOption',
slots: {
root: {
expectedClassName: optionClasses.root,
},
},
skip: [
'componentProp',
'reactTestRenderer', // Need to be wrapped in SelectContext
],
}));
});
| 6,174 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Option/Option.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { OptionProps, OptionOwnerState, OptionType, OptionRootSlotProps } from './Option.types';
import { getOptionUtilityClass } from './optionClasses';
import { WithOptionalOwnerState, useSlotProps } from '../utils';
import { useOption, useOptionContextStabilizer } from '../useOption';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { ListContext } from '../useList';
function useUtilityClasses<OptionValue>(ownerState: OptionOwnerState<OptionValue>) {
const { disabled, highlighted, selected } = ownerState;
const slots = {
root: ['root', disabled && 'disabled', highlighted && 'highlighted', selected && 'selected'],
};
return composeClasses(slots, useClassNamesOverride(getOptionUtilityClass));
}
const InnerOption = React.memo(
React.forwardRef(function Option<OptionValue, RootComponentType extends React.ElementType>(
props: OptionProps<OptionValue, RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
children,
disabled = false,
label,
slotProps = {},
slots = {},
value,
...other
} = props;
const Root = slots.root ?? 'li';
const optionRef = React.useRef<HTMLElement>(null);
const combinedRef = useForkRef(optionRef, forwardedRef);
// If `label` is not explicitly provided, the `children` are used for convenience.
// This is used to populate the select's trigger with the selected option's label.
const computedLabel =
label ?? (typeof children === 'string' ? children : optionRef.current?.innerText);
const { getRootProps, selected, highlighted, index } = useOption({
disabled,
label: computedLabel,
rootRef: combinedRef,
value,
});
const ownerState: OptionOwnerState<OptionValue> = {
...props,
disabled,
highlighted,
index,
selected,
};
const classes = useUtilityClasses(ownerState);
const rootProps: WithOptionalOwnerState<OptionRootSlotProps<OptionValue>> = useSlotProps({
getSlotProps: getRootProps,
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
className: classes.root,
ownerState,
});
return <Root {...rootProps}>{children}</Root>;
}),
);
/**
* An unstyled option to be used within a Select.
*
* Demos:
*
* - [Select](https://mui.com/base-ui/react-select/)
*
* API:
*
* - [Option API](https://mui.com/base-ui/react-select/components-api/#option)
*/
const Option = React.forwardRef(function Option<OptionValue>(
props: OptionProps<OptionValue>,
ref: React.ForwardedRef<Element>,
) {
const { value } = props;
// This wrapper component is used as a performance optimization.
// `useOptionContextStabilizer` ensures that the context value
// is stable across renders, so that the actual Option re-renders
// only when it needs to.
const { contextValue } = useOptionContextStabilizer(value);
return (
<ListContext.Provider value={contextValue}>
<InnerOption {...props} ref={ref} />
</ListContext.Provider>
);
}) as OptionType;
Option.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the option will be disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* A text representation of the option's content.
* Used for keyboard text navigation matching.
*/
label: PropTypes.string,
/**
* The props used for each slot inside the Option.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Option.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* The value of the option.
*/
value: PropTypes.any.isRequired,
} as any;
export { Option };
| 6,175 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Option/Option.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { UseOptionRootSlotProps } from '../useOption';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface OptionRootSlotPropsOverrides {}
export interface OptionOwnProps<OptionValue> {
/**
* The value of the option.
*/
value: OptionValue;
children?: React.ReactNode;
/**
* If `true`, the option will be disabled.
* @default false
*/
disabled?: boolean;
className?: string;
/**
* The props used for each slot inside the Option.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'li', OptionRootSlotPropsOverrides, OptionOwnerState<OptionValue>>;
};
/**
* The components used for each slot inside the Option.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: OptionSlots;
/**
* A text representation of the option's content.
* Used for keyboard text navigation matching.
*/
label?: string;
}
export interface OptionSlots {
/**
* The component that renders the root.
* @default 'li'
*/
root?: React.ElementType;
}
export interface OptionTypeMap<
OptionValue,
AdditionalProps = {},
RootComponentType extends React.ElementType = 'li',
> {
props: OptionOwnProps<OptionValue> & AdditionalProps;
defaultComponent: RootComponentType;
}
export type OptionProps<
OptionValue,
RootComponentType extends React.ElementType = OptionTypeMap<OptionValue>['defaultComponent'],
> = PolymorphicProps<OptionTypeMap<OptionValue, {}, RootComponentType>, RootComponentType>;
export interface OptionType {
<
OptionValue,
RootComponentType extends React.ElementType = OptionTypeMap<OptionValue>['defaultComponent'],
>(
props: PolymorphicProps<OptionTypeMap<OptionValue>, RootComponentType>,
): JSX.Element | null;
propTypes?: any;
displayName?: string | undefined;
}
export type OptionOwnerState<OptionValue> = Simplify<
OptionOwnProps<OptionValue> & {
selected: boolean;
highlighted: boolean;
index: number;
}
>;
export type OptionRootSlotProps<OptionValue> = Simplify<
UseOptionRootSlotProps & {
children?: React.ReactNode;
className: string;
ref: React.Ref<HTMLElement>;
ownerState: OptionOwnerState<OptionValue>;
}
>;
| 6,176 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Option/index.ts | 'use client';
export * from './Option';
export * from './Option.types';
export * from './optionClasses';
| 6,177 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Option/optionClasses.tsx | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface OptionClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root `li` element if `disabled={true}`. */
disabled: string;
/** State class applied to the root `li` element if `selected={true}`. */
selected: string;
/** State class applied to the root `li` element if `highlighted={true}`. */
highlighted: string;
}
export type OptionClassKey = keyof OptionClasses;
export function getOptionUtilityClass(slot: string): string {
return generateUtilityClass('MuiOption', slot);
}
export const optionClasses: OptionClasses = generateUtilityClasses('MuiOption', [
'root',
'disabled',
'selected',
'highlighted',
]);
| 6,178 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/OptionGroup/OptionGroup.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import {
OptionGroup,
OptionGroupLabelSlotProps,
OptionGroupListSlotProps,
OptionGroupRootSlotProps,
} from '@mui/base/OptionGroup';
const Root = React.forwardRef(function Root(
props: OptionGroupRootSlotProps,
ref: React.ForwardedRef<HTMLLIElement>,
) {
return <li {...props} ref={ref} />;
});
const Label = React.forwardRef(function Label(
props: OptionGroupLabelSlotProps,
ref: React.ForwardedRef<HTMLLIElement>,
) {
return <li {...props} ref={ref} />;
});
const List = React.forwardRef(function List(
props: OptionGroupListSlotProps,
ref: React.ForwardedRef<HTMLLIElement>,
) {
return <li {...props} ref={ref} />;
});
const option = <OptionGroup slots={{ root: Root, label: Label, list: List }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<OptionGroup invalidProp={0} />
<OptionGroup<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<OptionGroup<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<OptionGroup<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<OptionGroup<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<OptionGroup<'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,179 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/OptionGroup/OptionGroup.test.tsx | import * as React from 'react';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { OptionGroup, optionGroupClasses } from '@mui/base/OptionGroup';
describe('<OptionGroup />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<OptionGroup />, () => ({
inheritComponent: 'li',
render,
mount,
refInstanceof: window.HTMLLIElement,
testComponentPropWith: 'span',
muiName: 'MuiOptionGroup',
slots: {
root: {
expectedClassName: optionGroupClasses.root,
},
label: {
expectedClassName: optionGroupClasses.label,
},
list: {
expectedClassName: optionGroupClasses.list,
},
},
skip: [
'componentProp',
'ownerStatePropagation', // the component does not have its own state
],
}));
});
| 6,180 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/OptionGroup/OptionGroup.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getOptionGroupUtilityClass } from './optionGroupClasses';
import {
OptionGroupLabelSlotProps,
OptionGroupListSlotProps,
OptionGroupProps,
OptionGroupRootSlotProps,
OptionGroupTypeMap,
} from './OptionGroup.types';
import { useSlotProps, WithOptionalOwnerState } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
function useUtilityClasses(disabled: boolean) {
const slots = {
root: ['root', disabled && 'disabled'],
label: ['label'],
list: ['list'],
};
return composeClasses(slots, useClassNamesOverride(getOptionGroupUtilityClass));
}
/**
* An unstyled option group to be used within a Select.
*
* Demos:
*
* - [Select](https://mui.com/base-ui/react-select/)
*
* API:
*
* - [OptionGroup API](https://mui.com/base-ui/react-select/components-api/#option-group)
*/
const OptionGroup = React.forwardRef(function OptionGroup<
RootComponentType extends React.ElementType,
>(props: OptionGroupProps<RootComponentType>, forwardedRef: React.ForwardedRef<Element>) {
const { disabled = false, slotProps = {}, slots = {}, ...other } = props;
const Root = slots?.root || 'li';
const Label = slots?.label || 'span';
const List = slots?.list || 'ul';
const classes = useUtilityClasses(disabled);
const rootProps: WithOptionalOwnerState<OptionGroupRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
},
ownerState: props,
className: classes.root,
});
const labelProps: WithOptionalOwnerState<OptionGroupLabelSlotProps> = useSlotProps({
elementType: Label,
externalSlotProps: slotProps.label,
ownerState: props,
className: classes.label,
});
const listProps: WithOptionalOwnerState<OptionGroupListSlotProps> = useSlotProps({
elementType: List,
externalSlotProps: slotProps.list,
ownerState: props,
className: classes.list,
});
return (
<Root {...rootProps}>
<Label {...labelProps}>{props.label}</Label>
<List {...listProps}>{props.children}</List>
</Root>
);
}) as PolymorphicComponent<OptionGroupTypeMap>;
OptionGroup.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true` all the options in the group will be disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* The human-readable description of the group.
*/
label: PropTypes.node,
/**
* The props used for each slot inside the Input.
* @default {}
*/
slotProps: PropTypes.shape({
label: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
list: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the OptionGroup.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
label: PropTypes.elementType,
list: PropTypes.elementType,
root: PropTypes.elementType,
}),
} as any;
export { OptionGroup };
| 6,181 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/OptionGroup/OptionGroup.types.ts | import * as React from 'react';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface OptionGroupRootSlotPropsOverrides {}
export interface OptionGroupLabelSlotPropsOverrides {}
export interface OptionGroupListSlotPropsOverrides {}
export interface OptionGroupOwnProps {
/**
* The human-readable description of the group.
*/
label?: React.ReactNode;
className?: string;
children?: React.ReactNode;
/**
* If `true` all the options in the group will be disabled.
* @default false
*/
disabled?: boolean;
/**
* The components used for each slot inside the OptionGroup.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: OptionGroupSlots;
/**
* The props used for each slot inside the Input.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'li', OptionGroupRootSlotPropsOverrides, OptionGroupOwnerState>;
label?: SlotComponentProps<'span', OptionGroupLabelSlotPropsOverrides, OptionGroupOwnerState>;
list?: SlotComponentProps<'ul', OptionGroupListSlotPropsOverrides, OptionGroupOwnerState>;
};
}
export interface OptionGroupSlots {
/**
* The component that renders the root.
* @default 'li'
*/
root?: React.ElementType;
/**
* The component that renders the label.
* @default 'span'
*/
label?: React.ElementType;
/**
* The component that renders the list.
* @default 'ul'
*/
list?: React.ElementType;
}
export interface OptionGroupTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'li',
> {
props: OptionGroupOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type OptionGroupProps<
RootComponentType extends React.ElementType = OptionGroupTypeMap['defaultComponent'],
> = PolymorphicProps<OptionGroupTypeMap<{}, RootComponentType>, RootComponentType>;
export type OptionGroupOwnerState = OptionGroupOwnProps;
export type OptionGroupRootSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: OptionGroupOwnerState;
ref: React.Ref<HTMLLIElement>;
};
export type OptionGroupLabelSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: OptionGroupOwnerState;
};
export type OptionGroupListSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: OptionGroupOwnerState;
};
| 6,182 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/OptionGroup/index.ts | 'use client';
export { OptionGroup } from './OptionGroup';
export * from './OptionGroup.types';
export * from './optionGroupClasses';
| 6,183 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/OptionGroup/optionGroupClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface OptionGroupClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root `li` element if `disabled={true}`. */
disabled: string;
/** Class name applied to the label element. */
label: string;
/** Class name applied to the list element. */
list: string;
}
export type OptionGroupClassKey = keyof OptionGroupClasses;
export function getOptionGroupUtilityClass(slot: string): string {
return generateUtilityClass('MuiOptionGroup', slot);
}
export const optionGroupClasses: OptionGroupClasses = generateUtilityClasses('MuiOptionGroup', [
'root',
'disabled',
'label',
'list',
]);
| 6,184 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Popper/Popper.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Popper, PopperRootSlotProps } from '@mui/base/Popper';
function Root(props: PopperRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-open={ownerState.open} {...other} />;
}
const styledPopper = <Popper slots={{ root: Root }} open />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
<Popper open>
{(props) => {
return <div>{props.placement}</div>;
}}
</Popper>
{/* @ts-expect-error */}
<Popper invalidProp={0} open />
<Popper<'a'> open slots={{ root: 'a' }} href="#" />
<Popper<typeof CustomComponent>
open
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Popper open component={CustomComponent} />
<Popper<'button'>
open
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Popper<'button'>
open
slots={{ root: 'button' }}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,185 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Popper/Popper.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import {
createRenderer,
createMount,
describeConformanceUnstyled,
screen,
} from '@mui-internal/test-utils';
import { Popper, popperClasses } from '@mui/base/Popper';
describe('<Popper />', () => {
const { render } = createRenderer();
const mount = createMount();
const defaultProps = {
anchorEl: () => document.createElement('svg'),
children: <span>Hello World</span>,
open: true,
};
describeConformanceUnstyled(<Popper {...defaultProps} />, () => ({
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
skip: [
// https://github.com/facebook/react/issues/11565
'reactTestRenderer',
'componentProp',
],
slots: {
root: {
expectedClassName: popperClasses.root,
},
},
}));
it('should not pass ownerState to overridable component', () => {
const CustomComponent = React.forwardRef<HTMLDivElement, any>(({ ownerState }, ref) => (
<div ref={ref} data-testid="foo" id={ownerState.id} />
));
render(
<Popper
anchorEl={() => document.createElement('div')}
open
slots={{ root: CustomComponent }}
/>,
);
expect(screen.getByTestId('foo')).to.not.have.attribute('id', 'id');
});
});
| 6,186 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Popper/Popper.tsx | 'use client';
import * as React from 'react';
import {
chainPropTypes,
HTMLElementType,
refType,
unstable_ownerDocument as ownerDocument,
unstable_useEnhancedEffect as useEnhancedEffect,
unstable_useForkRef as useForkRef,
} from '@mui/utils';
import { createPopper, Instance, Modifier, Placement, State, VirtualElement } from '@popperjs/core';
import PropTypes from 'prop-types';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { Portal } from '../Portal';
import { getPopperUtilityClass } from './popperClasses';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import {
PopperPlacementType,
PopperTooltipProps,
PopperTooltipTypeMap,
PopperChildrenProps,
PopperProps,
PopperRootSlotProps,
PopperTransitionProps,
PopperTypeMap,
} from './Popper.types';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
function flipPlacement(placement?: PopperPlacementType, direction?: 'ltr' | 'rtl') {
if (direction === 'ltr') {
return placement;
}
switch (placement) {
case 'bottom-end':
return 'bottom-start';
case 'bottom-start':
return 'bottom-end';
case 'top-end':
return 'top-start';
case 'top-start':
return 'top-end';
default:
return placement;
}
}
function resolveAnchorEl(
anchorEl:
| VirtualElement
| (() => VirtualElement)
| HTMLElement
| (() => HTMLElement)
| null
| undefined,
): HTMLElement | VirtualElement | null | undefined {
return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}
function isHTMLElement(element: HTMLElement | VirtualElement): element is HTMLElement {
return (element as HTMLElement).nodeType !== undefined;
}
function isVirtualElement(element: HTMLElement | VirtualElement): element is VirtualElement {
return !isHTMLElement(element);
}
const useUtilityClasses = () => {
const slots = {
root: ['root'],
};
return composeClasses(slots, useClassNamesOverride(getPopperUtilityClass));
};
const defaultPopperOptions = {};
const PopperTooltip = React.forwardRef(function PopperTooltip<
RootComponentType extends React.ElementType,
>(props: PopperTooltipProps<RootComponentType>, forwardedRef: React.ForwardedRef<HTMLDivElement>) {
const {
anchorEl,
children,
direction,
disablePortal,
modifiers,
open,
placement: initialPlacement,
popperOptions,
popperRef: popperRefProp,
slotProps = {},
slots = {},
TransitionProps,
// @ts-ignore internal logic
ownerState: ownerStateProp, // prevent from spreading to DOM, it can come from the parent component e.g. Select.
...other
} = props;
const tooltipRef = React.useRef<HTMLElement>(null);
const ownRef = useForkRef(tooltipRef, forwardedRef);
const popperRef = React.useRef<Instance | null>(null);
const handlePopperRef = useForkRef(popperRef, popperRefProp);
const handlePopperRefRef = React.useRef(handlePopperRef);
useEnhancedEffect(() => {
handlePopperRefRef.current = handlePopperRef;
}, [handlePopperRef]);
React.useImperativeHandle(popperRefProp, () => popperRef.current!, []);
const rtlPlacement = flipPlacement(initialPlacement, direction);
/**
* placement initialized from prop but can change during lifetime if modifiers.flip.
* modifiers.flip is essentially a flip for controlled/uncontrolled behavior
*/
const [placement, setPlacement] = React.useState<Placement | undefined>(rtlPlacement);
const [resolvedAnchorElement, setResolvedAnchorElement] = React.useState<
HTMLElement | VirtualElement | null | undefined
>(resolveAnchorEl(anchorEl));
React.useEffect(() => {
if (popperRef.current) {
popperRef.current.forceUpdate();
}
});
React.useEffect(() => {
if (anchorEl) {
setResolvedAnchorElement(resolveAnchorEl(anchorEl));
}
}, [anchorEl]);
useEnhancedEffect(() => {
if (!resolvedAnchorElement || !open) {
return undefined;
}
const handlePopperUpdate = (data: State) => {
setPlacement(data.placement);
};
if (process.env.NODE_ENV !== 'production') {
if (
resolvedAnchorElement &&
isHTMLElement(resolvedAnchorElement) &&
resolvedAnchorElement.nodeType === 1
) {
const box = resolvedAnchorElement.getBoundingClientRect();
if (
process.env.NODE_ENV !== 'test' &&
box.top === 0 &&
box.left === 0 &&
box.right === 0 &&
box.bottom === 0
) {
console.warn(
[
'MUI: The `anchorEl` prop provided to the component is invalid.',
'The anchor element should be part of the document layout.',
"Make sure the element is present in the document or that it's not display none.",
].join('\n'),
);
}
}
}
let popperModifiers: Partial<Modifier<any, any>>[] = [
{
name: 'preventOverflow',
options: {
altBoundary: disablePortal,
},
},
{
name: 'flip',
options: {
altBoundary: disablePortal,
},
},
{
name: 'onUpdate',
enabled: true,
phase: 'afterWrite',
fn: ({ state }) => {
handlePopperUpdate(state);
},
},
];
if (modifiers != null) {
popperModifiers = popperModifiers.concat(modifiers);
}
if (popperOptions && popperOptions.modifiers != null) {
popperModifiers = popperModifiers.concat(popperOptions.modifiers);
}
const popper = createPopper(resolvedAnchorElement, tooltipRef.current!, {
placement: rtlPlacement,
...popperOptions,
modifiers: popperModifiers,
});
handlePopperRefRef.current!(popper);
return () => {
popper.destroy();
handlePopperRefRef.current!(null);
};
}, [resolvedAnchorElement, disablePortal, modifiers, open, popperOptions, rtlPlacement]);
const childProps: PopperChildrenProps = { placement: placement! };
if (TransitionProps !== null) {
childProps.TransitionProps = TransitionProps;
}
const classes = useUtilityClasses();
const Root = slots.root ?? 'div';
const rootProps: WithOptionalOwnerState<PopperRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
role: 'tooltip',
ref: ownRef,
},
ownerState: props,
className: classes.root,
});
return (
<Root {...rootProps}>{typeof children === 'function' ? children(childProps) : children}</Root>
);
}) as PolymorphicComponent<PopperTooltipTypeMap>;
/**
* Poppers rely on the 3rd party library [Popper.js](https://popper.js.org/docs/v2/) for positioning.
*
* Demos:
*
* - [Popper](https://mui.com/base-ui/react-popper/)
*
* API:
*
* - [Popper API](https://mui.com/base-ui/react-popper/components-api/#popper)
*/
const Popper = React.forwardRef(function Popper<RootComponentType extends React.ElementType>(
props: PopperProps<RootComponentType>,
forwardedRef: React.ForwardedRef<HTMLDivElement>,
) {
const {
anchorEl,
children,
container: containerProp,
direction = 'ltr',
disablePortal = false,
keepMounted = false,
modifiers,
open,
placement = 'bottom',
popperOptions = defaultPopperOptions,
popperRef,
style,
transition = false,
slotProps = {},
slots = {},
...other
} = props;
const [exited, setExited] = React.useState(true);
const handleEnter = () => {
setExited(false);
};
const handleExited = () => {
setExited(true);
};
if (!keepMounted && !open && (!transition || exited)) {
return null;
}
// If the container prop is provided, use that
// If the anchorEl prop is provided, use its parent body element as the container
// If neither are provided let the Modal take care of choosing the container
let container;
if (containerProp) {
container = containerProp;
} else if (anchorEl) {
const resolvedAnchorEl = resolveAnchorEl(anchorEl);
container =
resolvedAnchorEl && isHTMLElement(resolvedAnchorEl)
? ownerDocument(resolvedAnchorEl).body
: ownerDocument(null).body;
}
const display = !open && keepMounted && (!transition || exited) ? 'none' : undefined;
const transitionProps: PopperTransitionProps | undefined = transition
? {
in: open,
onEnter: handleEnter,
onExited: handleExited,
}
: undefined;
return (
<Portal disablePortal={disablePortal} container={container}>
<PopperTooltip
anchorEl={anchorEl}
direction={direction}
disablePortal={disablePortal}
modifiers={modifiers}
ref={forwardedRef}
open={transition ? !exited : open}
placement={placement}
popperOptions={popperOptions}
popperRef={popperRef}
slotProps={slotProps}
slots={slots}
{...other}
style={{
// Prevents scroll issue, waiting for Popper.js to add this style once initiated.
position: 'fixed',
// Fix Popper.js display issue
top: 0,
left: 0,
display,
...style,
}}
TransitionProps={transitionProps}
>
{children}
</PopperTooltip>
</Portal>
);
}) as PolymorphicComponent<PopperTypeMap>;
Popper.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),
* or a function that returns either.
* It's used to set the position of the popper.
* The return value will passed as the reference object of the Popper instance.
*/
anchorEl: chainPropTypes(
PropTypes.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]),
(props) => {
if (props.open) {
const resolvedAnchorEl = resolveAnchorEl(props.anchorEl);
if (
resolvedAnchorEl &&
isHTMLElement(resolvedAnchorEl) &&
resolvedAnchorEl.nodeType === 1
) {
const box = resolvedAnchorEl.getBoundingClientRect();
if (
process.env.NODE_ENV !== 'test' &&
box.top === 0 &&
box.left === 0 &&
box.right === 0 &&
box.bottom === 0
) {
return new Error(
[
'MUI: The `anchorEl` prop provided to the component is invalid.',
'The anchor element should be part of the document layout.',
"Make sure the element is present in the document or that it's not display none.",
].join('\n'),
);
}
} else if (
!resolvedAnchorEl ||
typeof resolvedAnchorEl.getBoundingClientRect !== 'function' ||
(isVirtualElement(resolvedAnchorEl) &&
resolvedAnchorEl.contextElement != null &&
resolvedAnchorEl.contextElement.nodeType !== 1)
) {
return new Error(
[
'MUI: The `anchorEl` prop provided to the component is invalid.',
'It should be an HTML element instance or a virtualElement ',
'(https://popper.js.org/docs/v2/virtual-elements/).',
].join('\n'),
);
}
}
return null;
},
),
/**
* Popper render function or node.
*/
children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.node,
PropTypes.func,
]),
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
HTMLElementType,
PropTypes.func,
]),
/**
* Direction of the text.
* @default 'ltr'
*/
direction: PropTypes.oneOf(['ltr', 'rtl']),
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Popper.
* @default false
*/
keepMounted: PropTypes.bool,
/**
* Popper.js is based on a "plugin-like" architecture,
* most of its features are fully encapsulated "modifiers".
*
* A modifier is a function that is called each time Popper.js needs to
* compute the position of the popper.
* For this reason, modifiers should be very performant to avoid bottlenecks.
* To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).
*/
modifiers: PropTypes.arrayOf(
PropTypes.shape({
data: PropTypes.object,
effect: PropTypes.func,
enabled: PropTypes.bool,
fn: PropTypes.func,
name: PropTypes.any,
options: PropTypes.object,
phase: PropTypes.oneOf([
'afterMain',
'afterRead',
'afterWrite',
'beforeMain',
'beforeRead',
'beforeWrite',
'main',
'read',
'write',
]),
requires: PropTypes.arrayOf(PropTypes.string),
requiresIfExists: PropTypes.arrayOf(PropTypes.string),
}),
),
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool.isRequired,
/**
* Popper placement.
* @default 'bottom'
*/
placement: PropTypes.oneOf([
'auto-end',
'auto-start',
'auto',
'bottom-end',
'bottom-start',
'bottom',
'left-end',
'left-start',
'left',
'right-end',
'right-start',
'right',
'top-end',
'top-start',
'top',
]),
/**
* Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.
* @default {}
*/
popperOptions: PropTypes.shape({
modifiers: PropTypes.array,
onFirstUpdate: PropTypes.func,
placement: PropTypes.oneOf([
'auto-end',
'auto-start',
'auto',
'bottom-end',
'bottom-start',
'bottom',
'left-end',
'left-start',
'left',
'right-end',
'right-start',
'right',
'top-end',
'top-start',
'top',
]),
strategy: PropTypes.oneOf(['absolute', 'fixed']),
}),
/**
* A ref that points to the used popper instance.
*/
popperRef: refType,
/**
* The props used for each slot inside the Popper.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Popper.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* Help supporting a react-transition-group/Transition component.
* @default false
*/
transition: PropTypes.bool,
} as any;
export { Popper };
| 6,187 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Popper/Popper.types.ts | import * as React from 'react';
import { Instance, Options, OptionsGeneric, VirtualElement } from '@popperjs/core';
import { PortalProps } from '../Portal';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export type PopperPlacementType = Options['placement'];
export interface PopperRootSlotPropsOverrides {}
export interface PopperTransitionProps {
in: boolean;
onEnter: () => void;
onExited: () => void;
}
export interface PopperChildrenProps {
placement: PopperPlacementType;
TransitionProps?: PopperTransitionProps;
}
export interface PopperOwnProps {
/**
* An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),
* or a function that returns either.
* It's used to set the position of the popper.
* The return value will passed as the reference object of the Popper instance.
*/
anchorEl?: null | VirtualElement | HTMLElement | (() => HTMLElement) | (() => VirtualElement);
/**
* Popper render function or node.
*/
children?: React.ReactNode | ((props: PopperChildrenProps) => React.ReactNode);
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container?: PortalProps['container'];
/**
* Direction of the text.
* @default 'ltr'
*/
direction?: 'ltr' | 'rtl';
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal?: PortalProps['disablePortal'];
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Popper.
* @default false
*/
keepMounted?: boolean;
/**
* Popper.js is based on a "plugin-like" architecture,
* most of its features are fully encapsulated "modifiers".
*
* A modifier is a function that is called each time Popper.js needs to
* compute the position of the popper.
* For this reason, modifiers should be very performant to avoid bottlenecks.
* To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).
*/
modifiers?: Options['modifiers'];
/**
* If `true`, the component is shown.
*/
open: boolean;
/**
* Popper placement.
* @default 'bottom'
*/
placement?: PopperPlacementType;
/**
* Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.
* @default {}
*/
popperOptions?: Partial<OptionsGeneric<any>>;
/**
* A ref that points to the used popper instance.
*/
popperRef?: React.Ref<Instance>;
/**
* The props used for each slot inside the Popper.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', PopperRootSlotPropsOverrides, PopperOwnerState>;
};
/**
* The components used for each slot inside the Popper.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: PopperSlots;
/**
* Help supporting a react-transition-group/Transition component.
* @default false
*/
transition?: boolean;
}
export interface PopperSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export type PopperOwnerState = PopperOwnProps;
export interface PopperTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: PopperOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type PopperProps<
RootComponentType extends React.ElementType = PopperTypeMap['defaultComponent'],
> = PolymorphicProps<PopperTypeMap<{}, RootComponentType>, RootComponentType>;
export type PopperTooltipOwnProps = Omit<
PopperOwnProps,
'container' | 'keepMounted' | 'transition'
> & {
TransitionProps?: PopperTransitionProps;
};
export interface PopperTooltipTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: PopperTooltipOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type PopperTooltipProps<
RootComponentType extends React.ElementType = PopperTooltipTypeMap['defaultComponent'],
> = PolymorphicProps<PopperTooltipTypeMap<{}, RootComponentType>, RootComponentType>;
export interface PopperRootSlotProps {
className?: string;
ref: React.Ref<any>;
ownerState: PopperOwnerState;
}
| 6,188 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Popper/index.ts | 'use client';
export { Popper } from './Popper';
export type {
PopperPlacementType,
PopperTransitionProps,
PopperChildrenProps,
PopperOwnProps,
PopperOwnerState,
PopperTypeMap,
PopperProps,
PopperRootSlotProps,
PopperRootSlotPropsOverrides,
} from './Popper.types';
export { popperClasses, getPopperUtilityClass } from './popperClasses';
export type { PopperClassKey, PopperClasses } from './popperClasses';
| 6,189 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Popper/popperClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface PopperClasses {
/** Class name applied to the root element. */
root: string;
}
export type PopperClassKey = keyof PopperClasses;
export function getPopperUtilityClass(slot: string): string {
return generateUtilityClass('MuiPopper', slot);
}
export const popperClasses: PopperClasses = generateUtilityClasses('MuiPopper', ['root']);
| 6,190 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Portal/Portal.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer } from '@mui-internal/test-utils';
import { Portal, PortalProps } from '@mui/base/Portal';
describe('<Portal />', () => {
const { render, renderToString } = createRenderer();
describe('server-side', () => {
before(function beforeHook() {
// Only run the test on node.
if (!/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
});
it('render nothing on the server', () => {
const { container } = renderToString(
<Portal>
<div>Bar</div>
</Portal>,
);
expect(container.firstChild).to.equal(null);
});
});
describe('ref', () => {
it('should have access to the mountNode when disabledPortal={false}', () => {
const refSpy = spy();
const { unmount } = render(
<Portal ref={refSpy}>
<h1>Foo</h1>
</Portal>,
);
expect(refSpy.args).to.deep.equal([[document.body]]);
unmount();
expect(refSpy.args).to.deep.equal([[document.body], [null]]);
});
it('should have access to the mountNode when disabledPortal={true}', () => {
const refSpy = spy();
const { unmount } = render(
<Portal disablePortal ref={refSpy}>
<h1 className="woofPortal">Foo</h1>
</Portal>,
);
const mountNode = document.querySelector('.woofPortal');
expect(refSpy.args).to.deep.equal([[mountNode]]);
unmount();
expect(refSpy.args).to.deep.equal([[mountNode], [null]]);
});
it('should have access to the mountNode when switching disabledPortal', () => {
const refSpy = spy();
const { setProps, unmount } = render(
<Portal disablePortal ref={refSpy}>
<h1 className="woofPortal">Foo</h1>
</Portal>,
);
const mountNode = document.querySelector('.woofPortal');
expect(refSpy.args).to.deep.equal([[mountNode]]);
setProps({
disablePortal: false,
ref: refSpy,
});
expect(refSpy.args).to.deep.equal([[mountNode], [null], [document.body]]);
unmount();
expect(refSpy.args).to.deep.equal([[mountNode], [null], [document.body], [null]]);
});
});
it('should render in a different node', () => {
render(
<div id="test1">
<h1 className="woofPortal1">Foo</h1>
<Portal>
<h1 className="woofPortal2">Foo</h1>
</Portal>
</div>,
);
const rootElement = document.querySelector<HTMLDivElement>('#test1')!;
expect(rootElement.contains(document.querySelector('.woofPortal1'))).to.equal(true);
expect(rootElement.contains(document.querySelector('.woofPortal2'))).to.equal(false);
});
it('should unmount when parent unmounts', () => {
function Child() {
const containerRef = React.useRef<HTMLDivElement>(null);
return (
<div>
<div ref={containerRef} />
<Portal container={() => containerRef.current}>
<div id="test1" />
</Portal>
</div>
);
}
function Parent(props: { show?: boolean }) {
const { show = true } = props;
return <div>{show ? <Child /> : null}</div>;
}
const { setProps } = render(<Parent />);
expect(document.querySelectorAll('#test1').length).to.equal(1);
setProps({ show: false });
expect(document.querySelectorAll('#test1').length).to.equal(0);
});
it('should render overlay into container (document)', () => {
render(
<Portal>
<div className="test2" />
<div className="test2" />
</Portal>,
);
expect(document.querySelectorAll('.test2').length).to.equal(2);
});
it('should render overlay into container (DOMNode)', () => {
const container = document.createElement('div');
render(
<Portal container={container}>
<div id="test2" />
</Portal>,
);
expect(container.querySelectorAll('#test2').length).to.equal(1);
});
it('should change container on prop change', () => {
type ContainerProps = {
disablePortal?: boolean;
containerElement?: boolean;
};
function ContainerTest(props: ContainerProps) {
const { containerElement = false, disablePortal = true } = props;
const containerRef = React.useRef<HTMLElement>(null);
const container = React.useCallback(
() => (containerElement ? containerRef.current : null),
[containerElement],
);
return (
<span>
<strong ref={containerRef} />
<Portal disablePortal={disablePortal} container={container}>
<div id="test3" />
</Portal>
</span>
);
}
const { setProps } = render(<ContainerTest />);
expect(document.querySelector('#test3')?.parentElement?.nodeName).to.equal('SPAN');
setProps({
containerElement: true,
disablePortal: true,
});
expect(document.querySelector('#test3')?.parentElement?.nodeName).to.equal('SPAN');
setProps({
containerElement: true,
disablePortal: false,
});
expect(document.querySelector('#test3')?.parentElement?.nodeName).to.equal('STRONG');
setProps({
containerElement: false,
disablePortal: false,
});
expect(document.querySelector('#test3')?.parentElement?.nodeName).to.equal('BODY');
});
it('should call ref after child effect', () => {
const callOrder: Array<string> = [];
const handleRef = (node: Element | null) => {
if (node) {
callOrder.push('ref');
}
};
const updateFunction = () => {
callOrder.push('effect');
};
function Test(props: PortalProps) {
const { container } = props;
const containerRef = React.useRef<PortalProps['container']>(null);
React.useEffect(() => {
if (containerRef.current !== container) {
updateFunction();
}
containerRef.current = container;
}, [container]);
return (
<Portal ref={handleRef} container={container}>
<div />
</Portal>
);
}
const { setProps } = render(<Test container={document.createElement('div')} />);
setProps({ container: null });
setProps({ container: document.createElement('div') });
setProps({ container: null });
expect(callOrder).to.deep.equal([
'effect',
'ref',
'effect',
'ref',
'effect',
'ref',
'effect',
'ref',
]);
});
});
| 6,191 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Portal/Portal.tsx | 'use client';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import {
exactProp,
HTMLElementType,
unstable_useEnhancedEffect as useEnhancedEffect,
unstable_useForkRef as useForkRef,
unstable_setRef as setRef,
} from '@mui/utils';
import { PortalProps } from './Portal.types';
function getContainer(container: PortalProps['container']) {
return typeof container === 'function' ? container() : container;
}
/**
* Portals provide a first-class way to render children into a DOM node
* that exists outside the DOM hierarchy of the parent component.
*
* Demos:
*
* - [Portal](https://mui.com/base-ui/react-portal/)
*
* API:
*
* - [Portal API](https://mui.com/base-ui/react-portal/components-api/#portal)
*/
const Portal = React.forwardRef(function Portal(
props: PortalProps,
forwardedRef: React.ForwardedRef<Element>,
) {
const { children, container, disablePortal = false } = props;
const [mountNode, setMountNode] = React.useState<ReturnType<typeof getContainer>>(null);
// @ts-expect-error TODO upstream fix
const handleRef = useForkRef(React.isValidElement(children) ? children.ref : null, forwardedRef);
useEnhancedEffect(() => {
if (!disablePortal) {
setMountNode(getContainer(container) || document.body);
}
}, [container, disablePortal]);
useEnhancedEffect(() => {
if (mountNode && !disablePortal) {
setRef(forwardedRef, mountNode);
return () => {
setRef(forwardedRef, null);
};
}
return undefined;
}, [forwardedRef, mountNode, disablePortal]);
if (disablePortal) {
if (React.isValidElement(children)) {
const newProps = {
ref: handleRef,
};
return React.cloneElement(children, newProps);
}
return <React.Fragment>{children}</React.Fragment>;
}
return (
<React.Fragment>
{mountNode ? ReactDOM.createPortal(children, mountNode) : mountNode}
</React.Fragment>
);
}) as React.ForwardRefExoticComponent<PortalProps & React.RefAttributes<Element>>;
Portal.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The children to render into the `container`.
*/
children: PropTypes.node,
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
HTMLElementType,
PropTypes.func,
]),
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal: PropTypes.bool,
} as any;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
(Portal as any)['propTypes' + ''] = exactProp((Portal as any).propTypes);
}
export { Portal };
| 6,192 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Portal/Portal.types.ts | import * as React from 'react';
export interface PortalProps {
/**
* The children to render into the `container`.
*/
children?: React.ReactNode;
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container?: Element | (() => Element | null) | null;
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal?: boolean;
}
| 6,193 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Portal/index.ts | 'use client';
export { Portal } from './Portal';
export * from './Portal.types';
| 6,194 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Select/Select.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import {
Select,
SelectRootSlotProps,
SelectPopperSlotProps,
Popper,
WithOptionalOwnerState,
} from '@mui/base';
const SelectSlotPropsOverridesTest = (
<Select
slotProps={{
root: {
// @ts-expect-error - requires module augmentation
size: 'red',
className: 'test',
},
popper: {
className: 'popper',
disablePortal: true,
},
listbox: {
className: 'listbox',
onMouseOver: () => {},
},
}}
/>
);
function CustomRoot<OptionValue extends {}, Multiple extends boolean>(
props: SelectRootSlotProps<OptionValue, Multiple>,
) {
const { ownerState, ...other } = props;
return <div {...other} />;
}
function CustomPopper<OptionValue extends {}, Multiple extends boolean>(
props: WithOptionalOwnerState<SelectPopperSlotProps<OptionValue, Multiple>>,
) {
const { ownerState, ...other } = props;
return <Popper {...other} />;
}
const SelectRootComponentOverridesTest = (
<Select
slots={{
root: CustomRoot,
listbox: 'ul',
popper: Popper,
}}
/>
);
const SelectPopperComponentOverridesTest = (
<Select
slots={{
popper: CustomPopper,
}}
/>
);
function InvalidPopper({ requiredProp }: { requiredProp: string }) {
return <div />;
}
const SelectSlotsOverridesUsingInvalidComponentTest = (
<Select
slots={{
// @ts-expect-error - provided a component that requires a prop Select does not provide
popper: InvalidPopper,
}}
/>
);
const SelectSlotsOverridesUsingHostComponentTest = (
<Select
slots={{
// @ts-expect-error - provided a host element instead of a component
popper: 'div',
}}
/>
);
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Select invalidProp={0} />
<Select<string, false, 'a'>
slots={{
root: 'a',
}}
href="#"
/>
<Select<string, false, typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Select<string, false, typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<Select<string, false, 'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Select<string, false, 'button'>
slots={{
root: 'button',
}}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
| 6,195 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Select/Select.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
userEvent,
act,
screen,
} from '@mui-internal/test-utils';
import { Select, SelectListboxSlotProps, selectClasses } from '@mui/base/Select';
import { SelectOption } from '@mui/base/useOption';
import { Option, OptionProps, OptionRootSlotProps, optionClasses } from '@mui/base/Option';
import { OptionGroup } from '@mui/base/OptionGroup';
describe('<Select />', () => {
const mount = createMount();
const { render } = createRenderer();
const componentToTest = (
<Select defaultListboxOpen defaultValue={1} slotProps={{ popper: { disablePortal: true } }}>
<OptionGroup label="Group">
<Option value={1}>1</Option>
</OptionGroup>
</Select>
);
describeConformanceUnstyled(componentToTest, () => ({
inheritComponent: 'button',
render,
mount,
refInstanceof: window.HTMLButtonElement,
testComponentPropWith: 'span',
muiName: 'MuiSelect',
slots: {
root: {
expectedClassName: selectClasses.root,
},
listbox: {
expectedClassName: selectClasses.listbox,
testWithElement: 'ul',
},
popper: {
expectedClassName: selectClasses.popper,
testWithElement: null,
},
},
skip: ['componentProp'],
}));
describe('keyboard navigation', () => {
['Enter', 'ArrowDown', 'ArrowUp', ' '].forEach((key) => {
it(`opens the dropdown when the "${key}" key is down on the button`, () => {
// can't use the default native `button` as it doesn't treat enter or space press as a click
const { getByRole } = render(<Select slots={{ root: 'div' }} />);
const select = getByRole('combobox');
act(() => {
select.focus();
});
fireEvent.keyDown(select, { key });
expect(select).to.have.attribute('aria-expanded', 'true');
expect(getByRole('listbox')).not.to.equal(null);
});
});
['Enter', ' ', 'Escape'].forEach((key) => {
it(`closes the dropdown when the "${key}" key is pressed`, () => {
const { getByRole } = render(
<Select>
<Option value={1}>1</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
fireEvent.mouseDown(select);
});
const listbox = getByRole('listbox');
fireEvent.keyDown(select, { key });
expect(select).to.have.attribute('aria-expanded', 'false');
expect(listbox).not.toBeVisible();
});
});
['Enter', ' '].forEach((key) => {
it(`does not close the multiselect dropdown when the "${key}" key is pressed`, () => {
const { getByRole, queryByRole } = render(
<Select multiple>
<Option value={1}>1</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key });
expect(select).to.have.attribute('aria-expanded', 'true');
expect(queryByRole('listbox')).not.to.equal(null);
});
});
describe('item selection', () => {
['Enter', ' '].forEach((key) =>
it(`selects a highlighted item using the "${key}" key`, () => {
const { getByRole } = render(
<Select>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
fireEvent.mouseDown(select);
});
userEvent.keyPress(select, { key: 'ArrowDown' }); // highlights '2'
fireEvent.keyDown(select, { key });
expect(select).to.have.text('2');
}),
);
});
describe('text navigation', () => {
it('navigate to matched key', () => {
const { getByRole, getByText } = render(
<Select>
<Option value={1}>Apple</Option>
<Option value={2}>Banana</Option>
<Option value={3}>Cherry</Option>
<Option value={4}>Calamondin</Option>
<Option value={5}>Dragon Fruit</Option>
<Option value={6}>Grapes</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key: 'd' });
expect(getByText('Dragon Fruit')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'r' });
expect(getByText('Dragon Fruit')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'z' });
expect(getByText('Dragon Fruit')).to.have.class(optionClasses.highlighted);
});
it('navigate to next element with same starting character on repeated keys', () => {
const { getByRole, getByText } = render(
<Select>
<Option value={1}>Apple</Option>
<Option value={2}>Banana</Option>
<Option value={3}>Cherry</Option>
<Option value={4}>Calamondin</Option>
<Option value={5}>Dragon Fruit</Option>
<Option value={6}>Grapes</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key: 'c' });
expect(getByText('Cherry')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'c' });
expect(getByText('Calamondin')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'c' });
expect(getByText('Cherry')).to.have.class(optionClasses.highlighted);
});
it('navigate using the label prop', () => {
function RichOption(props: OptionProps<number>) {
return (
<Option {...props}>
<div>
Option Title
<div>
Nested information
<p>{props.label || props.value}</p>
</div>
</div>
</Option>
);
}
const { getByRole, getByTestId } = render(
<Select>
<RichOption data-testid="1" value={1} label="Apple" />
<RichOption data-testid="2" value={2} label="Banana" />
<RichOption data-testid="3" value={3} label="Cherry" />
<RichOption data-testid="4" value={4} label="Calamondin" />
<RichOption data-testid="5" value={5} label="Dragon Fruit" />
<RichOption data-testid="6" value={6} label="Grapes" />
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key: 'd' });
expect(getByTestId('5')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'r' });
expect(getByTestId('5')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'z' });
expect(getByTestId('5')).to.have.class(optionClasses.highlighted);
});
it('skips the non-stringifiable options', () => {
const { getByRole, getByText } = render(
<Select>
<Option value={{ key: 'Apple' }}>Apple</Option>
<Option value={{ key: 'Banana' }}>Banana</Option>
<Option value={{ key: 'Cherry' }}>Cherry</Option>
<Option value={<div />} />
<Option value={{ key: 'Cherry' }}>
<div>Nested Content</div>
</Option>{' '}
<Option value={{}}>{null}</Option>
<Option value={{ key: 'Calamondin' }}>Calamondin</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key: 'c' });
expect(getByText('Cherry')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'c' });
expect(getByText('Calamondin')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'c' });
expect(getByText('Cherry')).to.have.class(optionClasses.highlighted);
});
it('navigate to options with diacritic characters', () => {
const { getByRole, getByText } = render(
<Select>
<Option value={{ key: 'Aa' }}>Aa</Option>
<Option value={{ key: 'Ba' }}>Ba</Option>
<Option value={{ key: 'Bb' }}>Bb</Option>
<Option value={{ key: 'Bc' }}>Bc</Option>
<Option value={{ key: 'Bą' }}>Bą</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key: 'b' });
expect(getByText('Ba')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'Control' });
userEvent.keyPress(select, { key: 'Alt' });
userEvent.keyPress(select, { key: 'ą' });
expect(getByText('Bą')).to.have.class(optionClasses.highlighted);
});
it('navigate to next options with beginning diacritic characters', () => {
const { getByRole, getByText } = render(
<Select>
<Option value={{ key: 'Aa' }}>Aa</Option>
<Option value={{ key: 'ąa' }}>ąa</Option>
<Option value={{ key: 'ąb' }}>ąb</Option>
<Option value={{ key: 'ąc' }}>ąc</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
userEvent.keyPress(select, { key: 'Control' });
userEvent.keyPress(select, { key: 'Alt' });
userEvent.keyPress(select, { key: 'ą' });
expect(getByText('ąa')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'Alt' });
userEvent.keyPress(select, { key: 'Control' });
userEvent.keyPress(select, { key: 'ą' });
expect(getByText('ąb')).to.have.class(optionClasses.highlighted);
userEvent.keyPress(select, { key: 'Control' });
userEvent.keyPress(select, { key: 'AltGraph' });
userEvent.keyPress(select, { key: 'ą' });
expect(getByText('ąc')).to.have.class(optionClasses.highlighted);
});
});
it('closes the listbox without selecting an option when "Escape" is pressed', () => {
const { getByRole, queryByRole } = render(
<Select defaultValue={1}>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
fireEvent.keyDown(select, { key: 'ArrowDown' }); // highlights '2'
fireEvent.keyDown(select, { key: 'Escape' });
expect(select).to.have.attribute('aria-expanded', 'false');
expect(select).to.have.text('1');
expect(queryByRole('listbox', { hidden: true })).not.toBeVisible();
});
it('scrolls to highlighted option so it is visible', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
// two options are visible at a time
const SelectListbox = React.forwardRef(function SelectListbox(
props: SelectListboxSlotProps<string, false>,
ref: React.ForwardedRef<HTMLUListElement>,
) {
const { ownerState, ...other } = props;
return <ul {...other} ref={ref} style={{ maxHeight: '100px', overflow: 'auto' }} />;
});
const CustomOption = React.forwardRef(function CustomOption(
props: { value: string; children?: React.ReactNode },
ref: React.Ref<HTMLLIElement>,
) {
return <Option {...props} ref={ref} slotProps={{ root: { style: { height: '50px' } } }} />;
});
const { getByRole } = render(
<Select slots={{ listbox: SelectListbox }}>
<CustomOption value="1">1</CustomOption>
<CustomOption value="2">2</CustomOption>
<CustomOption value="3">3</CustomOption>
<CustomOption value="4">4</CustomOption>
<CustomOption value="5">5</CustomOption>
<CustomOption value="6">6</CustomOption>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
});
fireEvent.keyDown(select, { key: 'ArrowDown' }); // opens the listbox and highlights 1
const listbox = getByRole('listbox');
fireEvent.keyDown(select, { key: 'ArrowDown' }); // highlights 2
expect(listbox.scrollTop).to.equal(0);
fireEvent.keyDown(select, { key: 'ArrowDown' }); // highlights 3
expect(listbox.scrollTop).to.equal(50);
fireEvent.keyDown(select, { key: 'ArrowDown' }); // highlights 4
expect(listbox.scrollTop).to.equal(100);
fireEvent.keyDown(select, { key: 'ArrowUp' }); // highlights 3
expect(listbox.scrollTop).to.equal(100);
fireEvent.keyDown(select, { key: 'ArrowUp' }); // highlights 2
expect(listbox.scrollTop).to.equal(50);
});
});
describe('form submission', () => {
describe('using single-select mode', () => {
it('includes the Select value in the submitted form data when the `name` attribute is provided', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// FormData is not available in JSDOM
this.skip();
}
let isEventHandled = false;
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
expect(formData.get('test-select')).to.equal('2');
isEventHandled = true;
};
const { getByText } = render(
<form onSubmit={handleSubmit}>
<Select defaultValue={2} name="test-select">
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
<button type="submit">Submit</button>
</form>,
);
const button = getByText('Submit');
act(() => {
button.click();
});
expect(isEventHandled).to.equal(true);
});
it('transforms the selected value before posting using the getSerializedValue prop, if provided', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// FormData is not available in JSDOM
this.skip();
}
let isEventHandled = false;
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
expect(formData.get('test-select')).to.equal('option 2');
isEventHandled = true;
};
const customFormValueProvider = (option: SelectOption<number> | null) =>
option != null ? `option ${option.value}` : '';
const { getByText } = render(
<form onSubmit={handleSubmit}>
<Select
defaultValue={2}
multiple={false}
name="test-select"
getSerializedValue={customFormValueProvider}
>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
<button type="submit">Submit</button>
</form>,
);
const button = getByText('Submit');
act(() => {
button.click();
});
expect(isEventHandled).to.equal(true);
});
it('formats the object values as JSON before posting', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// FormData is not available in JSDOM
this.skip();
}
let isEventHandled = false;
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
expect(formData.get('test-select')).to.equal('{"firstName":"Olivia"}');
isEventHandled = true;
};
const options = [
{ value: { firstName: 'Alice' }, label: 'Alice' },
{ value: { firstName: 'Olivia' }, label: 'Olivia' },
];
const { getByText } = render(
<form onSubmit={handleSubmit}>
<Select defaultValue={options[1].value} name="test-select">
{options.map((o) => (
<Option key={o.value.firstName} value={o.value}>
{o.label}
</Option>
))}
</Select>
<button type="submit">Submit</button>
</form>,
);
const button = getByText('Submit');
act(() => {
button.click();
});
expect(isEventHandled).to.equal(true);
});
});
describe('using multi-select mode', () => {
it('includes the Select value in the submitted form data when the `name` attribute is provided', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// FormData is not available in JSDOM
this.skip();
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
expect(formData.get('test-select')).to.equal('[2,3]');
};
const { getByText } = render(
<form onSubmit={handleSubmit}>
<Select multiple defaultValue={[2, 3]} name="test-select">
<Option value={1}>1</Option>
<Option value={2}>2</Option>
<Option value={3}>3</Option>
</Select>
<button type="submit">Submit</button>
</form>,
);
const button = getByText('Submit');
act(() => {
button.click();
});
});
it('transforms the selected value before posting using the getSerializedValue prop, if provided', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// FormData is not available in JSDOM
this.skip();
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
expect(formData.get('test-select')).to.equal('2; 3');
};
const customFormValueProvider = (options: SelectOption<number>[]) =>
options.map((o) => o.value).join('; ');
const { getByText } = render(
<form onSubmit={handleSubmit}>
<Select
multiple
defaultValue={[2, 3]}
name="test-select"
getSerializedValue={customFormValueProvider}
>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
<Option value={3}>3</Option>
</Select>
<button type="submit">Submit</button>
</form>,
);
const button = getByText('Submit');
act(() => {
button.click();
});
});
it('formats the object values as JSON before posting', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// FormData is not available in JSDOM
this.skip();
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
expect(formData.get('test-select')).to.equal('[{"firstName":"Olivia"}]');
};
const options = [
{ value: { firstName: 'Alice' }, label: 'Alice' },
{ value: { firstName: 'Olivia' }, label: 'Olivia' },
];
const { getByText } = render(
<form onSubmit={handleSubmit}>
<Select multiple defaultValue={[options[1].value]} name="test-select">
{options.map((o) => (
<Option key={o.value.firstName} value={o.value}>
{o.label}
</Option>
))}
</Select>
<button type="submit">Submit</button>
</form>,
);
const button = getByText('Submit');
act(() => {
button.click();
});
});
});
});
describe('prop: onChange', () => {
it('is called when the Select value changes', () => {
const handleChange = spy();
const { getByRole, getByText } = render(
<Select defaultValue={1} onChange={handleChange}>
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.click();
});
const optionTwo = getByText('Two');
act(() => {
optionTwo.click();
});
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][0]).to.haveOwnProperty('type', 'click');
expect(handleChange.args[0][0]).to.haveOwnProperty('target', optionTwo);
expect(handleChange.args[0][1]).to.equal(2);
});
it('is not called if `value` is modified externally', () => {
function TestComponent({ onChange }: { onChange: (value: number[]) => void }) {
const [value, setValue] = React.useState([1]);
const handleChange = (ev: React.SyntheticEvent | null, newValue: number[]) => {
setValue(newValue);
onChange(newValue);
};
return (
<div>
<button onClick={() => setValue([1, 2])}>Update value</button>
<Select value={value} multiple onChange={handleChange}>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
</div>
);
}
const onChange = spy();
const { getByText } = render(<TestComponent onChange={onChange} />);
const button = getByText('Update value');
act(() => button.click());
expect(onChange.notCalled).to.equal(true);
});
it('is not called after initial render when when controlled value is set to null', () => {
function TestComponent({ onChange }: { onChange: (value: string | null) => void }) {
const [value, setValue] = React.useState<string | null>(null);
const handleChange = (event: React.SyntheticEvent | null, newValue: string | null) => {
setValue(newValue);
onChange(newValue);
};
return (
<Select value={value} onChange={handleChange}>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>
);
}
const onChange = spy();
render(<TestComponent onChange={onChange} />);
expect(onChange.notCalled).to.equal(true);
});
it('is not called after initial render when when the default uncontrolled value is set to null', () => {
function TestComponent({ onChange }: { onChange: (value: string | null) => void }) {
const handleChange = (event: React.SyntheticEvent | null, newValue: string | null) => {
onChange(newValue);
};
return (
<Select defaultValue={null as string | null} onChange={handleChange}>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>
);
}
const onChange = spy();
render(<TestComponent onChange={onChange} />);
expect(onChange.notCalled).to.equal(true);
});
it('is not called after initial render when the controlled value is set to a valid option', () => {
function TestComponent({ onChange }: { onChange: (value: string | null) => void }) {
const [value, setValue] = React.useState<string | null>('1');
const handleChange = (event: React.SyntheticEvent | null, newValue: string | null) => {
setValue(newValue);
onChange(newValue);
};
return (
<Select value={value} onChange={handleChange}>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>
);
}
const onChange = spy();
render(<TestComponent onChange={onChange} />);
expect(onChange.notCalled).to.equal(true);
});
it('is not called after initial render when when the default uncontrolled value is set to a valid option', () => {
function TestComponent({ onChange }: { onChange: (value: string | null) => void }) {
const handleChange = (event: React.SyntheticEvent | null, newValue: string | null) => {
onChange(newValue);
};
return (
<Select defaultValue="1" onChange={handleChange}>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>
);
}
const onChange = spy();
render(<TestComponent onChange={onChange} />);
expect(onChange.notCalled).to.equal(true);
});
it('is called after initial render with `null` when the controlled value is set to a nonexistent option', () => {
function TestComponent({ onChange }: { onChange: (value: string | null) => void }) {
const [value, setValue] = React.useState<string | null>('42');
const handleChange = (event: React.SyntheticEvent | null, newValue: string | null) => {
setValue(newValue);
onChange(newValue);
};
return (
<Select value={value} onChange={handleChange}>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>
);
}
const onChange = spy();
render(<TestComponent onChange={onChange} />);
expect(onChange.called).to.equal(true);
expect(onChange.args[0][0]).to.equal(null);
});
it('is called after initial render when when the default uncontrolled value is set to a nonexistent option', () => {
function TestComponent({ onChange }: { onChange: (value: string | null) => void }) {
const handleChange = (event: React.SyntheticEvent | null, newValue: string | null) => {
onChange(newValue);
};
return (
<Select defaultValue="42" onChange={handleChange}>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>
);
}
const onChange = spy();
render(<TestComponent onChange={onChange} />);
expect(onChange.called).to.equal(true);
expect(onChange.args[0][0]).to.equal(null);
});
});
describe('prop: placeholder', () => {
it('renders when no value is selected ', () => {
const { getByRole } = render(
<Select placeholder="Placeholder text">
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
expect(getByRole('combobox')).to.have.text('Placeholder text');
});
});
describe('prop: renderValue', () => {
it('renders the selected value using the renderValue prop', () => {
const { getByRole } = render(
<Select defaultValue={1} renderValue={(value) => `${value?.label} (${value?.value})`}>
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
expect(getByRole('combobox')).to.have.text('One (1)');
});
it('renders the selected value as a label if renderValue is not provided', () => {
const { getByRole } = render(
<Select defaultValue={1}>
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
expect(getByRole('combobox')).to.have.text('One');
});
it('renders a zero-width space when there is no selected value nor placeholder and renderValue is not provided', () => {
const { getByRole } = render(
<Select>
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
const select = getByRole('combobox');
const zws = select.querySelector('.notranslate');
expect(zws).not.to.equal(null);
});
it('renders the selected values (multiple) using the renderValue prop', () => {
const { getByRole } = render(
<Select
multiple
defaultValue={[1, 2]}
renderValue={(values) => values.map((v) => `${v.label} (${v.value})`).join(', ')}
>
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
expect(getByRole('combobox')).to.have.text('One (1), Two (2)');
});
it('renders the selected values (multiple) as comma-separated list of labels if renderValue is not provided', () => {
const { getByRole } = render(
<Select multiple defaultValue={[1, 2]}>
<Option value={1}>One</Option>
<Option value={2}>Two</Option>
</Select>,
);
expect(getByRole('combobox')).to.have.text('One, Two');
});
});
describe('prop: areOptionsEqual', () => {
it('should use the `areOptionsEqual` prop to determine if an option is selected', () => {
interface TestValue {
id: string;
}
const areOptionsEqual = (a: TestValue, b: TestValue) => a.id === b.id;
const { getByRole } = render(
<Select defaultValue={{ id: '1' }} areOptionsEqual={areOptionsEqual}>
<Option value={{ id: '1' }}>One</Option>
<Option value={{ id: '2' }}>Two</Option>
</Select>,
);
expect(getByRole('combobox')).to.have.text('One');
});
});
// according to WAI-ARIA 1.2 (https://www.w3.org/TR/wai-aria-1.2/#combobox)
describe('a11y attributes', () => {
it('should have the `combobox` role', () => {
render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
expect(screen.queryByRole('combobox')).not.to.equal(null);
});
it('should have the aria-expanded attribute', () => {
render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
expect(screen.getByRole('combobox')).to.have.attribute('aria-expanded', 'false');
});
it('should have the aria-expanded attribute set to true when the listbox is open', () => {
render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
const select = screen.getByRole('combobox');
act(() => {
fireEvent.mouseDown(select);
});
expect(select).to.have.attribute('aria-expanded', 'true');
});
it('should have the aria-controls attribute', () => {
render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
const select = screen.getByRole('combobox');
act(() => {
fireEvent.mouseDown(select);
});
const listbox = screen.getByRole('listbox');
const listboxId = listbox.getAttribute('id');
expect(listboxId).not.to.equal(null);
expect(select).to.have.attribute('aria-controls', listboxId!);
});
it('should have the aria-activedescendant attribute', () => {
render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
const select = screen.getByRole('combobox');
act(() => {
select.focus();
select.click();
});
fireEvent.keyDown(select, { key: 'ArrowDown' });
const options = screen.getAllByRole('option');
expect(select).to.have.attribute('aria-activedescendant', options[0].getAttribute('id')!);
});
});
describe('open/close behavior', () => {
it('opens the listbox when the select is clicked', () => {
const { getByRole } = render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
fireEvent.mouseDown(select);
});
expect(select).to.have.attribute('aria-expanded', 'true');
});
it('closes the listbox when the select is clicked again', () => {
const { getByRole } = render(
<Select>
<Option value={1}>One</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
fireEvent.mouseDown(select);
});
act(() => {
fireEvent.mouseDown(select);
});
expect(select).to.have.attribute('aria-expanded', 'false');
});
it('closes the listbox without selecting an option when focus is lost', () => {
const { getByRole, getByTestId } = render(
<div>
<Select defaultValue={1}>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
<p data-testid="focus-target" tabIndex={0}>
focus target
</p>
</div>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
fireEvent.mouseDown(select);
});
const listbox = getByRole('listbox');
userEvent.keyPress(select, { key: 'ArrowDown' }); // highlights '2'
const focusTarget = getByTestId('focus-target');
act(() => {
focusTarget.focus();
});
expect(select).to.have.attribute('aria-expanded', 'false');
expect(select).to.have.text('1');
expect(listbox).not.toBeVisible();
});
it('closes the listbox when already selected option is selected again with a click', () => {
const { getByRole, getByTestId } = render(
<Select defaultValue={1}>
<Option data-testid="selected-option" value={1}>
1
</Option>
<Option value={2}>2</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.click();
});
const selectedOption = getByTestId('selected-option');
fireEvent.click(selectedOption);
expect(select).to.have.attribute('aria-expanded', 'false');
expect(select).to.have.text('1');
});
it('keeps the trigger focused when the listbox is opened and interacted with', () => {
const { getByRole } = render(
<Select>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>,
);
const select = getByRole('combobox');
act(() => {
select.focus();
select.click();
});
expect(document.activeElement).to.equal(select);
fireEvent.keyDown(select, { key: 'ArrowDown' });
expect(document.activeElement).to.equal(select);
});
it('does not steal focus from other elements on page when it is open on mount', () => {
const { getAllByRole } = render(
<div>
<input autoFocus />
<Select defaultListboxOpen>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
</div>,
);
const input = getAllByRole('textbox')[0];
expect(document.activeElement).to.equal(input);
});
it('scrolls to initially highlighted option after opening', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
// two options are visible at a time
const SelectListbox = React.forwardRef(function SelectListbox(
props: SelectListboxSlotProps<string, false>,
ref: React.ForwardedRef<HTMLUListElement>,
) {
const { ownerState, ...other } = props;
return <ul {...other} ref={ref} style={{ maxHeight: '100px', overflow: 'auto' }} />;
});
const CustomOption = React.forwardRef(function CustomOption(
props: { value: string; children?: React.ReactNode },
ref: React.Ref<HTMLLIElement>,
) {
return <Option {...props} ref={ref} slotProps={{ root: { style: { height: '50px' } } }} />;
});
const { getByRole } = render(
<Select slots={{ listbox: SelectListbox }} defaultValue={'4'}>
<CustomOption value="1">1</CustomOption>
<CustomOption value="2">2</CustomOption>
<CustomOption value="3">3</CustomOption>
<CustomOption value="4">4</CustomOption>
<CustomOption value="5">5</CustomOption>
<CustomOption value="6">6</CustomOption>
</Select>,
);
const select = getByRole('combobox');
act(() => {
fireEvent.mouseDown(select);
});
const listbox = getByRole('listbox');
expect(listbox.scrollTop).to.equal(100);
});
});
describe('prop: autoFocus', () => {
it('should focus the select after mounting', () => {
const { getByRole } = render(
<div>
<input />
<Select autoFocus>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
</div>,
);
const select = getByRole('combobox');
expect(document.activeElement).to.equal(select);
});
});
it('sets a value correctly when interacted by a user and external code', () => {
function TestComponent() {
const [value, setValue] = React.useState<number[]>([]);
return (
<div>
<button data-testid="update-externally" onClick={() => setValue([1])}>
Update value
</button>
<Select
multiple
value={value}
onChange={(_, v) => setValue(v)}
slotProps={{
root: {
'data-testid': 'select',
} as any,
}}
>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>
</div>
);
}
const { getByTestId, getByText } = render(<TestComponent />);
const updateButton = getByTestId('update-externally');
const selectButton = getByTestId('select');
act(() => updateButton.click());
act(() => selectButton.click());
const option2 = getByText('2');
act(() => option2.click());
expect(selectButton).to.have.text('1, 2');
});
it('perf: does not rerender options unnecessarily', () => {
const renderOption1Spy = spy();
const renderOption2Spy = spy();
const renderOption3Spy = spy();
const renderOption4Spy = spy();
const LoggingRoot = React.forwardRef(function LoggingRoot(
props: OptionRootSlotProps<number> & { renderSpy: () => void },
ref: React.ForwardedRef<HTMLLIElement>,
) {
const { renderSpy, ownerState, ...other } = props;
renderSpy();
return <li {...other} ref={ref} />;
});
const { getByRole } = render(
<Select>
<Option
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderOption1Spy } as any }}
value={1}
>
1
</Option>
<Option
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderOption2Spy } as any }}
value={2}
>
2
</Option>
<Option
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderOption3Spy } as any }}
value={3}
>
3
</Option>
<Option
slots={{ root: LoggingRoot }}
slotProps={{ root: { renderSpy: renderOption4Spy } as any }}
value={4}
>
4
</Option>
</Select>,
);
renderOption1Spy.resetHistory();
renderOption2Spy.resetHistory();
renderOption3Spy.resetHistory();
renderOption4Spy.resetHistory();
const select = getByRole('combobox');
act(() => {
select.focus();
fireEvent.mouseDown(select); // opens and highlights '1'
});
// React renders twice in strict mode, so we expect twice the number of spy calls
expect(renderOption1Spy.callCount).to.equal(2);
fireEvent.keyDown(select, { key: 'ArrowDown' }); // highlights '2'
expect(renderOption1Spy.callCount).to.equal(4); // '1' rerenders as it loses highlight
expect(renderOption2Spy.callCount).to.equal(2); // '2' rerenders as it receives highlight
fireEvent.keyDown(select, { key: 'Enter' }); // selects '2'
expect(renderOption1Spy.callCount).to.equal(4);
expect(renderOption2Spy.callCount).to.equal(4);
// neither the highlighted nor the selected state of these options changed,
// so they don't need to rerender:
expect(renderOption3Spy.callCount).to.equal(0);
expect(renderOption4Spy.callCount).to.equal(0);
});
describe('browser autofill', () => {
it('sets value and calls external onChange when browser autofills', () => {
const onChangeHandler = spy();
const { container } = render(
<Select onChange={onChangeHandler} defaultValue="germany" autoComplete="country">
<Option value="france">France</Option>
<Option value="germany">Germany</Option>
<Option value="china">China</Option>
</Select>,
);
const hiddenInput = container.querySelector('[autocomplete="country"]');
expect(hiddenInput).not.to.eq(null);
expect(hiddenInput).to.have.value('germany');
fireEvent.change(hiddenInput!, {
target: {
value: 'france',
},
});
expect(onChangeHandler.calledOnce).to.equal(true);
expect(onChangeHandler.firstCall.args[1]).to.equal('france');
expect(hiddenInput).to.have.value('france');
});
it('does not set value when browser autofills invalid value', () => {
const onChangeHandler = spy();
const { container } = render(
<Select onChange={onChangeHandler} defaultValue="germany" autoComplete="country">
<Option value="france">France</Option>
<Option value="germany">Germany</Option>
<Option value="china">China</Option>
</Select>,
);
const hiddenInput = container.querySelector('[autocomplete="country"]');
expect(hiddenInput).not.to.eq(null);
expect(hiddenInput).to.have.value('germany');
fireEvent.change(hiddenInput!, {
target: {
value: 'portugal',
},
});
expect(onChangeHandler.called).to.equal(false);
expect(hiddenInput).to.have.value('germany');
});
it('clears value and calls external onChange when browser clears autofill', () => {
const onChangeHandler = spy();
const { container } = render(
<Select onChange={onChangeHandler} defaultValue="germany" autoComplete="country">
<Option value="france">France</Option>
<Option value="germany">Germany</Option>
<Option value="china">China</Option>
</Select>,
);
const hiddenInput = container.querySelector('[autocomplete="country"]');
expect(hiddenInput).not.to.eq(null);
expect(hiddenInput).to.have.value('germany');
fireEvent.change(hiddenInput!, {
target: {
value: '',
},
});
expect(onChangeHandler.calledOnce).to.equal(true);
expect(onChangeHandler.firstCall.args[1]).to.equal(null);
expect(hiddenInput).to.have.value('');
});
});
});
| 6,196 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Select/Select.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import {
SelectListboxSlotProps,
SelectOwnerState,
SelectPopperSlotProps,
SelectProps,
SelectRootSlotProps,
SelectType,
} from './Select.types';
import { useSelect, SelectValue } from '../useSelect';
import { useSlotProps, WithOptionalOwnerState } from '../utils';
import { Popper } from '../Popper';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getSelectUtilityClass } from './selectClasses';
import { defaultOptionStringifier } from '../useSelect/defaultOptionStringifier';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { SelectOption } from '../useOption';
import { SelectProvider } from '../useSelect/SelectProvider';
function defaultRenderValue<OptionValue>(
selectedOptions: SelectOption<OptionValue> | SelectOption<OptionValue>[] | null,
) {
if (Array.isArray(selectedOptions)) {
return <React.Fragment>{selectedOptions.map((o) => o.label).join(', ')}</React.Fragment>;
}
return selectedOptions?.label ?? null;
}
function useUtilityClasses<OptionValue extends {}, Multiple extends boolean>(
ownerState: SelectOwnerState<OptionValue, Multiple>,
) {
const { active, disabled, open, focusVisible } = ownerState;
const slots = {
root: [
'root',
disabled && 'disabled',
focusVisible && 'focusVisible',
active && 'active',
open && 'expanded',
],
listbox: ['listbox', disabled && 'disabled'],
popper: ['popper'],
};
return composeClasses(slots, useClassNamesOverride(getSelectUtilityClass));
}
/**
* The foundation for building custom-styled select components.
*
* Demos:
*
* - [Select](https://mui.com/base-ui/react-select/)
*
* API:
*
* - [Select API](https://mui.com/base-ui/react-select/components-api/#select)
*/
const Select = React.forwardRef(function Select<
OptionValue extends {},
Multiple extends boolean,
RootComponentType extends React.ElementType,
>(
props: SelectProps<OptionValue, Multiple, RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
areOptionsEqual,
autoComplete,
autoFocus,
children,
defaultValue,
defaultListboxOpen = false,
disabled: disabledProp,
getSerializedValue,
listboxId,
listboxOpen: listboxOpenProp,
multiple = false as Multiple,
name,
required = false,
onChange,
onListboxOpenChange,
getOptionAsString = defaultOptionStringifier,
renderValue: renderValueProp,
placeholder,
slotProps = {},
slots = {},
value: valueProp,
...other
} = props;
const renderValue: (option: SelectValue<SelectOption<OptionValue>, Multiple>) => React.ReactNode =
renderValueProp ?? defaultRenderValue;
const [buttonDefined, setButtonDefined] = React.useState(false);
const buttonRef = React.useRef<HTMLElement>(null);
const listboxRef = React.useRef<HTMLElement>(null);
const Button = slots.root ?? 'button';
const ListboxRoot = slots.listbox ?? 'ul';
const PopperComponent = slots.popper ?? Popper;
const handleButtonRefChange = React.useCallback((element: HTMLElement | null) => {
setButtonDefined(element != null);
}, []);
const handleButtonRef = useForkRef(forwardedRef, buttonRef, handleButtonRefChange);
React.useEffect(() => {
if (autoFocus) {
buttonRef.current!.focus();
}
}, [autoFocus]);
const {
buttonActive,
buttonFocusVisible,
contextValue,
disabled,
getButtonProps,
getListboxProps,
getHiddenInputProps,
getOptionMetadata,
value,
open,
} = useSelect({
name,
required,
getSerializedValue,
areOptionsEqual,
buttonRef: handleButtonRef,
defaultOpen: defaultListboxOpen,
defaultValue,
disabled: disabledProp,
listboxId,
multiple,
open: listboxOpenProp,
onChange,
onOpenChange: onListboxOpenChange,
getOptionAsString,
value: valueProp,
});
const ownerState: SelectOwnerState<OptionValue, Multiple> = {
...props,
active: buttonActive,
defaultListboxOpen,
disabled,
focusVisible: buttonFocusVisible,
open,
multiple,
renderValue,
value,
};
const classes = useUtilityClasses(ownerState);
const buttonProps: WithOptionalOwnerState<SelectRootSlotProps<OptionValue, Multiple>> =
useSlotProps({
elementType: Button,
getSlotProps: getButtonProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
ownerState,
className: classes.root,
});
const listboxProps: WithOptionalOwnerState<SelectListboxSlotProps<OptionValue, Multiple>> =
useSlotProps({
elementType: ListboxRoot,
getSlotProps: getListboxProps,
externalSlotProps: slotProps.listbox,
additionalProps: {
ref: listboxRef,
},
ownerState,
className: classes.listbox,
});
const popperProps: WithOptionalOwnerState<SelectPopperSlotProps<OptionValue, Multiple>> =
useSlotProps({
elementType: PopperComponent,
externalSlotProps: slotProps.popper,
additionalProps: {
anchorEl: buttonRef.current,
keepMounted: true,
open,
placement: 'bottom-start' as const,
role: undefined,
},
ownerState,
className: classes.popper,
});
let selectedOptionsMetadata: SelectValue<SelectOption<OptionValue>, Multiple>;
if (multiple) {
selectedOptionsMetadata = (value as OptionValue[])
.map((v) => getOptionMetadata(v))
.filter((o) => o !== undefined) as SelectValue<SelectOption<OptionValue>, Multiple>;
} else {
selectedOptionsMetadata = (getOptionMetadata(value as OptionValue) ?? null) as SelectValue<
SelectOption<OptionValue>,
Multiple
>;
}
return (
<React.Fragment>
<Button {...buttonProps}>
{renderValue(selectedOptionsMetadata) ?? placeholder ?? (
// fall back to a zero-width space to prevent layout shift
// from https://github.com/mui/material-ui/pull/24563
<span className="notranslate">​</span>
)}
</Button>
{buttonDefined && (
<PopperComponent {...popperProps}>
<ListboxRoot {...listboxProps}>
<SelectProvider value={contextValue}>{children}</SelectProvider>
</ListboxRoot>
</PopperComponent>
)}
<input {...getHiddenInputProps()} autoComplete={autoComplete} />
</React.Fragment>
);
}) as SelectType;
Select.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A function used to determine if two options' values are equal.
* By default, reference equality is used.
*
* There is a performance impact when using the `areOptionsEqual` prop (proportional to the number of options).
* Therefore, it's recommented to use the default reference equality comparison whenever possible.
*/
areOptionsEqual: PropTypes.func,
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the select element is focused during the first mount
* @default false
*/
autoFocus: PropTypes.bool,
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the select will be initially open.
* @default false
*/
defaultListboxOpen: PropTypes.bool,
/**
* The default selected value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the select is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* A function used to convert the option label to a string.
* It's useful when labels are elements and need to be converted to plain text
* to enable navigation using character keys on a keyboard.
*
* @default defaultOptionStringifier
*/
getOptionAsString: PropTypes.func,
/**
* A function to convert the currently selected value to a string.
* Used to set a value of a hidden input associated with the select,
* so that the selected value can be posted with a form.
*/
getSerializedValue: PropTypes.func,
/**
* `id` attribute of the listbox element.
*/
listboxId: PropTypes.string,
/**
* Controls the open state of the select's listbox.
* @default undefined
*/
listboxOpen: PropTypes.bool,
/**
* If `true`, selecting multiple values is allowed.
* This affects the type of the `value`, `defaultValue`, and `onChange` props.
*
* @default false
*/
multiple: PropTypes.bool,
/**
* Name of the element. For example used by the server to identify the fields in form submits.
* If the name is provided, the component will render a hidden input element that can be submitted to a server.
*/
name: PropTypes.string,
/**
* Callback fired when an option is selected.
*/
onChange: PropTypes.func,
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see listboxOpen).
*/
onListboxOpenChange: PropTypes.func,
/**
* Text to show when there is no selected value.
*/
placeholder: PropTypes.node,
/**
* Function that customizes the rendering of the selected value.
*/
renderValue: PropTypes.func,
/**
* If `true`, the Select cannot be empty when submitting form.
* @default false
*/
required: PropTypes.bool,
/**
* The props used for each slot inside the Input.
* @default {}
*/
slotProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({
listbox: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
popper: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Select.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes /* @typescript-to-proptypes-ignore */.shape({
listbox: PropTypes.elementType,
popper: PropTypes.elementType,
root: PropTypes.elementType,
}),
/**
* The selected value.
* Set to `null` to deselect all options.
*/
value: PropTypes.any,
} as any;
export { Select };
| 6,197 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Select/Select.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { SelectValue, UseSelectButtonSlotProps, UseSelectListboxSlotProps } from '../useSelect';
import { SelectOption } from '../useOption';
import { Popper, PopperProps } from '../Popper';
import { PolymorphicProps, SlotComponentProps, WithOptionalOwnerState } from '../utils';
export interface SelectRootSlotPropsOverrides {}
export interface SelectListboxSlotPropsOverrides {}
export interface SelectPopperSlotPropsOverrides {}
export interface SelectOwnProps<OptionValue extends {}, Multiple extends boolean> {
/**
* A function used to determine if two options' values are equal.
* By default, reference equality is used.
*
* There is a performance impact when using the `areOptionsEqual` prop (proportional to the number of options).
* Therefore, it's recommented to use the default reference equality comparison whenever possible.
*/
areOptionsEqual?: (a: OptionValue, b: OptionValue) => boolean;
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete?: string;
/**
* If `true`, the select element is focused during the first mount
* @default false
*/
autoFocus?: boolean;
children?: React.ReactNode;
className?: string;
/**
* If `true`, the select will be initially open.
* @default false
*/
defaultListboxOpen?: boolean;
/**
* The default selected value. Use when the component is not controlled.
*/
defaultValue?: SelectValue<OptionValue, Multiple>;
/**
* If `true`, the select is disabled.
* @default false
*/
disabled?: boolean;
/**
* A function to convert the currently selected value to a string.
* Used to set a value of a hidden input associated with the select,
* so that the selected value can be posted with a form.
*/
getSerializedValue?: (
option: SelectValue<SelectOption<OptionValue>, Multiple>,
) => React.InputHTMLAttributes<HTMLInputElement>['value'];
/**
* `id` attribute of the listbox element.
*/
listboxId?: string;
/**
* Controls the open state of the select's listbox.
* @default undefined
*/
listboxOpen?: boolean;
/**
* If `true`, selecting multiple values is allowed.
* This affects the type of the `value`, `defaultValue`, and `onChange` props.
*
* @default false
*/
multiple?: Multiple;
/**
* Name of the element. For example used by the server to identify the fields in form submits.
* If the name is provided, the component will render a hidden input element that can be submitted to a server.
*/
name?: string;
/**
* Callback fired when an option is selected.
*/
onChange?: (
event: React.MouseEvent | React.KeyboardEvent | React.FocusEvent | null,
value: SelectValue<OptionValue, Multiple>,
) => void;
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see listboxOpen).
*/
onListboxOpenChange?: (isOpen: boolean) => void;
/**
* A function used to convert the option label to a string.
* It's useful when labels are elements and need to be converted to plain text
* to enable navigation using character keys on a keyboard.
*
* @default defaultOptionStringifier
*/
getOptionAsString?: (option: SelectOption<OptionValue>) => string;
/**
* Function that customizes the rendering of the selected value.
*/
renderValue?: (option: SelectValue<SelectOption<OptionValue>, Multiple>) => React.ReactNode;
/**
* Text to show when there is no selected value.
*/
placeholder?: React.ReactNode;
/**
* The props used for each slot inside the Input.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<
'button',
SelectRootSlotPropsOverrides,
SelectOwnerState<OptionValue, Multiple>
>;
listbox?: SlotComponentProps<
'ul',
SelectListboxSlotPropsOverrides,
SelectOwnerState<OptionValue, Multiple>
>;
popper?: SlotComponentProps<
typeof Popper,
SelectPopperSlotPropsOverrides,
SelectOwnerState<OptionValue, Multiple>
>;
};
/**
* If `true`, the Select cannot be empty when submitting form.
* @default false
*/
required?: boolean;
/**
* The components used for each slot inside the Select.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: SelectSlots<OptionValue, Multiple>;
/**
* The selected value.
* Set to `null` to deselect all options.
*/
value?: SelectValue<OptionValue, Multiple>;
}
export interface SelectSlots<OptionValue extends {}, Multiple extends boolean> {
/**
* The component that renders the root.
* @default 'button'
*/
root?: React.ElementType;
/**
* The component that renders the listbox.
* @default 'ul'
*/
listbox?: React.ElementType;
/**
* The component that renders the popper.
* @default Popper
*/
popper?: React.ComponentType<
WithOptionalOwnerState<SelectPopperSlotProps<OptionValue, Multiple>>
>;
}
export interface SelectTypeMap<
OptionValue extends {},
Multiple extends boolean,
AdditionalProps = {},
RootComponentType extends React.ElementType = 'button',
> {
props: SelectOwnProps<OptionValue, Multiple> & AdditionalProps;
defaultComponent: RootComponentType;
}
export type SelectProps<
OptionValue extends {},
Multiple extends boolean,
RootComponentType extends React.ElementType = SelectTypeMap<
OptionValue,
Multiple
>['defaultComponent'],
> = PolymorphicProps<
SelectTypeMap<OptionValue, Multiple, {}, RootComponentType>,
RootComponentType
>;
// OverridableComponent cannot be used below as Select's props are generic.
export interface SelectType {
<
OptionValue extends {},
Multiple extends boolean = false,
RootComponentType extends React.ElementType = SelectTypeMap<
OptionValue,
Multiple
>['defaultComponent'],
>(
props: PolymorphicProps<SelectTypeMap<OptionValue, Multiple>, RootComponentType>,
): JSX.Element | null;
propTypes?: any;
displayName?: string | undefined;
}
export type SelectOwnerState<OptionValue extends {}, Multiple extends boolean> = Simplify<
SelectOwnProps<OptionValue, Multiple> & {
active: boolean;
disabled: boolean;
focusVisible: boolean;
open: boolean;
}
>;
export type SelectRootSlotProps<OptionValue extends {}, Multiple extends boolean> = Simplify<
UseSelectButtonSlotProps & {
className?: string;
children?: React.ReactNode;
ownerState: SelectOwnerState<OptionValue, Multiple>;
}
>;
export type SelectListboxSlotProps<OptionValue extends {}, Multiple extends boolean> = Simplify<
UseSelectListboxSlotProps & {
className?: string;
children?: React.ReactNode;
ownerState: SelectOwnerState<OptionValue, Multiple>;
}
>;
export type SelectPopperSlotProps<OptionValue extends {}, Multiple extends boolean> = {
anchorEl: PopperProps['anchorEl'];
children?: PopperProps['children'];
className?: string;
keepMounted: PopperProps['keepMounted'];
open: boolean;
ownerState: SelectOwnerState<OptionValue, Multiple>;
placement: PopperProps['placement'];
};
| 6,198 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Select/index.ts | 'use client';
export { Select } from './Select';
export * from './selectClasses';
export * from './Select.types';
| 6,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.