index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Select/selectClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface SelectClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the listbox element. */
listbox: string;
/** Class name applied to the popper element. */
popper: string;
/** State class applied to the root `button` element if `active={true}`. */
active: string;
/** State class applied to the root `button` element if `expanded={true}`. */
expanded: string;
/** State class applied to the root `button` element and the listbox 'ul' element if `disabled={true}`. */
disabled: string;
/** State class applied to the root `button` element if `focusVisible={true}`. */
focusVisible: string;
}
export type SelectClassKey = keyof SelectClasses;
export function getSelectUtilityClass(slot: string): string {
return generateUtilityClass('MuiSelect', slot);
}
export const selectClasses: SelectClasses = generateUtilityClasses('MuiSelect', [
'root',
'button',
'listbox',
'popper',
'active',
'expanded',
'disabled',
'focusVisible',
]);
| 6,200 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Slider/Slider.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import {
Slider,
SliderInputSlotProps,
SliderMarkLabelSlotProps,
SliderMarkSlotProps,
SliderRailSlotProps,
SliderRootSlotProps,
SliderThumbSlotProps,
SliderTrackSlotProps,
SliderValueLabelSlotProps,
} from '@mui/base/Slider';
const Root = React.forwardRef(function Root(
props: SliderRootSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const Track = React.forwardRef(function Track(
props: SliderTrackSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const Rail = React.forwardRef(function Rail(
props: SliderRailSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const Thumb = React.forwardRef(function Thumb(
props: SliderThumbSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { 'data-index': index, ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const Mark = React.forwardRef(function Mark(
props: SliderMarkSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { 'data-index': index, ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const MarkLabel = React.forwardRef(function MarkLabel(
props: SliderMarkLabelSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { 'data-index': index, ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const ValueLabel = React.forwardRef(function ValueLabel(
props: SliderValueLabelSlotProps,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const { index, open, valueLabel, ownerState, ...other } = props;
return <div data-track={ownerState.track} {...other} ref={ref} />;
});
const Input = React.forwardRef(function Input(
props: SliderInputSlotProps,
ref: React.ForwardedRef<HTMLInputElement>,
) {
const { 'data-index': index, step, ownerState, ...other } = props;
return <input data-track={ownerState.track} {...other} ref={ref} />;
});
const styledSlider = (
<Slider
slots={{ root: Root, track: Track, rail: Rail, thumb: Thumb, mark: Mark, markLabel: MarkLabel }}
/>
);
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Slider invalidProp={0} />
<Slider<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<Slider<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Slider<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<Slider<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Slider<'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,201 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Slider/Slider.test.tsx | import { expect } from 'chai';
import * as React from 'react';
import { spy, stub } from 'sinon';
import {
act,
createRenderer,
createMount,
describeConformanceUnstyled,
fireEvent,
screen,
} from '@mui-internal/test-utils';
import {
Slider,
sliderClasses as classes,
SliderRootSlotProps,
SliderValueLabelSlotProps,
} from '@mui/base/Slider';
type Touches = Array<Pick<Touch, 'identifier' | 'clientX' | 'clientY'>>;
function createTouches(touches: Touches) {
return {
changedTouches: touches.map(
(touch) =>
new Touch({
target: document.body,
...touch,
}),
),
};
}
describe('<Slider />', () => {
before(function beforeHook() {
if (typeof Touch === 'undefined') {
this.skip();
}
});
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<Slider value={0} />, () => ({
classes,
inheritComponent: 'span',
render,
mount,
refInstanceof: window.HTMLSpanElement,
testComponentPropWith: 'div',
muiName: 'MuiSlider',
slots: {
root: {
expectedClassName: classes.root,
},
thumb: {
expectedClassName: classes.thumb,
},
track: {
expectedClassName: classes.track,
},
rail: {
expectedClassName: classes.rail,
},
},
skip: ['componentProp'],
}));
it('forwards style props on the Root component', () => {
let ownerState = null;
let theme = null;
const Root = React.forwardRef(
(
{
ownerState: ownerStateProp,
theme: themeProp,
...other
}: SliderRootSlotProps & {
theme: any;
},
ref: React.ForwardedRef<HTMLSpanElement>,
) => {
ownerState = ownerStateProp;
theme = themeProp;
return <span {...other} ref={ref} />;
},
);
render(<Slider slots={{ root: Root }} />);
expect(ownerState).not.to.equal(null);
expect(theme).not.to.equal(null);
});
it('does not forward style props as DOM attributes if component slot is primitive', () => {
const elementRef = React.createRef<HTMLSpanElement>();
render(
<Slider
slots={{
root: 'span',
}}
ref={elementRef}
/>,
);
const { current: element } = elementRef;
if (element !== null) {
expect(element.getAttribute('ownerState')).to.equal(null);
expect(element.getAttribute('theme')).to.equal(null);
}
});
describe('prop: marks', () => {
it('does not cause unknown-prop error', () => {
const marks = [
{
value: 33,
},
];
expect(() => {
render(<Slider marks={marks} />);
}).not.to.throw();
});
});
describe('prop: orientation', () => {
it('sets the orientation via ARIA', () => {
render(<Slider orientation="vertical" />);
const slider = screen.getByRole('slider');
expect(slider).to.have.attribute('aria-orientation', 'vertical');
});
it('does not set the orientation via appearance for WebKit browsers', function test() {
if (/jsdom/.test(window.navigator.userAgent) || !/WebKit/.test(window.navigator.userAgent)) {
this.skip();
}
render(<Slider orientation="vertical" />);
const slider = screen.getByRole('slider');
expect(slider).to.have.property('tagName', 'INPUT');
expect(slider).to.have.property('type', 'range');
// Only relevant if we implement `[role="slider"]` with `input[type="range"]`
// We're not setting this by default because it changes horizontal keyboard navigation in WebKit: https://bugs.chromium.org/p/chromium/issues/detail?id=1162640
expect(slider).not.toHaveComputedStyle({ webkitAppearance: 'slider-vertical' });
});
});
it('renders a slider', () => {
render(<Slider value={30} />);
expect(screen.getByRole('slider')).to.have.attribute('aria-valuenow', '30');
});
type Values = Array<[string, number[]]>;
const values = [
['readonly range', Object.freeze([2, 1])],
['range', [2, 1]],
] as Values;
values.forEach(([valueLabel, value]) => {
it(`calls onChange even if the ${valueLabel} did not change`, () => {
const handleChange = spy();
render(
<Slider min={0} max={5} onChange={handleChange} value={value} data-testid="slider-root" />,
);
const sliderRoot = screen.getByTestId('slider-root');
stub(sliderRoot, 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 10,
bottom: 10,
left: 0,
x: 0,
y: 0,
right: 0,
top: 0,
toJSON() {},
}));
// pixel: 0 20 40 60 80 100
// slider: |---|---|---|---|---|
// values: 0 1 2 3 4 5
// value: ↑ ↑
// mouse: ↑
fireEvent.mouseDown(sliderRoot, {
buttons: 1,
clientX: 41,
});
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).not.to.equal(value);
expect(handleChange.args[0][1]).to.deep.equal(value.slice().sort((a, b) => a - b));
});
});
describe('prop: disabled', () => {
it('should render the disabled classes', () => {
const { container, getByRole } = render(<Slider disabled value={0} />);
expect(container.firstChild).to.have.class(classes.disabled);
expect(getByRole('slider')).not.to.have.attribute('tabIndex');
});
it('should not respond to drag events after becoming disabled', function test() {
// TODO: Don't skip once a fix for https://github.com/jsdom/jsdom/issues/3029 is released.
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
const { getByRole, setProps, getByTestId } = render(
<Slider defaultValue={0} data-testid="slider-root" />,
);
const sliderRoot = getByTestId('slider-root');
stub(sliderRoot, 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 10,
bottom: 10,
left: 0,
x: 0,
y: 0,
top: 0,
right: 0,
toJSON() {},
}));
fireEvent.touchStart(sliderRoot, createTouches([{ identifier: 1, clientX: 21, clientY: 0 }]));
const thumb = getByRole('slider');
expect(thumb).to.have.attribute('aria-valuenow', '21');
expect(thumb).toHaveFocus();
setProps({ disabled: true });
expect(thumb).not.toHaveFocus();
expect(thumb).not.to.have.class(classes.active);
fireEvent.touchMove(sliderRoot, createTouches([{ identifier: 1, clientX: 30, clientY: 0 }]));
expect(thumb).to.have.attribute('aria-valuenow', '21');
});
it('should not respond to drag events if disabled', function test() {
// TODO: Don't skip once a fix for https://github.com/jsdom/jsdom/issues/3029 is released.
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
const { getByRole, getByTestId } = render(
<Slider disabled defaultValue={21} data-testid="slider-root" />,
);
const thumb = getByRole('slider');
const sliderRoot = getByTestId('slider-root');
stub(sliderRoot, 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 10,
bottom: 10,
left: 0,
x: 0,
y: 0,
top: 0,
right: 0,
toJSON() {},
}));
fireEvent.touchStart(sliderRoot, createTouches([{ identifier: 1, clientX: 21, clientY: 0 }]));
fireEvent.touchMove(
document.body,
createTouches([{ identifier: 1, clientX: 30, clientY: 0 }]),
);
fireEvent.touchEnd(
document.body,
createTouches([{ identifier: 1, clientX: 30, clientY: 0 }]),
);
expect(thumb).to.have.attribute('aria-valuenow', '21');
});
});
describe('marks', () => {
it('should not render marks that are out of min&max bounds', function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
const { container } = render(
<Slider
marks={[
{
value: -1,
label: -1,
},
{
value: 0,
label: 0,
},
{
value: 100,
label: 100,
},
{
value: 120,
label: 120,
},
]}
/>,
);
expect(container.querySelectorAll(`.${classes.markLabel}`).length).to.equal(2);
expect(container.querySelectorAll(`.${classes.mark}`).length).to.equal(2);
expect(container.querySelectorAll(`.${classes.markLabel}`)[0].textContent).to.equal('0');
expect(container.querySelectorAll(`.${classes.markLabel}`)[1].textContent).to.equal('100');
});
});
describe('ARIA', () => {
it('should have the correct aria attributes', () => {
const { getByRole, container } = render(
<Slider
value={50}
marks={[
{
value: 0,
label: 0,
},
{
value: 50,
label: 50,
},
{
value: 100,
label: 100,
},
]}
aria-label="a slider"
aria-labelledby="a slider label"
/>,
);
const sliderWrapperElement = container.firstChild;
const slider = getByRole('slider');
const markLabels = container.querySelectorAll(`.${classes.markLabel}`);
const input = container.querySelector('input');
expect(slider).to.have.attribute('aria-valuemin', '0');
expect(slider).to.have.attribute('aria-valuemax', '100');
expect(slider).to.have.attribute('aria-valuenow', '50');
expect(slider).to.have.attribute('aria-labelledby');
expect(markLabels[0]).to.have.attribute('aria-hidden', 'true');
expect(sliderWrapperElement).not.to.have.attribute('aria-labelledby');
expect(input).to.have.attribute('aria-labelledby', 'a slider label');
expect(input).to.have.attribute('aria-label', 'a slider');
expect(input).to.have.attribute('aria-valuenow', '50');
});
});
describe('slots', () => {
it('should show the value label passed through custom value label slot', () => {
function ValueLabel({ children }: SliderValueLabelSlotProps) {
return <span data-testid="value-label">{children}</span>;
}
render(<Slider defaultValue={20} slots={{ valueLabel: ValueLabel }} />);
expect(screen.getByTestId('value-label')).to.have.text('20');
});
it('should provide focused state to the slotProps.thumb', () => {
const { getByTestId } = render(
<Slider
defaultValue={[20, 40]}
slotProps={{
thumb: (_, { index, focused, active }) => ({
'data-testid': `thumb-${index}`,
'data-focused': focused,
'data-active': active,
}),
}}
/>,
);
const firstThumb = getByTestId('thumb-0');
const secondThumb = getByTestId('thumb-1');
fireEvent.keyDown(document.body, { key: 'TAB' });
act(() => {
(firstThumb.firstChild as HTMLInputElement).focus();
});
expect(firstThumb.getAttribute('data-focused')).to.equal('true');
expect(secondThumb.getAttribute('data-focused')).to.equal('false');
act(() => {
(secondThumb.firstChild as HTMLInputElement).focus();
});
expect(firstThumb.getAttribute('data-focused')).to.equal('false');
expect(secondThumb.getAttribute('data-focused')).to.equal('true');
});
it('should provide active state to the slotProps.thumb', function test() {
// TODO: Don't skip once a fix for https://github.com/jsdom/jsdom/issues/3029 is released.
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
const { getByTestId } = render(
<Slider
defaultValue={[20, 40]}
slotProps={{
thumb: (_, { index, focused, active }) => ({
'data-testid': `thumb-${index}`,
'data-focused': focused,
'data-active': active,
}),
}}
data-testid="slider-root"
/>,
);
const sliderRoot = getByTestId('slider-root');
stub(sliderRoot, 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 10,
bottom: 10,
left: 0,
x: 0,
y: 0,
top: 0,
right: 0,
toJSON() {},
}));
fireEvent.touchStart(sliderRoot, createTouches([{ identifier: 1, clientX: 21, clientY: 0 }]));
const firstThumb = getByTestId('thumb-0');
const secondThumb = getByTestId('thumb-1');
expect(firstThumb.getAttribute('data-active')).to.equal('true');
expect(secondThumb.getAttribute('data-active')).to.equal('false');
});
});
});
| 6,202 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Slider/Slider.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes } from '@mui/utils';
import { PolymorphicComponent } from '../utils/PolymorphicComponent';
import { isHostComponent } from '../utils/isHostComponent';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getSliderUtilityClass } from './sliderClasses';
import { useSlider, valueToPercent } from '../useSlider';
import { useSlotProps } from '../utils/useSlotProps';
import { resolveComponentProps } from '../utils/resolveComponentProps';
import { SliderOwnerState, SliderProps, SliderTypeMap } from './Slider.types';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
// @ts-ignore
function Identity(x) {
return x;
}
const useUtilityClasses = (ownerState: SliderOwnerState) => {
const { disabled, dragging, marked, orientation, track } = ownerState;
const slots = {
root: [
'root',
disabled && 'disabled',
dragging && 'dragging',
marked && 'marked',
orientation === 'vertical' && 'vertical',
track === 'inverted' && 'trackInverted',
track === false && 'trackFalse',
],
rail: ['rail'],
track: ['track'],
mark: ['mark'],
markActive: ['markActive'],
markLabel: ['markLabel'],
markLabelActive: ['markLabelActive'],
valueLabel: ['valueLabel'],
thumb: ['thumb', disabled && 'disabled'],
active: ['active'],
disabled: ['disabled'],
focusVisible: ['focusVisible'],
};
return composeClasses(slots, useClassNamesOverride(getSliderUtilityClass));
};
/**
*
* Demos:
*
* - [Slider](https://mui.com/base-ui/react-slider/)
*
* API:
*
* - [Slider API](https://mui.com/base-ui/react-slider/components-api/#slider)
*/
const Slider = React.forwardRef(function Slider<RootComponentType extends React.ElementType>(
props: SliderProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
'aria-label': ariaLabel,
'aria-valuetext': ariaValuetext,
'aria-labelledby': ariaLabelledby,
className,
disableSwap = false,
disabled = false,
getAriaLabel,
getAriaValueText,
marks: marksProp = false,
max = 100,
min = 0,
name,
onChange,
onChangeCommitted,
orientation = 'horizontal',
scale = Identity,
step = 1,
tabIndex,
track = 'normal',
value: valueProp,
valueLabelFormat = Identity,
isRtl = false,
defaultValue,
slotProps = {},
slots = {},
...other
} = props;
// all props with defaults
// consider extracting to hook an reusing the lint rule for the variants
const partialOwnerState: Omit<
SliderOwnerState,
'focusedThumbIndex' | 'activeThumbIndex' | 'marked' | 'dragging'
> = {
...props,
marks: marksProp,
disabled,
disableSwap,
isRtl,
defaultValue,
max,
min,
orientation,
scale,
step,
track,
valueLabelFormat,
};
const {
axisProps,
getRootProps,
getHiddenInputProps,
getThumbProps,
active,
axis,
range,
focusedThumbIndex,
dragging,
marks,
values,
trackOffset,
trackLeap,
getThumbStyle,
} = useSlider({ ...partialOwnerState, rootRef: forwardedRef });
const ownerState: SliderOwnerState = {
...partialOwnerState,
marked: marks.length > 0 && marks.some((mark) => mark.label),
dragging,
focusedThumbIndex,
activeThumbIndex: active,
};
const classes = useUtilityClasses(ownerState);
const Root = slots.root ?? 'span';
const rootProps = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
ownerState,
className: [classes.root, className],
});
const Rail = slots.rail ?? 'span';
const railProps = useSlotProps({
elementType: Rail,
externalSlotProps: slotProps.rail,
ownerState,
className: classes.rail,
});
const Track = slots.track ?? 'span';
const trackProps = useSlotProps({
elementType: Track,
externalSlotProps: slotProps.track,
additionalProps: {
style: {
...axisProps[axis].offset(trackOffset),
...axisProps[axis].leap(trackLeap),
},
},
ownerState,
className: classes.track,
});
const Thumb = slots.thumb ?? 'span';
const thumbProps = useSlotProps({
elementType: Thumb,
getSlotProps: getThumbProps,
externalSlotProps: slotProps.thumb,
ownerState,
skipResolvingSlotProps: true,
});
const ValueLabel = slots.valueLabel;
const valueLabelProps = useSlotProps({
elementType: ValueLabel,
externalSlotProps: slotProps.valueLabel,
ownerState,
});
const Mark = slots.mark ?? 'span';
const markProps = useSlotProps({
elementType: Mark,
externalSlotProps: slotProps.mark,
ownerState,
className: classes.mark,
});
const MarkLabel = slots.markLabel ?? 'span';
const markLabelProps = useSlotProps({
elementType: MarkLabel,
externalSlotProps: slotProps.markLabel,
ownerState,
});
const Input = slots.input || 'input';
const inputProps = useSlotProps({
elementType: Input,
getSlotProps: getHiddenInputProps,
externalSlotProps: slotProps.input,
ownerState,
});
return (
<Root {...rootProps}>
<Rail {...railProps} />
<Track {...trackProps} />
{marks
.filter((mark) => mark.value >= min && mark.value <= max)
.map((mark, index) => {
const percent = valueToPercent(mark.value, min, max);
const style = axisProps[axis].offset(percent);
let markActive;
if (track === false) {
markActive = values.indexOf(mark.value) !== -1;
} else {
markActive =
(track === 'normal' &&
(range
? mark.value >= values[0] && mark.value <= values[values.length - 1]
: mark.value <= values[0])) ||
(track === 'inverted' &&
(range
? mark.value <= values[0] || mark.value >= values[values.length - 1]
: mark.value >= values[0]));
}
return (
<React.Fragment key={index}>
<Mark
data-index={index}
{...markProps}
{...(!isHostComponent(Mark) && {
markActive,
})}
style={{ ...style, ...markProps.style }}
className={clsx(markProps.className, {
[classes.markActive]: markActive,
})}
/>
{mark.label != null ? (
<MarkLabel
aria-hidden
data-index={index}
{...markLabelProps}
{...(!isHostComponent(MarkLabel) && {
markLabelActive: markActive,
})}
style={{ ...style, ...markLabelProps.style }}
className={clsx(classes.markLabel, markLabelProps.className, {
[classes.markLabelActive]: markActive,
})}
>
{mark.label}
</MarkLabel>
) : null}
</React.Fragment>
);
})}
{values.map((value, index) => {
const percent = valueToPercent(value, min, max);
const style = axisProps[axis].offset(percent);
const resolvedSlotProps = resolveComponentProps(slotProps.thumb, ownerState, {
index,
focused: focusedThumbIndex === index,
active: active === index,
});
return (
<Thumb
key={index}
data-index={index}
{...thumbProps}
{...resolvedSlotProps}
className={clsx(classes.thumb, thumbProps.className, resolvedSlotProps?.className, {
[classes.active]: active === index,
[classes.focusVisible]: focusedThumbIndex === index,
})}
style={{
...style,
...getThumbStyle(index),
...thumbProps.style,
...resolvedSlotProps?.style,
}}
>
<Input
data-index={index}
aria-label={getAriaLabel ? getAriaLabel(index) : ariaLabel}
aria-valuenow={scale(value)}
aria-labelledby={ariaLabelledby}
aria-valuetext={
getAriaValueText ? getAriaValueText(scale(value), index) : ariaValuetext
}
value={values[index]}
{...inputProps}
/>
{ValueLabel ? (
<ValueLabel
{...(!isHostComponent(ValueLabel) && {
valueLabelFormat,
index,
disabled,
})}
{...valueLabelProps}
>
{typeof valueLabelFormat === 'function'
? valueLabelFormat(scale(value), index)
: valueLabelFormat}
</ValueLabel>
) : null}
</Thumb>
);
})}
</Root>
);
}) as PolymorphicComponent<SliderTypeMap>;
Slider.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The label of the slider.
*/
'aria-label': chainPropTypes(PropTypes.string, (props) => {
const range = Array.isArray(props.value || props.defaultValue);
if (range && props['aria-label'] != null) {
return new Error(
'MUI: You need to use the `getAriaLabel` prop instead of `aria-label` when using a range slider.',
);
}
return null;
}),
/**
* The id of the element containing a label for the slider.
*/
'aria-labelledby': PropTypes.string,
/**
* A string value that provides a user-friendly name for the current value of the slider.
*/
'aria-valuetext': chainPropTypes(PropTypes.string, (props) => {
const range = Array.isArray(props.value || props.defaultValue);
if (range && props['aria-valuetext'] != null) {
return new Error(
'MUI: You need to use the `getAriaValueText` prop instead of `aria-valuetext` when using a range slider.',
);
}
return null;
}),
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]),
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb.
* @default false
*/
disableSwap: PropTypes.bool,
/**
* Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider.
* This is important for screen reader users.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaLabel: PropTypes.func,
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider.
* This is important for screen reader users.
* @param {number} value The thumb label's value to format.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaValueText: PropTypes.func,
/**
* If `true` the Slider will be rendered right-to-left (with the lowest value on the right-hand side).
* @default false
*/
isRtl: PropTypes.bool,
/**
* Marks indicate predetermined values to which the user can move the slider.
* If `true` the marks are spaced according the value of the `step` prop.
* If an array, it should contain objects with `value` and an optional `label` keys.
* @default false
*/
marks: PropTypes.oneOfType([
PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.node,
value: PropTypes.number.isRequired,
}),
),
PropTypes.bool,
]),
/**
* The maximum allowed value of the slider.
* Should not be equal to min.
* @default 100
*/
max: PropTypes.number,
/**
* The minimum allowed value of the slider.
* Should not be equal to max.
* @default 0
*/
min: PropTypes.number,
/**
* Name attribute of the hidden `input` element.
*/
name: PropTypes.string,
/**
* Callback function that is fired when the slider's value changed.
*
* @param {Event} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
* @param {number} activeThumb Index of the currently moved thumb.
*/
onChange: PropTypes.func,
/**
* Callback function that is fired when the `mouseup` is triggered.
*
* @param {React.SyntheticEvent | Event} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
*/
onChangeCommitted: PropTypes.func,
/**
* The component orientation.
* @default 'horizontal'
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* A transformation function, to change the scale of the slider.
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
scale: PropTypes.func,
/**
* The props used for each slot inside the Slider.
* @default {}
*/
slotProps: PropTypes.shape({
input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
mark: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
markLabel: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
rail: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
thumb: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
track: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
valueLabel: PropTypes.oneOfType([PropTypes.any, PropTypes.func]),
}),
/**
* The components used for each slot inside the Slider.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
input: PropTypes.elementType,
mark: PropTypes.elementType,
markLabel: PropTypes.elementType,
rail: PropTypes.elementType,
root: PropTypes.elementType,
thumb: PropTypes.elementType,
track: PropTypes.elementType,
valueLabel: PropTypes.elementType,
}),
/**
* The granularity with which the slider can step through values. (A "discrete" slider.)
* The `min` prop serves as the origin for the valid values.
* We recommend (max - min) to be evenly divisible by the step.
*
* When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
* @default 1
*/
step: PropTypes.number,
/**
* Tab index attribute of the hidden `input` element.
*/
tabIndex: PropTypes.number,
/**
* The track presentation:
*
* - `normal` the track will render a bar representing the slider value.
* - `inverted` the track will render a bar representing the remaining slider value.
* - `false` the track will render without a bar.
* @default 'normal'
*/
track: PropTypes.oneOf(['inverted', 'normal', false]),
/**
* The value of the slider.
* For ranged sliders, provide an array with two values.
*/
value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]),
/**
* The format function the value label's value.
*
* When a function is provided, it should have the following signature:
*
* - {number} value The value label's value to format
* - {number} index The value label's index to format
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
valueLabelFormat: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
} as any;
export { Slider };
| 6,203 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Slider/Slider.types.ts | import { Simplify } from '@mui/types';
import * as React from 'react';
import { PolymorphicProps, SlotComponentProps, SlotComponentPropsWithSlotState } from '../utils';
import {
UseSliderHiddenInputProps,
UseSliderParameters,
UseSliderRootSlotProps,
UseSliderThumbSlotProps,
} from '../useSlider';
export type SliderOwnerState = Simplify<
SliderOwnProps & {
disabled: boolean;
focusedThumbIndex: number;
activeThumbIndex: number;
isRtl: boolean;
max: number;
min: number;
dragging: boolean;
marked: boolean;
orientation: 'horizontal' | 'vertical';
scale: (value: number) => number;
step: number | null;
track: 'normal' | false | 'inverted';
valueLabelFormat: string | ((value: number, index: number) => React.ReactNode);
}
>;
export interface SliderRootSlotPropsOverrides {}
export interface SliderTrackSlotPropsOverrides {}
export interface SliderRailSlotPropsOverrides {}
export interface SliderThumbSlotPropsOverrides {}
export interface SliderMarkSlotPropsOverrides {}
export interface SliderMarkLabelSlotPropsOverrides {}
export interface SliderValueLabelSlotPropsOverrides {}
export interface SliderInputSlotPropsOverrides {}
export interface SliderThumbSlotState {
focused: boolean;
active: boolean;
index: number;
}
export interface SliderOwnProps extends Omit<UseSliderParameters, 'ref'> {
/**
* The label of the slider.
*/
'aria-label'?: string;
/**
* A string value that provides a user-friendly name for the current value of the slider.
*/
'aria-valuetext'?: string;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider.
* This is important for screen reader users.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaLabel?: (index: number) => string;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider.
* This is important for screen reader users.
* @param {number} value The thumb label's value to format.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaValueText?: (value: number, index: number) => string;
/**
* The props used for each slot inside the Slider.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'span', SliderRootSlotPropsOverrides, SliderOwnerState>;
track?: SlotComponentProps<'span', SliderTrackSlotPropsOverrides, SliderOwnerState>;
rail?: SlotComponentProps<'span', SliderRailSlotPropsOverrides, SliderOwnerState>;
thumb?: SlotComponentPropsWithSlotState<
'span',
SliderThumbSlotPropsOverrides,
SliderOwnerState,
SliderThumbSlotState
>;
mark?: SlotComponentProps<'span', SliderMarkSlotPropsOverrides, SliderOwnerState>;
markLabel?: SlotComponentProps<'span', SliderMarkLabelSlotPropsOverrides, SliderOwnerState>;
valueLabel?: SlotComponentProps<
React.ElementType,
SliderValueLabelSlotPropsOverrides,
SliderOwnerState
>;
input?: SlotComponentProps<'input', SliderInputSlotPropsOverrides, SliderOwnerState>;
};
/**
* The components used for each slot inside the Slider.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: SliderSlots;
/**
* The track presentation:
*
* - `normal` the track will render a bar representing the slider value.
* - `inverted` the track will render a bar representing the remaining slider value.
* - `false` the track will render without a bar.
* @default 'normal'
*/
track?: 'normal' | false | 'inverted';
/**
* The format function the value label's value.
*
* When a function is provided, it should have the following signature:
*
* - {number} value The value label's value to format
* - {number} index The value label's index to format
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
valueLabelFormat?: string | ((value: number, index: number) => React.ReactNode);
}
export interface SliderSlots {
/**
* The component that renders the root.
* @default 'span'
*/
root?: React.ElementType;
/**
* The component that renders the track.
* @default 'span'
*/
track?: React.ElementType;
/**
* The component that renders the rail.
* @default 'span'
*/
rail?: React.ElementType;
/**
* The component that renders the thumb.
* @default 'span'
*/
thumb?: React.ElementType;
/**
* The component that renders the mark.
* @default 'span'
*/
mark?: React.ElementType;
/**
* The component that renders the mark label.
* @default 'span'
*/
markLabel?: React.ElementType;
/**
* The component that renders the value label.
*/
valueLabel?: React.ElementType;
/**
* The component that renders the input.
* @default 'input'
*/
input?: React.ElementType;
}
export interface SliderTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'span',
> {
props: SliderOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type SliderProps<
RootComponentType extends React.ElementType = SliderTypeMap['defaultComponent'],
> = PolymorphicProps<SliderTypeMap<{}, RootComponentType>, RootComponentType>;
export type SliderRootSlotProps = UseSliderRootSlotProps & {
children: React.ReactNode;
className: string;
ownerState: SliderOwnerState;
};
export type SliderTrackSlotProps = {
className?: string;
ownerState: SliderOwnerState;
style: React.CSSProperties;
};
export type SliderRailSlotProps = {
className?: string;
ownerState: SliderOwnerState;
};
export type SliderThumbSlotProps = UseSliderThumbSlotProps & {
'data-index': number;
children: React.ReactNode;
className?: string;
ownerState: SliderOwnerState;
style: React.CSSProperties;
};
export type SliderMarkSlotProps = {
'data-index': number;
className?: string;
markActive?: boolean;
ownerState: SliderOwnerState;
style: React.CSSProperties;
};
export type SliderMarkLabelSlotProps = {
'aria-hidden': boolean;
'data-index': number;
className?: string;
markLabelActive?: boolean;
ownerState: SliderOwnerState;
style: React.CSSProperties;
};
export type SliderValueLabelSlotProps = {
children: React.ReactNode;
className?: string;
disabled?: boolean;
index?: number;
open?: boolean;
ownerState: SliderOwnerState;
valueLabel?: string | React.ReactNode;
valueLabelFormat?: string | ((value: number, index: number) => React.ReactNode);
};
export type SliderInputSlotProps = UseSliderHiddenInputProps & {
'aria-label': React.AriaAttributes['aria-label'];
'aria-valuenow': React.AriaAttributes['aria-valuenow'];
'aria-valuetext': React.AriaAttributes['aria-valuetext'];
'data-index': number;
ownerState: SliderOwnerState;
style: React.CSSProperties;
value: number;
};
| 6,204 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Slider/index.ts | 'use client';
export { Slider } from './Slider';
export * from './Slider.types';
export * from './sliderClasses';
| 6,205 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Slider/sliderClasses.ts | import { generateUtilityClasses } from '../generateUtilityClasses';
import { generateUtilityClass } from '../generateUtilityClass';
export interface SliderClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the root element if `marks` is provided with at least one label. */
marked: string;
/** Class name applied to the root element if `orientation="vertical"`. */
vertical: string;
/** State class applied to the root and thumb element if `disabled={true}`. */
disabled: string;
/** State class applied to the root if a thumb is being dragged. */
dragging: string;
/** Class name applied to the rail element. */
rail: string;
/** Class name applied to the track element. */
track: string;
/** Class name applied to the root element if `track={false}`. */
trackFalse: string;
/** Class name applied to the root element if `track="inverted"`. */
trackInverted: string;
/** Class name applied to the thumb element. */
thumb: string;
/** State class applied to the thumb element if it's active. */
active: string;
/** State class applied to the thumb element if keyboard focused. */
focusVisible: string;
/** Class name applied to the mark element. */
mark: string;
/** Class name applied to the mark element if active (depending on the value). */
markActive: string;
/** Class name applied to the mark label element. */
markLabel: string;
/** Class name applied to the mark label element if active (depending on the value). */
markLabelActive: string;
}
export type SliderClassKey = keyof SliderClasses;
export function getSliderUtilityClass(slot: string): string {
return generateUtilityClass('MuiSlider', slot);
}
export const sliderClasses: SliderClasses = generateUtilityClasses('MuiSlider', [
'root',
'active',
'focusVisible',
'disabled',
'dragging',
'marked',
'vertical',
'trackInverted',
'trackFalse',
'rail',
'track',
'mark',
'markActive',
'markLabel',
'markLabelActive',
'thumb',
]);
| 6,206 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Snackbar/Snackbar.spec.tsx | import * as React from 'react';
import { Snackbar, SnackbarProps, SnackbarRootSlotProps } from '@mui/base/Snackbar';
const Root = React.forwardRef(
(props: SnackbarRootSlotProps, ref: React.ForwardedRef<HTMLDivElement>) => {
const { ownerState, ...other } = props;
return !ownerState.exited && ownerState.open ? (
<div {...other} ref={ref}>
Hello World
</div>
) : null;
},
);
function SnackbarWithCustomRoot(props: SnackbarProps) {
return <Snackbar {...props} slots={{ root: Root }} />;
}
| 6,207 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Snackbar/Snackbar.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
act,
createRenderer,
createMount,
describeConformanceUnstyled,
fireEvent,
} from '@mui-internal/test-utils';
import { Snackbar, snackbarClasses as classes } from '@mui/base/Snackbar';
describe('<Snackbar />', () => {
const { clock, render: clientRender } = 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: [React.ReactElement]) {
const result = clientRender(...args);
clock.tick(0);
return result;
}
const mount = createMount();
describeConformanceUnstyled(
<Snackbar open>
<div />
</Snackbar>,
() => ({
classes,
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
muiName: 'BaseSnackbar',
slots: {
root: {
expectedClassName: classes.root,
},
},
skip: ['componentProp'],
}),
);
describe('prop: onClose', () => {
it('should be called when clicking away', () => {
const handleClose = spy();
render(
<Snackbar open onClose={handleClose}>
message
</Snackbar>,
);
const event = new window.Event('click', { bubbles: true, cancelable: true });
document.body.dispatchEvent(event);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([event, 'clickaway']);
});
it('should be called when pressing Escape', () => {
const handleClose = spy();
render(
<Snackbar open onClose={handleClose}>
message
</Snackbar>,
);
expect(fireEvent.keyDown(document.body, { key: 'Escape' })).to.equal(true);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0][1]).to.deep.equal('escapeKeyDown');
});
it('can limit which Snackbars are closed when pressing Escape', () => {
const handleCloseA = spy((event) => event.preventDefault());
const handleCloseB = spy();
render(
<React.Fragment>
<Snackbar open onClose={handleCloseA}>
messageA
</Snackbar>
,
<Snackbar open onClose={handleCloseB}>
messageB
</Snackbar>
,
</React.Fragment>,
);
fireEvent.keyDown(document.body, { key: 'Escape' });
expect(handleCloseA.callCount).to.equal(1);
expect(handleCloseB.callCount).to.equal(0);
});
});
describe('prop: autoHideDuration', () => {
it('should call onClose when the timer is done', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
const { setProps } = render(
<Snackbar open={false} onClose={handleClose} autoHideDuration={autoHideDuration}>
Hello World
</Snackbar>,
);
setProps({ open: true });
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([null, 'timeout']);
});
it('calls onClose at timeout even if the prop changes', () => {
const handleClose1 = spy();
const handleClose2 = spy();
const autoHideDuration = 2e3;
const { setProps } = render(
<Snackbar open={false} onClose={handleClose1} autoHideDuration={autoHideDuration}>
Hello World
</Snackbar>,
);
setProps({ open: true });
clock.tick(autoHideDuration / 2);
setProps({ open: true, onClose: handleClose2 });
clock.tick(autoHideDuration / 2);
expect(handleClose1.callCount).to.equal(0);
expect(handleClose2.callCount).to.equal(1);
});
it('should not call onClose when the autoHideDuration is reset', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
const { setProps } = render(
<Snackbar open={false} onClose={handleClose} autoHideDuration={autoHideDuration}>
Hello World
</Snackbar>,
);
setProps({ open: true });
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration / 2);
setProps({ autoHideDuration: undefined });
clock.tick(autoHideDuration / 2);
expect(handleClose.callCount).to.equal(0);
});
it('should not call onClose if autoHideDuration is undefined', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
render(
<Snackbar open={false} onClose={handleClose} autoHideDuration={undefined}>
Hello World
</Snackbar>,
);
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration);
expect(handleClose.callCount).to.equal(0);
});
it('should not call onClose if autoHideDuration is null', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
render(
<Snackbar open={false} onClose={handleClose} autoHideDuration={null}>
Hello World
</Snackbar>,
);
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration);
expect(handleClose.callCount).to.equal(0);
});
it('should not call onClose when closed', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
const { setProps } = render(
<Snackbar open={false} onClose={handleClose} autoHideDuration={autoHideDuration}>
Hello World
</Snackbar>,
);
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration / 2);
setProps({ open: false });
clock.tick(autoHideDuration / 2);
expect(handleClose.callCount).to.equal(0);
});
});
[
{
type: 'mouse',
enter: (container: HTMLElement) => fireEvent.mouseEnter(container.querySelector('button')!),
leave: (container: HTMLElement) => fireEvent.mouseLeave(container.querySelector('button')!),
},
{
type: 'keyboard',
enter: (container: HTMLElement) => act(() => container.querySelector('button')!.focus()),
leave: (container: HTMLElement) => act(() => container.querySelector('button')!.blur()),
},
].forEach((userInteraction) => {
describe(`interacting with ${userInteraction.type}`, () => {
it('should be able to interrupt the timer', () => {
const handleMouseEnter = spy();
const handleMouseLeave = spy();
const handleBlur = spy();
const handleFocus = spy();
const handleClose = spy();
const autoHideDuration = 2e3;
const { container } = render(
<Snackbar
open
onBlur={handleBlur}
onFocus={handleFocus}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onClose={handleClose}
autoHideDuration={autoHideDuration}
>
message
{<button>undo</button>}
</Snackbar>,
);
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration / 2);
userInteraction.enter(container.querySelector('div')!);
if (userInteraction.type === 'keyboard') {
expect(handleFocus.callCount).to.equal(1);
} else {
expect(handleMouseEnter.callCount).to.equal(1);
}
clock.tick(autoHideDuration / 2);
userInteraction.leave(container.querySelector('div')!);
if (userInteraction.type === 'keyboard') {
expect(handleBlur.callCount).to.equal(1);
} else {
expect(handleMouseLeave.callCount).to.equal(1);
}
expect(handleClose.callCount).to.equal(0);
clock.tick(2e3);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([null, 'timeout']);
});
it('should not call onClose with not timeout after user interaction', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
const resumeHideDuration = 3e3;
const { container } = render(
<Snackbar
open
onClose={handleClose}
autoHideDuration={autoHideDuration}
resumeHideDuration={resumeHideDuration}
>
message{<button>undo</button>}
</Snackbar>,
);
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration / 2);
userInteraction.enter(container.querySelector('div')!);
clock.tick(autoHideDuration / 2);
userInteraction.leave(container.querySelector('div')!);
expect(handleClose.callCount).to.equal(0);
clock.tick(2e3);
expect(handleClose.callCount).to.equal(0);
});
it('should call onClose when timer done after user interaction', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
const resumeHideDuration = 3e3;
const { container } = render(
<Snackbar
open
onClose={handleClose}
autoHideDuration={autoHideDuration}
resumeHideDuration={resumeHideDuration}
>
message{<button>undo</button>}
</Snackbar>,
);
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration / 2);
userInteraction.enter(container.querySelector('div')!);
clock.tick(autoHideDuration / 2);
userInteraction.leave(container.querySelector('div')!);
expect(handleClose.callCount).to.equal(0);
clock.tick(resumeHideDuration);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([null, 'timeout']);
});
it('should call onClose immediately after user interaction when 0', () => {
const handleClose = spy();
const autoHideDuration = 6e3;
const resumeHideDuration = 0;
const { setProps, container } = render(
<Snackbar
open
onClose={handleClose}
autoHideDuration={autoHideDuration}
resumeHideDuration={resumeHideDuration}
>
message{<button>undo</button>}
</Snackbar>,
);
setProps({ open: true });
expect(handleClose.callCount).to.equal(0);
userInteraction.enter(container.querySelector('div')!);
clock.tick(100);
userInteraction.leave(container.querySelector('div')!);
clock.tick(resumeHideDuration);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([null, 'timeout']);
});
});
});
describe('prop: disableWindowBlurListener', () => {
it('should pause auto hide when not disabled and window lost focus', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
render(
<Snackbar
open
onClose={handleClose}
autoHideDuration={autoHideDuration}
disableWindowBlurListener={false}
>
message
</Snackbar>,
);
act(() => {
const bEvent = new window.Event('blur', {
bubbles: false,
cancelable: false,
});
window.dispatchEvent(bEvent);
});
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration);
expect(handleClose.callCount).to.equal(0);
act(() => {
const fEvent = new window.Event('focus', {
bubbles: false,
cancelable: false,
});
window.dispatchEvent(fEvent);
});
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([null, 'timeout']);
});
it('should not pause auto hide when disabled and window lost focus', () => {
const handleClose = spy();
const autoHideDuration = 2e3;
render(
<Snackbar
open
onClose={handleClose}
autoHideDuration={autoHideDuration}
disableWindowBlurListener
>
message
</Snackbar>,
);
act(() => {
const event = new window.Event('blur', { bubbles: false, cancelable: false });
window.dispatchEvent(event);
});
expect(handleClose.callCount).to.equal(0);
clock.tick(autoHideDuration);
expect(handleClose.callCount).to.equal(1);
expect(handleClose.args[0]).to.deep.equal([null, 'timeout']);
});
});
describe('prop: open', () => {
it('should not render anything when closed', () => {
const { container } = render(<Snackbar open={false}>Hello, World!</Snackbar>);
expect(container).to.have.text('');
});
it('should be able show it after mounted', () => {
const { container, setProps } = render(<Snackbar open={false}>Hello, World!</Snackbar>);
expect(container).to.have.text('');
setProps({ open: true });
expect(container).to.have.text('Hello, World!');
});
});
describe('prop: children', () => {
it('should render the children', () => {
const nodeRef = React.createRef<HTMLDivElement>();
const children = <div ref={nodeRef} />;
const { container } = render(<Snackbar open>{children}</Snackbar>);
expect(container).to.contain(nodeRef.current);
});
});
});
| 6,208 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Snackbar/Snackbar.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { ClickAwayListener } from '../ClickAwayListener';
import {
SnackbarOwnerState,
SnackbarProps,
SnackbarRootSlotProps,
SnackbarTypeMap,
SnackbarClickAwayListenerSlotProps,
} from './Snackbar.types';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getSnackbarUtilityClass } from './snackbarClasses';
import { useSnackbar } from '../useSnackbar';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = () => {
const slots = {
root: ['root'],
};
return composeClasses(slots, useClassNamesOverride(getSnackbarUtilityClass));
};
/**
*
* Demos:
*
* - [Snackbar](https://mui.com/base-ui/react-snackbar/)
* - [Snackbar](https://mui.com/joy-ui/react-snackbar/)
* - [Snackbar](https://mui.com/material-ui/react-snackbar/)
*
* API:
*
* - [Snackbar API](https://mui.com/base-ui/react-snackbar/components-api/#snackbar)
*/
const Snackbar = React.forwardRef(function Snackbar<RootComponentType extends React.ElementType>(
props: SnackbarProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
autoHideDuration = null,
children,
disableWindowBlurListener = false,
exited = true,
onBlur,
onClose,
onFocus,
onMouseEnter,
onMouseLeave,
open,
resumeHideDuration,
slotProps = {},
slots = {},
...other
} = props;
const classes = useUtilityClasses();
const { getRootProps, onClickAway } = useSnackbar({
...props,
autoHideDuration,
disableWindowBlurListener,
onClose,
open,
resumeHideDuration,
});
const ownerState: SnackbarOwnerState = props;
const Root = slots.root || 'div';
const rootProps: WithOptionalOwnerState<SnackbarRootSlotProps> = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalForwardedProps: other,
externalSlotProps: slotProps.root,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
const clickAwayListenerProps: WithOptionalOwnerState<
Omit<SnackbarClickAwayListenerSlotProps, 'children'>
> = useSlotProps({
elementType: ClickAwayListener,
externalSlotProps: slotProps.clickAwayListener,
additionalProps: {
onClickAway,
},
ownerState,
});
// ClickAwayListener doesn't support ownerState
delete clickAwayListenerProps.ownerState;
// So that we only render active snackbars.
if (!open && exited) {
return null;
}
return (
<ClickAwayListener {...clickAwayListenerProps}>
<Root {...rootProps}>{children}</Root>
</ClickAwayListener>
);
}) as PolymorphicComponent<SnackbarTypeMap>;
Snackbar.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The number of milliseconds to wait before automatically calling the
* `onClose` function. `onClose` should then set the state of the `open`
* prop to hide the Snackbar. This behavior is disabled by default with
* the `null` value.
* @default null
*/
autoHideDuration: PropTypes.number,
/**
* @ignore
*/
children: PropTypes.node,
/**
* If `true`, the `autoHideDuration` timer will expire even if the window is not focused.
* @default false
*/
disableWindowBlurListener: PropTypes.bool,
/**
* The prop used to handle exited transition and unmount the component.
* @default true
*/
exited: PropTypes.bool,
/**
* Callback fired when the component requests to be closed.
* Typically `onClose` is used to set state in the parent component,
* which is used to control the `Snackbar` `open` prop.
* The `reason` parameter can optionally be used to control the response to `onClose`,
* for example ignoring `clickaway`.
*
* @param {React.SyntheticEvent<any> | Event} event The event source of the callback.
* @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`, or `"escapeKeyDown"`.
*/
onClose: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* The number of milliseconds to wait before dismissing after user interaction.
* If `autoHideDuration` prop isn't specified, it does nothing.
* If `autoHideDuration` prop is specified but `resumeHideDuration` isn't,
* we default to `autoHideDuration / 2` ms.
*/
resumeHideDuration: PropTypes.number,
/**
* The props used for each slot inside the Snackbar.
* @default {}
*/
slotProps: PropTypes.shape({
clickAwayListener: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({
children: PropTypes.element.isRequired,
disableReactTree: PropTypes.bool,
mouseEvent: PropTypes.oneOf([
'onClick',
'onMouseDown',
'onMouseUp',
'onPointerDown',
'onPointerUp',
false,
]),
onClickAway: PropTypes.func,
touchEvent: PropTypes.oneOf(['onTouchEnd', 'onTouchStart', false]),
}),
]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Snackbar.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
} as any;
export { Snackbar };
| 6,209 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Snackbar/Snackbar.types.ts | import * as React from 'react';
import { ClickAwayListener, ClickAwayListenerProps } from '../ClickAwayListener';
import { UseSnackbarParameters } from '../useSnackbar';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface SnackbarRootSlotPropsOverrides {}
export interface SnackbarClickAwayListenerSlotPropsOverrides {}
export interface SnackbarOwnProps extends Omit<UseSnackbarParameters, 'ref'> {
children?: React.ReactNode;
/**
* The components used for each slot inside the Snackbar.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: SnackbarSlots;
/**
* The props used for each slot inside the Snackbar.
* @default {}
*/
slotProps?: {
clickAwayListener?: SlotComponentProps<
typeof ClickAwayListener,
SnackbarClickAwayListenerSlotPropsOverrides,
SnackbarOwnerState
>;
root?: SlotComponentProps<'div', SnackbarRootSlotPropsOverrides, SnackbarOwnerState>;
};
/**
* The prop used to handle exited transition and unmount the component.
* @default true
*/
exited?: boolean;
}
export interface SnackbarSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export interface SnackbarTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: SnackbarOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type SnackbarProps<
RootComponentType extends React.ElementType = SnackbarTypeMap['defaultComponent'],
> = PolymorphicProps<SnackbarTypeMap<{}, RootComponentType>, RootComponentType>;
export type SnackbarOwnerState = SnackbarOwnProps;
export type SnackbarRootSlotProps = {
ownerState: SnackbarOwnerState;
className?: string;
children?: React.ReactNode;
ref: React.Ref<any>;
};
export interface SnackbarClickAwayListenerSlotProps extends ClickAwayListenerProps {
ownerState: SnackbarOwnerState;
}
| 6,210 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Snackbar/index.ts | 'use client';
export { Snackbar } from './Snackbar';
export * from './Snackbar.types';
export * from './snackbarClasses';
| 6,211 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Snackbar/snackbarClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface SnackbarClasses {
/** Class name applied to the root element. */
root: string;
}
export function getSnackbarUtilityClass(slot: string): string {
return generateUtilityClass('MuiSnackbar', slot);
}
export const snackbarClasses: SnackbarClasses = generateUtilityClasses('MuiSnackbar', ['root']);
| 6,212 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Switch/Switch.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import {
Switch,
SwitchRootSlotProps,
SwitchThumbSlotProps,
SwitchTrackSlotProps,
SwitchInputSlotProps,
} from '@mui/base/Switch';
const Root = React.forwardRef(function Root(
props: SwitchRootSlotProps,
ref: React.Ref<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-checked={ownerState.checked} {...other} ref={ref} />;
});
const Input = React.forwardRef(function Input(
props: SwitchInputSlotProps,
ref: React.Ref<HTMLInputElement>,
) {
const { ownerState, ...other } = props;
return <input data-checked={ownerState.checked} {...other} ref={ref} />;
});
const Thumb = React.forwardRef(function Thumb(
props: SwitchThumbSlotProps,
ref: React.Ref<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-checked={ownerState.checked} {...other} ref={ref} />;
});
const Track = React.forwardRef(function Track(
props: SwitchTrackSlotProps,
ref: React.Ref<HTMLDivElement>,
) {
const { ownerState, ...other } = props;
return <div data-checked={ownerState.checked} {...other} ref={ref} />;
});
const styledSwitch = <Switch slots={{ root: Root, thumb: Thumb, track: Track, input: Input }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Switch invalidProp={0} />
<Switch<'a'>
slots={{
root: 'a',
}}
href="#"
/>
<Switch<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Switch<typeof CustomComponent>
slots={{
root: CustomComponent,
}}
/>
<Switch<'button'>
slots={{
root: 'button',
}}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Switch<'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,213 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Switch/Switch.test.tsx | import * as React from 'react';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { expect } from 'chai';
import { Switch, SwitchOwnerState, switchClasses } from '@mui/base/Switch';
describe('<Switch />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<Switch />, () => ({
inheritComponent: 'span',
render,
mount,
refInstanceof: window.HTMLSpanElement,
testComponentPropWith: 'span',
muiName: 'MuiSwitch',
slots: {
root: {
expectedClassName: switchClasses.root,
},
thumb: {
expectedClassName: switchClasses.thumb,
},
input: {
testWithElement: 'input',
expectedClassName: switchClasses.input,
},
track: {
expectedClassName: switchClasses.track,
isOptional: true,
},
},
skip: ['componentProp'],
}));
describe('componentState', () => {
it('passes the ownerState prop to all the slots', () => {
interface CustomSlotProps {
ownerState: SwitchOwnerState;
children?: React.ReactNode;
}
const CustomSlot = React.forwardRef(
({ ownerState: sp, children }: CustomSlotProps, ref: React.Ref<any>) => {
return (
<div
ref={ref}
data-checked={sp.checked}
data-disabled={sp.disabled}
data-readonly={sp.readOnly}
data-focusvisible={sp.focusVisible}
data-testid="custom"
>
{children}
</div>
);
},
);
const slots = {
root: CustomSlot,
input: CustomSlot,
thumb: CustomSlot,
};
const { getAllByTestId } = render(<Switch defaultChecked disabled slots={slots} />);
const renderedComponents = getAllByTestId('custom');
expect(renderedComponents.length).to.equal(3);
for (let i = 0; i < renderedComponents.length; i += 1) {
expect(renderedComponents[i]).to.have.attribute('data-checked', 'true');
expect(renderedComponents[i]).to.have.attribute('data-disabled', 'true');
expect(renderedComponents[i]).to.have.attribute('data-readonly', 'false');
expect(renderedComponents[i]).to.have.attribute('data-focusvisible', 'false');
}
});
});
});
| 6,214 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Switch/Switch.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 { useSwitch } from '../useSwitch';
import {
SwitchProps,
SwitchOwnerState,
SwitchInputSlotProps,
SwitchRootSlotProps,
SwitchThumbSlotProps,
SwitchTrackSlotProps,
SwitchTypeMap,
} from './Switch.types';
import { useSlotProps, WithOptionalOwnerState } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { getSwitchUtilityClass } from './switchClasses';
const useUtilityClasses = (ownerState: SwitchOwnerState) => {
const { checked, disabled, focusVisible, readOnly } = ownerState;
const slots = {
root: [
'root',
checked && 'checked',
disabled && 'disabled',
focusVisible && 'focusVisible',
readOnly && 'readOnly',
],
thumb: ['thumb'],
input: ['input'],
track: ['track'],
};
return composeClasses(slots, useClassNamesOverride(getSwitchUtilityClass));
};
/**
* The foundation for building custom-styled switches.
*
* Demos:
*
* - [Switch](https://mui.com/base-ui/react-switch/)
*
* API:
*
* - [Switch API](https://mui.com/base-ui/react-switch/components-api/#switch)
*/
const Switch = React.forwardRef(function Switch<RootComponentType extends React.ElementType>(
props: SwitchProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
checked: checkedProp,
defaultChecked,
disabled: disabledProp,
onBlur,
onChange,
onFocus,
onFocusVisible,
readOnly: readOnlyProp,
required,
slotProps = {},
slots = {},
...other
} = props;
const { getInputProps, checked, disabled, focusVisible, readOnly } = useSwitch(props);
const ownerState: SwitchOwnerState = {
...props,
checked,
disabled,
focusVisible,
readOnly,
};
const classes = useUtilityClasses(ownerState);
const Root: React.ElementType = slots.root ?? 'span';
const rootProps: WithOptionalOwnerState<SwitchRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
const Thumb: React.ElementType = slots.thumb ?? 'span';
const thumbProps: WithOptionalOwnerState<SwitchThumbSlotProps> = useSlotProps({
elementType: Thumb,
externalSlotProps: slotProps.thumb,
ownerState,
className: classes.thumb,
});
const Input: React.ElementType = slots.input ?? 'input';
const inputProps: WithOptionalOwnerState<SwitchInputSlotProps> = useSlotProps({
elementType: Input,
getSlotProps: getInputProps,
externalSlotProps: slotProps.input,
ownerState,
className: classes.input,
});
const Track: React.ElementType = slots.track === null ? () => null : slots.track ?? 'span';
const trackProps: WithOptionalOwnerState<SwitchTrackSlotProps> = useSlotProps({
elementType: Track,
externalSlotProps: slotProps.track,
ownerState,
className: classes.track,
});
return (
<Root {...rootProps}>
<Track {...trackProps} />
<Thumb {...thumbProps} />
<Input {...inputProps} />
</Root>
);
}) as PolymorphicComponent<SwitchTypeMap>;
Switch.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the component is checked.
*/
checked: PropTypes.bool,
/**
* Class name applied to the root element.
*/
className: PropTypes.string,
/**
* The default checked state. Use when the component is not controlled.
*/
defaultChecked: PropTypes.bool,
/**
* If `true`, the component is disabled.
*/
disabled: PropTypes.bool,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the state is changed.
*
* @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* @ignore
*/
onFocusVisible: PropTypes.func,
/**
* If `true`, the component is read only.
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element is required.
*/
required: PropTypes.bool,
/**
* The props used for each slot inside the Switch.
* @default {}
*/
slotProps: PropTypes.shape({
input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
thumb: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
track: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Switch.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes /* @typescript-to-proptypes-ignore */.shape({
input: PropTypes.elementType,
root: PropTypes.elementType,
thumb: PropTypes.elementType,
track: PropTypes.oneOfType([PropTypes.elementType, PropTypes.oneOf([null])]),
}),
} as any;
export { Switch };
| 6,215 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Switch/Switch.types.ts | import { Simplify } from '@mui/types';
import { PolymorphicProps, SlotComponentProps } from '../utils';
import { UseSwitchInputSlotProps, UseSwitchParameters } from '../useSwitch';
export interface SwitchRootSlotPropsOverrides {}
export interface SwitchThumbSlotPropsOverrides {}
export interface SwitchInputSlotPropsOverrides {}
export interface SwitchTrackSlotPropsOverrides {}
export interface SwitchOwnProps extends UseSwitchParameters {
/**
* Class name applied to the root element.
*/
className?: string;
/**
* The components used for each slot inside the Switch.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: SwitchSlots;
/**
* The props used for each slot inside the Switch.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'span', SwitchRootSlotPropsOverrides, SwitchOwnerState>;
thumb?: SlotComponentProps<'span', SwitchThumbSlotPropsOverrides, SwitchOwnerState>;
input?: SlotComponentProps<'input', SwitchInputSlotPropsOverrides, SwitchOwnerState>;
track?: SlotComponentProps<'span', SwitchTrackSlotPropsOverrides, SwitchOwnerState>;
};
}
export interface SwitchSlots {
/**
* The component that renders the root.
* @default 'span'
*/
root?: React.ElementType;
/**
* The component that renders the input.
* @default 'input'
*/
input?: React.ElementType;
/**
* The component that renders the thumb.
* @default 'span'
*/
thumb?: React.ElementType;
/**
* The component that renders the track.
* @default 'span'
*/
track?: React.ElementType | null;
}
export interface SwitchTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'span',
> {
props: SwitchOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type SwitchProps<
RootComponentType extends React.ElementType = SwitchTypeMap['defaultComponent'],
> = PolymorphicProps<SwitchTypeMap<{}, RootComponentType>, RootComponentType>;
export type SwitchOwnerState = Simplify<
SwitchOwnProps & {
checked: boolean;
disabled: boolean;
focusVisible: boolean;
readOnly: boolean;
}
>;
export type SwitchRootSlotProps = {
ownerState: SwitchOwnerState;
className?: string;
children?: React.ReactNode;
};
export type SwitchThumbSlotProps = {
ownerState: SwitchOwnerState;
className?: string;
children?: React.ReactNode;
};
export type SwitchTrackSlotProps = {
ownerState: SwitchOwnerState;
className?: string;
children?: React.ReactNode;
};
export type SwitchInputSlotProps = Simplify<
UseSwitchInputSlotProps & {
ownerState: SwitchOwnerState;
className?: string;
children?: React.ReactNode;
}
>;
| 6,216 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Switch/index.ts | 'use client';
export { Switch } from './Switch';
export * from './Switch.types';
export * from './switchClasses';
| 6,217 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Switch/switchClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface SwitchClasses {
/** Class applied to the root element. */
root: string;
/** Class applied to the internal input element */
input: string;
/** Class applied to the track element */
track: string;
/** Class applied to the thumb element */
thumb: string;
/** State class applied to the root element if the switch is checked */
checked: string;
/** State class applied to the root element if the switch is disabled */
disabled: string;
/** State class applied to the root element if the switch has visible focus */
focusVisible: string;
/** Class applied to the root element if the switch is read-only */
readOnly: string;
}
export type SwitchClassKey = keyof SwitchClasses;
export function getSwitchUtilityClass(slot: string): string {
return generateUtilityClass('MuiSwitch', slot);
}
export const switchClasses: SwitchClasses = generateUtilityClasses('MuiSwitch', [
'root',
'input',
'track',
'thumb',
'checked',
'disabled',
'focusVisible',
'readOnly',
]);
| 6,218 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tab/Tab.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Tab, TabRootSlotProps } from '@mui/base/Tab';
function Root(props: TabRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-active={ownerState.active} {...other} />;
}
const styledTab = <Tab value={0} slots={{ root: Root }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Tab value={0} invalidProp={0} />
<Tab value={0} slots={{ root: 'a' }} href="#" />
<Tab<typeof CustomComponent>
value={0}
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<Tab value={0} slots={{ root: { CustomComponent } }} />
<Tab
value={0}
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Tab<'button'>
value={0}
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,219 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tab/Tab.test.tsx | import * as React from 'react';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { Tab, tabClasses } from '@mui/base/Tab';
import { TabsListProvider, TabsListProviderValue } from '../useTabsList';
import { TabsContext } from '../Tabs';
describe('<Tab />', () => {
const mount = createMount();
const { render } = createRenderer();
const testTabsListContext: TabsListProviderValue = {
dispatch: () => {},
registerItem: () => ({ id: 0, deregister: () => {} }),
getItemIndex: () => 0,
totalSubitemCount: 1,
getItemState() {
return { disabled: false, highlighted: false, selected: false, focusable: true, index: 0 };
},
};
describeConformanceUnstyled(<Tab value="1" />, () => ({
inheritComponent: 'div',
render: (node) => {
const { container, ...other } = render(
<TabsContext.Provider
value={{
value: 0,
onSelected() {},
registerTabIdLookup() {},
getTabId: () => '',
getTabPanelId: () => '',
}}
>
<TabsListProvider value={testTabsListContext}>{node}</TabsListProvider>
</TabsContext.Provider>,
);
return { container, ...other };
},
mount: (node: any) => {
const wrapper = mount(
<TabsContext.Provider
value={{
value: 0,
onSelected() {},
registerTabIdLookup() {},
getTabId: () => '',
getTabPanelId: () => '',
}}
>
<TabsListProvider value={testTabsListContext}>{node}</TabsListProvider>
</TabsContext.Provider>,
);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLButtonElement,
testComponentPropWith: 'div',
muiName: 'MuiTab',
slots: {
root: {
expectedClassName: tabClasses.root,
},
},
skip: [
'reactTestRenderer', // Need to be wrapped with TabsContext
'componentProp',
],
}));
});
| 6,220 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tab/Tab.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 { getTabUtilityClass } from './tabClasses';
import { TabProps, TabTypeMap, TabRootSlotProps, TabOwnerState } from './Tab.types';
import { useTab } from '../useTab';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: TabOwnerState) => {
const { selected, disabled } = ownerState;
const slots = {
root: ['root', selected && 'selected', disabled && 'disabled'],
};
return composeClasses(slots, useClassNamesOverride(getTabUtilityClass));
};
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/)
*
* API:
*
* - [Tab API](https://mui.com/base-ui/react-tabs/components-api/#tab)
*/
const Tab = React.forwardRef(function Tab<RootComponentType extends React.ElementType>(
props: TabProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
action,
children,
disabled = false,
onChange,
onClick,
onFocus,
slotProps = {},
slots = {},
value,
...other
} = props;
const tabRef = React.useRef<HTMLButtonElement | HTMLAnchorElement | HTMLElement>();
const handleRef = useForkRef(tabRef, forwardedRef);
const { active, highlighted, selected, getRootProps } = useTab({
...props,
rootRef: handleRef,
value,
});
const ownerState: TabOwnerState = {
...props,
active,
disabled,
highlighted,
selected,
};
const classes = useUtilityClasses(ownerState);
const TabRoot: React.ElementType = slots.root ?? 'button';
const tabRootProps: WithOptionalOwnerState<TabRootSlotProps> = useSlotProps({
elementType: TabRoot,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
return <TabRoot {...tabRootProps}>{children}</TabRoot>;
}) as PolymorphicComponent<TabTypeMap>;
Tab.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,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* Callback invoked when new value is being set.
*/
onChange: PropTypes.func,
/**
* The props used for each slot inside the Tab.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Tab.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* You can provide your own value. Otherwise, it falls back to the child position index.
*/
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
} as any;
export { Tab };
| 6,221 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tab/Tab.types.ts | import { Simplify } from '@mui/types';
import * as React from 'react';
import { ButtonOwnProps } from '../Button';
import { SlotComponentProps } from '../utils';
import { UseTabRootSlotProps } from '../useTab';
import { PolymorphicProps } from '../utils/PolymorphicComponent';
export interface TabRootSlotPropsOverrides {}
export interface TabOwnProps extends Omit<ButtonOwnProps, 'onChange' | 'slots' | 'slotProps'> {
/**
* You can provide your own value. Otherwise, it falls back to the child position index.
*/
value?: number | string;
/**
* Callback invoked when new value is being set.
*/
onChange?: (event: React.SyntheticEvent, value: number | string) => void;
/**
* The props used for each slot inside the Tab.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'button', TabRootSlotPropsOverrides, TabOwnerState>;
};
/**
* The components used for each slot inside the Tab.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: TabSlots;
}
export interface TabSlots {
/**
* The component that renders the root.
* @default 'button'
*/
root?: React.ElementType;
}
export type TabProps<RootComponentType extends React.ElementType = TabTypeMap['defaultComponent']> =
PolymorphicProps<TabTypeMap<{}, RootComponentType>, RootComponentType>;
export interface TabTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'button',
> {
props: TabOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type TabOwnerState = Simplify<
TabOwnProps & {
active: boolean;
disabled: boolean;
highlighted: boolean;
selected: boolean;
}
>;
export type TabRootSlotProps = Simplify<
UseTabRootSlotProps & {
className?: string;
ref: React.Ref<any>;
ownerState: TabOwnerState;
}
>;
| 6,222 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tab/index.ts | 'use client';
export { Tab } from './Tab';
export * from './Tab.types';
export * from './tabClasses';
| 6,223 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tab/tabClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface TabClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root `button` element if `selected={true}`. */
selected: string;
/** State class applied to the root `button` element if `disabled={true}`. */
disabled: string;
}
export type TabClassKey = keyof TabClasses;
export function getTabUtilityClass(slot: string): string {
return generateUtilityClass('MuiTab', slot);
}
export const tabClasses: TabClasses = generateUtilityClasses('MuiTab', [
'root',
'selected',
'disabled',
]);
| 6,224 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabPanel/TabPanel.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { TabPanel, TabPanelRootSlotProps } from '@mui/base/TabPanel';
function Root(props: TabPanelRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-hidden={ownerState.hidden} {...other} />;
}
const styledTabPanel = <TabPanel slots={{ root: Root }} value={0} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<TabPanel value={1} invalidProp={0} />
<TabPanel<'a'> value={1} slots={{ root: 'a' }} href="#" />
<TabPanel<typeof CustomComponent>
value={1}
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<TabPanel<typeof CustomComponent> value={1} slots={{ root: CustomComponent }} />
<TabPanel<'button'>
value={1}
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<TabPanel<'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,225 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabPanel/TabPanel.test.tsx | import * as React from 'react';
import { createMount, createRenderer, describeConformanceUnstyled } from '@mui-internal/test-utils';
import { TabPanel, tabPanelClasses } from '@mui/base/TabPanel';
import { TabsProvider, TabsProviderValue } from '../useTabs';
describe('<TabPanel />', () => {
const mount = createMount();
const { render } = createRenderer();
const tabsProviderDefaultValue: TabsProviderValue = {
value: '1',
onSelected: () => {},
registerTabIdLookup() {},
getTabId: () => '',
getTabPanelId: () => '',
getItemIndex: () => 0,
registerItem: () => ({ id: 0, deregister: () => {} }),
totalSubitemCount: 1,
direction: 'ltr',
orientation: 'horizontal',
selectionFollowsFocus: false,
};
describeConformanceUnstyled(<TabPanel value="1" />, () => ({
inheritComponent: 'div',
render: (node) => {
const { container, ...other } = render(
<TabsProvider value={tabsProviderDefaultValue}>{node}</TabsProvider>,
);
return { container, ...other };
},
mount: (node: any) => {
const wrapper = mount(<TabsProvider value={tabsProviderDefaultValue}>{node}</TabsProvider>);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'div',
muiName: 'MuiTabPanel',
slots: {
root: {
expectedClassName: tabPanelClasses.root,
},
},
skip: [
'reactTestRenderer', // Need to be wrapped with TabsContext
'componentProp',
],
}));
});
| 6,226 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabPanel/TabPanel.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getTabPanelUtilityClass } from './tabPanelClasses';
import { useTabPanel } from '../useTabPanel/useTabPanel';
import {
TabPanelOwnerState,
TabPanelProps,
TabPanelRootSlotProps,
TabPanelTypeMap,
} from './TabPanel.types';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: { hidden: boolean }) => {
const { hidden } = ownerState;
const slots = {
root: ['root', hidden && 'hidden'],
};
return composeClasses(slots, useClassNamesOverride(getTabPanelUtilityClass));
};
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/)
*
* API:
*
* - [TabPanel API](https://mui.com/base-ui/react-tabs/components-api/#tab-panel)
*/
const TabPanel = React.forwardRef(function TabPanel<RootComponentType extends React.ElementType>(
props: TabPanelProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const { children, value, slotProps = {}, slots = {}, ...other } = props;
const { hidden, getRootProps } = useTabPanel(props);
const ownerState: TabPanelOwnerState = {
...props,
hidden,
};
const classes = useUtilityClasses(ownerState);
const TabPanelRoot: React.ElementType = slots.root ?? 'div';
const tabPanelRootProps: WithOptionalOwnerState<TabPanelRootSlotProps> = useSlotProps({
elementType: TabPanelRoot,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
role: 'tabpanel',
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
return <TabPanelRoot {...tabPanelRootProps}>{!hidden && children}</TabPanelRoot>;
}) as PolymorphicComponent<TabPanelTypeMap>;
TabPanel.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.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The props used for each slot inside the TabPanel.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the TabPanel.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* The value of the TabPanel. It will be shown when the Tab with the corresponding value is selected.
* If not provided, it will fall back to the index of the panel.
* It is recommended to explicitly provide it, as it's required for the tab panel to be rendered on the server.
*/
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
} as any;
export { TabPanel };
| 6,227 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabPanel/TabPanel.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { UseTabPanelRootSlotProps } from '../useTabPanel';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface TabPanelRootSlotPropsOverrides {}
export interface TabPanelOwnProps {
/**
* The content of the component.
*/
children?: React.ReactNode;
className?: string;
/**
* The value of the TabPanel. It will be shown when the Tab with the corresponding value is selected.
* If not provided, it will fall back to the index of the panel.
* It is recommended to explicitly provide it, as it's required for the tab panel to be rendered on the server.
*/
value?: number | string;
/**
* The components used for each slot inside the TabPanel.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: TabPanelSlots;
/**
* The props used for each slot inside the TabPanel.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', TabPanelRootSlotPropsOverrides, TabPanelOwnerState>;
};
}
export interface TabPanelSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export interface TabPanelTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: TabPanelOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type TabPanelProps<
RootComponentType extends React.ElementType = TabPanelTypeMap['defaultComponent'],
> = PolymorphicProps<TabPanelTypeMap<{}, RootComponentType>, RootComponentType>;
export type TabPanelOwnerState = Simplify<
TabPanelOwnProps & {
hidden: boolean;
}
>;
export type TabPanelRootSlotProps = UseTabPanelRootSlotProps & {
children?: React.ReactNode;
className?: string;
ownerState: TabPanelOwnerState;
ref: React.Ref<any>;
role: React.AriaRole;
};
| 6,228 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabPanel/index.ts | 'use client';
export { TabPanel } from './TabPanel';
export * from './TabPanel.types';
export * from './tabPanelClasses';
| 6,229 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabPanel/tabPanelClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface TabPanelClasses {
/** Class name applied to the root element. */
root: string;
/** State class applied to the root `div` element if `hidden={true}`. */
hidden: string;
}
export type TabPanelClassKey = keyof TabPanelClasses;
export function getTabPanelUtilityClass(slot: string): string {
return generateUtilityClass('MuiTabPanel', slot);
}
export const tabPanelClasses: TabPanelClasses = generateUtilityClasses('MuiTabPanel', [
'root',
'hidden',
]);
| 6,230 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePagination.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { TablePagination } from '@mui/base/TablePagination';
import {
TablePaginationActionsSlotProps,
TablePaginationDisplayedRowsSlotProps,
TablePaginationMenuItemSlotProps,
TablePaginationRootSlotProps,
TablePaginationSelectLabelSlotProps,
TablePaginationSelectSlotProps,
TablePaginationSpacerSlotProps,
TablePaginationToolbarSlotProps,
} from './TablePagination.types';
function Root(props: TablePaginationRootSlotProps) {
const { ownerState, ...other } = props;
return <td data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function Select(props: TablePaginationSelectSlotProps) {
const { ownerState, ...other } = props;
return <input data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function Actions(props: TablePaginationActionsSlotProps) {
const { ownerState, onPageChange, getItemAriaLabel, count, page, rowsPerPage, ...other } = props;
return <div data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function MenuItem(props: TablePaginationMenuItemSlotProps) {
const { ownerState, ...other } = props;
return <option data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function SelectLabel(props: TablePaginationSelectLabelSlotProps) {
const { ownerState, ...other } = props;
return <p data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function DisplayedRows(props: TablePaginationDisplayedRowsSlotProps) {
const { ownerState, ...other } = props;
return <p data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function Toolbar(props: TablePaginationToolbarSlotProps) {
const { ownerState, ...other } = props;
return <div data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function Spacer(props: TablePaginationSpacerSlotProps) {
const { ownerState, ...other } = props;
return <div data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
const styledTablePagination = (
<TablePagination
count={10}
onPageChange={() => {}}
page={0}
rowsPerPage={10}
slots={{
root: Root,
actions: Actions,
select: Select,
menuItem: MenuItem,
selectLabel: SelectLabel,
displayedRows: DisplayedRows,
toolbar: Toolbar,
spacer: Spacer,
}}
slotProps={{
actions: {
showFirstButton: true,
showLastButton: true,
},
}}
/>
);
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
const requiredProps = {
count: 10,
getItemAriaLabel: () => '',
onPageChange: () => {},
page: 0,
rowsPerPage: 10,
showFirstButton: true,
showLastButton: true,
};
return (
<div>
{/* @ts-expect-error */}
<TablePagination {...requiredProps} invalidProp={0} />
<TablePagination<'a'> {...requiredProps} slots={{ root: 'a' }} href="#" />
<TablePagination<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<TablePagination<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
/>
<TablePagination<'button'>
{...requiredProps}
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<TablePagination<'button'>
{...requiredProps}
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,231 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePagination.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import PropTypes from 'prop-types';
import {
describeConformanceUnstyled,
fireEvent,
createRenderer,
createMount,
} from '@mui-internal/test-utils';
import TableFooter from '@mui/material/TableFooter';
import TableRow from '@mui/material/TableRow';
import {
TablePagination,
tablePaginationClasses as classes,
LabelDisplayedRowsArgs,
} from '@mui/base/TablePagination';
interface WithClassName {
className: string;
}
describe('<TablePagination />', () => {
const noop = () => {};
const { render } = createRenderer();
const mount = createMount();
const CustomRootComponent = React.forwardRef(
({ className }: WithClassName, ref: React.Ref<any>) => (
<th className={className} ref={ref} data-testid="custom" />
),
);
describeConformanceUnstyled(
<TablePagination count={1} onPageChange={noop} page={0} rowsPerPage={10} />,
() => ({
inheritComponent: 'td',
render: (node) => {
const { container, ...other } = render(
<table>
<tbody>
<tr>{node}</tr>
</tbody>
</table>,
);
return {
container: container?.firstChild?.firstChild?.firstChild as HTMLElement,
...other,
};
},
mount: (node: any) => {
const wrapper = mount(
<table>
<tbody>
<tr>{node}</tr>
</tbody>
</table>,
);
return wrapper.find('tr').childAt(0);
},
refInstanceof: window.HTMLTableCellElement,
testComponentPropWith: 'th',
muiName: 'MuiTablePagination',
slots: {
root: {
expectedClassName: classes.root,
testWithComponent: CustomRootComponent as any,
testWithElement: 'th',
},
},
skip: ['componentProp'],
}),
);
describe('prop: labelDisplayedRows', () => {
it('should use the labelDisplayedRows callback', () => {
let labelDisplayedRowsCalled = false;
function labelDisplayedRows({ from, to, count, page }: LabelDisplayedRowsArgs) {
labelDisplayedRowsCalled = true;
expect(from).to.equal(11);
expect(to).to.equal(20);
expect(count).to.equal(42);
expect(page).to.equal(1);
return `Page ${page}`;
}
const { container } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={42}
page={1}
onPageChange={noop}
onRowsPerPageChange={noop}
rowsPerPage={10}
labelDisplayedRows={labelDisplayedRows}
/>
</TableRow>
</TableFooter>
</table>,
);
expect(labelDisplayedRowsCalled).to.equal(true);
expect(container.innerHTML.includes('Page 1')).to.equal(true);
});
});
describe('prop: labelRowsPerPage', () => {
it('labels the select for the current page', () => {
const { container } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={1}
page={0}
onPageChange={noop}
onRowsPerPageChange={noop}
rowsPerPage={10}
labelRowsPerPage="lines per page:"
/>
</TableRow>
</TableFooter>
</table>,
);
const combobox = container.getElementsByTagName('select')[0];
expect(combobox).toHaveAccessibleName('lines per page: 10');
});
it('accepts React nodes', () => {
const { container } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={1}
page={0}
onPageChange={noop}
onRowsPerPageChange={noop}
rowsPerPage={10}
labelRowsPerPage={
<React.Fragment>
<em>lines</em> per page:
</React.Fragment>
}
/>
</TableRow>
</TableFooter>
</table>,
);
// will be `getByRole('combobox')` in aria 1.2
const combobox = container.getElementsByTagName('select')[0];
expect(combobox).toHaveAccessibleName('lines per page: 10');
});
});
describe('prop: page', () => {
it('should disable the back button on the first page', () => {
const { getByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={11}
page={0}
onPageChange={noop}
onRowsPerPageChange={noop}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
</table>,
);
const nextButton = getByRole('button', { name: 'Go to next page' });
const backButton = getByRole('button', { name: 'Go to previous page' });
expect(backButton).to.have.property('disabled', true);
expect(nextButton).to.have.property('disabled', false);
});
it('should disable the next button on the last page', () => {
const { getByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={11}
page={1}
onPageChange={noop}
onRowsPerPageChange={noop}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
</table>,
);
const nextButton = getByRole('button', { name: 'Go to next page' });
const backButton = getByRole('button', { name: 'Go to previous page' });
expect(backButton).to.have.property('disabled', false);
expect(nextButton).to.have.property('disabled', true);
});
});
describe('prop: onPageChange', () => {
it('should handle next button clicks properly', () => {
let page = 1;
const { getByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={30}
page={page}
onPageChange={(event, nextPage) => {
page = nextPage;
}}
onRowsPerPageChange={noop}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
</table>,
);
const nextButton = getByRole('button', { name: 'Go to next page' });
fireEvent.click(nextButton);
expect(page).to.equal(2);
});
it('should handle back button clicks properly', () => {
let page = 1;
const { getByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={30}
page={page}
onPageChange={(event, nextPage) => {
page = nextPage;
}}
onRowsPerPageChange={noop}
rowsPerPage={10}
/>
</TableRow>
</TableFooter>
</table>,
);
const backButton = getByRole('button', { name: 'Go to previous page' });
fireEvent.click(backButton);
expect(page).to.equal(0);
});
});
describe('label', () => {
it('should display 0 as start number if the table is empty ', () => {
const { container } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={0}
page={0}
rowsPerPage={10}
onPageChange={noop}
onRowsPerPageChange={noop}
/>
</TableRow>
</TableFooter>
</table>,
);
expect(container.querySelectorAll('p')[1]).to.have.text('0–0 of 0');
});
it('should hide the rows per page selector if there are less than two options', () => {
const { container, queryByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
page={0}
rowsPerPage={5}
rowsPerPageOptions={[5]}
onPageChange={noop}
onRowsPerPageChange={noop}
count={10}
/>
</TableRow>
</TableFooter>
</table>,
);
expect(container).not.to.include.text('Rows per page');
expect(queryByRole('listbox')).to.equal(null);
});
});
describe('prop: count=-1', () => {
it('should display the "of more than" text and keep the nextButton enabled', () => {
function Test() {
const [page, setPage] = React.useState(0);
return (
<table>
<TableFooter>
<TableRow>
<TablePagination
page={page}
rowsPerPage={10}
count={-1}
onPageChange={(_, newPage) => {
setPage(newPage);
}}
slotProps={{
displayedRows: {
'data-testid': 'displayedRows',
} as any,
}}
/>
</TableRow>
</TableFooter>
</table>
);
}
const { getByRole, getByTestId } = render(<Test />);
expect(getByTestId('displayedRows')).to.have.text('1–10 of more than 10');
fireEvent.click(getByRole('button', { name: 'Go to next page' }));
expect(getByTestId('displayedRows')).to.have.text('11–20 of more than 20');
});
});
describe('prop: showFirstButton', () => {
it('should change the page', () => {
const handleChangePage = spy();
const { getByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
page={1}
rowsPerPage={10}
count={98}
onPageChange={handleChangePage}
slotProps={{
actions: {
showFirstButton: true,
} as any,
}}
/>
</TableRow>
</TableFooter>
</table>,
);
fireEvent.click(getByRole('button', { name: 'Go to first page' }));
expect(handleChangePage.args[0][1]).to.equal(0);
});
});
describe('prop: showLastButton', () => {
it('should change the page', () => {
const handleChangePage = spy();
const { getByRole } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
page={0}
rowsPerPage={10}
count={98}
onPageChange={handleChangePage}
slotProps={{
actions: {
showLastButton: true,
} as any,
}}
/>
</TableRow>
</TableFooter>
</table>,
);
fireEvent.click(getByRole('button', { name: 'Go to last page' }));
expect(handleChangePage.args[0][1]).to.equal(9);
});
});
describe('warnings', () => {
beforeEach(() => {
PropTypes.resetWarningCache();
});
it('should raise a warning if the page prop is out of range', () => {
expect(() => {
PropTypes.checkPropTypes(
TablePagination.propTypes,
{
classes: {},
page: 2,
count: 20,
rowsPerPage: 10,
onPageChange: noop,
onRowsPerPageChange: noop,
},
'prop',
'MockedTablePagination',
);
}).toErrorDev(
'MUI: The page prop of a TablePagination is out of range (0 to 1, but page is 2).',
);
});
});
describe('prop: selectId, labelId', () => {
it('does allow manual label ids', () => {
const { container } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
count={1}
page={0}
onPageChange={noop}
onRowsPerPageChange={noop}
rowsPerPage={10}
selectId="foo"
labelId="bar"
/>
</TableRow>
</TableFooter>
</table>,
);
// will be `getByRole('combobox')` in aria 1.2
const combobox = container.getElementsByTagName('select')[0];
expect(combobox).toHaveAccessibleName('Rows per page: 10');
});
});
describe('prop: rowsPerPage', () => {
it('should display max number of rows text when prop is -1', () => {
const { container } = render(
<table>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]}
count={25}
page={0}
rowsPerPage={-1}
onPageChange={noop}
/>
</TableRow>
</TableFooter>
</table>,
);
expect(container).to.include.text('All');
expect(container).to.include.text('1–25 of 25');
});
});
describe('duplicated keys', () => {
it('should not raise a warning due to duplicated keys', () => {
render(
<table>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions={[5, 10, { label: 'All', value: 10 }]}
count={10}
rowsPerPage={10}
page={0}
onPageChange={noop}
slotProps={{
select: { 'aria-label': 'rows per page' },
}}
/>
</TableRow>
</TableFooter>
</table>,
);
});
});
});
| 6,232 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePagination.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { unstable_useId as useId, chainPropTypes, integerPropType } from '@mui/utils';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { isHostComponent } from '../utils/isHostComponent';
import { TablePaginationActions } from './TablePaginationActions';
import { getTablePaginationUtilityClass } from './tablePaginationClasses';
import {
TablePaginationProps,
LabelDisplayedRowsArgs,
TablePaginationTypeMap,
TablePaginationRootSlotProps,
TablePaginationSelectSlotProps,
TablePaginationActionsSlotProps,
TablePaginationMenuItemSlotProps,
TablePaginationSelectLabelSlotProps,
TablePaginationDisplayedRowsSlotProps,
TablePaginationToolbarSlotProps,
TablePaginationSpacerSlotProps,
} from './TablePagination.types';
import { ItemAriaLabelType } from './common.types';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
function defaultLabelDisplayedRows({ from, to, count }: LabelDisplayedRowsArgs) {
return `${from}–${to} of ${count !== -1 ? count : `more than ${to}`}`;
}
function defaultGetAriaLabel(type: ItemAriaLabelType) {
return `Go to ${type} page`;
}
const useUtilityClasses = () => {
const slots = {
root: ['root'],
toolbar: ['toolbar'],
spacer: ['spacer'],
selectLabel: ['selectLabel'],
select: ['select'],
input: ['input'],
selectIcon: ['selectIcon'],
menuItem: ['menuItem'],
displayedRows: ['displayedRows'],
actions: ['actions'],
};
return composeClasses(slots, useClassNamesOverride(getTablePaginationUtilityClass));
};
/**
* A pagination for tables.
*
* Demos:
*
* - [Table Pagination](https://mui.com/base-ui/react-table-pagination/)
*
* API:
*
* - [TablePagination API](https://mui.com/base-ui/react-table-pagination/components-api/#table-pagination)
*/
const TablePagination = React.forwardRef(function TablePagination<
RootComponentType extends React.ElementType,
>(props: TablePaginationProps<RootComponentType>, forwardedRef: React.ForwardedRef<Element>) {
const {
colSpan: colSpanProp,
count,
getItemAriaLabel = defaultGetAriaLabel,
labelDisplayedRows = defaultLabelDisplayedRows,
labelId: labelIdProp,
labelRowsPerPage = 'Rows per page:',
onPageChange,
onRowsPerPageChange,
page,
rowsPerPage,
rowsPerPageOptions = [10, 25, 50, 100],
selectId: selectIdProp,
slotProps = {},
slots = {},
...other
} = props;
const ownerState = props;
const classes = useUtilityClasses();
let colSpan;
const Root = slots.root ?? 'td';
if (Root === 'td' || !isHostComponent(Root)) {
colSpan = colSpanProp || 1000; // col-span over everything
}
const getLabelDisplayedRowsTo = () => {
if (count === -1) {
return (page + 1) * rowsPerPage;
}
return rowsPerPage === -1 ? count : Math.min(count, (page + 1) * rowsPerPage);
};
const selectId = useId(selectIdProp);
const labelId = useId(labelIdProp);
const rootProps: WithOptionalOwnerState<TablePaginationRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
colSpan,
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
const Select = slots.select ?? 'select';
const selectProps: WithOptionalOwnerState<TablePaginationSelectSlotProps> = useSlotProps({
elementType: Select,
externalSlotProps: slotProps.select,
additionalProps: {
value: rowsPerPage,
id: selectId,
onChange: (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) =>
onRowsPerPageChange && onRowsPerPageChange(event),
'aria-label': rowsPerPage.toString(),
'aria-labelledby': [labelId, selectId].filter(Boolean).join(' ') || undefined,
},
ownerState,
className: classes.select,
});
const Actions = slots.actions ?? TablePaginationActions;
const actionsProps: WithOptionalOwnerState<TablePaginationActionsSlotProps> = useSlotProps({
elementType: Actions,
externalSlotProps: slotProps.actions,
additionalProps: {
page,
rowsPerPage,
count,
onPageChange,
getItemAriaLabel,
},
ownerState,
className: classes.actions,
});
const MenuItem = slots.menuItem ?? 'option';
const menuItemProps: WithOptionalOwnerState<TablePaginationMenuItemSlotProps> = useSlotProps({
elementType: MenuItem,
externalSlotProps: slotProps.menuItem,
additionalProps: {
value: undefined,
},
ownerState,
className: classes.menuItem,
});
const SelectLabel = slots.selectLabel ?? 'p';
const selectLabelProps: WithOptionalOwnerState<TablePaginationSelectLabelSlotProps> =
useSlotProps({
elementType: SelectLabel,
externalSlotProps: slotProps.selectLabel,
additionalProps: {
id: labelId,
},
ownerState,
className: classes.selectLabel,
});
const DisplayedRows = slots.displayedRows ?? 'p';
const displayedRowsProps: WithOptionalOwnerState<TablePaginationDisplayedRowsSlotProps> =
useSlotProps({
elementType: DisplayedRows,
externalSlotProps: slotProps.displayedRows,
ownerState,
className: classes.displayedRows,
});
const Toolbar = slots.toolbar ?? 'div';
const toolbarProps: WithOptionalOwnerState<TablePaginationToolbarSlotProps> = useSlotProps({
elementType: Toolbar,
externalSlotProps: slotProps.toolbar,
ownerState,
className: classes.toolbar,
});
const Spacer = slots.spacer ?? 'div';
const spacerProps: WithOptionalOwnerState<TablePaginationSpacerSlotProps> = useSlotProps({
elementType: Spacer,
externalSlotProps: slotProps.spacer,
ownerState,
className: classes.spacer,
});
return (
<Root {...rootProps}>
<Toolbar {...toolbarProps}>
<Spacer {...spacerProps} />
{rowsPerPageOptions.length > 1 && (
<SelectLabel {...selectLabelProps}>{labelRowsPerPage}</SelectLabel>
)}
{rowsPerPageOptions.length > 1 && (
<Select {...selectProps}>
{rowsPerPageOptions.map(
(rowsPerPageOption: number | { label: string; value: number }) => (
<MenuItem
{...menuItemProps}
key={
typeof rowsPerPageOption !== 'number' && rowsPerPageOption.label
? rowsPerPageOption.label
: rowsPerPageOption
}
value={
typeof rowsPerPageOption !== 'number' && rowsPerPageOption.value
? rowsPerPageOption.value
: rowsPerPageOption
}
>
{typeof rowsPerPageOption !== 'number' && rowsPerPageOption.label
? rowsPerPageOption.label
: rowsPerPageOption}
</MenuItem>
),
)}
</Select>
)}
<DisplayedRows {...displayedRowsProps}>
{labelDisplayedRows({
from: count === 0 ? 0 : page * rowsPerPage + 1,
to: getLabelDisplayedRowsTo(),
count: count === -1 ? -1 : count,
page,
})}
</DisplayedRows>
<Actions {...actionsProps} />
</Toolbar>
</Root>
);
}) as PolymorphicComponent<TablePaginationTypeMap>;
TablePagination.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
colSpan: PropTypes.number,
/**
* The total number of rows.
*
* To enable server side pagination for an unknown number of items, provide -1.
*/
count: PropTypes.number.isRequired,
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current page.
* This is important for screen reader users.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @param {string} type The link or button type to format ('first' | 'last' | 'next' | 'previous').
* @returns {string}
* @default function defaultGetAriaLabel(type: ItemAriaLabelType) {
* return `Go to ${type} page`;
* }
*/
getItemAriaLabel: PropTypes.func,
/**
* Customize the displayed rows label. Invoked with a `{ from, to, count, page }`
* object.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @default function defaultLabelDisplayedRows({ from, to, count }: LabelDisplayedRowsArgs) {
* return `${from}–${to} of ${count !== -1 ? count : `more than ${to}`}`;
* }
*/
labelDisplayedRows: PropTypes.func,
/**
* Id of the label element within the pagination.
*/
labelId: PropTypes.string,
/**
* Customize the rows per page label.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @default 'Rows per page:'
*/
labelRowsPerPage: PropTypes.node,
/**
* Callback fired when the page is changed.
*
* @param {React.MouseEvent<HTMLButtonElement> | null} event The event source of the callback.
* @param {number} page The page selected.
*/
onPageChange: PropTypes.func.isRequired,
/**
* Callback fired when the number of rows per page is changed.
*
* @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
*/
onRowsPerPageChange: PropTypes.func,
/**
* The zero-based index of the current page.
*/
page: chainPropTypes(integerPropType.isRequired, (props) => {
const { count, page, rowsPerPage } = props;
if (count === -1) {
return null;
}
const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1);
if (page < 0 || page > newLastPage) {
return new Error(
'MUI: The page prop of a TablePagination is out of range ' +
`(0 to ${newLastPage}, but page is ${page}).`,
);
}
return null;
}),
/**
* The number of rows per page.
*
* Set -1 to display all the rows.
*/
rowsPerPage: integerPropType.isRequired,
/**
* Customizes the options of the rows per page select field. If less than two options are
* available, no select field will be displayed.
* Use -1 for the value with a custom label to show all the rows.
* @default [10, 25, 50, 100]
*/
rowsPerPageOptions: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.number.isRequired,
}),
]).isRequired,
),
/**
* Id of the select element within the pagination.
*/
selectId: PropTypes.string,
/**
* The props used for each slot inside the TablePagination.
* @default {}
*/
slotProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({
actions: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
displayedRows: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
menuItem: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
select: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
selectLabel: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
spacer: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
toolbar: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the TablePagination.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
actions: PropTypes.elementType,
displayedRows: PropTypes.elementType,
menuItem: PropTypes.elementType,
root: PropTypes.elementType,
select: PropTypes.elementType,
selectLabel: PropTypes.elementType,
spacer: PropTypes.elementType,
toolbar: PropTypes.elementType,
}),
} as any;
export { TablePagination };
| 6,233 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePagination.types.ts | import * as React from 'react';
import { PolymorphicProps, SlotComponentProps } from '../utils';
import { TablePaginationActions } from './TablePaginationActions';
import { ItemAriaLabelType } from './common.types';
export interface LabelDisplayedRowsArgs {
from: number;
to: number;
count: number;
page: number;
}
export interface TablePaginationRootSlotPropsOverrides {}
export interface TablePaginationActionsSlotPropsOverrides {}
export interface TablePaginationSelectSlotPropsOverrides {}
export interface TablePaginationSelectLabelSlotPropsOverrides {}
export interface TablePaginationMenuItemSlotPropsOverrides {}
export interface TablePaginationDisplayedRowsSlotPropsOverrides {}
export interface TablePaginationToolbarSlotPropsOverrides {}
export interface TablePaginationSpacerSlotPropsOverrides {}
export interface TablePaginationOwnProps {
/**
* @ignore
*/
colSpan?: number;
/**
* The components used for each slot inside the TablePagination.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: TablePaginationSlots;
/**
* The props used for each slot inside the TablePagination.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<
'td',
TablePaginationRootSlotPropsOverrides,
TablePaginationOwnerState
>;
actions?: SlotComponentProps<
typeof TablePaginationActions,
TablePaginationActionsSlotPropsOverrides,
TablePaginationOwnerState
>;
select?: SlotComponentProps<
'select',
TablePaginationSelectSlotPropsOverrides,
TablePaginationOwnerState
>;
selectLabel?: SlotComponentProps<
'p',
TablePaginationSelectLabelSlotPropsOverrides,
TablePaginationOwnerState
>;
menuItem?: SlotComponentProps<
'option',
TablePaginationMenuItemSlotPropsOverrides,
TablePaginationOwnerState
>;
displayedRows?: SlotComponentProps<
'p',
TablePaginationDisplayedRowsSlotPropsOverrides,
TablePaginationOwnerState
>;
toolbar?: SlotComponentProps<
'div',
TablePaginationToolbarSlotPropsOverrides,
TablePaginationOwnerState
>;
spacer?: SlotComponentProps<
'div',
TablePaginationSpacerSlotPropsOverrides,
TablePaginationOwnerState
>;
};
/**
* The total number of rows.
*
* To enable server side pagination for an unknown number of items, provide -1.
*/
count: number;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current page.
* This is important for screen reader users.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @param {string} type The link or button type to format ('first' | 'last' | 'next' | 'previous').
* @returns {string}
* @default function defaultGetAriaLabel(type: ItemAriaLabelType) {
* return `Go to ${type} page`;
* }
*/
getItemAriaLabel?: (type: ItemAriaLabelType) => string;
/**
* Customize the displayed rows label. Invoked with a `{ from, to, count, page }`
* object.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @default function defaultLabelDisplayedRows({ from, to, count }: LabelDisplayedRowsArgs) {
* return `${from}–${to} of ${count !== -1 ? count : `more than ${to}`}`;
* }
*/
labelDisplayedRows?: (paginationInfo: LabelDisplayedRowsArgs) => React.ReactNode;
/**
* Id of the label element within the pagination.
*/
labelId?: string;
/**
* Customize the rows per page label.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @default 'Rows per page:'
*/
labelRowsPerPage?: React.ReactNode;
/**
* Callback fired when the page is changed.
*
* @param {React.MouseEvent<HTMLButtonElement> | null} event The event source of the callback.
* @param {number} page The page selected.
*/
onPageChange: (event: React.MouseEvent<HTMLButtonElement> | null, page: number) => void;
/**
* Callback fired when the number of rows per page is changed.
*
* @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback.
*/
onRowsPerPageChange?: React.ChangeEventHandler<HTMLTextAreaElement | HTMLInputElement>;
/**
* The zero-based index of the current page.
*/
page: number;
/**
* The number of rows per page.
*
* Set -1 to display all the rows.
*/
rowsPerPage: number;
/**
* Customizes the options of the rows per page select field. If less than two options are
* available, no select field will be displayed.
* Use -1 for the value with a custom label to show all the rows.
* @default [10, 25, 50, 100]
*/
rowsPerPageOptions?: Array<number | { value: number; label: string }>;
/**
* Id of the select element within the pagination.
*/
selectId?: string;
}
export interface TablePaginationSlots {
/**
* The component that renders the root.
* @default 'td'
*/
root?: React.ElementType;
/**
* The component that renders the actions.
* @default TablePaginationActions
*/
actions?: React.ElementType;
/**
* The component that renders the select.
* @default 'select'
*/
select?: React.ElementType;
/**
* The component that renders the select label.
* @default 'p'
*/
selectLabel?: React.ElementType;
/**
* The component that renders the menu item.
* @default 'option'
*/
menuItem?: React.ElementType;
/**
* The component that renders the displayed rows.
* @default 'p'
*/
displayedRows?: React.ElementType;
/**
* The component that renders the toolbar.
* @default 'div'
*/
toolbar?: React.ElementType;
/**
* The component that renders the spacer.
* @default 'div'
*/
spacer?: React.ElementType;
}
export interface TablePaginationTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'td',
> {
props: TablePaginationOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type TablePaginationProps<
RootComponentType extends React.ElementType = TablePaginationTypeMap['defaultComponent'],
> = PolymorphicProps<TablePaginationTypeMap<{}, RootComponentType>, RootComponentType>;
export type TablePaginationOwnerState = TablePaginationOwnProps;
export type TablePaginationRootSlotProps = {
children?: React.ReactNode;
className?: string;
colSpan?: number;
ownerState: TablePaginationOwnerState;
ref?: React.Ref<any>;
};
export type TablePaginationSelectSlotProps = {
['aria-label']: string;
['aria-labelledby']?: string;
children?: React.ReactNode;
className?: string;
id?: string;
onChange: (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => void;
ownerState: TablePaginationOwnerState;
value: React.SelectHTMLAttributes<HTMLSelectElement>['value'];
};
export type TablePaginationActionsSlotProps = {
className?: string;
count: number;
getItemAriaLabel: (type: ItemAriaLabelType) => string;
onPageChange: (event: React.MouseEvent<HTMLButtonElement> | null, page: number) => void;
ownerState: TablePaginationOwnerState;
page: number;
rowsPerPage: number;
};
export type TablePaginationMenuItemSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: TablePaginationOwnerState;
value: React.SelectHTMLAttributes<HTMLSelectElement>['value'];
};
export type TablePaginationSelectLabelSlotProps = {
children?: React.ReactNode;
className?: string;
id?: string;
ownerState: TablePaginationOwnerState;
};
export type TablePaginationDisplayedRowsSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: TablePaginationOwnerState;
};
export type TablePaginationToolbarSlotProps = {
children?: React.ReactNode;
className?: string;
ownerState: TablePaginationOwnerState;
};
export type TablePaginationSpacerSlotProps = {
className?: string;
ownerState: TablePaginationOwnerState;
};
| 6,234 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePaginationActions.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import {
TablePaginationActions,
TablePaginationActionsButtonSlotProps,
TablePaginationActionsRootSlotProps,
} from '@mui/base/TablePagination';
function Root(props: TablePaginationActionsRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
function Button(props: TablePaginationActionsButtonSlotProps) {
const { ownerState, ...other } = props;
return <button type="button" data-rows-per-page={ownerState.rowsPerPage} {...other} />;
}
const styledTablePaginationActions = (
<TablePaginationActions
slots={{
root: Root,
backButton: Button,
nextButton: Button,
firstButton: Button,
lastButton: Button,
}}
count={10}
getItemAriaLabel={() => ''}
onPageChange={() => {}}
page={0}
rowsPerPage={10}
showFirstButton
showLastButton
/>
);
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
const requiredProps = {
count: 10,
getItemAriaLabel: () => '',
onPageChange: () => {},
page: 0,
rowsPerPage: 10,
showFirstButton: true,
showLastButton: true,
};
return (
<div>
{/* @ts-expect-error */}
<TablePaginationActions {...requiredProps} invalidProp={0} />
<TablePaginationActions<'a'> {...requiredProps} slots={{ root: 'a' }} href="#" />
<TablePaginationActions<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<TablePaginationActions<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
/>
<TablePaginationActions
{...requiredProps}
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<TablePaginationActions<'button'>
{...requiredProps}
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,235 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePaginationActions.tsx | 'use client';
import * as React from 'react';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import {
TablePaginationActionsButtonSlotProps,
TablePaginationActionsProps,
TablePaginationActionsRootSlotProps,
TablePaginationActionsTypeMap,
} from './TablePaginationActions.types';
import { ItemAriaLabelType } from './common.types';
function LastPageIconDefault() {
return <span>{'⇾|'}</span>;
}
function FirstPageIconDefault() {
return <span>{'|⇽'}</span>;
}
function NextPageIconDefault() {
return <span>{'⇾'}</span>;
}
function BackPageIconDefault() {
return <span>{'⇽'}</span>;
}
function defaultGetAriaLabel(type: ItemAriaLabelType) {
return `Go to ${type} page`;
}
/**
* @ignore - internal component.
*/
const TablePaginationActions = React.forwardRef(function TablePaginationActions<
RootComponentType extends React.ElementType,
>(
props: TablePaginationActionsProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
count,
getItemAriaLabel = defaultGetAriaLabel,
onPageChange,
page,
rowsPerPage,
showFirstButton = false,
showLastButton = false,
direction,
// @ts-ignore
ownerState: ownerStateProp,
slotProps = {},
slots = {},
...other
} = props;
const ownerState = props;
const handleFirstPageButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, 0);
};
const handleBackButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, page - 1);
};
const handleNextButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, page + 1);
};
const handleLastPageButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
};
const Root = slots.root ?? 'div';
const rootProps: WithOptionalOwnerState<TablePaginationActionsRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: { ref: forwardedRef },
ownerState,
});
const FirstButton = slots.firstButton ?? 'button';
const firstButtonProps: WithOptionalOwnerState<TablePaginationActionsButtonSlotProps> =
useSlotProps({
elementType: FirstButton,
externalSlotProps: slotProps.firstButton,
additionalProps: {
onClick: handleFirstPageButtonClick,
disabled: page === 0,
'aria-label': getItemAriaLabel('first', page),
title: getItemAriaLabel('first', page),
},
ownerState,
});
const LastButton = slots.lastButton ?? 'button';
const lastButtonProps: WithOptionalOwnerState<TablePaginationActionsButtonSlotProps> =
useSlotProps({
elementType: LastButton,
externalSlotProps: slotProps.lastButton,
additionalProps: {
onClick: handleLastPageButtonClick,
disabled: page >= Math.ceil(count / rowsPerPage) - 1,
'aria-label': getItemAriaLabel('last', page),
title: getItemAriaLabel('last', page),
},
ownerState,
});
const NextButton = slots.nextButton ?? 'button';
const nextButtonProps: WithOptionalOwnerState<TablePaginationActionsButtonSlotProps> =
useSlotProps({
elementType: NextButton,
externalSlotProps: slotProps.nextButton,
additionalProps: {
onClick: handleNextButtonClick,
disabled: count !== -1 ? page >= Math.ceil(count / rowsPerPage) - 1 : false,
'aria-label': getItemAriaLabel('next', page),
title: getItemAriaLabel('next', page),
},
ownerState,
});
const BackButton = slots.backButton ?? 'button';
const backButtonProps: WithOptionalOwnerState<TablePaginationActionsButtonSlotProps> =
useSlotProps({
elementType: BackButton,
externalSlotProps: slotProps.backButton,
additionalProps: {
onClick: handleBackButtonClick,
disabled: page === 0,
'aria-label': getItemAriaLabel('previous', page),
title: getItemAriaLabel('previous', page),
},
ownerState,
});
const LastPageIcon = slots.lastPageIcon ?? LastPageIconDefault;
const FirstPageIcon = slots.firstPageIcon ?? FirstPageIconDefault;
const NextPageIcon = slots.nextPageIcon ?? NextPageIconDefault;
const BackPageIcon = slots.backPageIcon ?? BackPageIconDefault;
return (
<Root {...rootProps}>
{showFirstButton && (
<FirstButton {...firstButtonProps}>
{direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
</FirstButton>
)}
<BackButton {...backButtonProps}>
{direction === 'rtl' ? <NextPageIcon /> : <BackPageIcon />}
</BackButton>
<NextButton {...nextButtonProps}>
{direction === 'rtl' ? <BackPageIcon /> : <NextPageIcon />}
</NextButton>
{showLastButton && (
<LastButton {...lastButtonProps}>
{direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
</LastButton>
)}
</Root>
);
}) as PolymorphicComponent<TablePaginationActionsTypeMap>;
export { TablePaginationActions };
| 6,236 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/TablePaginationActions.types.ts | import * as React from 'react';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface TablePaginationActionsRootSlotPropsOverrides {}
export interface TablePaginationActionsFirstButtonSlotPropsOverrides {}
export interface TablePaginationActionsLastButtonSlotPropsOverrides {}
export interface TablePaginationActionsNextButtonSlotPropsOverrides {}
export interface TablePaginationActionsBackButtonSlotPropsOverrides {}
export interface TablePaginationActionsOwnProps {
count: number;
/**
* The components used for each slot inside the TablePagination.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: TablePaginationActionsSlots;
/**
* The props used for each slot inside the TablePagination.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<
'div',
TablePaginationActionsRootSlotPropsOverrides,
TablePaginationActionsOwnerState
>;
firstButton?: SlotComponentProps<
'button',
TablePaginationActionsFirstButtonSlotPropsOverrides,
TablePaginationActionsOwnerState
>;
lastButton?: SlotComponentProps<
'button',
TablePaginationActionsLastButtonSlotPropsOverrides,
TablePaginationActionsOwnerState
>;
nextButton?: SlotComponentProps<
'button',
TablePaginationActionsNextButtonSlotPropsOverrides,
TablePaginationActionsOwnerState
>;
backButton?: SlotComponentProps<
'button',
TablePaginationActionsBackButtonSlotPropsOverrides,
TablePaginationActionsOwnerState
>;
};
/**
* Direction of the text.
* @default 'ltr'
*/
direction?: 'ltr' | 'rtl';
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current page.
* This is important for screen reader users.
*
* For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
* @param {string} type The link or button type to format ('first' | 'last' | 'next' | 'previous').
* @returns {string}
*/
getItemAriaLabel: (type: 'first' | 'last' | 'next' | 'previous', page: number) => string;
onPageChange: (event: React.MouseEvent<HTMLButtonElement> | null, page: number) => void;
page: number;
rowsPerPage: number;
showFirstButton: boolean;
showLastButton: boolean;
}
export interface TablePaginationActionsSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
/**
* The component that renders the first button.
* @default 'button'
*/
firstButton?: React.ElementType;
/**
* The component that renders the last button.
* @default 'button'
*/
lastButton?: React.ElementType;
/**
* The component that renders the next button.
* @default 'button'
*/
nextButton?: React.ElementType;
/**
* The component that renders the back button.
* @default 'button'
*/
backButton?: React.ElementType;
/**
* The component that renders the first page icon.
* @default FirstPageIconDefault
*/
firstPageIcon?: React.ElementType;
/**
* The component that renders the last page icon.
* @default LastPageIconDefault
*/
lastPageIcon?: React.ElementType;
/**
* The component that renders the next page icon.
* @default NextPageIconDefault
*/
nextPageIcon?: React.ElementType;
/**
* The component that renders the back page icon.
* @default BackPageIconDefault
*/
backPageIcon?: React.ElementType;
}
export type TablePaginationActionsProps<
RootComponentType extends React.ElementType = TablePaginationActionsTypeMap['defaultComponent'],
> = PolymorphicProps<TablePaginationActionsTypeMap<{}, RootComponentType>, RootComponentType>;
export interface TablePaginationActionsTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'button',
> {
props: TablePaginationActionsOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type TablePaginationActionsOwnerState = TablePaginationActionsOwnProps;
export type TablePaginationActionsRootSlotProps = {
children?: React.ReactNode;
ownerState: TablePaginationActionsOwnerState;
ref: React.Ref<any>;
};
export type TablePaginationActionsButtonSlotProps = {
'aria-label': string;
children?: React.ReactNode;
disabled: boolean;
onClick: React.MouseEventHandler<HTMLButtonElement>;
ownerState: TablePaginationActionsOwnerState;
title: string;
};
| 6,237 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/common.types.ts | export type ItemAriaLabelType = 'first' | 'last' | 'next' | 'previous';
| 6,238 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/index.ts | 'use client';
export { TablePagination } from './TablePagination';
export * from './TablePagination.types';
export { TablePaginationActions } from './TablePaginationActions';
export * from './TablePaginationActions.types';
export * from './tablePaginationClasses';
export * from './common.types';
| 6,239 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TablePagination/tablePaginationClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface TablePaginationClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the Toolbar component. */
toolbar: string;
/** Class name applied to the spacer element. */
spacer: string;
/** Class name applied to the select label Typography element. */
selectLabel: string;
/** Class name applied to the Select component `root` element. */
selectRoot: string;
/** Class name applied to the Select component `select` class. */
select: string;
/** Class name applied to the Select component `icon` class. */
selectIcon: string;
/** Class name applied to the Select component `root` element. */
input: string;
/** Class name applied to the MenuItem component. */
menuItem: string;
/** Class name applied to the displayed rows Typography element. */
displayedRows: string;
/** Class name applied to the internal `TablePaginationActions` component. */
actions: string;
}
export type TablePaginationClassKey = keyof TablePaginationClasses;
export function getTablePaginationUtilityClass(slot: string): string {
return generateUtilityClass('MuiTablePagination', slot);
}
export const tablePaginationClasses: TablePaginationClasses = generateUtilityClasses(
'MuiTablePagination',
[
'root',
'toolbar',
'spacer',
'selectLabel',
'selectRoot',
'select',
'selectIcon',
'input',
'menuItem',
'displayedRows',
'actions',
],
);
| 6,240 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/Tabs.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { Tabs, TabsRootSlotProps } from '@mui/base/Tabs';
function Root(props: TabsRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-orientation={ownerState.orientation} {...other} />;
}
const styledTabs = <Tabs slots={{ root: Root }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<Tabs invalidProp={0} />
<Tabs<'a'> slots={{ root: 'a' }} href="#" />
<Tabs<typeof CustomComponent>
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error required props not specified */}
<Tabs<typeof CustomComponent> slots={{ root: CustomComponent }} />
<Tabs<'button'>
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<Tabs<'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,241 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/Tabs.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import {
describeConformanceUnstyled,
act,
createRenderer,
fireEvent,
screen,
createMount,
} from '@mui-internal/test-utils';
import { Tab } from '@mui/base/Tab';
import { Tabs, tabsClasses as classes, TabsProps } from '@mui/base/Tabs';
import { TabsList } from '@mui/base/TabsList';
import { TabPanel } from '@mui/base/TabPanel';
describe('<Tabs />', () => {
const mount = createMount();
const { render } = createRenderer();
before(function beforeHook() {
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
// The test fails on Safari with just:
//
// container.scrollLeft = 200;
// expect(container.scrollLeft).to.equal(200); 💥
if (isSafari) {
this.skip();
}
});
describeConformanceUnstyled(<Tabs value={0} />, () => ({
classes,
inheritComponent: 'div',
render,
mount,
muiName: 'MuiTabs',
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'header',
slots: {
root: {
expectedClassName: classes.root,
},
},
skip: ['componentProp'],
}));
it('can be named via `aria-label`', () => {
render(
<Tabs>
<TabsList aria-label="string label">
<Tab value={0} />
</TabsList>
</Tabs>,
);
expect(screen.getByRole('tablist')).toHaveAccessibleName('string label');
});
it('can be named via `aria-labelledby`', () => {
render(
<React.Fragment>
<h3 id="label-id">complex name</h3>
<Tabs>
<TabsList aria-labelledby="label-id">
<Tab value={0} />
</TabsList>
</Tabs>
</React.Fragment>,
);
expect(screen.getByRole('tablist')).toHaveAccessibleName('complex name');
});
describe('prop: children', () => {
it('should accept a null child', () => {
const { getAllByRole } = render(
<Tabs value={0}>
{null}
<TabsList>
<Tab value={1} />
</TabsList>
</Tabs>,
);
expect(getAllByRole('tab')).to.have.lengthOf(1);
});
it('should support empty children', () => {
render(<Tabs value={1} />);
});
it('puts the selected child in tab order', () => {
const { getAllByRole, setProps } = render(
<Tabs value={1}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>,
);
expect(getAllByRole('tab').map((tab) => tab.tabIndex)).to.have.ordered.members([-1, 0]);
setProps({ value: 0 });
expect(getAllByRole('tab').map((tab) => tab.tabIndex)).to.have.ordered.members([0, -1]);
});
it('sets the aria-labelledby attribute on tab panels to the corresponding tab id', () => {
const { getAllByRole } = render(
<Tabs>
<TabsList>
<Tab value="tab-0" />
<Tab value="tab-1" id="explicit-tab-id-1" />
<Tab />
<Tab id="explicit-tab-id-3" />
</TabsList>
<TabPanel value="tab-1" />
<TabPanel value="tab-0" />
<TabPanel />
<TabPanel />
</Tabs>,
);
const tabs = getAllByRole('tab');
const tabPanels = getAllByRole('tabpanel', { hidden: true });
expect(tabPanels[0]).to.have.attribute('aria-labelledby', tabs[1].id);
expect(tabPanels[1]).to.have.attribute('aria-labelledby', tabs[0].id);
expect(tabPanels[2]).to.have.attribute('aria-labelledby', tabs[2].id);
expect(tabPanels[3]).to.have.attribute('aria-labelledby', tabs[3].id);
});
it('sets the aria-controls attribute on tabs to the corresponding tab panel id', () => {
const { getAllByRole } = render(
<Tabs>
<TabsList>
<Tab value="tab-0" />
<Tab value="tab-1" id="explicit-tab-id-1" />
<Tab />
<Tab id="explicit-tab-id-3" />
</TabsList>
<TabPanel value="tab-1" />
<TabPanel value="tab-0" />
<TabPanel />
<TabPanel />
</Tabs>,
);
const tabs = getAllByRole('tab');
const tabPanels = getAllByRole('tabpanel', { hidden: true });
expect(tabs[0]).to.have.attribute('aria-controls', tabPanels[1].id);
expect(tabs[1]).to.have.attribute('aria-controls', tabPanels[0].id);
expect(tabs[2]).to.have.attribute('aria-controls', tabPanels[2].id);
expect(tabs[3]).to.have.attribute('aria-controls', tabPanels[3].id);
});
});
describe('prop: value', () => {
const tabs = (
<Tabs value={1}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>
);
it('should pass selected prop to children', () => {
const { getAllByRole } = render(tabs);
const tabElements = getAllByRole('tab');
expect(tabElements[0]).to.have.attribute('aria-selected', 'false');
expect(tabElements[1]).to.have.attribute('aria-selected', 'true');
});
});
describe('prop: onChange', () => {
it('should call onChange when clicking', () => {
const handleChange = spy();
const { getAllByRole } = render(
<Tabs value={0} onChange={handleChange}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>,
);
fireEvent.click(getAllByRole('tab')[1]);
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.equal(1);
});
it('should not call onChange when already selected', () => {
const handleChange = spy();
const { getAllByRole } = render(
<Tabs value={0} onChange={handleChange}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>,
);
fireEvent.click(getAllByRole('tab')[0]);
expect(handleChange.callCount).to.equal(0);
});
it('when `selectionFollowsFocus` should call if an unselected tab gets focused', () => {
const handleChange = spy();
const { getAllByRole } = render(
<Tabs value={0} onChange={handleChange} selectionFollowsFocus>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>,
);
const [firstTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: 'ArrowRight' });
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(1);
});
it('when `selectionFollowsFocus` should not call if an selected tab gets focused', () => {
const handleChange = spy();
const { getAllByRole } = render(
<Tabs value={0} onChange={handleChange} selectionFollowsFocus>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>,
);
const [firstTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
expect(handleChange.callCount).to.equal(0);
});
});
describe('prop: orientation', () => {
it('does not add aria-orientation by default', () => {
render(
<Tabs value={0}>
<TabsList>
<Tabs />
</TabsList>
</Tabs>,
);
expect(screen.getByRole('tablist')).not.to.have.attribute('aria-orientation');
});
it('adds the proper aria-orientation when vertical', () => {
render(
<Tabs value={0} orientation="vertical">
<TabsList>
<Tabs />
</TabsList>
</Tabs>,
);
expect(screen.getByRole('tablist')).to.have.attribute('aria-orientation', 'vertical');
});
});
describe('keyboard navigation when focus is on a tab', () => {
[
['horizontal', 'ltr', 'ArrowLeft', 'ArrowRight'],
['horizontal', 'rtl', 'ArrowRight', 'ArrowLeft'],
['vertical', undefined, 'ArrowUp', 'ArrowDown'],
].forEach((entry) => {
const [orientation, direction, previousItemKey, nextItemKey] = entry;
describe(`when focus is on a tab element in a ${orientation} ${direction} tablist`, () => {
describe(previousItemKey ?? '', () => {
it('moves focus to the last tab without activating it if focus is on the first tab', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
value={0}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: previousItemKey });
expect(lastTab).toHaveFocus();
expect(handleChange.callCount).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('when `selectionFollowsFocus` moves focus to the last tab while activating it if focus is on the first tab', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
selectionFollowsFocus
value={0}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: previousItemKey });
expect(lastTab).toHaveFocus();
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(2);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('moves focus to the previous tab without activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
value={1}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, secondTab] = getAllByRole('tab');
act(() => {
secondTab.focus();
});
fireEvent.keyDown(secondTab, { key: previousItemKey });
expect(firstTab).toHaveFocus();
expect(handleChange.callCount).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('when `selectionFollowsFocus` moves focus to the previous tab while activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
selectionFollowsFocus
value={1}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, secondTab] = getAllByRole('tab');
act(() => {
secondTab.focus();
});
fireEvent.keyDown(secondTab, { key: previousItemKey });
expect(firstTab).toHaveFocus();
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('skips over disabled tabs', () => {
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
selectionFollowsFocus
value={2}
>
<TabsList>
<Tab value={0} />
<Tab value={1} disabled />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
lastTab.focus();
});
fireEvent.keyDown(lastTab, { key: previousItemKey });
expect(firstTab).toHaveFocus();
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
});
describe(nextItemKey ?? '', () => {
it('moves focus to the first tab without activating it if focus is on the last tab', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
value={2}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
lastTab.focus();
});
fireEvent.keyDown(lastTab, { key: nextItemKey });
expect(firstTab).toHaveFocus();
expect(handleChange.callCount).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('when `selectionFollowsFocus` moves focus to the first tab while activating it if focus is on the last tab', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
selectionFollowsFocus
value={2}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
lastTab.focus();
});
fireEvent.keyDown(lastTab, { key: nextItemKey });
expect(firstTab).toHaveFocus();
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('moves focus to the next tab without activating it it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
value={1}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [, secondTab, lastTab] = getAllByRole('tab');
act(() => {
secondTab.focus();
});
fireEvent.keyDown(secondTab, { key: nextItemKey });
expect(lastTab).toHaveFocus();
expect(handleChange.callCount).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('when `selectionFollowsFocus` moves focus to the next tab while activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onChange={handleChange}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
selectionFollowsFocus
value={1}
>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [, secondTab, lastTab] = getAllByRole('tab');
act(() => {
secondTab.focus();
});
fireEvent.keyDown(secondTab, { key: nextItemKey });
expect(lastTab).toHaveFocus();
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(2);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('skips over disabled tabs', () => {
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs
direction={direction as TabsProps['direction']}
onKeyDown={handleKeyDown}
orientation={orientation as TabsProps['orientation']}
selectionFollowsFocus
value={0}
>
<TabsList>
<Tab value={0} />
<Tab value={1} disabled />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: nextItemKey });
expect(lastTab).toHaveFocus();
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
});
});
});
describe('when focus is on a tab regardless of orientation', () => {
describe('Home', () => {
it('moves focus to the first tab without activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs onChange={handleChange} onKeyDown={handleKeyDown} value={2}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
lastTab.focus();
});
fireEvent.keyDown(lastTab, { key: 'Home' });
expect(firstTab).toHaveFocus();
expect(handleChange.callCount).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('when `selectionFollowsFocus` moves focus to the first tab without activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs onChange={handleChange} onKeyDown={handleKeyDown} selectionFollowsFocus value={2}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
lastTab.focus();
});
fireEvent.keyDown(lastTab, { key: 'Home' });
expect(firstTab).toHaveFocus();
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('moves focus to first non-disabled tab', () => {
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs onKeyDown={handleKeyDown} selectionFollowsFocus value={2}>
<TabsList>
<Tab value={0} disabled />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [, secondTab, lastTab] = getAllByRole('tab');
act(() => {
lastTab.focus();
});
fireEvent.keyDown(lastTab, { key: 'Home' });
expect(secondTab).toHaveFocus();
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
});
describe('End', () => {
it('moves focus to the last tab without activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs onChange={handleChange} onKeyDown={handleKeyDown} value={0}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: 'End' });
expect(lastTab).toHaveFocus();
expect(handleChange.callCount).to.equal(0);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('when `selectionFollowsFocus` moves focus to the last tab without activating it', () => {
const handleChange = spy();
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs onChange={handleChange} onKeyDown={handleKeyDown} selectionFollowsFocus value={0}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} />
</TabsList>
</Tabs>,
);
const [firstTab, , lastTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: 'End' });
expect(lastTab).toHaveFocus();
expect(handleChange.callCount).to.equal(1);
expect(handleChange.firstCall.args[1]).to.equal(2);
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
it('moves focus to first non-disabled tab', () => {
const handleKeyDown = spy();
const { getAllByRole } = render(
<Tabs onKeyDown={handleKeyDown} selectionFollowsFocus value={0}>
<TabsList>
<Tab value={0} />
<Tab value={1} />
<Tab value={2} disabled />
</TabsList>
</Tabs>,
);
const [firstTab, secondTab] = getAllByRole('tab');
act(() => {
firstTab.focus();
});
fireEvent.keyDown(firstTab, { key: 'End' });
expect(secondTab).toHaveFocus();
expect(handleKeyDown.callCount).to.equal(1);
expect(handleKeyDown.firstCall.args[0]).to.have.property('defaultPrevented', true);
});
});
});
it('should allow to focus first tab when there are no active tabs', () => {
const { getAllByRole } = render(
<Tabs>
<TabsList>
<Tab value={0} />
<Tab value={1} />
</TabsList>
</Tabs>,
);
expect(getAllByRole('tab').map((tab) => tab.getAttribute('tabIndex'))).to.deep.equal([
'0',
'-1',
]);
});
});
});
| 6,242 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/Tabs.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { getTabsUtilityClass } from './tabsClasses';
import { TabsOwnerState, TabsProps, TabsRootSlotProps, TabsTypeMap } from './Tabs.types';
import { useTabs } from '../useTabs';
import { TabsProvider } from '../useTabs/TabsProvider';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: { orientation: 'horizontal' | 'vertical' }) => {
const { orientation } = ownerState;
const slots = {
root: ['root', orientation],
};
return composeClasses(slots, useClassNamesOverride(getTabsUtilityClass));
};
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/)
*
* API:
*
* - [Tabs API](https://mui.com/base-ui/react-tabs/components-api/#tabs)
*/
const Tabs = React.forwardRef(function Tabs<RootComponentType extends React.ElementType>(
props: TabsProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
children,
value: valueProp,
defaultValue,
orientation = 'horizontal',
direction = 'ltr',
onChange,
selectionFollowsFocus,
slotProps = {},
slots = {},
...other
} = props;
const ownerState: TabsOwnerState = {
...props,
orientation,
direction,
};
const { contextValue } = useTabs(ownerState);
const classes = useUtilityClasses(ownerState);
const TabsRoot: React.ElementType = slots.root ?? 'div';
const tabsRootProps: WithOptionalOwnerState<TabsRootSlotProps> = useSlotProps({
elementType: TabsRoot,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: classes.root,
});
return (
<TabsRoot {...tabsRootProps}>
<TabsProvider value={contextValue}>{children}</TabsProvider>
</TabsRoot>
);
}) as PolymorphicComponent<TabsTypeMap>;
Tabs.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.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The direction of the text.
* @default 'ltr'
*/
direction: PropTypes.oneOf(['ltr', 'rtl']),
/**
* Callback invoked when new value is being set.
*/
onChange: PropTypes.func,
/**
* The component orientation (layout flow direction).
* @default 'horizontal'
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* If `true` the selected tab changes on focus. Otherwise it only
* changes on activation.
*/
selectionFollowsFocus: PropTypes.bool,
/**
* The props used for each slot inside the Tabs.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Tabs.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* The value of the currently selected `Tab`.
* If you don't want any selected `Tab`, you can set this prop to `null`.
*/
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
} as any;
export { Tabs };
| 6,243 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/Tabs.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { SlotComponentProps } from '../utils';
import { PolymorphicProps } from '../utils/PolymorphicComponent';
export interface TabsRootSlotPropsOverrides {}
type TabsOrientation = 'horizontal' | 'vertical';
type TabsDirection = 'ltr' | 'rtl';
export interface TabsOwnProps {
/**
* The content of the component.
*/
children?: React.ReactNode;
/**
* The value of the currently selected `Tab`.
* If you don't want any selected `Tab`, you can set this prop to `null`.
*/
value?: string | number | null;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: string | number | null;
/**
* The component orientation (layout flow direction).
* @default 'horizontal'
*/
orientation?: TabsOrientation;
/**
* The direction of the text.
* @default 'ltr'
*/
direction?: TabsDirection;
className?: string;
/**
* Callback invoked when new value is being set.
*/
onChange?: (event: React.SyntheticEvent | null, value: number | string | null) => void;
/**
* If `true` the selected tab changes on focus. Otherwise it only
* changes on activation.
*/
selectionFollowsFocus?: boolean;
/**
* The props used for each slot inside the Tabs.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', TabsRootSlotPropsOverrides, TabsOwnerState>;
};
/**
* The components used for each slot inside the Tabs.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: TabsSlots;
}
export interface TabsSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export interface TabsTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: TabsOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type TabsProps<
RootComponentType extends React.ElementType = TabsTypeMap['defaultComponent'],
> = PolymorphicProps<TabsTypeMap<{}, RootComponentType>, RootComponentType>;
export type TabsOwnerState = Simplify<
TabsOwnProps & {
orientation: TabsOrientation;
direction: TabsDirection;
}
>;
export type TabsRootSlotProps = {
ownerState: TabsOwnerState;
ref: React.Ref<any>;
className?: string;
};
| 6,244 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/TabsContext.ts | import * as React from 'react';
export interface TabsContextValue {
/**
* The currently selected tab's value.
*/
value: number | string | null;
/**
* Callback for setting new value.
*/
onSelected: (event: React.SyntheticEvent | null, value: number | string | null) => void;
/**
* The component orientation (layout flow direction).
*/
orientation?: 'horizontal' | 'vertical';
/**
* The direction of the tabs.
*/
direction?: 'ltr' | 'rtl';
/**
* Registers a function that returns the id of the tab with the given value.
*/
registerTabIdLookup: (lookupFunction: (id: string | number) => string | undefined) => void;
/**
* If `true` the selected tab changes on focus. Otherwise it only
* changes on activation.
*/
selectionFollowsFocus?: boolean;
/**
* Gets the id of the tab with the given value.
* @param value Value to find the tab for.
*/
getTabId: (value: number | string) => string | undefined;
/**
* Gets the id of the tab panel with the given value.
* @param value Value to find the tab panel for.
*/
getTabPanelId: (value: number | string) => string | undefined;
}
/**
* @ignore - internal component.
*/
const TabsContext = React.createContext<TabsContextValue | null>(null);
if (process.env.NODE_ENV !== 'production') {
TabsContext.displayName = 'TabsContext';
}
export function useTabsContext() {
const context = React.useContext(TabsContext);
if (context == null) {
throw new Error('No TabsContext provided');
}
return context;
}
export { TabsContext };
| 6,245 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/index.ts | 'use client';
export { Tabs } from './Tabs';
export * from './TabsContext';
export * from './tabsClasses';
export * from './Tabs.types';
| 6,246 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Tabs/tabsClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface TabsClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the root element if `orientation='horizontal'`. */
horizontal: string;
/** Class name applied to the root element if `orientation='vertical'`. */
vertical: string;
}
export type TabsClassKey = keyof TabsClasses;
export function getTabsUtilityClass(slot: string): string {
return generateUtilityClass('MuiTabs', slot);
}
export const tabsClasses: TabsClasses = generateUtilityClasses('MuiTabs', [
'root',
'horizontal',
'vertical',
]);
| 6,247 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabsList/TabsList.spec.tsx | import * as React from 'react';
import { expectType } from '@mui/types';
import { TabsList, TabsListRootSlotProps } from '@mui/base/TabsList';
function Root(props: TabsListRootSlotProps) {
const { ownerState, ...other } = props;
return <div data-orientation={ownerState.orientation} {...other} />;
}
const styledTabsList = <TabsList slots={{ root: Root }} />;
const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};
return (
<div>
{/* @ts-expect-error */}
<TabsList invalidProp={0} />
<TabsList<'a'> slots={{ root: 'a' }} href="#" />
<TabsList<typeof CustomComponent>
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<TabsList<typeof CustomComponent> slots={{ root: CustomComponent }} />
<TabsList<'button'>
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>
<TabsList<'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,248 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabsList/TabsList.test.tsx | import * as React from 'react';
import {
act,
createMount,
createRenderer,
describeConformanceUnstyled,
} from '@mui-internal/test-utils';
import { Tab } from '@mui/base/Tab';
import { Tabs, TabsContext } from '@mui/base/Tabs';
import { TabsList, tabsListClasses } from '@mui/base/TabsList';
import { expect } from 'chai';
describe('<TabsList />', () => {
const { render } = createRenderer();
const mount = createMount();
describeConformanceUnstyled(<TabsList />, () => ({
inheritComponent: 'div',
render: (node) => {
const { container, ...other } = render(
<TabsContext.Provider
value={{
value: '1',
onSelected: () => {},
registerTabIdLookup() {},
getTabId: () => '',
getTabPanelId: () => '',
}}
>
{node}
</TabsContext.Provider>,
);
return { container, ...other };
},
mount: (node: any) => {
const wrapper = mount(
<TabsContext.Provider
value={{
value: '1',
onSelected: () => {},
registerTabIdLookup() {},
getTabId: () => '',
getTabPanelId: () => '',
}}
>
{node}
</TabsContext.Provider>,
);
return wrapper.childAt(0);
},
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'div',
muiName: 'MuiTabPanel',
slots: {
root: {
expectedClassName: tabsListClasses.root,
},
},
skip: [
'reactTestRenderer', // Need to be wrapped with TabsContext
'componentProp',
],
}));
describe('accessibility attributes', () => {
it('sets the aria-selected attribute on the selected tab', () => {
const { getByText } = render(
<Tabs defaultValue={1}>
<TabsList>
<Tab value={1}>Tab 1</Tab>
<Tab value={2}>Tab 2</Tab>
<Tab value={3}>Tab 3</Tab>
</TabsList>
</Tabs>,
);
const tab1 = getByText('Tab 1');
const tab2 = getByText('Tab 2');
const tab3 = getByText('Tab 3');
expect(tab1).to.have.attribute('aria-selected', 'true');
expect(tab2).to.have.attribute('aria-selected', 'false');
expect(tab3).to.have.attribute('aria-selected', 'false');
act(() => {
tab2.click();
});
expect(tab1).to.have.attribute('aria-selected', 'false');
expect(tab2).to.have.attribute('aria-selected', 'true');
expect(tab3).to.have.attribute('aria-selected', 'false');
act(() => {
tab3.click();
});
expect(tab1).to.have.attribute('aria-selected', 'false');
expect(tab2).to.have.attribute('aria-selected', 'false');
expect(tab3).to.have.attribute('aria-selected', 'true');
act(() => {
tab1.click();
});
expect(tab1).to.have.attribute('aria-selected', 'true');
expect(tab2).to.have.attribute('aria-selected', 'false');
expect(tab3).to.have.attribute('aria-selected', 'false');
});
});
});
| 6,249 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabsList/TabsList.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import { getTabsListUtilityClass } from './tabsListClasses';
import {
TabsListOwnerState,
TabsListProps,
TabsListRootSlotProps,
TabsListTypeMap,
} from './TabsList.types';
import { useTabsList } from '../useTabsList';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { TabsListProvider } from '../useTabsList/TabsListProvider';
const useUtilityClasses = (ownerState: { orientation: 'horizontal' | 'vertical' }) => {
const { orientation } = ownerState;
const slots = {
root: ['root', orientation],
};
return composeClasses(slots, useClassNamesOverride(getTabsListUtilityClass));
};
/**
*
* Demos:
*
* - [Tabs](https://mui.com/base-ui/react-tabs/)
*
* API:
*
* - [TabsList API](https://mui.com/base-ui/react-tabs/components-api/#tabs-list)
*/
const TabsList = React.forwardRef(function TabsList<RootComponentType extends React.ElementType>(
props: TabsListProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const { children, slotProps = {}, slots = {}, ...other } = props;
const { isRtl, orientation, getRootProps, contextValue } = useTabsList({
rootRef: forwardedRef,
});
const ownerState: TabsListOwnerState = {
...props,
isRtl,
orientation,
};
const classes = useUtilityClasses(ownerState);
const TabsListRoot: React.ElementType = slots.root ?? 'div';
const tabsListRootProps: WithOptionalOwnerState<TabsListRootSlotProps> = useSlotProps({
elementType: TabsListRoot,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
ownerState,
className: classes.root,
});
return (
<TabsListProvider value={contextValue}>
<TabsListRoot {...tabsListRootProps}>{children}</TabsListRoot>
</TabsListProvider>
);
}) as PolymorphicComponent<TabsListTypeMap>;
TabsList.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.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The props used for each slot inside the TabsList.
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the TabsList.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
} as any;
export { TabsList };
| 6,250 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabsList/TabsList.types.ts | import * as React from 'react';
import { Simplify } from '@mui/types';
import { UseTabsListRootSlotProps } from '../useTabsList';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface TabsListRootSlotPropsOverrides {}
export interface TabsListOwnProps {
/**
* The content of the component.
*/
children?: React.ReactNode;
className?: string;
/**
* The props used for each slot inside the TabsList.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', TabsListRootSlotPropsOverrides, TabsListOwnerState>;
};
/**
* The components used for each slot inside the TabsList.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: TabsListSlots;
}
export interface TabsListSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export interface TabsListTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: TabsListOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type TabsListProps<
RootComponentType extends React.ElementType = TabsListTypeMap['defaultComponent'],
> = PolymorphicProps<TabsListTypeMap<{}, RootComponentType>, RootComponentType>;
export type TabsListOwnerState = Simplify<
TabsListOwnProps & {
isRtl: boolean;
orientation: 'horizontal' | 'vertical';
}
>;
export type TabsListRootSlotProps = UseTabsListRootSlotProps & {
className?: string;
ownerState: TabsListOwnerState;
};
| 6,251 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabsList/index.ts | 'use client';
export { TabsList } from './TabsList';
export * from './TabsList.types';
export * from './tabsListClasses';
| 6,252 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TabsList/tabsListClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface TabsListClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the root element if `orientation='horizontal'`. */
horizontal: string;
/** Class name applied to the root element if `orientation='vertical'`. */
vertical: string;
}
export type TabsListClassKey = keyof TabsListClasses;
export function getTabsListUtilityClass(slot: string): string {
return generateUtilityClass('MuiTabsList', slot);
}
export const tabsListClasses: TabsListClasses = generateUtilityClasses('MuiTabsList', [
'root',
'horizontal',
'vertical',
]);
| 6,253 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TextareaAutosize/TextareaAutosize.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import sinon, { spy, stub } from 'sinon';
import {
describeConformanceUnstyled,
act,
screen,
waitFor,
createMount,
createRenderer,
fireEvent,
strictModeDoubleLoggingSuppressed,
} from '@mui-internal/test-utils';
import { TextareaAutosize } from '@mui/base/TextareaAutosize';
function getStyleValue(value: string) {
return parseInt(value, 10) || 0;
}
// TODO: merge into a shared test helpers.
// MUI X already have one under mui-x/test/utils/helperFn.ts
function sleep(duration: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
}, duration);
});
}
async function raf() {
return new Promise<void>((resolve) => {
// Chrome and Safari have a bug where calling rAF once returns the current
// frame instead of the next frame, so we need to call a double rAF here.
// See crbug.com/675795 for more.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
resolve();
});
});
});
}
describe('<TextareaAutosize />', () => {
const { clock, render } = createRenderer();
const mount = createMount();
describeConformanceUnstyled(<TextareaAutosize />, () => ({
render,
mount,
inheritComponent: 'textarea',
refInstanceof: window.HTMLTextAreaElement,
slots: {},
skip: [
// doesn't have slots, so these tests are irrelevant:
'componentProp',
'mergeClassName',
'ownerStatePropagation',
'propsSpread',
'refForwarding',
'slotsProp',
],
}));
// For https://github.com/mui/material-ui/pull/33238
it('should not crash when unmounting with Suspense', async () => {
const LazyRoute = React.lazy(() => {
// Force react to show fallback suspense
return new Promise<any>((resolve) => {
setTimeout(() => {
resolve({
default: () => <div>LazyRoute</div>,
});
}, 0);
});
});
function App() {
const [toggle, setToggle] = React.useState(false);
return (
<React.Suspense fallback={null}>
<button onClick={() => setToggle((r) => !r)}>Toggle</button>
{toggle ? <LazyRoute /> : <TextareaAutosize />}
</React.Suspense>
);
}
render(<App />);
const button = screen.getByRole('button');
fireEvent.click(button);
await waitFor(() => {
expect(screen.queryByText('LazyRoute')).not.to.equal(null);
});
});
// For https://github.com/mui/material-ui/pull/33253
it('should update height without an infinite rendering loop', async () => {
function App() {
const [value, setValue] = React.useState('Controlled');
const handleChange = (event: React.ChangeEvent<any>) => {
setValue(event.target.value);
};
return <TextareaAutosize value={value} onChange={handleChange} />;
}
const { container } = render(<App />);
const input = container.querySelector<HTMLTextAreaElement>('textarea')!;
act(() => {
input.focus();
});
const activeElement = document.activeElement!;
// set the value of the input to be 1 larger than its content width
fireEvent.change(activeElement, {
target: { value: 'Controlled\n' },
});
await sleep(0);
fireEvent.change(activeElement, {
target: { value: 'Controlled\n\n' },
});
});
// For https://github.com/mui/material-ui/pull/37135
it('should update height without delay', async function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
// It depends on ResizeObserver
this.skip();
}
function App() {
const ref = React.useRef<HTMLTextAreaElement>(null);
return (
<div>
<button
onClick={() => {
ref.current!.style.width = '250px';
}}
>
change
</button>
<div>
<TextareaAutosize
ref={ref}
style={{
width: 150,
padding: 0,
fontSize: 14,
lineHeight: '15px',
border: '1px solid',
}}
defaultValue="qdzqzd qzd qzd qzd qz dqz"
/>
</div>
</div>
);
}
const { container } = render(<App />);
const input = container.querySelector<HTMLTextAreaElement>('textarea')!;
const button = screen.getByRole('button');
expect(parseInt(input.style.height, 10)).to.be.within(30, 32);
fireEvent.click(button);
await raf();
await raf();
expect(parseInt(input.style.height, 10)).to.be.within(15, 17);
});
describe('layout', () => {
const getComputedStyleStub = new Map<Element, Partial<CSSStyleDeclaration>>();
function setLayout(
input: HTMLTextAreaElement,
shadow: Element,
{
getComputedStyle,
scrollHeight: scrollHeightArg,
lineHeight: lineHeightArg,
}: {
getComputedStyle: Partial<CSSStyleDeclaration>;
scrollHeight?: number | (() => number);
lineHeight?: number | (() => number);
},
) {
const lineHeight = typeof lineHeightArg === 'function' ? lineHeightArg : () => lineHeightArg;
const scrollHeight =
typeof scrollHeightArg === 'function' ? scrollHeightArg : () => scrollHeightArg;
getComputedStyleStub.set(input, getComputedStyle);
let index = 0;
stub(shadow, 'scrollHeight').get(() => {
index += 1;
return index % 2 === 1 ? scrollHeight() : lineHeight();
});
}
before(function beforeHook() {
// Only run the test on node.
if (!/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
stub(window, 'getComputedStyle').value(
(node: Element) => getComputedStyleStub.get(node) || {},
);
});
after(() => {
sinon.restore();
});
describe('resize', () => {
clock.withFakeTimers();
it('should handle the resize event', () => {
const { container } = render(<TextareaAutosize />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
expect(input.style).to.have.property('height', '0px');
expect(input.style).to.have.property('overflow', 'hidden');
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: 30,
lineHeight: 15,
});
window.dispatchEvent(new window.Event('resize', {}));
clock.tick(166);
expect(input.style).to.have.property('height', '30px');
expect(input.style).to.have.property('overflow', 'hidden');
});
});
it('should update when uncontrolled', () => {
const handleChange = spy();
const { container } = render(<TextareaAutosize onChange={handleChange} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
expect(input.style).to.have.property('height', '0px');
expect(input.style).to.have.property('overflow', 'hidden');
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: 30,
lineHeight: 15,
});
act(() => {
input.focus();
});
const activeElement = document.activeElement!;
fireEvent.change(activeElement, { target: { value: 'a' } });
expect(input.style).to.have.property('height', '30px');
expect(input.style).to.have.property('overflow', 'hidden');
expect(handleChange.callCount).to.equal(1);
});
it('should take the border into account with border-box', () => {
const border = 5;
const { container, forceUpdate } = render(<TextareaAutosize />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
expect(input.style).to.have.property('height', '0px');
expect(input.style).to.have.property('overflow', 'hidden');
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'border-box',
borderBottomWidth: `${border}px`,
},
scrollHeight: 30,
lineHeight: 15,
});
forceUpdate();
expect(input.style).to.have.property('height', `${30 + border}px`);
expect(input.style).to.have.property('overflow', 'hidden');
});
it('should take the padding into account with content-box', () => {
const padding = 5;
const { container, forceUpdate } = render(<TextareaAutosize />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'border-box',
paddingTop: `${padding}px`,
},
scrollHeight: 30,
lineHeight: 15,
});
forceUpdate();
expect(input.style).to.have.property('height', `${30 + padding}px`);
expect(input.style).to.have.property('overflow', 'hidden');
});
it('should have at least height of "minRows"', () => {
const minRows = 3;
const lineHeight = 15;
const { container, forceUpdate } = render(<TextareaAutosize minRows={minRows} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: 30,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * minRows}px`);
expect(input.style).to.have.property('overflow', '');
});
it('should have at max "maxRows" rows', () => {
const maxRows = 3;
const lineHeight = 15;
const { container, forceUpdate } = render(<TextareaAutosize maxRows={maxRows} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: 100,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * maxRows}px`);
expect(input.style).to.have.property('overflow', '');
});
it('should show scrollbar when having more rows than "maxRows"', () => {
const maxRows = 3;
const lineHeight = 15;
const { container, forceUpdate } = render(<TextareaAutosize maxRows={maxRows} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'border-box',
},
scrollHeight: lineHeight * 2,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * 2}px`);
expect(input.style).to.have.property('overflow', 'hidden');
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'border-box',
},
scrollHeight: lineHeight * 3,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * 3}px`);
expect(input.style).to.have.property('overflow', 'hidden');
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'border-box',
},
scrollHeight: lineHeight * 4,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * 3}px`);
expect(input.style).to.have.property('overflow', '');
});
it('should update its height when the "maxRows" prop changes', () => {
const lineHeight = 15;
const { container, forceUpdate, setProps } = render(<TextareaAutosize maxRows={3} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: 100,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * 3}px`);
expect(input.style).to.have.property('overflow', '');
setProps({ maxRows: 2 });
expect(input.style).to.have.property('height', `${lineHeight * 2}px`);
expect(input.style).to.have.property('overflow', '');
});
it('should not sync height if container width is 0px', () => {
const lineHeight = 15;
const { container, forceUpdate } = render(<TextareaAutosize />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: lineHeight * 2,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * 2}px`);
expect(input.style).to.have.property('overflow', 'hidden');
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
width: '0px',
},
scrollHeight: lineHeight * 3,
lineHeight,
});
forceUpdate();
expect(input.style).to.have.property('height', `${lineHeight * 2}px`);
expect(input.style).to.have.property('overflow', 'hidden');
});
it('should compute the correct height if padding-right is greater than 0px', () => {
const paddingRight = 50;
const { container, forceUpdate } = render(<TextareaAutosize style={{ paddingRight }} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')! as HTMLTextAreaElement;
const contentWidth = 100;
const lineHeight = 15;
const width = contentWidth + paddingRight;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'border-box',
width: `${width}px`,
},
scrollHeight: () => {
// assuming that the width of the word is 1px, and substract the width of the paddingRight
const lineNum = Math.ceil(
input.value.length / (width - getStyleValue(shadow.style.paddingRight)),
);
return lineNum * lineHeight;
},
lineHeight,
});
act(() => {
input.focus();
});
const activeElement = document.activeElement!;
// set the value of the input to be 1 larger than its content width
fireEvent.change(activeElement, {
target: { value: new Array(contentWidth + 1).fill('a').join('') },
});
forceUpdate();
// the input should be 2 lines
expect(input.style).to.have.property('height', `${lineHeight * 2}px`);
});
describe('warnings', () => {
it('warns if layout is unstable but not crash', () => {
const { container, forceUpdate } = render(<TextareaAutosize maxRows={3} />);
const input = container.querySelector<HTMLTextAreaElement>('textarea[aria-hidden=null]')!;
const shadow = container.querySelector('textarea[aria-hidden=true]')!;
let index = 0;
setLayout(input, shadow, {
getComputedStyle: {
boxSizing: 'content-box',
},
scrollHeight: 100,
lineHeight: () => {
index += 1;
return index;
},
});
expect(() => {
forceUpdate();
}).toErrorDev([
'MUI: Too many re-renders.',
!strictModeDoubleLoggingSuppressed && 'MUI: Too many re-renders.',
!strictModeDoubleLoggingSuppressed && 'MUI: Too many re-renders.',
]);
});
});
});
});
| 6,254 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TextareaAutosize/TextareaAutosize.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import * as ReactDOM from 'react-dom';
import {
unstable_debounce as debounce,
unstable_useForkRef as useForkRef,
unstable_useEnhancedEffect as useEnhancedEffect,
unstable_ownerWindow as ownerWindow,
} from '@mui/utils';
import { TextareaAutosizeProps } from './TextareaAutosize.types';
type State = {
outerHeightStyle: number;
overflow?: boolean | undefined;
};
function getStyleValue(value: string) {
return parseInt(value, 10) || 0;
}
const styles: {
shadow: React.CSSProperties;
} = {
shadow: {
// Visibility needed to hide the extra text area on iPads
visibility: 'hidden',
// Remove from the content flow
position: 'absolute',
// Ignore the scrollbar width
overflow: 'hidden',
height: 0,
top: 0,
left: 0,
// Create a new layer, increase the isolation of the computed values
transform: 'translateZ(0)',
},
};
function isEmpty(obj: State) {
return (
obj === undefined ||
obj === null ||
Object.keys(obj).length === 0 ||
(obj.outerHeightStyle === 0 && !obj.overflow)
);
}
/**
*
* Demos:
*
* - [Textarea Autosize](https://mui.com/base-ui/react-textarea-autosize/)
* - [Textarea Autosize](https://mui.com/material-ui/react-textarea-autosize/)
*
* API:
*
* - [TextareaAutosize API](https://mui.com/base-ui/react-textarea-autosize/components-api/#textarea-autosize)
*/
const TextareaAutosize = React.forwardRef(function TextareaAutosize(
props: TextareaAutosizeProps,
forwardedRef: React.ForwardedRef<Element>,
) {
const { onChange, maxRows, minRows = 1, style, value, ...other } = props;
const { current: isControlled } = React.useRef(value != null);
const inputRef = React.useRef<HTMLInputElement>(null);
const handleRef = useForkRef(forwardedRef, inputRef);
const shadowRef = React.useRef<HTMLTextAreaElement>(null);
const renders = React.useRef(0);
const [state, setState] = React.useState<State>({
outerHeightStyle: 0,
});
const getUpdatedState = React.useCallback(() => {
const input = inputRef.current!;
const containerWindow = ownerWindow(input);
const computedStyle = containerWindow.getComputedStyle(input);
// If input's width is shrunk and it's not visible, don't sync height.
if (computedStyle.width === '0px') {
return {
outerHeightStyle: 0,
};
}
const inputShallow = shadowRef.current!;
inputShallow.style.width = computedStyle.width;
inputShallow.value = input.value || props.placeholder || 'x';
if (inputShallow.value.slice(-1) === '\n') {
// Certain fonts which overflow the line height will cause the textarea
// to report a different scrollHeight depending on whether the last line
// is empty. Make it non-empty to avoid this issue.
inputShallow.value += ' ';
}
const boxSizing = computedStyle.boxSizing;
const padding =
getStyleValue(computedStyle.paddingBottom) + getStyleValue(computedStyle.paddingTop);
const border =
getStyleValue(computedStyle.borderBottomWidth) + getStyleValue(computedStyle.borderTopWidth);
// The height of the inner content
const innerHeight = inputShallow.scrollHeight;
// Measure height of a textarea with a single row
inputShallow.value = 'x';
const singleRowHeight = inputShallow.scrollHeight;
// The height of the outer content
let outerHeight = innerHeight;
if (minRows) {
outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight);
}
if (maxRows) {
outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight);
}
outerHeight = Math.max(outerHeight, singleRowHeight);
// Take the box sizing into account for applying this value as a style.
const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);
const overflow = Math.abs(outerHeight - innerHeight) <= 1;
return { outerHeightStyle, overflow };
}, [maxRows, minRows, props.placeholder]);
const updateState = (prevState: State, newState: State) => {
const { outerHeightStyle, overflow } = newState;
// Need a large enough difference to update the height.
// This prevents infinite rendering loop.
if (
renders.current < 20 &&
((outerHeightStyle > 0 &&
Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1) ||
prevState.overflow !== overflow)
) {
renders.current += 1;
return {
overflow,
outerHeightStyle,
};
}
if (process.env.NODE_ENV !== 'production') {
if (renders.current === 20) {
console.error(
[
'MUI: Too many re-renders. The layout is unstable.',
'TextareaAutosize limits the number of renders to prevent an infinite loop.',
].join('\n'),
);
}
}
return prevState;
};
const syncHeight = React.useCallback(() => {
const newState = getUpdatedState();
if (isEmpty(newState)) {
return;
}
setState((prevState) => updateState(prevState, newState));
}, [getUpdatedState]);
useEnhancedEffect(() => {
const syncHeightWithFlushSync = () => {
const newState = getUpdatedState();
if (isEmpty(newState)) {
return;
}
// In React 18, state updates in a ResizeObserver's callback are happening after
// the paint, this leads to an infinite rendering.
//
// Using flushSync ensures that the states is updated before the next pain.
// Related issue - https://github.com/facebook/react/issues/24331
ReactDOM.flushSync(() => {
setState((prevState) => updateState(prevState, newState));
});
};
const handleResize = () => {
renders.current = 0;
syncHeightWithFlushSync();
};
// Workaround a "ResizeObserver loop completed with undelivered notifications" error
// in test.
// Note that we might need to use this logic in production per https://github.com/WICG/resize-observer/issues/38
// Also see https://github.com/mui/mui-x/issues/8733
let rAF: any;
const rAFHandleResize = () => {
cancelAnimationFrame(rAF);
rAF = requestAnimationFrame(() => {
handleResize();
});
};
const debounceHandleResize = debounce(handleResize);
const input = inputRef.current!;
const containerWindow = ownerWindow(input);
containerWindow.addEventListener('resize', debounceHandleResize);
let resizeObserver: ResizeObserver;
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(
process.env.NODE_ENV === 'test' ? rAFHandleResize : handleResize,
);
resizeObserver.observe(input);
}
return () => {
debounceHandleResize.clear();
cancelAnimationFrame(rAF);
containerWindow.removeEventListener('resize', debounceHandleResize);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [getUpdatedState]);
useEnhancedEffect(() => {
syncHeight();
});
React.useEffect(() => {
renders.current = 0;
}, [value]);
const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
renders.current = 0;
if (!isControlled) {
syncHeight();
}
if (onChange) {
onChange(event);
}
};
return (
<React.Fragment>
<textarea
value={value}
onChange={handleChange}
ref={handleRef}
// Apply the rows prop to get a "correct" first SSR paint
rows={minRows as number}
style={{
height: state.outerHeightStyle,
// Need a large enough difference to allow scrolling.
// This prevents infinite rendering loop.
overflow: state.overflow ? 'hidden' : undefined,
...style,
}}
{...other}
/>
<textarea
aria-hidden
className={props.className}
readOnly
ref={shadowRef}
tabIndex={-1}
style={{
...styles.shadow,
...style,
paddingTop: 0,
paddingBottom: 0,
}}
/>
</React.Fragment>
);
}) as React.ForwardRefExoticComponent<TextareaAutosizeProps & React.RefAttributes<Element>>;
TextareaAutosize.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
className: PropTypes.string,
/**
* Maximum number of rows to display.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display.
* @default 1
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* @ignore
*/
onChange: PropTypes.func,
/**
* @ignore
*/
placeholder: PropTypes.string,
/**
* @ignore
*/
style: PropTypes.object,
/**
* @ignore
*/
value: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.string),
PropTypes.number,
PropTypes.string,
]),
} as any;
export { TextareaAutosize };
| 6,255 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TextareaAutosize/TextareaAutosize.types.ts | import * as React from 'react';
export interface TextareaAutosizeProps
extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'children' | 'rows'> {
ref?: React.Ref<HTMLTextAreaElement>;
/**
* Maximum number of rows to display.
*/
maxRows?: string | number;
/**
* Minimum number of rows to display.
* @default 1
*/
minRows?: string | number;
}
| 6,256 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/TextareaAutosize/index.ts | 'use client';
export { TextareaAutosize } from './TextareaAutosize';
export * from './TextareaAutosize.types';
| 6,257 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_NumberInput/NumberInput.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import userEvent from '@testing-library/user-event';
import {
act,
createMount,
createRenderer,
describeConformanceUnstyled,
fireEvent,
} from '@mui-internal/test-utils';
import {
Unstable_NumberInput as NumberInput,
numberInputClasses,
NumberInputOwnerState,
NumberInputIncrementButtonSlotProps,
NumberInputDecrementButtonSlotProps,
} from '@mui/base/Unstable_NumberInput';
// TODO v6: initialize @testing-library/user-event using userEvent.setup() instead of directly calling methods e.g. userEvent.click() for all related tests in this file
// currently the setup() method uses the ClipboardEvent constructor which is incompatible with our lowest supported version of iOS Safari (12.2) https://github.com/mui/material-ui/blob/master/.browserslistrc#L44
// userEvent.setup() requires Safari 14 or up to work
describe('<NumberInput />', () => {
const mount = createMount();
const { render } = createRenderer();
describeConformanceUnstyled(<NumberInput />, () => ({
inheritComponent: 'div',
render,
mount,
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'div',
muiName: 'MuiNumberInput',
slots: {
root: {
expectedClassName: numberInputClasses.root,
},
input: {
expectedClassName: numberInputClasses.input,
testWithElement: 'input',
},
incrementButton: {
expectedClassName: numberInputClasses.incrementButton,
testWithElement: 'button',
},
decrementButton: {
expectedClassName: numberInputClasses.decrementButton,
testWithElement: 'button',
},
},
skip: ['componentProp'],
}));
it('should be able to attach input ref passed through props', () => {
const inputRef = React.createRef<HTMLInputElement>();
const { getByTestId } = render(
<NumberInput slotProps={{ input: { 'data-testid': 'input', ref: inputRef } as any }} />,
);
expect(inputRef.current).to.deep.equal(getByTestId('input'));
});
it('passes ownerState to all the slots', () => {
interface SlotProps {
ownerState: NumberInputOwnerState;
children?: React.ReactNode;
}
const CustomComponent = React.forwardRef(
({ ownerState, children }: SlotProps, ref: React.Ref<any>) => {
return (
<div
ref={ref}
data-disabled={ownerState.disabled}
data-focused={ownerState.focused}
data-readonly={ownerState.readOnly}
data-decrementdisabled={ownerState.isDecrementDisabled}
data-incrementdisabled={ownerState.isIncrementDisabled}
data-testid="custom"
>
{children}
</div>
);
},
);
const slots = {
root: CustomComponent,
input: CustomComponent,
decrementButton: CustomComponent,
incrementButton: CustomComponent,
};
const { getAllByTestId } = render(<NumberInput readOnly disabled slots={slots} />);
const renderedComponents = getAllByTestId('custom');
expect(renderedComponents.length).to.equal(4);
for (let i = 0; i < renderedComponents.length; i += 1) {
expect(renderedComponents[i]).to.have.attribute('data-disabled', 'true');
expect(renderedComponents[i]).to.have.attribute('data-focused', 'false');
expect(renderedComponents[i]).to.have.attribute('data-readonly', 'true');
expect(renderedComponents[i]).to.have.attribute('data-decrementdisabled', 'true');
expect(renderedComponents[i]).to.have.attribute('data-incrementdisabled', 'true');
}
});
describe('prop: onClick', () => {
it('registers `onClick` on the root slot', () => {
const handleClick = spy((event) => event.currentTarget);
const { getByTestId, getByRole } = render(
<NumberInput defaultValue={10} data-testid="root" onClick={handleClick} />,
);
const input = getByRole('textbox');
const root = getByTestId('root');
fireEvent.click(input);
expect(handleClick.callCount).to.equal(1);
// return value is event.currentTarget
expect(handleClick.returned(root)).to.equal(true);
});
it('works when passed through slotProps', () => {
const handleClick = spy((event) => event.currentTarget);
const slotPropsHandleClick = spy((event) => event.currentTarget);
const { getByTestId, getByRole } = render(
<NumberInput
defaultValue={10}
data-testid="root"
onClick={handleClick}
slotProps={{
root: {
onClick: slotPropsHandleClick,
},
}}
/>,
);
const input = getByRole('textbox');
const root = getByTestId('root');
fireEvent.click(input);
expect(handleClick.callCount).to.equal(0);
expect(slotPropsHandleClick.callCount).to.equal(1);
// return value is event.currentTarget
expect(slotPropsHandleClick.returned(root)).to.equal(true);
});
});
describe('prop: onInputChange', () => {
it('should not cause an "unknown event handler" error by entering the DOM as a normal prop', () => {
expect(() => {
render(<NumberInput defaultValue={10} onInputChange={() => {}} />);
}).not.toErrorDev();
});
it('should throw an "unknown event handler" error if passed through slotProps', () => {
expect(() => {
render(
<NumberInput
defaultValue={10}
slotProps={{
input: {
// @ts-expect-error
onInputChange: () => {},
},
}}
/>,
);
}).toErrorDev('Warning: Unknown event handler property `onInputChange`. It will be ignored.');
});
it('should fire on keyboard input in the textbox instead of onChange', async () => {
const handleInputChange = spy((event) => event.currentTarget);
const handleChange = spy();
const { getByRole } = render(
<NumberInput defaultValue={10} onChange={handleChange} onInputChange={handleInputChange} />,
);
const input = getByRole('textbox');
await userEvent.click(input);
await userEvent.keyboard('3');
expect(handleChange.callCount).to.equal(0);
expect(handleInputChange.callCount).to.equal(1);
// return value is event.currentTarget
expect(handleInputChange.returned(input)).to.equal(true);
});
it('is overridden by slotProps.input.onChange', async () => {
const handleInputChange = spy();
const slotPropsHandleChange = spy((event) => event.currentTarget);
const { getByRole } = render(
<NumberInput
defaultValue={10}
onInputChange={handleInputChange}
slotProps={{
input: {
onChange: slotPropsHandleChange,
},
}}
/>,
);
const input = getByRole('textbox');
await userEvent.click(input);
await userEvent.keyboard('3');
expect(handleInputChange.callCount).to.equal(0);
expect(slotPropsHandleChange.callCount).to.equal(1);
// return value is event.currentTarget
expect(slotPropsHandleChange.returned(input)).to.equal(true);
});
});
describe('prop: onChange', () => {
it('fires when the textbox is blurred', async () => {
const handleChange = spy((event) => event.target);
const { getByRole } = render(<NumberInput defaultValue={10} onChange={handleChange} />);
const input = getByRole('textbox');
await userEvent.click(input);
await userEvent.keyboard('3');
expect(handleChange.callCount).to.equal(0);
await userEvent.keyboard('[Tab]');
expect(handleChange.callCount).to.equal(1);
expect(handleChange.returned(input)).to.equal(true);
});
it('fires when changing the value with step buttons', async () => {
const handleChange = spy((event) => event.target);
const { getByTestId } = render(
<NumberInput
defaultValue={10}
onChange={handleChange}
slotProps={{
incrementButton: {
'data-testid': 'increment-btn',
} as NumberInputIncrementButtonSlotProps & { 'data-testid': string },
decrementButton: {
'data-testid': 'decrement-btn',
} as NumberInputDecrementButtonSlotProps & { 'data-testid': string },
}}
/>,
);
const incrementButton = getByTestId('increment-btn');
const decrementButton = getByTestId('decrement-btn');
await userEvent.click(incrementButton);
expect(handleChange.callCount).to.equal(1);
expect(handleChange.returned(incrementButton)).to.equal(true);
await userEvent.click(decrementButton);
expect(handleChange.callCount).to.equal(2);
expect(handleChange.returned(decrementButton)).to.equal(true);
});
});
describe('step buttons', () => {
it('clicking the increment and decrement buttons changes the value', async () => {
const handleChange = spy();
const { getByTestId, getByRole } = render(
<NumberInput
defaultValue={10}
onChange={handleChange}
slotProps={{
incrementButton: {
'data-testid': 'increment-btn',
} as NumberInputIncrementButtonSlotProps & { 'data-testid': string },
decrementButton: {
'data-testid': 'decrement-btn',
} as NumberInputDecrementButtonSlotProps & { 'data-testid': string },
}}
/>,
);
const input = getByRole('textbox') as HTMLInputElement;
const incrementButton = getByTestId('increment-btn');
const decrementButton = getByTestId('decrement-btn');
await userEvent.click(incrementButton);
expect(handleChange.args[0][1]).to.equal(11);
expect(input.value).to.equal('11');
await userEvent.click(decrementButton);
await userEvent.click(decrementButton);
expect(handleChange.callCount).to.equal(3);
expect(handleChange.args[2][1]).to.equal(9);
expect(input.value).to.equal('9');
});
it('clicking the increment and decrement buttons changes the value based on shiftMultiplier if the Shift key is held', () => {
const handleChange = spy();
const { getByTestId, getByRole } = render(
<NumberInput
defaultValue={20}
shiftMultiplier={5}
onChange={handleChange}
slotProps={{
incrementButton: {
'data-testid': 'increment-btn',
} as NumberInputIncrementButtonSlotProps & { 'data-testid': string },
decrementButton: {
'data-testid': 'decrement-btn',
} as NumberInputDecrementButtonSlotProps & { 'data-testid': string },
}}
/>,
);
const input = getByRole('textbox') as HTMLInputElement;
const incrementButton = getByTestId('increment-btn');
const decrementButton = getByTestId('decrement-btn');
fireEvent.click(incrementButton, { shiftKey: true });
fireEvent.click(incrementButton, { shiftKey: true });
expect(handleChange.args[1][1]).to.equal(30);
expect(input.value).to.equal('30');
fireEvent.click(decrementButton, { shiftKey: true });
expect(handleChange.args[2][1]).to.equal(25);
expect(handleChange.callCount).to.equal(3);
expect(input.value).to.equal('25');
});
it('clicking on the stepper buttons will focus the input', async () => {
const { getByTestId, getByRole } = render(
<NumberInput
defaultValue={10}
slotProps={{
incrementButton: {
'data-testid': 'increment-btn',
} as NumberInputIncrementButtonSlotProps & { 'data-testid': string },
decrementButton: {
'data-testid': 'decrement-btn',
} as NumberInputDecrementButtonSlotProps & { 'data-testid': string },
}}
/>,
);
const input = getByRole('textbox') as HTMLInputElement;
const incrementButton = getByTestId('increment-btn');
const decrementButton = getByTestId('decrement-btn');
expect(document.activeElement).to.equal(document.body);
await userEvent.click(incrementButton);
expect(document.activeElement).to.equal(input);
act(() => {
input.blur();
});
expect(document.activeElement).to.equal(document.body);
await userEvent.click(decrementButton);
expect(document.activeElement).to.equal(input);
});
});
describe('keyboard interaction', () => {
it('ArrowUp and ArrowDown changes the value', async () => {
const handleChange = spy();
const { getByRole } = render(<NumberInput defaultValue={10} onChange={handleChange} />);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[ArrowUp]');
await userEvent.keyboard('[ArrowUp]');
expect(handleChange.callCount).to.equal(2);
expect(handleChange.args[1][1]).to.equal(12);
expect(input.value).to.equal('12');
await userEvent.keyboard('[ArrowDown]');
expect(handleChange.callCount).to.equal(3);
expect(handleChange.args[2][1]).to.equal(11);
expect(input.value).to.equal('11');
});
it('ArrowUp and ArrowDown changes the value based on a custom step', async () => {
const handleChange = spy();
const { getByRole } = render(
<NumberInput defaultValue={10} step={5} onChange={handleChange} />,
);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[ArrowUp]');
await userEvent.keyboard('[ArrowUp]');
expect(handleChange.args[1][1]).to.equal(20);
expect(input.value).to.equal('20');
await userEvent.keyboard('[ArrowDown]');
expect(handleChange.args[2][1]).to.equal(15);
expect(handleChange.callCount).to.equal(3);
expect(input.value).to.equal('15');
});
it('ArrowUp and ArrowDown changes the value based on shiftMultiplier if the Shift key is held', async () => {
const handleChange = spy();
const { getByRole } = render(
<NumberInput defaultValue={20} shiftMultiplier={5} onChange={handleChange} />,
);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('{Shift>}[ArrowUp]/');
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.equal(25);
expect(input.value).to.equal('25');
await userEvent.keyboard('{Shift>}[ArrowDown][ArrowDown]{/Shift}');
expect(handleChange.args[2][1]).to.equal(15);
expect(handleChange.callCount).to.equal(3);
expect(input.value).to.equal('15');
});
it('PageUp and PageDown changes the value based on shiftMultiplier', async () => {
const handleChange = spy();
const { getByRole } = render(
<NumberInput defaultValue={20} shiftMultiplier={5} onChange={handleChange} />,
);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[PageUp]');
expect(handleChange.args[0][1]).to.equal(25);
expect(input.value).to.equal('25');
await userEvent.keyboard('[PageDown][PageDown]');
expect(handleChange.args[2][1]).to.equal(15);
expect(handleChange.callCount).to.equal(3);
expect(input.value).to.equal('15');
});
it('sets value to max when Home is pressed', async () => {
const handleChange = spy();
const { getByRole } = render(
<NumberInput defaultValue={10} max={50} onChange={handleChange} />,
);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[Home]');
expect(handleChange.args[0][1]).to.equal(50);
expect(input.value).to.equal('50');
});
it('sets value to min when End is pressed', async () => {
const handleChange = spy();
const { getByRole } = render(
<NumberInput defaultValue={10} min={1} onChange={handleChange} />,
);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[End]');
expect(handleChange.args[0][1]).to.equal(1);
expect(input.value).to.equal('1');
});
it('sets value to min when the input has no value and ArrowUp is pressed', async () => {
const handleChange = spy();
const { getByRole } = render(<NumberInput min={5} onChange={handleChange} />);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[ArrowUp]');
expect(handleChange.args[0][1]).to.equal(5);
expect(input.value).to.equal('5');
});
it('sets value to max when the input has no value and ArrowDown is pressed', async () => {
const handleChange = spy();
const { getByRole } = render(<NumberInput max={9} onChange={handleChange} />);
const input = getByRole('textbox') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('[ArrowDown]');
expect(handleChange.args[0][1]).to.equal(9);
expect(input.value).to.equal('9');
});
it('only includes the input element in the tab order', async () => {
const { getByRole } = render(<NumberInput />);
const input = getByRole('textbox') as HTMLInputElement;
expect(document.activeElement).to.equal(document.body);
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(input);
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
});
});
describe('prop: startAdornment, prop: endAdornment', () => {
it('should render adornment before input', () => {
const { getByTestId } = render(
<NumberInput startAdornment={<span data-testid="adornment">$</span>} />,
);
expect(getByTestId('adornment')).not.to.equal(null);
});
it('should render adornment after input', () => {
const { getByTestId } = render(
<NumberInput endAdornment={<span data-testid="adornment">$</span>} />,
);
expect(getByTestId('adornment')).not.to.equal(null);
});
});
});
| 6,258 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_NumberInput/NumberInput.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { OverridableComponent } from '@mui/types';
import { getNumberInputUtilityClass } from './numberInputClasses';
import { unstable_useNumberInput as useNumberInput } from '../unstable_useNumberInput';
import {
NumberInputOwnerState,
NumberInputProps,
NumberInputRootSlotProps,
NumberInputInputSlotProps,
NumberInputIncrementButtonSlotProps,
NumberInputDecrementButtonSlotProps,
NumberInputTypeMap,
} from './NumberInput.types';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { EventHandlers, useSlotProps, WithOptionalOwnerState } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
const useUtilityClasses = (ownerState: NumberInputOwnerState) => {
const {
disabled,
error,
focused,
readOnly,
formControlContext,
isIncrementDisabled,
isDecrementDisabled,
startAdornment,
endAdornment,
} = ownerState;
const slots = {
root: [
'root',
disabled && 'disabled',
error && 'error',
focused && 'focused',
readOnly && 'readOnly',
Boolean(formControlContext) && 'formControl',
Boolean(startAdornment) && 'adornedStart',
Boolean(endAdornment) && 'adornedEnd',
],
input: ['input', disabled && 'disabled', readOnly && 'readOnly'],
incrementButton: ['incrementButton', isIncrementDisabled && 'disabled'],
decrementButton: ['decrementButton', isDecrementDisabled && 'disabled'],
};
return composeClasses(slots, useClassNamesOverride(getNumberInputUtilityClass));
};
/**
*
* Demos:
*
* - [Number Input](https://mui.com/base-ui/react-number-input/)
*
* API:
*
* - [NumberInput API](https://mui.com/base-ui/react-number-input/components-api/#number-input)
*/
const NumberInput = React.forwardRef(function NumberInput(
props: NumberInputProps,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
className,
defaultValue,
disabled,
endAdornment,
error,
id,
max,
min,
onBlur,
onInputChange,
onFocus,
onChange,
placeholder,
required,
readOnly = false,
shiftMultiplier,
startAdornment,
step,
value,
slotProps = {},
slots = {},
...rest
} = props;
const {
getRootProps,
getInputProps,
getIncrementButtonProps,
getDecrementButtonProps,
focused,
error: errorState,
disabled: disabledState,
formControlContext,
isIncrementDisabled,
isDecrementDisabled,
} = useNumberInput({
min,
max,
step,
shiftMultiplier,
defaultValue,
disabled,
error,
onFocus,
onInputChange,
onBlur,
onChange,
required,
readOnly,
value,
inputId: id,
});
const ownerState: NumberInputOwnerState = {
...props,
disabled: disabledState,
error: errorState,
focused,
readOnly,
formControlContext,
isIncrementDisabled,
isDecrementDisabled,
};
const classes = useUtilityClasses(ownerState);
const propsForwardedToInputSlot = {
placeholder,
};
const Root = slots.root ?? 'div';
const rootProps: WithOptionalOwnerState<NumberInputRootSlotProps> = useSlotProps({
elementType: Root,
getSlotProps: getRootProps,
externalSlotProps: slotProps.root,
externalForwardedProps: rest,
additionalProps: {
ref: forwardedRef,
},
ownerState,
className: [classes.root, className],
});
const Input = slots.input ?? 'input';
const inputProps: WithOptionalOwnerState<NumberInputInputSlotProps> = useSlotProps({
elementType: Input,
getSlotProps: (otherHandlers: EventHandlers) =>
getInputProps({ ...propsForwardedToInputSlot, ...otherHandlers }),
externalSlotProps: slotProps.input,
ownerState,
className: classes.input,
});
const IncrementButton = slots.incrementButton ?? 'button';
const incrementButtonProps: WithOptionalOwnerState<NumberInputIncrementButtonSlotProps> =
useSlotProps({
elementType: IncrementButton,
getSlotProps: getIncrementButtonProps,
externalSlotProps: slotProps.incrementButton,
ownerState,
className: classes.incrementButton,
});
const DecrementButton = slots.decrementButton ?? 'button';
const decrementButtonProps: WithOptionalOwnerState<NumberInputDecrementButtonSlotProps> =
useSlotProps({
elementType: DecrementButton,
getSlotProps: getDecrementButtonProps,
externalSlotProps: slotProps.decrementButton,
ownerState,
className: classes.decrementButton,
});
return (
<Root {...rootProps}>
<DecrementButton {...decrementButtonProps} />
<IncrementButton {...incrementButtonProps} />
{startAdornment}
<Input {...inputProps} />
{endAdornment}
</Root>
);
}) as OverridableComponent<NumberInputTypeMap>;
NumberInput.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,
/**
* 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.
*/
error: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The maximum value.
*/
max: PropTypes.number,
/**
* The minimum value.
*/
min: PropTypes.number,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired after the value is clamped and changes - when the `input` is blurred or when
* the stepper buttons are triggered.
* Called with `undefined` when the value is unset.
*
* @param {React.FocusEvent<HTMLInputElement>|React.PointerEvent|React.KeyboardEvent} event The event source of the callback
* @param {number|undefined} value The new value of the component
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* Callback fired when the `input` value changes after each keypress, before clamping is applied.
* Note that `event.target.value` may contain values that fall outside of `min` and `max` or
* are otherwise "invalid".
*
* @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
*/
onInputChange: PropTypes.func,
/**
* @ignore
*/
placeholder: PropTypes.string,
/**
* If `true`, the `input` element becomes read-only. The stepper buttons remain active,
* with the addition that they are now keyboard focusable.
* @default false
*/
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,
/**
* Multiplier applied to `step` if the shift key is held while incrementing
* or decrementing the value. Defaults to `10`.
*/
shiftMultiplier: PropTypes.number,
/**
* The props used for each slot inside the NumberInput.
* @default {}
*/
slotProps: PropTypes.shape({
decrementButton: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
incrementButton: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
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({
decrementButton: PropTypes.elementType,
incrementButton: PropTypes.elementType,
input: PropTypes.elementType,
root: PropTypes.elementType,
}),
/**
* Leading adornment for this input.
*/
startAdornment: PropTypes.node,
/**
* The amount that the value changes on each increment or decrement.
*/
step: PropTypes.number,
/**
* The current value. Use when the component is controlled.
*/
value: PropTypes.number,
} as any;
export { NumberInput };
| 6,259 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_NumberInput/NumberInput.types.ts | import { Simplify } from '@mui/types';
import { FormControlState } from '../FormControl';
import {
UseNumberInputParameters,
UseNumberInputRootSlotProps,
UseNumberInputIncrementButtonSlotProps,
UseNumberInputDecrementButtonSlotProps,
} from '../unstable_useNumberInput/useNumberInput.types';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export interface NumberInputRootSlotPropsOverrides {}
export interface NumberInputInputSlotPropsOverrides {}
export interface NumberInputStepperButtonSlotPropsOverrides {}
export type NumberInputOwnProps = Omit<UseNumberInputParameters, 'error'> & {
/**
* 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.
*/
error?: boolean;
/**
* The id of the `input` element.
*/
id?: string;
/**
* The props used for each slot inside the NumberInput.
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', NumberInputRootSlotPropsOverrides, NumberInputOwnerState>;
input?: SlotComponentProps<'input', NumberInputInputSlotPropsOverrides, NumberInputOwnerState>;
incrementButton?: SlotComponentProps<
'button',
NumberInputStepperButtonSlotPropsOverrides,
NumberInputOwnerState
>;
decrementButton?: SlotComponentProps<
'button',
NumberInputStepperButtonSlotPropsOverrides,
NumberInputOwnerState
>;
};
/**
* The components used for each slot inside the InputBase.
* Either a string to use a HTML element or a component.
* @default {}
*/
slots?: NumberInputSlots;
/**
* Leading adornment for this input.
*/
startAdornment?: React.ReactNode;
};
export interface NumberInputSlots {
/**
* 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 increment button.
* @default 'button'
*/
incrementButton?: React.ElementType;
/**
* The component that renders the decrement button.
* @default 'button'
*/
decrementButton?: React.ElementType;
}
export interface NumberInputTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: AdditionalProps & NumberInputOwnProps;
defaultComponent: RootComponentType;
}
export type NumberInputProps<
RootComponentType extends React.ElementType = NumberInputTypeMap['defaultComponent'],
> = PolymorphicProps<NumberInputTypeMap<{}, RootComponentType>, RootComponentType>;
export type NumberInputOwnerState = Simplify<
NumberInputOwnProps & {
formControlContext: FormControlState | undefined;
focused: boolean;
isIncrementDisabled: boolean;
isDecrementDisabled: boolean;
}
>;
export type NumberInputRootSlotProps = Simplify<
UseNumberInputRootSlotProps & {
ownerState: NumberInputOwnerState;
className?: string;
children?: React.ReactNode;
ref?: React.Ref<Element>;
}
>;
export type NumberInputInputSlotProps = Simplify<
Omit<UseNumberInputRootSlotProps, 'onClick'> & {
id: string | undefined;
ownerState: NumberInputOwnerState;
placeholder: string | undefined;
ref: React.Ref<HTMLInputElement>;
}
>;
export type NumberInputIncrementButtonSlotProps = Simplify<
UseNumberInputIncrementButtonSlotProps & {
ownerState: NumberInputOwnerState;
}
>;
export type NumberInputDecrementButtonSlotProps = Simplify<
UseNumberInputDecrementButtonSlotProps & {
ownerState: NumberInputOwnerState;
}
>;
| 6,260 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_NumberInput/index.ts | 'use client';
export { NumberInput as Unstable_NumberInput } from './NumberInput';
export * from './numberInputClasses';
export * from './NumberInput.types';
| 6,261 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_NumberInput/numberInputClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface NumberInputClasses {
/** 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;
/** Class name applied to the root element if the component is focused. */
focused: string;
/** Class name applied to the root element if `disabled={true}`. */
disabled: string;
/** State class applied to the root element if `readOnly={true}`. */
readOnly: string;
/** State class applied to the root element if `error={true}`. */
error: string;
/** Class name applied to the input element. */
input: string;
/** Class name applied to the increment button element. */
incrementButton: string;
/** Class name applied to the decrement button element. */
decrementButton: string;
}
export type NumberInputClassKey = keyof NumberInputClasses;
export function getNumberInputUtilityClass(slot: string): string {
return generateUtilityClass('MuiNumberInput', slot);
}
export const numberInputClasses: NumberInputClasses = generateUtilityClasses('MuiNumberInput', [
'root',
'formControl',
'focused',
'disabled',
'readOnly',
'error',
'input',
'incrementButton',
'decrementButton',
'adornedStart',
'adornedEnd',
]);
| 6,262 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_Popup/Popup.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import {
act,
createRenderer,
createMount,
describeConformanceUnstyled,
screen,
fireEvent,
} from '@mui-internal/test-utils';
import {
Unstable_Popup as Popup,
popupClasses,
PopupProps,
PopupChildrenProps,
} from '@mui/base/Unstable_Popup';
type FakeTransitionProps = Omit<PopupChildrenProps, 'placement'> & {
children: React.ReactNode;
};
const TRANSITION_DURATION = 100;
function FakeTransition(props: FakeTransitionProps) {
const { children: transitionChildren, requestOpen, onExited, onEnter } = props;
React.useEffect(() => {
let timeoutId: NodeJS.Timeout | null = null;
if (requestOpen) {
onEnter();
} else {
timeoutId = setTimeout(() => {
act(() => onExited());
}, TRANSITION_DURATION);
}
return () => {
if (timeoutId !== null) {
onExited();
clearTimeout(timeoutId);
timeoutId = null;
}
};
}, [requestOpen, onExited, onEnter]);
return <div>{transitionChildren}</div>;
}
describe('<Popup />', () => {
const { clock, render } = createRenderer();
const mount = createMount();
// https://floating-ui.com/docs/react#testing
async function waitForPosition() {
if (/jsdom/.test(window.navigator.userAgent)) {
// This is only needed for JSDOM and causes issues in real browsers
await act(() => async () => {});
}
}
const defaultProps: PopupProps = {
anchor: () => document.createElement('div'),
children: <span>Hello World</span>,
open: true,
};
describeConformanceUnstyled(<Popup {...defaultProps} />, () => ({
inheritComponent: 'div',
render: async (...renderArgs) => {
const result = render(...renderArgs);
await waitForPosition();
return result;
},
mount,
refInstanceof: window.HTMLDivElement,
skip: [
// https://github.com/facebook/react/issues/11565
'reactTestRenderer',
'componentProp',
],
slots: {
root: {
expectedClassName: popupClasses.root,
},
},
}));
describe('prop: placement', () => {
it('should have top placement', async () => {
render(
<Popup {...defaultProps} placement="top">
{({ placement }: PopupChildrenProps) => {
return <span data-testid="renderSpy" data-placement={placement} />;
}}
</Popup>,
);
await waitForPosition();
expect(screen.getByTestId('renderSpy')).to.have.attribute('data-placement', 'top');
});
it('should respect the RTL setting', async function test() {
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
function RtlTest() {
const [anchor, setAnchor] = React.useState<HTMLDivElement | null>(null);
const [isRtl, setIsRtl] = React.useState(false);
const handleClick = () => {
setIsRtl((rtl) => !rtl);
};
return (
<div dir={isRtl ? 'rtl' : undefined}>
<div
tabIndex={0}
role="button"
ref={setAnchor}
style={{ width: '200px' }}
onClick={handleClick}
>
Anchor
</div>
<Popup anchor={anchor} open placement="top-start" disablePortal>
<div style={{ width: '50px', overflow: 'hidden' }}>Popup</div>
</Popup>
</div>
);
}
render(<RtlTest />);
await waitForPosition();
await new Promise((resolve) => {
requestAnimationFrame(resolve);
});
const anchor = screen.getByRole('button')!;
const popup = screen.getByRole('tooltip')!;
expect(popup.getBoundingClientRect().left).to.equal(anchor.getBoundingClientRect().left);
expect(popup.getBoundingClientRect().right).not.to.equal(
anchor.getBoundingClientRect().right,
);
act(() => {
anchor.click();
});
await waitForPosition();
expect(popup.getBoundingClientRect().right).to.equal(popup.getBoundingClientRect().right);
expect(popup.getBoundingClientRect().left).not.to.equal(anchor.getBoundingClientRect().left);
});
it('should flip placement when edge is reached', async function test() {
// JSDOM has no layout engine so PopperJS doesn't know that it should flip the placement.
if (/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
function FlipTest() {
const [anchor, setAnchor] = React.useState<HTMLButtonElement | null>(null);
const containerRef = React.useRef<HTMLDivElement>(null);
const handleClick = () => {
containerRef.current!.scrollTop = 30;
};
return (
<div
style={{ height: '100px', overflow: 'scroll', position: 'relative' }}
ref={containerRef}
>
<div style={{ height: '100px', padding: '20px' }}>
<button type="button" ref={setAnchor} onClick={handleClick}>
Scroll
</button>
<Popup anchor={anchor} open placement="top" disablePortal>
{({ placement }: PopupChildrenProps) => <span>{placement}</span>}
</Popup>
</div>
</div>
);
}
render(<FlipTest />);
expect(screen.getByRole('tooltip')).to.have.text('top');
act(() => screen.getByRole('button').click());
// wait for the scroll event to trigger the update
await new Promise((resolve) => {
requestAnimationFrame(resolve);
});
expect(screen.getByRole('tooltip')).to.have.text('bottom');
});
});
describe('prop: open', () => {
it('should open without any issues', async () => {
const { queryByRole, getByRole, setProps } = render(<Popup {...defaultProps} open={false} />);
await waitForPosition();
expect(queryByRole('tooltip')).to.equal(null);
setProps({ open: true });
await waitForPosition();
expect(getByRole('tooltip')).to.have.text('Hello World');
});
it('should close without any issues', async () => {
const { queryByRole, getByRole, setProps } = render(<Popup {...defaultProps} />);
await waitForPosition();
expect(getByRole('tooltip')).to.have.text('Hello World');
setProps({ open: false });
await waitForPosition();
expect(queryByRole('tooltip')).to.equal(null);
});
});
describe('prop: keepMounted', () => {
it('should keep the children mounted in the DOM', async () => {
render(<Popup {...defaultProps} keepMounted open={false} />);
await waitForPosition();
const tooltip = document.querySelector('[role="tooltip"]') as HTMLElement;
expect(tooltip).to.have.text('Hello World');
expect(tooltip.style.display).to.equal('none');
});
});
describe('prop: withTransition', () => {
clock.withFakeTimers();
it('should work', async () => {
const { queryByRole, getByRole, setProps } = render(
<Popup {...defaultProps} withTransition>
{({ requestOpen, onExited, onEnter }: PopupChildrenProps) => (
<FakeTransition requestOpen={requestOpen} onExited={onExited} onEnter={onEnter}>
<span>Hello World</span>
</FakeTransition>
)}
</Popup>,
);
await waitForPosition();
expect(getByRole('tooltip')).to.have.text('Hello World');
setProps({ open: false });
await waitForPosition();
clock.tick(TRANSITION_DURATION);
expect(queryByRole('tooltip')).to.equal(null);
});
// Test case for https://github.com/mui/material-ui/issues/15180
it('should remove the transition children in the DOM when closed whilst transition status is entering', async () => {
class OpenClose extends React.Component {
state = {
open: false,
};
handleClick = () => {
this.setState({ open: true }, () => {
this.setState({ open: false });
});
};
render() {
return (
<div>
<button type="button" onClick={this.handleClick}>
Toggle Tooltip
</button>
<Popup {...defaultProps} open={this.state.open} withTransition>
{({ requestOpen, onExited, onEnter }: PopupChildrenProps) => (
<FakeTransition requestOpen={requestOpen} onExited={onExited} onEnter={onEnter}>
<p>Hello World</p>
</FakeTransition>
)}
</Popup>
</div>
);
}
}
const { getByRole } = render(<OpenClose />);
await waitForPosition();
expect(document.querySelector('p')).to.equal(null);
fireEvent.click(getByRole('button'));
await waitForPosition();
expect(document.querySelector('p')).to.equal(null);
});
});
describe('prop: disablePortal', () => {
it('when enabled, should render the popup where is is defined', async () => {
const { getByRole, getByTestId } = render(
<div data-testid="parent">
<Popup {...defaultProps} disablePortal />
</div>,
);
await waitForPosition();
const tooltip = getByRole('tooltip');
const parent = getByTestId('parent');
// renders
expect(tooltip.parentNode).to.equal(parent);
});
it('by default, should render the popup in a portal appended to the body element', async () => {
const { getByRole } = render(
<div data-testid="parent">
<Popup {...defaultProps} />
</div>,
);
await waitForPosition();
const tooltip = getByRole('tooltip');
expect(tooltip.parentNode).to.equal(document.body);
});
});
describe('display', () => {
clock.withFakeTimers();
it('should keep display:none when not toggled and transition/keepMounted/disablePortal props are set', async () => {
const { getByRole, setProps } = render(
<Popup {...defaultProps} open={false} keepMounted withTransition disablePortal>
{({ requestOpen, onExited, onEnter }: PopupChildrenProps) => (
<FakeTransition requestOpen={requestOpen} onExited={onExited} onEnter={onEnter}>
<span>Hello World</span>
</FakeTransition>
)}
</Popup>,
);
await waitForPosition();
expect(getByRole('tooltip', { hidden: true }).style.display).to.equal('none');
setProps({ open: true });
await waitForPosition();
clock.tick(TRANSITION_DURATION);
setProps({ open: false });
await waitForPosition();
clock.tick(TRANSITION_DURATION);
expect(getByRole('tooltip', { hidden: true }).style.display).to.equal('none');
});
});
});
| 6,263 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_Popup/Popup.tsx | 'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { autoUpdate, flip, offset, useFloating, VirtualElement } from '@floating-ui/react-dom';
import {
HTMLElementType,
unstable_useEnhancedEffect as useEnhancedEffect,
unstable_useForkRef as useForkRef,
} from '@mui/utils';
import { unstable_composeClasses as composeClasses } from '../composeClasses';
import { Portal } from '../Portal';
import { useSlotProps } from '../utils';
import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
import { getPopupUtilityClass } from './popupClasses';
import { PopupChildrenProps, PopupOwnerState, PopupProps } from './Popup.types';
function useUtilityClasses(ownerState: PopupOwnerState) {
const { open } = ownerState;
const slots = {
root: ['root', open && 'open'],
};
return composeClasses(slots, useClassNamesOverride(getPopupUtilityClass));
}
function resolveAnchor(
anchor:
| VirtualElement
| (() => VirtualElement)
| HTMLElement
| (() => HTMLElement)
| null
| undefined,
): HTMLElement | VirtualElement | null | undefined {
return typeof anchor === 'function' ? anchor() : anchor;
}
/**
*
* Demos:
*
* - [Popup](https://mui.com/base-ui/react-popup/)
*
* API:
*
* - [Popup API](https://mui.com/base-ui/react-popup/components-api/#popup)
*/
const Popup = React.forwardRef(function Popup<RootComponentType extends React.ElementType>(
props: PopupProps<RootComponentType>,
forwardedRef: React.ForwardedRef<Element>,
) {
const {
anchor: anchorProp,
children,
container,
disablePortal = false,
keepMounted = false,
middleware,
offset: offsetProp = 0,
open = false,
placement = 'bottom',
slotProps = {},
slots = {},
strategy = 'absolute',
withTransition = false,
...other
} = props;
const {
refs,
elements,
floatingStyles,
update,
placement: finalPlacement,
} = useFloating({
elements: {
reference: resolveAnchor(anchorProp),
},
open,
middleware: middleware ?? [offset(offsetProp ?? 0), flip()],
placement,
strategy,
whileElementsMounted: !keepMounted ? autoUpdate : undefined,
});
const handleRef = useForkRef(refs.setFloating, forwardedRef);
const [exited, setExited] = React.useState(true);
const handleEntering = () => {
setExited(false);
};
const handleExited = () => {
setExited(true);
};
useEnhancedEffect(() => {
if (keepMounted && open && elements.reference && elements.floating) {
const cleanup = autoUpdate(elements.reference, elements.floating, update);
return cleanup;
}
return undefined;
}, [keepMounted, open, elements, update]);
const ownerState: PopupOwnerState = {
...props,
disablePortal,
keepMounted,
offset,
open,
placement,
finalPlacement,
strategy,
withTransition,
};
const display = !open && keepMounted && (!withTransition || exited) ? 'none' : undefined;
const classes = useUtilityClasses(ownerState);
const Root = slots?.root ?? 'div';
const rootProps = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
externalForwardedProps: other,
ownerState,
className: classes.root,
additionalProps: {
ref: handleRef,
role: 'tooltip',
style: { ...floatingStyles, display },
},
});
const shouldRender = open || keepMounted || (withTransition && !exited);
if (!shouldRender) {
return null;
}
const childProps: PopupChildrenProps = {
placement: finalPlacement,
requestOpen: open,
onExited: handleExited,
onEnter: handleEntering,
};
return (
<Portal disablePortal={disablePortal} container={container}>
<Root {...rootProps}>{typeof children === 'function' ? children(childProps) : children}</Root>
</Portal>
);
});
Popup.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, [virtual element](https://floating-ui.com/docs/virtual-elements),
* or a function that returns either.
* It's used to set the position of the popup.
*/
anchor: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
HTMLElementType,
PropTypes.object,
PropTypes.func,
]),
/**
* @ignore
*/
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 `document.body` in these cases.
*/
container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
HTMLElementType,
PropTypes.func,
]),
/**
* If `true`, the popup will be rendered where it is defined, without the use of portals.
* @default false
*/
disablePortal: PropTypes.bool,
/**
* If `true`, the popup will exist in the DOM even if it's closed.
* Its visibility will be controlled by the `display` CSS property.
*
* Otherwise, a closed popup will be removed from the DOM.
*
* @default false
*/
keepMounted: PropTypes.bool,
/**
* Collection of Floating UI middleware to use when positioning the popup.
* If not provided, the [`offset`](https://floating-ui.com/docs/offset)
* and [`flip`](https://floating-ui.com/docs/flip) functions will be used.
*
* @see https://floating-ui.com/docs/computePosition#middleware
*/
middleware: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.oneOf([false]),
PropTypes.shape({
fn: PropTypes.func.isRequired,
name: PropTypes.string.isRequired,
options: PropTypes.any,
}),
]),
),
/**
* Distance between a popup and the trigger element.
* This prop is ignored when custom `middleware` is provided.
*
* @default 0
* @see https://floating-ui.com/docs/offset
*/
offset: PropTypes.oneOfType([
PropTypes.func,
PropTypes.number,
PropTypes.shape({
alignmentAxis: PropTypes.number,
crossAxis: PropTypes.number,
mainAxis: PropTypes.number,
}),
]),
/**
* If `true`, the popup is visible.
*
* @default false
*/
open: PropTypes.bool,
/**
* Determines where to place the popup relative to the trigger element.
*
* @default 'bottom'
* @see https://floating-ui.com/docs/computePosition#placement
*/
placement: PropTypes.oneOf([
'bottom-end',
'bottom-start',
'bottom',
'left-end',
'left-start',
'left',
'right-end',
'right-start',
'right',
'top-end',
'top-start',
'top',
]),
/**
* The props used for each slot inside the Popup.
*
* @default {}
*/
slotProps: PropTypes.shape({
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside the Popup.
* Either a string to use a HTML element or a component.
*
* @default {}
*/
slots: PropTypes.shape({
root: PropTypes.elementType,
}),
/**
* The type of CSS position property to use (absolute or fixed).
*
* @default 'absolute'
* @see https://floating-ui.com/docs/computePosition#strategy
*/
strategy: PropTypes.oneOf(['absolute', 'fixed']),
/**
* If `true`, the popup will not disappear immediately when it needs to be closed
* but wait until the exit transition has finished.
* In such a case, a function form of `children` must be used and `onExited`
* callback function must be called when the transition or animation finish.
*
* @default false
*/
withTransition: PropTypes.bool,
} as any;
export { Popup };
| 6,264 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_Popup/Popup.types.ts | import {
Middleware as PopupMiddleware,
OffsetOptions as PopupOffsetOptions,
Placement as PopupPlacement,
Strategy as PopupStrategy,
VirtualElement as PopupVirtualElement,
} from '@floating-ui/react-dom';
import { PortalProps } from '../Portal';
import { PolymorphicProps, SlotComponentProps } from '../utils';
export type {
PopupPlacement,
PopupStrategy,
PopupOffsetOptions,
PopupMiddleware,
PopupVirtualElement,
};
export interface PopupRootSlotPropsOverrides {}
export interface PopupOwnProps {
/**
* An HTML element, [virtual element](https://floating-ui.com/docs/virtual-elements),
* or a function that returns either.
* It's used to set the position of the popup.
*/
anchor?:
| PopupVirtualElement
| HTMLElement
| (() => HTMLElement)
| (() => PopupVirtualElement)
| null;
children?: React.ReactNode | ((props: PopupChildrenProps) => 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 `document.body` in these cases.
*/
container?: PortalProps['container'];
/**
* If `true`, the popup will be rendered where it is defined, without the use of portals.
* @default false
*/
disablePortal?: boolean;
/**
* If `true`, the popup will exist in the DOM even if it's closed.
* Its visibility will be controlled by the `display` CSS property.
*
* Otherwise, a closed popup will be removed from the DOM.
*
* @default false
*/
keepMounted?: boolean;
/**
* Collection of Floating UI middleware to use when positioning the popup.
* If not provided, the [`offset`](https://floating-ui.com/docs/offset)
* and [`flip`](https://floating-ui.com/docs/flip) functions will be used.
*
* @see https://floating-ui.com/docs/computePosition#middleware
*/
middleware?: Array<PopupMiddleware | null | undefined | false>;
/**
* Distance between a popup and the trigger element.
* This prop is ignored when custom `middleware` is provided.
*
* @default 0
* @see https://floating-ui.com/docs/offset
*/
offset?: PopupOffsetOptions;
/**
* If `true`, the popup is visible.
*
* @default false
*/
open?: boolean;
/**
* Determines where to place the popup relative to the trigger element.
*
* @default 'bottom'
* @see https://floating-ui.com/docs/computePosition#placement
*/
placement?: PopupPlacement;
/**
* The components used for each slot inside the Popup.
* Either a string to use a HTML element or a component.
*
* @default {}
*/
slots?: {
root?: React.ElementType;
};
/**
* The props used for each slot inside the Popup.
*
* @default {}
*/
slotProps?: {
root?: SlotComponentProps<'div', PopupRootSlotPropsOverrides, PopupProps>;
};
/**
* The type of CSS position property to use (absolute or fixed).
*
* @default 'absolute'
* @see https://floating-ui.com/docs/computePosition#strategy
*/
strategy?: PopupStrategy;
/**
* If `true`, the popup will not disappear immediately when it needs to be closed
* but wait until the exit transition has finished.
* In such a case, a function form of `children` must be used and `onExited`
* callback function must be called when the transition or animation finish.
*
* @default false
*/
withTransition?: boolean;
}
export interface PopupSlots {
/**
* The component that renders the root.
* @default 'div'
*/
root?: React.ElementType;
}
export interface PopupChildrenProps {
placement: PopupPlacement;
requestOpen: boolean;
onExited: () => void;
onEnter: () => void;
}
export interface PopupTypeMap<
AdditionalProps = {},
RootComponentType extends React.ElementType = 'div',
> {
props: PopupOwnProps & AdditionalProps;
defaultComponent: RootComponentType;
}
export type PopupProps<
RootComponentType extends React.ElementType = PopupTypeMap['defaultComponent'],
> = PolymorphicProps<PopupTypeMap<{}, RootComponentType>, RootComponentType>;
export interface PopupOwnerState extends PopupOwnProps {
disablePortal: boolean;
open: boolean;
keepMounted: boolean;
offset: PopupOffsetOptions;
placement: PopupPlacement;
finalPlacement: PopupPlacement;
strategy: PopupStrategy;
withTransition: boolean;
}
| 6,265 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_Popup/index.ts | 'use client';
export { Popup as Unstable_Popup } from './Popup';
export * from './Popup.types';
export * from './popupClasses';
| 6,266 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/Unstable_Popup/popupClasses.ts | import { generateUtilityClass } from '../generateUtilityClass';
import { generateUtilityClasses } from '../generateUtilityClasses';
export interface PopupClasses {
/** Class name applied to the root element. */
root: string;
/** Class name applied to the root element when the popup is open. */
open: string;
}
export type PopupClassKey = keyof PopupClasses;
export function getPopupUtilityClass(slot: string): string {
return generateUtilityClass('MuiPopup', slot);
}
export const popupClasses: PopupClasses = generateUtilityClasses('MuiPopup', ['root', 'open']);
| 6,267 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/composeClasses/index.ts | export { unstable_composeClasses } from '@mui/utils';
| 6,268 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/generateUtilityClass/index.ts | export { unstable_generateUtilityClass as generateUtilityClass } from '@mui/utils';
export type { GlobalStateSlot } from '@mui/utils';
| 6,269 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/generateUtilityClasses/index.ts | export { unstable_generateUtilityClasses as generateUtilityClasses } from '@mui/utils';
| 6,270 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useModal/ModalManager.test.ts | import { expect } from 'chai';
import { unstable_getScrollbarSize as getScrollbarSize } from '@mui/utils';
import { ModalManager } from './ModalManager';
interface Modal {
mount: Element;
modalRef: Element;
}
function getDummyModal(): Modal {
return {
mount: document.createElement('div'),
modalRef: document.createElement('div'),
};
}
describe('ModalManager', () => {
let modalManager: ModalManager;
let container1: HTMLDivElement;
before(() => {
modalManager = new ModalManager();
container1 = document.createElement('div');
container1.style.paddingRight = '20px';
Object.defineProperty(container1, 'scrollHeight', {
value: 100,
writable: false,
});
Object.defineProperty(container1, 'clientHeight', {
value: 90,
writable: false,
});
document.body.appendChild(container1);
});
after(() => {
document.body.removeChild(container1);
});
it('should add a modal only once', () => {
const modal = getDummyModal();
const modalManager2 = new ModalManager();
const idx = modalManager2.add(modal, container1);
modalManager2.mount(modal, {});
expect(modalManager2.add(modal, container1)).to.equal(idx);
modalManager2.remove(modal);
});
describe('managing modals', () => {
let modal1: Modal;
let modal2: Modal;
let modal3: Modal;
before(() => {
modal1 = getDummyModal();
modal2 = getDummyModal();
modal3 = getDummyModal();
});
it('should add modal1', () => {
const idx = modalManager.add(modal1, container1);
modalManager.mount(modal1, {});
expect(idx).to.equal(0);
expect(modalManager.isTopModal(modal1)).to.equal(true);
});
it('should add modal2', () => {
const idx = modalManager.add(modal2, container1);
expect(idx).to.equal(1);
expect(modalManager.isTopModal(modal2)).to.equal(true);
});
it('should add modal3', () => {
const idx = modalManager.add(modal3, container1);
expect(idx).to.equal(2);
expect(modalManager.isTopModal(modal3)).to.equal(true);
});
it('should remove modal2', () => {
const idx = modalManager.remove(modal2);
expect(idx).to.equal(1);
});
it('should add modal2 2', () => {
const idx = modalManager.add(modal2, container1);
modalManager.mount(modal2, {});
expect(idx).to.equal(2);
expect(modalManager.isTopModal(modal2)).to.equal(true);
expect(modalManager.isTopModal(modal3)).to.equal(false);
});
it('should remove modal3', () => {
const idx = modalManager.remove(modal3);
expect(idx).to.equal(1);
});
it('should remove modal2 2', () => {
const idx = modalManager.remove(modal2);
expect(idx).to.equal(1);
expect(modalManager.isTopModal(modal1)).to.equal(true);
});
it('should remove modal1', () => {
const idx = modalManager.remove(modal1);
expect(idx).to.equal(0);
});
it('should not do anything', () => {
const idx = modalManager.remove(getDummyModal());
expect(idx).to.equal(-1);
});
});
describe('overflow', () => {
let fixedNode: HTMLDivElement;
beforeEach(() => {
container1.style.paddingRight = '20px';
fixedNode = document.createElement('div');
fixedNode.classList.add('mui-fixed');
document.body.appendChild(fixedNode);
window.innerWidth += 1; // simulate a scrollbar
});
afterEach(() => {
document.body.removeChild(fixedNode);
window.innerWidth -= 1;
});
it('should handle the scroll', () => {
fixedNode.style.paddingRight = '14px';
const modal = getDummyModal();
modalManager.add(modal, container1);
modalManager.mount(modal, {});
expect(container1.style.overflow).to.equal('hidden');
expect(container1.style.paddingRight).to.equal(`${20 + getScrollbarSize(document)}px`);
expect(fixedNode.style.paddingRight).to.equal(`${14 + getScrollbarSize(document)}px`);
modalManager.remove(modal);
expect(container1.style.overflow).to.equal('');
expect(container1.style.paddingRight).to.equal('20px');
expect(fixedNode.style.paddingRight).to.equal('14px');
});
it('should disable the scroll even when not overflowing', () => {
// simulate non-overflowing container
const container2 = document.createElement('div');
Object.defineProperty(container2, 'scrollHeight', {
value: 100,
writable: false,
});
Object.defineProperty(container2, 'clientHeight', {
value: 100,
writable: false,
});
document.body.appendChild(container2);
const modal = getDummyModal();
modalManager.add(modal, container2);
modalManager.mount(modal, {});
expect(container2.style.overflow).to.equal('hidden');
modalManager.remove(modal);
expect(container2.style.overflow).to.equal('');
document.body.removeChild(container2);
});
it('should restore styles correctly if none existed before', () => {
const modal = getDummyModal();
modalManager.add(modal, container1);
modalManager.mount(modal, {});
expect(container1.style.overflow).to.equal('hidden');
expect(container1.style.paddingRight).to.equal(`${20 + getScrollbarSize(document)}px`);
expect(fixedNode.style.paddingRight).to.equal(`${getScrollbarSize(document)}px`);
modalManager.remove(modal);
expect(container1.style.overflow).to.equal('');
expect(container1.style.paddingRight).to.equal('20px');
expect(fixedNode.style.paddingRight).to.equal('');
});
describe('shadow dom', () => {
let shadowContainer: HTMLDivElement;
let container2: HTMLDivElement;
beforeEach(() => {
shadowContainer = document.createElement('div');
const shadowRoot = shadowContainer.attachShadow({ mode: 'open' });
container2 = document.createElement('div');
shadowRoot.appendChild(container2);
});
afterEach(() => {
document.body.removeChild(shadowContainer);
});
it('should scroll body when parent is shadow root', () => {
const modal = getDummyModal();
container2.style.overflow = 'scroll';
document.body.appendChild(shadowContainer);
modalManager.add(modal, container2);
modalManager.mount(modal, {});
expect(container2.style.overflow).to.equal('scroll');
expect(document.body.style.overflow).to.equal('hidden');
modalManager.remove(modal);
expect(container2.style.overflow).to.equal('scroll');
expect(document.body.style.overflow).to.equal('');
});
});
describe('restore styles', () => {
let container2: HTMLDivElement;
beforeEach(() => {
container2 = document.createElement('div');
});
afterEach(() => {
document.body.removeChild(container2);
});
it('should restore styles correctly if overflow existed before', () => {
const modal = getDummyModal();
container2.style.overflow = 'scroll';
Object.defineProperty(container2, 'scrollHeight', {
value: 100,
writable: false,
});
Object.defineProperty(container2, 'clientHeight', {
value: 90,
writable: false,
});
document.body.appendChild(container2);
modalManager.add(modal, container2);
modalManager.mount(modal, {});
expect(container2.style.overflow).to.equal('hidden');
modalManager.remove(modal);
expect(container2.style.overflow).to.equal('scroll');
expect(fixedNode.style.paddingRight).to.equal('');
});
it('should restore styles correctly if overflow-x existed before', () => {
const modal = getDummyModal();
container2.style.overflowX = 'hidden';
Object.defineProperty(container2, 'scrollHeight', {
value: 100,
writable: false,
});
Object.defineProperty(container2, 'clientHeight', {
value: 90,
writable: false,
});
document.body.appendChild(container2);
modalManager.add(modal, container2);
modalManager.mount(modal, {});
expect(container2.style.overflow).to.equal('hidden');
modalManager.remove(modal);
expect(container2.style.overflow).to.equal('');
expect(container2.style.overflowX).to.equal('hidden');
});
});
});
describe('multi container', () => {
let container3: HTMLDivElement;
let container4: HTMLDivElement;
beforeEach(() => {
container3 = document.createElement('div');
document.body.appendChild(container3);
container3.appendChild(document.createElement('div'));
container4 = document.createElement('div');
document.body.appendChild(container4);
container4.appendChild(document.createElement('div'));
});
it('should work will multiple containers', () => {
modalManager = new ModalManager();
const modal1 = getDummyModal();
const modal2 = getDummyModal();
modalManager.add(modal1, container3);
modalManager.mount(modal1, {});
expect(container3.children[0]).toBeAriaHidden();
modalManager.add(modal2, container4);
modalManager.mount(modal2, {});
expect(container4.children[0]).toBeAriaHidden();
modalManager.remove(modal2);
expect(container4.children[0]).not.toBeAriaHidden();
modalManager.remove(modal1);
expect(container3.children[0]).not.toBeAriaHidden();
});
afterEach(() => {
document.body.removeChild(container3);
document.body.removeChild(container4);
});
});
describe('container aria-hidden', () => {
let modalRef1;
let container2: HTMLDivElement;
beforeEach(() => {
container2 = document.createElement('div');
document.body.appendChild(container2);
modalRef1 = document.createElement('div');
container2.appendChild(modalRef1);
modalManager = new ModalManager();
});
afterEach(() => {
document.body.removeChild(container2);
});
it('should not contain aria-hidden on modal', () => {
const modal2 = document.createElement('div');
modal2.setAttribute('aria-hidden', 'true');
expect(modal2).toBeAriaHidden();
modalManager.add({ ...getDummyModal(), modalRef: modal2 }, container2);
expect(modal2).not.toBeAriaHidden();
});
it('should add aria-hidden to container siblings', () => {
const secondSibling = document.createElement('input');
container2.appendChild(secondSibling);
modalManager.add(getDummyModal(), container2);
expect(container2.children[0]).toBeAriaHidden();
expect(container2.children[1]).toBeAriaHidden();
});
it('should not add aria-hidden to forbidden container siblings', () => {
[
'template',
'script',
'style',
'link',
'map',
'meta',
'noscript',
'picture',
'col',
'colgroup',
'param',
'slot',
'source',
'track',
].forEach(function createBlacklistSiblings(name) {
const sibling = document.createElement(name);
container2.appendChild(sibling);
});
const inputHiddenSibling = document.createElement('input');
inputHiddenSibling.setAttribute('type', 'hidden');
container2.appendChild(inputHiddenSibling);
const numberOfChildren = 16;
expect(container2.children.length).equal(numberOfChildren);
modalManager.add(getDummyModal(), container2);
expect(container2.children[0]).toBeAriaHidden();
for (let i = 1; i < numberOfChildren; i += 1) {
expect(container2.children[i]).not.toBeAriaHidden();
}
});
it('should add aria-hidden to previous modals', () => {
const modal2 = document.createElement('div');
const modal3 = document.createElement('div');
container2.appendChild(modal2);
container2.appendChild(modal3);
modalManager.add({ ...getDummyModal(), modalRef: modal2 }, container2);
// Simulate the main React DOM true.
expect(container2.children[0]).toBeAriaHidden();
expect(container2.children[1]).not.toBeAriaHidden();
modalManager.add({ ...getDummyModal(), modalRef: modal3 }, container2);
expect(container2.children[0]).toBeAriaHidden();
expect(container2.children[1]).toBeAriaHidden();
expect(container2.children[2]).not.toBeAriaHidden();
});
it('should remove aria-hidden on siblings', () => {
const modal = { ...getDummyModal(), modalRef: container2.children[0] };
modalManager.add(modal, container2);
modalManager.mount(modal, {});
expect(container2.children[0]).not.toBeAriaHidden();
modalManager.remove(modal);
expect(container2.children[0]).toBeAriaHidden();
});
it('should keep previous aria-hidden siblings hidden', () => {
const modal = { ...getDummyModal(), modalRef: container2.children[0] };
const sibling1 = document.createElement('div');
const sibling2 = document.createElement('div');
sibling1.setAttribute('aria-hidden', 'true');
container2.appendChild(sibling1);
container2.appendChild(sibling2);
modalManager.add(modal, container2);
modalManager.mount(modal, {});
expect(container2.children[0]).not.toBeAriaHidden();
modalManager.remove(modal);
expect(container2.children[0]).toBeAriaHidden();
expect(container2.children[1]).toBeAriaHidden();
expect(container2.children[2]).not.toBeAriaHidden();
});
});
});
| 6,271 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useModal/ModalManager.ts | import {
unstable_ownerWindow as ownerWindow,
unstable_ownerDocument as ownerDocument,
unstable_getScrollbarSize as getScrollbarSize,
} from '@mui/utils';
export interface ManagedModalProps {
disableScrollLock?: boolean;
}
// Is a vertical scrollbar displayed?
function isOverflowing(container: Element): boolean {
const doc = ownerDocument(container);
if (doc.body === container) {
return ownerWindow(container).innerWidth > doc.documentElement.clientWidth;
}
return container.scrollHeight > container.clientHeight;
}
export function ariaHidden(element: Element, show: boolean): void {
if (show) {
element.setAttribute('aria-hidden', 'true');
} else {
element.removeAttribute('aria-hidden');
}
}
function getPaddingRight(element: Element): number {
return parseInt(ownerWindow(element).getComputedStyle(element).paddingRight, 10) || 0;
}
function isAriaHiddenForbiddenOnElement(element: Element): boolean {
// The forbidden HTML tags are the ones from ARIA specification that
// can be children of body and can't have aria-hidden attribute.
// cf. https://www.w3.org/TR/html-aria/#docconformance
const forbiddenTagNames = [
'TEMPLATE',
'SCRIPT',
'STYLE',
'LINK',
'MAP',
'META',
'NOSCRIPT',
'PICTURE',
'COL',
'COLGROUP',
'PARAM',
'SLOT',
'SOURCE',
'TRACK',
];
const isForbiddenTagName = forbiddenTagNames.indexOf(element.tagName) !== -1;
const isInputHidden = element.tagName === 'INPUT' && element.getAttribute('type') === 'hidden';
return isForbiddenTagName || isInputHidden;
}
function ariaHiddenSiblings(
container: Element,
mountElement: Element,
currentElement: Element,
elementsToExclude: readonly Element[],
show: boolean,
): void {
const blacklist = [mountElement, currentElement, ...elementsToExclude];
[].forEach.call(container.children, (element: Element) => {
const isNotExcludedElement = blacklist.indexOf(element) === -1;
const isNotForbiddenElement = !isAriaHiddenForbiddenOnElement(element);
if (isNotExcludedElement && isNotForbiddenElement) {
ariaHidden(element, show);
}
});
}
function findIndexOf<T>(items: readonly T[], callback: (item: T) => boolean): number {
let idx = -1;
items.some((item, index) => {
if (callback(item)) {
idx = index;
return true;
}
return false;
});
return idx;
}
function handleContainer(containerInfo: Container, props: ManagedModalProps) {
const restoreStyle: Array<{
/**
* CSS property name (HYPHEN CASE) to be modified.
*/
property: string;
el: HTMLElement | SVGElement;
value: string;
}> = [];
const container = containerInfo.container;
if (!props.disableScrollLock) {
if (isOverflowing(container)) {
// Compute the size before applying overflow hidden to avoid any scroll jumps.
const scrollbarSize = getScrollbarSize(ownerDocument(container));
restoreStyle.push({
value: container.style.paddingRight,
property: 'padding-right',
el: container,
});
// Use computed style, here to get the real padding to add our scrollbar width.
container.style.paddingRight = `${getPaddingRight(container) + scrollbarSize}px`;
// .mui-fixed is a global helper.
const fixedElements = ownerDocument(container).querySelectorAll('.mui-fixed');
[].forEach.call(fixedElements, (element: HTMLElement | SVGElement) => {
restoreStyle.push({
value: element.style.paddingRight,
property: 'padding-right',
el: element,
});
element.style.paddingRight = `${getPaddingRight(element) + scrollbarSize}px`;
});
}
let scrollContainer: HTMLElement;
if (container.parentNode instanceof DocumentFragment) {
scrollContainer = ownerDocument(container).body;
} else {
// Support html overflow-y: auto for scroll stability between pages
// https://css-tricks.com/snippets/css/force-vertical-scrollbar/
const parent = container.parentElement;
const containerWindow = ownerWindow(container);
scrollContainer =
parent?.nodeName === 'HTML' &&
containerWindow.getComputedStyle(parent).overflowY === 'scroll'
? parent
: container;
}
// Block the scroll even if no scrollbar is visible to account for mobile keyboard
// screensize shrink.
restoreStyle.push(
{
value: scrollContainer.style.overflow,
property: 'overflow',
el: scrollContainer,
},
{
value: scrollContainer.style.overflowX,
property: 'overflow-x',
el: scrollContainer,
},
{
value: scrollContainer.style.overflowY,
property: 'overflow-y',
el: scrollContainer,
},
);
scrollContainer.style.overflow = 'hidden';
}
const restore = () => {
restoreStyle.forEach(({ value, el, property }) => {
if (value) {
el.style.setProperty(property, value);
} else {
el.style.removeProperty(property);
}
});
};
return restore;
}
function getHiddenSiblings(container: Element) {
const hiddenSiblings: Element[] = [];
[].forEach.call(container.children, (element: Element) => {
if (element.getAttribute('aria-hidden') === 'true') {
hiddenSiblings.push(element);
}
});
return hiddenSiblings;
}
interface Modal {
mount: Element;
modalRef: Element;
}
interface Container {
container: HTMLElement;
hiddenSiblings: Element[];
modals: Modal[];
restore: null | (() => void);
}
/**
* @ignore - do not document.
*
* Proper state management for containers and the modals in those containers.
* Simplified, but inspired by react-overlay's ModalManager class.
* Used by the Modal to ensure proper styling of containers.
*/
export class ModalManager {
private containers: Container[];
private modals: Modal[];
constructor() {
this.modals = [];
this.containers = [];
}
add(modal: Modal, container: HTMLElement): number {
let modalIndex = this.modals.indexOf(modal);
if (modalIndex !== -1) {
return modalIndex;
}
modalIndex = this.modals.length;
this.modals.push(modal);
// If the modal we are adding is already in the DOM.
if (modal.modalRef) {
ariaHidden(modal.modalRef, false);
}
const hiddenSiblings = getHiddenSiblings(container);
ariaHiddenSiblings(container, modal.mount, modal.modalRef, hiddenSiblings, true);
const containerIndex = findIndexOf(this.containers, (item) => item.container === container);
if (containerIndex !== -1) {
this.containers[containerIndex].modals.push(modal);
return modalIndex;
}
this.containers.push({
modals: [modal],
container,
restore: null,
hiddenSiblings,
});
return modalIndex;
}
mount(modal: Modal, props: ManagedModalProps): void {
const containerIndex = findIndexOf(
this.containers,
(item) => item.modals.indexOf(modal) !== -1,
);
const containerInfo = this.containers[containerIndex];
if (!containerInfo.restore) {
containerInfo.restore = handleContainer(containerInfo, props);
}
}
remove(modal: Modal, ariaHiddenState = true): number {
const modalIndex = this.modals.indexOf(modal);
if (modalIndex === -1) {
return modalIndex;
}
const containerIndex = findIndexOf(
this.containers,
(item) => item.modals.indexOf(modal) !== -1,
);
const containerInfo = this.containers[containerIndex];
containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);
this.modals.splice(modalIndex, 1);
// If that was the last modal in a container, clean up the container.
if (containerInfo.modals.length === 0) {
// The modal might be closed before it had the chance to be mounted in the DOM.
if (containerInfo.restore) {
containerInfo.restore();
}
if (modal.modalRef) {
// In case the modal wasn't in the DOM yet.
ariaHidden(modal.modalRef, ariaHiddenState);
}
ariaHiddenSiblings(
containerInfo.container,
modal.mount,
modal.modalRef,
containerInfo.hiddenSiblings,
false,
);
this.containers.splice(containerIndex, 1);
} else {
// Otherwise make sure the next top modal is visible to a screen reader.
const nextTop = containerInfo.modals[containerInfo.modals.length - 1];
// as soon as a modal is adding its modalRef is undefined. it can't set
// aria-hidden because the dom element doesn't exist either
// when modal was unmounted before modalRef gets null
if (nextTop.modalRef) {
ariaHidden(nextTop.modalRef, false);
}
}
return modalIndex;
}
isTopModal(modal: Modal): boolean {
return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;
}
}
| 6,272 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useModal/index.ts | 'use client';
export { useModal as unstable_useModal } from './useModal';
export * from './useModal.types';
export * from './ModalManager';
| 6,273 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useModal/useModal.ts | 'use client';
import * as React from 'react';
import {
unstable_ownerDocument as ownerDocument,
unstable_useForkRef as useForkRef,
unstable_useEventCallback as useEventCallback,
unstable_createChainedFunction as createChainedFunction,
} from '@mui/utils';
import { EventHandlers, extractEventHandlers } from '../utils';
import { ModalManager, ariaHidden } from './ModalManager';
import {
UseModalParameters,
UseModalReturnValue,
UseModalRootSlotProps,
UseModalBackdropSlotProps,
} from './useModal.types';
function getContainer(container: UseModalParameters['container']) {
return typeof container === 'function' ? container() : container;
}
function getHasTransition(children: UseModalParameters['children']) {
return children ? children.props.hasOwnProperty('in') : false;
}
// A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
const defaultManager = new ModalManager();
/**
*
* Demos:
*
* - [Modal](https://mui.com/base-ui/react-modal/#hook)
*
* API:
*
* - [useModal API](https://mui.com/base-ui/react-modal/hooks-api/#use-modal)
*/
export function useModal(parameters: UseModalParameters): UseModalReturnValue {
const {
container,
disableEscapeKeyDown = false,
disableScrollLock = false,
// @ts-ignore internal logic - Base UI supports the manager as a prop too
manager = defaultManager,
closeAfterTransition = false,
onTransitionEnter,
onTransitionExited,
children,
onClose,
open,
rootRef,
} = parameters;
// @ts-ignore internal logic
const modal = React.useRef<{ modalRef: HTMLDivElement; mount: HTMLElement }>({});
const mountNodeRef = React.useRef<null | HTMLElement>(null);
const modalRef = React.useRef<HTMLDivElement>(null);
const handleRef = useForkRef(modalRef, rootRef);
const [exited, setExited] = React.useState(!open);
const hasTransition = getHasTransition(children);
let ariaHiddenProp = true;
if (parameters['aria-hidden'] === 'false' || parameters['aria-hidden'] === false) {
ariaHiddenProp = false;
}
const getDoc = () => ownerDocument(mountNodeRef.current);
const getModal = () => {
modal.current.modalRef = modalRef.current!;
modal.current.mount = mountNodeRef.current!;
return modal.current;
};
const handleMounted = () => {
manager.mount(getModal(), { disableScrollLock });
// Fix a bug on Chrome where the scroll isn't initially 0.
if (modalRef.current) {
modalRef.current.scrollTop = 0;
}
};
const handleOpen = useEventCallback(() => {
const resolvedContainer = getContainer(container) || getDoc().body;
manager.add(getModal(), resolvedContainer);
// The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
const isTopModal = React.useCallback(() => manager.isTopModal(getModal()), [manager]);
const handlePortalRef = useEventCallback((node: HTMLElement) => {
mountNodeRef.current = node;
if (!node) {
return;
}
if (open && isTopModal()) {
handleMounted();
} else if (modalRef.current) {
ariaHidden(modalRef.current, ariaHiddenProp);
}
});
const handleClose = React.useCallback(() => {
manager.remove(getModal(), ariaHiddenProp);
}, [ariaHiddenProp, manager]);
React.useEffect(() => {
return () => {
handleClose();
};
}, [handleClose]);
React.useEffect(() => {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
const createHandleKeyDown = (otherHandlers: EventHandlers) => (event: React.KeyboardEvent) => {
otherHandlers.onKeyDown?.(event);
// 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.
if (
event.key !== 'Escape' ||
event.which === 229 || // Wait until IME is settled.
!isTopModal()
) {
return;
}
if (!disableEscapeKeyDown) {
// Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onClose) {
onClose(event, 'escapeKeyDown');
}
}
};
const createHandleBackdropClick = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
otherHandlers.onClick?.(event);
if (event.target !== event.currentTarget) {
return;
}
if (onClose) {
onClose(event, 'backdropClick');
}
};
const getRootProps = <TOther extends EventHandlers = {}>(
otherHandlers: TOther = {} as TOther,
): UseModalRootSlotProps<TOther> => {
const propsEventHandlers = extractEventHandlers(parameters) as Partial<UseModalParameters>;
// The custom event handlers shouldn't be spread on the root element
delete propsEventHandlers.onTransitionEnter;
delete propsEventHandlers.onTransitionExited;
const externalEventHandlers = {
...propsEventHandlers,
...otherHandlers,
};
return {
role: 'presentation',
...externalEventHandlers,
onKeyDown: createHandleKeyDown(externalEventHandlers),
ref: handleRef,
};
};
const getBackdropProps = <TOther extends EventHandlers = {}>(
otherHandlers: TOther = {} as TOther,
): UseModalBackdropSlotProps<TOther> => {
const externalEventHandlers = otherHandlers;
return {
'aria-hidden': true,
...externalEventHandlers,
onClick: createHandleBackdropClick(externalEventHandlers),
open,
};
};
const getTransitionProps = () => {
const handleEnter = () => {
setExited(false);
if (onTransitionEnter) {
onTransitionEnter();
}
};
const handleExited = () => {
setExited(true);
if (onTransitionExited) {
onTransitionExited();
}
if (closeAfterTransition) {
handleClose();
}
};
return {
onEnter: createChainedFunction(handleEnter, children?.props.onEnter),
onExited: createChainedFunction(handleExited, children?.props.onExited),
};
};
return {
getRootProps,
getBackdropProps,
getTransitionProps,
rootRef: handleRef,
portalRef: handlePortalRef,
isTopModal,
exited,
hasTransition,
};
}
| 6,274 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useModal/useModal.types.ts | import { PortalProps } from '../Portal';
import { EventHandlers } from '../utils';
export interface UseModalRootSlotOwnProps {
role: React.AriaRole;
onKeyDown: React.KeyboardEventHandler;
ref: React.RefCallback<Element> | null;
}
export interface UseModalBackdropSlotOwnProps {
'aria-hidden': React.AriaAttributes['aria-hidden'];
onClick: React.MouseEventHandler;
open?: boolean;
}
export type UseModalBackdropSlotProps<TOther = {}> = TOther & UseModalBackdropSlotOwnProps;
export type UseModalRootSlotProps<TOther = {}> = TOther & UseModalRootSlotOwnProps;
export type UseModalParameters = {
'aria-hidden'?: React.AriaAttributes['aria-hidden'];
/**
* A single child content element.
*/
children: React.ReactElement | undefined | null;
/**
* 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`, hitting escape will not fire the `onClose` callback.
* @default false
*/
disableEscapeKeyDown?: boolean;
/**
* Disable the scroll lock behavior.
* @default false
*/
disableScrollLock?: boolean;
/**
* 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'];
onKeyDown?: React.KeyboardEventHandler;
/**
* 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;
rootRef: React.Ref<Element>;
};
export interface UseModalReturnValue {
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <TOther extends EventHandlers = {}>(
externalProps?: TOther,
) => UseModalRootSlotProps<TOther>;
/**
* Resolver for the backdrop slot's props.
* @param externalProps props for the backdrop slot
* @returns props that should be spread on the backdrop slot
*/
getBackdropProps: <TOther extends EventHandlers = {}>(
externalProps?: TOther,
) => UseModalBackdropSlotProps<TOther>;
/**
* Resolver for the transition related props.
* @param externalProps props for the transition element
* @returns props that should be spread on the transition element
*/
getTransitionProps: <TOther extends EventHandlers = {}>(
externalProps?: TOther,
) => { onEnter: () => void; onExited: () => void };
/**
* A ref to the component's root DOM element.
*/
rootRef: React.RefCallback<Element> | null;
/**
* A ref to the component's portal DOM element.
*/
portalRef: React.RefCallback<Element> | null;
/**
* If `true`, the modal is the top most one.
*/
isTopModal: () => boolean;
/**
* If `true`, the exiting transition finished (to be used for unmounting the component).
*/
exited: boolean;
/**
* If `true`, the component's child is transition component.
*/
hasTransition: boolean;
}
| 6,275 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/index.ts | 'use client';
export { useNumberInput as unstable_useNumberInput } from './useNumberInput';
export * from './useNumberInput.types';
| 6,276 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/numberInputAction.types.ts | export const NumberInputActionTypes = {
clamp: 'numberInput:clamp',
inputChange: 'numberInput:inputChange',
increment: 'numberInput:increment',
decrement: 'numberInput:decrement',
decrementToMin: 'numberInput:decrementToMin',
incrementToMax: 'numberInput:incrementToMax',
} as const;
interface NumberInputClampAction {
type: typeof NumberInputActionTypes.clamp;
inputValue: string;
}
interface NumberInputInputChangeAction {
type: typeof NumberInputActionTypes.inputChange;
inputValue: string;
}
interface NumberInputIncrementAction {
type: typeof NumberInputActionTypes.increment;
applyMultiplier: boolean;
}
interface NumberInputDecrementAction {
type: typeof NumberInputActionTypes.decrement;
applyMultiplier: boolean;
}
interface NumberInputIncrementToMaxAction {
type: typeof NumberInputActionTypes.incrementToMax;
}
interface NumberInputDecrementToMinAction {
type: typeof NumberInputActionTypes.decrementToMin;
}
export type NumberInputAction =
| NumberInputClampAction
| NumberInputInputChangeAction
| NumberInputIncrementAction
| NumberInputDecrementAction
| NumberInputIncrementToMaxAction
| NumberInputDecrementToMinAction;
| 6,277 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/numberInputReducer.test.ts | import { expect } from 'chai';
import { NumberInputState, NumberInputReducerAction } from './useNumberInput.types';
import { NumberInputActionTypes } from './numberInputAction.types';
import { numberInputReducer } from './numberInputReducer';
import { getInputValueAsString as defaultGetInputValueAsString } from './useNumberInput';
describe('numberInputReducer', () => {
describe('action: clamp', () => {
it('clamps the inputValue', () => {
const state: NumberInputState = {
value: 1,
inputValue: '1',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.clamp,
inputValue: '1',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(1);
expect(result.inputValue).to.equal('1');
});
it('clamps the inputValue with a custom step', () => {
const state: NumberInputState = {
value: 0,
inputValue: '0',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.clamp,
inputValue: '3',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
step: 4,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(4);
expect(result.inputValue).to.equal('4');
});
it('clamps the inputValue within min if min is set', () => {
const state: NumberInputState = {
value: 0,
inputValue: '0',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.clamp,
inputValue: '0',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
min: 5,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(5);
expect(result.inputValue).to.equal('5');
});
it('clamps the inputValue within max if max is set', () => {
const state: NumberInputState = {
value: 10,
inputValue: '10',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.clamp,
inputValue: '10',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
max: 9,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(9);
expect(result.inputValue).to.equal('9');
});
it('empty value', () => {
const state: NumberInputState = {
value: '',
inputValue: '',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.clamp,
inputValue: '',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal('');
expect(result.inputValue).to.equal('');
});
});
describe('action: inputChange', () => {
it('value contains integers only', () => {
const state: NumberInputState = {
value: 0,
inputValue: '0',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.inputChange,
inputValue: '1',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(1);
expect(result.inputValue).to.equal('1');
});
it('value contains invalid characters', () => {
const state: NumberInputState = {
value: 1,
inputValue: '1',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.inputChange,
inputValue: '1a',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(1);
expect(result.inputValue).to.equal('1');
});
it('value is minus sign', () => {
const state: NumberInputState = {
value: -1,
inputValue: '-1',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.inputChange,
inputValue: '-',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal('');
expect(result.inputValue).to.equal('-');
});
it('empty value', () => {
const state: NumberInputState = {
value: 1,
inputValue: '1',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.inputChange,
inputValue: '',
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal('');
expect(result.inputValue).to.equal('');
});
});
describe('action: increment', () => {
it('increments the value', () => {
const state: NumberInputState = {
value: 0,
inputValue: '0',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.increment,
applyMultiplier: false,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(1);
expect(result.inputValue).to.equal('1');
});
it('increments the value based on the step prop', () => {
const state: NumberInputState = {
value: 0,
inputValue: '0',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.increment,
applyMultiplier: false,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
step: 5,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(5);
expect(result.inputValue).to.equal('5');
});
it('applys the shiftMultiplier when incrementing with shift+click', () => {
const state: NumberInputState = {
value: 0,
inputValue: '0',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.increment,
applyMultiplier: true,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
step: 1,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(10);
expect(result.inputValue).to.equal('10');
});
});
describe('action: decrement', () => {
it('decrements the value', () => {
const state: NumberInputState = {
value: 15,
inputValue: '15',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.decrement,
applyMultiplier: false,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(14);
expect(result.inputValue).to.equal('14');
});
it('decrements the value based on the step prop', () => {
const state: NumberInputState = {
value: 10,
inputValue: '10',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.decrement,
applyMultiplier: false,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
step: 2,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(8);
expect(result.inputValue).to.equal('8');
});
it('applys the shiftMultiplier when decrementing with shift+click', () => {
const state: NumberInputState = {
value: 20,
inputValue: '20',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.decrement,
applyMultiplier: true,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
step: 1,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(10);
expect(result.inputValue).to.equal('10');
});
});
describe('action: incrementToMax', () => {
it('sets the value to max if max is set', () => {
const state: NumberInputState = {
value: 20,
inputValue: '20',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.incrementToMax,
context: {
getInputValueAsString: defaultGetInputValueAsString,
max: 99,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(99);
expect(result.inputValue).to.equal('99');
});
it('does not change the state if max is not set', () => {
const state: NumberInputState = {
value: 20,
inputValue: '20',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.incrementToMax,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result).to.equal(state);
});
});
describe('action: decrementToMin', () => {
it('sets the value to min if min is set', () => {
const state: NumberInputState = {
value: 20,
inputValue: '20',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.decrementToMin,
context: {
getInputValueAsString: defaultGetInputValueAsString,
min: 1,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result.value).to.equal(1);
expect(result.inputValue).to.equal('1');
});
it('does not change the state if min is not set', () => {
const state: NumberInputState = {
value: 20,
inputValue: '20',
};
const action: NumberInputReducerAction = {
type: NumberInputActionTypes.decrementToMin,
context: {
getInputValueAsString: defaultGetInputValueAsString,
shiftMultiplier: 10,
},
};
const result = numberInputReducer(state, action);
expect(result).to.equal(state);
});
});
});
| 6,278 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/numberInputReducer.ts | import {
NumberInputActionContext,
NumberInputReducerAction,
NumberInputState,
StepDirection,
} from './useNumberInput.types';
import { NumberInputActionTypes } from './numberInputAction.types';
import { clamp, isNumber } from './utils';
// extracted from handleValueChange
function getClampedValues(rawValue: number | undefined, context: NumberInputActionContext) {
const { min, max, step } = context;
const clampedValue = rawValue === undefined ? '' : clamp(rawValue, min, max, step);
const newInputValue = clampedValue === undefined ? '' : String(clampedValue);
return {
value: clampedValue,
inputValue: newInputValue,
};
}
function stepValue(
state: NumberInputState,
context: NumberInputActionContext,
direction: StepDirection,
multiplier: number,
) {
const { value } = state;
const { step = 1, min, max } = context;
if (isNumber(value)) {
return {
up: value + (step ?? 1) * multiplier,
down: value - (step ?? 1) * multiplier,
}[direction];
}
return {
up: min ?? 0,
down: max ?? 0,
}[direction];
}
function handleClamp<State extends NumberInputState>(
state: State,
context: NumberInputActionContext,
inputValue: string,
) {
const { getInputValueAsString } = context;
const numberValueAsString = getInputValueAsString(inputValue);
const intermediateValue =
numberValueAsString === '' || numberValueAsString === '-'
? undefined
: parseInt(numberValueAsString, 10);
const clampedValues = getClampedValues(intermediateValue, context);
return {
...state,
...clampedValues,
};
}
function handleInputChange<State extends NumberInputState>(
state: State,
context: NumberInputActionContext,
inputValue: string,
) {
const { getInputValueAsString } = context;
const numberValueAsString = getInputValueAsString(inputValue);
if (numberValueAsString === '' || numberValueAsString === '-') {
return {
...state,
inputValue: numberValueAsString,
value: '',
};
}
if (numberValueAsString.match(/^-?\d+?$/)) {
return {
...state,
inputValue: numberValueAsString,
value: parseInt(numberValueAsString, 10),
};
}
return state;
}
// use this for ArrowUp, ArrowDown, button clicks
// use this with applyMultiplier: true for PageUp, PageDown, button shift-clicks
function handleStep<State extends NumberInputState>(
state: State,
context: NumberInputActionContext,
applyMultiplier: boolean,
direction: StepDirection,
) {
const multiplier = applyMultiplier ? context.shiftMultiplier : 1;
const newValue = stepValue(state, context, direction, multiplier);
const clampedValues = getClampedValues(newValue, context);
return {
...state,
...clampedValues,
};
}
function handleToMinOrMax<State extends NumberInputState>(
state: State,
context: NumberInputActionContext,
to: 'min' | 'max',
) {
const newValue = context[to];
if (!isNumber(newValue)) {
return state;
}
return {
...state,
value: newValue,
inputValue: String(newValue),
};
}
export function numberInputReducer(
state: NumberInputState,
action: NumberInputReducerAction,
): NumberInputState {
const { type, context } = action;
switch (type) {
case NumberInputActionTypes.clamp:
return handleClamp(state, context, action.inputValue);
case NumberInputActionTypes.inputChange:
return handleInputChange(state, context, action.inputValue);
case NumberInputActionTypes.increment:
return handleStep(state, context, action.applyMultiplier, 'up');
case NumberInputActionTypes.decrement:
return handleStep(state, context, action.applyMultiplier, 'down');
case NumberInputActionTypes.incrementToMax:
return handleToMinOrMax(state, context, 'max');
case NumberInputActionTypes.decrementToMin:
return handleToMinOrMax(state, context, 'min');
default:
return state;
}
}
| 6,279 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/useNumberInput.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import userEvent from '@testing-library/user-event';
import { createRenderer, screen } from '@mui-internal/test-utils';
import {
unstable_useNumberInput as useNumberInput,
UseNumberInputParameters,
} from '@mui/base/unstable_useNumberInput';
// TODO v6: initialize @testing-library/user-event using userEvent.setup() instead of directly calling methods e.g. userEvent.click() for all related tests in this file
// currently the setup() method uses the ClipboardEvent constructor which is incompatible with our lowest supported version of iOS Safari (12.2) https://github.com/mui/material-ui/blob/master/.browserslistrc#L44
// userEvent.setup() requires Safari 14 or up to work
describe('useNumberInput', () => {
const { render } = createRenderer();
const invokeUseNumberInput = (props: UseNumberInputParameters) => {
const ref = React.createRef<ReturnType<typeof useNumberInput>>();
function TestComponent() {
const numberInputDefinition = useNumberInput(props);
React.useImperativeHandle(ref, () => numberInputDefinition, [numberInputDefinition]);
return null;
}
render(<TestComponent />);
return ref.current!;
};
it('should return correct ARIA attributes', () => {
const INPUT_ID = 'TestInput';
const props: UseNumberInputParameters = {
inputId: INPUT_ID,
value: 50,
min: 10,
max: 100,
disabled: true,
};
const { getInputProps, getIncrementButtonProps, getDecrementButtonProps } =
invokeUseNumberInput(props);
const inputProps = getInputProps();
const incrementButtonProps = getIncrementButtonProps();
const decrementButtonProps = getDecrementButtonProps();
expect(inputProps['aria-valuenow']).to.equal(50);
expect(inputProps['aria-valuemin']).to.equal(10);
expect(inputProps['aria-valuemax']).to.equal(100);
expect(inputProps['aria-disabled']).to.equal(true);
expect(decrementButtonProps.tabIndex).to.equal(-1);
expect(decrementButtonProps['aria-controls']).to.equal(INPUT_ID);
expect(decrementButtonProps['aria-disabled']).to.equal(true);
expect(incrementButtonProps.tabIndex).to.equal(-1);
expect(incrementButtonProps['aria-controls']).to.equal(INPUT_ID);
expect(incrementButtonProps['aria-disabled']).to.equal(true);
});
it('should accept defaultValue in uncontrolled mode', () => {
const props: UseNumberInputParameters = {
defaultValue: 100,
disabled: true,
required: true,
};
const { getInputProps } = invokeUseNumberInput(props);
const inputProps = getInputProps();
expect(inputProps.value).to.equal(100);
expect(inputProps.required).to.equal(true);
});
describe('prop: onInputChange', () => {
it('should call onInputChange accordingly when inputting valid characters', async () => {
const handleInputChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({ onInputChange: handleInputChange });
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('-12');
expect(handleInputChange.callCount).to.equal(3);
expect(handleInputChange.args[2][0].target.value).to.equal('-12');
expect(input.value).to.equal('-12');
});
it('should not change the input value when inputting invalid characters', async () => {
const handleInputChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({ onInputChange: handleInputChange });
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('-5a');
expect(handleInputChange.callCount).to.equal(3);
expect(input.value).to.equal('-5');
});
});
describe('prop: onChange', () => {
it('should call onChange when the input is blurred', async () => {
const handleChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({ onChange: handleChange });
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input');
await userEvent.click(input);
await userEvent.keyboard('34');
expect(handleChange.callCount).to.equal(0);
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
expect(handleChange.callCount).to.equal(1);
});
it('should call onChange with a value within max', async () => {
const handleChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({
onChange: handleChange,
max: 5,
});
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input');
await userEvent.click(input);
await userEvent.keyboard('9');
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
expect(handleChange.args[0][1]).to.equal(5);
});
it('should call onChange with a value within min', async () => {
const handleChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({
onChange: handleChange,
min: 5,
});
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input');
await userEvent.click(input);
await userEvent.keyboard('-9');
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
expect(handleChange.args[0][1]).to.equal(5);
});
it('should call onChange with a value based on a custom step', async () => {
const handleChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({
onChange: handleChange,
min: 0,
step: 5,
});
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input');
await userEvent.click(input);
await userEvent.keyboard('4');
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
expect(handleChange.args[0][1]).to.equal(5);
});
it('should call onChange with undefined when the value is cleared', async () => {
const handleChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({
onChange: handleChange,
});
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('9');
expect(input.value).to.equal('9');
await userEvent.keyboard('[Backspace]');
expect(input.value).to.equal('');
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.equal(undefined);
});
it('should call onChange with undefined when input value is -', async () => {
const handleChange = spy();
function NumberInput() {
const { getInputProps } = useNumberInput({
onChange: handleChange,
});
return <input data-testid="test-input" {...getInputProps()} />;
}
render(<NumberInput />);
const input = screen.getByTestId('test-input') as HTMLInputElement;
await userEvent.click(input);
await userEvent.keyboard('-5');
expect(input.value).to.equal('-5');
await userEvent.keyboard('[Backspace]');
expect(input.value).to.equal('-');
await userEvent.keyboard('[Tab]');
expect(document.activeElement).to.equal(document.body);
expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.equal(undefined);
});
});
describe('warnings', () => {
it('should warn when switching from uncontrolled to controlled', () => {
const handleChange = spy();
function NumberInput({ value }: { value?: number }) {
const { getInputProps } = useNumberInput({
onChange: handleChange,
value,
});
return <input {...getInputProps()} />;
}
const { setProps } = render(<NumberInput />);
expect(() => {
setProps({ value: 5 });
}).to.toErrorDev(
'MUI: A component is changing the uncontrolled value state of NumberInput to be controlled',
);
});
it('should warn when switching from controlled to uncontrolled', () => {
const handleChange = spy();
function NumberInput({ value }: { value?: number }) {
const { getInputProps } = useNumberInput({
onChange: handleChange,
value,
});
return <input {...getInputProps()} />;
}
const { setProps } = render(<NumberInput value={5} />);
expect(() => {
setProps({ value: undefined });
}).to.toErrorDev(
'MUI: A component is changing the controlled value state of NumberInput to be uncontrolled',
);
});
});
});
| 6,280 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/useNumberInput.ts | 'use client';
import * as React from 'react';
import MuiError from '@mui/utils/macros/MuiError.macro';
import {
unstable_useForkRef as useForkRef,
unstable_useId as useId,
unstable_useControlled as useControlled,
} from '@mui/utils';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
import { EventHandlers } from '../utils/types';
import { FormControlState, useFormControlContext } from '../FormControl';
import {
UseNumberInputParameters,
UseNumberInputRootSlotProps,
UseNumberInputInputSlotProps,
UseNumberInputIncrementButtonSlotProps,
UseNumberInputDecrementButtonSlotProps,
UseNumberInputReturnValue,
StepDirection,
} from './useNumberInput.types';
import { clamp, isNumber } from './utils';
const STEP_KEYS = ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown'];
const SUPPORTED_KEYS = [...STEP_KEYS, 'Home', 'End'];
export function getInputValueAsString(v: string): string {
return v ? String(v.trim()) : String(v);
}
/**
*
* Demos:
*
* - [Number Input](https://mui.com/base-ui/react-number-input/#hook)
*
* API:
*
* - [useNumberInput API](https://mui.com/base-ui/react-number-input/hooks-api/#use-number-input)
*/
export function useNumberInput(parameters: UseNumberInputParameters): UseNumberInputReturnValue {
const {
min,
max,
step,
shiftMultiplier = 10,
defaultValue: defaultValueProp,
disabled: disabledProp = false,
error: errorProp = false,
onBlur,
onInputChange,
onFocus,
onChange,
required: requiredProp = false,
readOnly: readOnlyProp = false,
value: valueProp,
inputRef: inputRefProp,
inputId: inputIdProp,
} = parameters;
// TODO: make it work with FormControl
const formControlContext: FormControlState | undefined = useFormControlContext();
const { current: isControlled } = React.useRef(valueProp != null);
const handleInputRefWarning = React.useCallback((instance: HTMLElement) => {
if (process.env.NODE_ENV !== 'production') {
if (instance && instance.nodeName !== 'INPUT' && !instance.focus) {
console.error(
[
'MUI: You have provided a `slots.input` to the input component',
'that does not correctly handle the `ref` prop.',
'Make sure the `ref` prop is called with a HTMLInputElement.',
].join('\n'),
);
}
}
}, []);
const inputRef = React.useRef<HTMLInputElement>(null);
const handleInputRef = useForkRef(inputRef, inputRefProp, handleInputRefWarning);
const inputId = useId(inputIdProp);
const [focused, setFocused] = React.useState(false);
// the "final" value
const [value, setValue] = useControlled({
controlled: valueProp,
default: defaultValueProp,
name: 'NumberInput',
});
// the (potentially) dirty or invalid input value
const [dirtyValue, setDirtyValue] = React.useState<string | undefined>(
value ? String(value) : undefined,
);
React.useEffect(() => {
if (!formControlContext && disabledProp && focused) {
setFocused(false);
onBlur?.();
}
}, [formControlContext, disabledProp, focused, onBlur]);
const createHandleFocus =
(otherHandlers: Partial<EventHandlers>) =>
(event: React.FocusEvent<HTMLInputElement> & MuiCancellableEvent) => {
otherHandlers.onFocus?.(event);
if (event.defaultMuiPrevented || event.defaultPrevented) {
return;
}
if (formControlContext && formControlContext.onFocus) {
formControlContext?.onFocus?.();
}
setFocused(true);
};
const handleValueChange =
() =>
(
event: React.FocusEvent<HTMLInputElement> | React.PointerEvent | React.KeyboardEvent,
val: number | undefined,
) => {
let newValue;
if (val === undefined) {
newValue = val;
setDirtyValue('');
} else {
newValue = clamp(val, min, max, step);
setDirtyValue(String(newValue));
}
setValue(newValue);
if (isNumber(newValue)) {
onChange?.(event, newValue);
} else {
onChange?.(event, undefined);
}
};
const createHandleInputChange =
(otherHandlers: Partial<EventHandlers>) =>
(event: React.ChangeEvent<HTMLInputElement> & MuiCancellableEvent) => {
if (!isControlled && event.target === null) {
throw new MuiError(
'MUI: Expected valid input target. ' +
'Did you use a custom `slots.input` and forget to forward refs? ' +
'See https://mui.com/r/input-component-ref-interface for more info.',
);
}
formControlContext?.onChange?.(event);
otherHandlers.onInputChange?.(event);
if (event.defaultMuiPrevented || event.defaultPrevented) {
return;
}
// TODO: event.currentTarget.value will be passed straight into the InputChange action
const val = getInputValueAsString(event.currentTarget.value);
if (val === '' || val === '-') {
setDirtyValue(val);
setValue(undefined);
}
if (val.match(/^-?\d+?$/)) {
setDirtyValue(val);
setValue(parseInt(val, 10));
}
};
const createHandleBlur =
(otherHandlers: Partial<EventHandlers>) =>
(event: React.FocusEvent<HTMLInputElement> & MuiCancellableEvent) => {
otherHandlers.onBlur?.(event);
if (event.defaultMuiPrevented || event.defaultPrevented) {
return;
}
// TODO: event.currentTarget.value will be passed straight into the Blur action, or just pass inputValue from state
const val = getInputValueAsString(event.currentTarget.value);
if (val === '' || val === '-') {
handleValueChange()(event, undefined);
} else {
handleValueChange()(event, parseInt(val, 10));
}
if (formControlContext && formControlContext.onBlur) {
formControlContext.onBlur();
}
setFocused(false);
};
const createHandleClick =
(otherHandlers: Partial<EventHandlers>) =>
(event: React.MouseEvent<HTMLInputElement> & MuiCancellableEvent) => {
otherHandlers.onClick?.(event);
if (event.defaultMuiPrevented || event.defaultPrevented) {
return;
}
if (inputRef.current && event.currentTarget === event.target) {
inputRef.current.focus();
}
};
const handleStep =
(direction: StepDirection) => (event: React.PointerEvent | React.KeyboardEvent) => {
let newValue;
if (isNumber(value)) {
const multiplier =
event.shiftKey ||
(event as React.KeyboardEvent).key === 'PageUp' ||
(event as React.KeyboardEvent).key === 'PageDown'
? shiftMultiplier
: 1;
newValue = {
up: value + (step ?? 1) * multiplier,
down: value - (step ?? 1) * multiplier,
}[direction];
} else {
// no value
newValue = {
up: min ?? 0,
down: max ?? 0,
}[direction];
}
handleValueChange()(event, newValue);
};
const createHandleKeyDown =
(otherHandlers: Partial<EventHandlers>) =>
(event: React.KeyboardEvent<HTMLInputElement> & MuiCancellableEvent) => {
otherHandlers.onKeyDown?.(event);
if (event.defaultMuiPrevented || event.defaultPrevented) {
return;
}
if (event.defaultPrevented) {
return;
}
if (SUPPORTED_KEYS.includes(event.key)) {
event.preventDefault();
}
if (STEP_KEYS.includes(event.key)) {
const direction = {
ArrowUp: 'up',
ArrowDown: 'down',
PageUp: 'up',
PageDown: 'down',
}[event.key] as StepDirection;
handleStep(direction)(event);
}
if (event.key === 'Home' && isNumber(max)) {
handleValueChange()(event, max);
}
if (event.key === 'End' && isNumber(min)) {
handleValueChange()(event, min);
}
};
const getRootProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseNumberInputRootSlotProps<ExternalProps> => {
const propsEventHandlers = extractEventHandlers(parameters, [
// these are handled by the input slot
'onBlur',
'onInputChange',
'onFocus',
'onChange',
]);
const externalEventHandlers = {
...propsEventHandlers,
...extractEventHandlers(externalProps),
};
return {
...externalProps,
...externalEventHandlers,
onClick: createHandleClick(externalEventHandlers),
};
};
const getInputProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseNumberInputInputSlotProps<ExternalProps> => {
const propsEventHandlers = {
onBlur,
onFocus,
// onChange from normal props is the custom onChange so we ignore it here
onChange: onInputChange,
};
const externalEventHandlers: Partial<EventHandlers> = {
...propsEventHandlers,
...extractEventHandlers(externalProps, [
// onClick is handled by the root slot
'onClick',
// do not ignore 'onInputChange', we want slotProps.input.onInputChange to enter the DOM and throw
]),
};
const mergedEventHandlers = {
...externalEventHandlers,
onFocus: createHandleFocus(externalEventHandlers),
// slotProps.onChange is renamed to onInputChange and passed to createHandleInputChange
onChange: createHandleInputChange({
...externalEventHandlers,
onInputChange: externalEventHandlers.onChange,
}),
onBlur: createHandleBlur(externalEventHandlers),
onKeyDown: createHandleKeyDown(externalEventHandlers),
};
const displayValue = (focused ? dirtyValue : value) ?? '';
// get rid of slotProps.input.onInputChange before returning to prevent it from entering the DOM
// if it was passed, it will be in mergedEventHandlers and throw
delete externalProps.onInputChange;
return {
type: 'text',
id: inputId,
'aria-invalid': errorProp || undefined,
defaultValue: undefined,
value: displayValue as number | undefined,
'aria-valuenow': displayValue as number | undefined,
'aria-valuetext': String(displayValue),
'aria-valuemin': min,
'aria-valuemax': max,
autoComplete: 'off',
autoCorrect: 'off',
spellCheck: 'false',
required: requiredProp,
readOnly: readOnlyProp,
'aria-disabled': disabledProp,
disabled: disabledProp,
...externalProps,
ref: handleInputRef,
...mergedEventHandlers,
};
};
const handleStepperButtonMouseDown = (event: React.PointerEvent) => {
event.preventDefault();
if (inputRef.current) {
inputRef.current.focus();
}
};
const stepperButtonCommonProps = {
'aria-controls': inputId,
tabIndex: -1,
};
const isIncrementDisabled =
disabledProp || (isNumber(value) ? value >= (max ?? Number.MAX_SAFE_INTEGER) : false);
const getIncrementButtonProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseNumberInputIncrementButtonSlotProps<ExternalProps> => {
return {
...externalProps,
...stepperButtonCommonProps,
disabled: isIncrementDisabled,
'aria-disabled': isIncrementDisabled,
onMouseDown: handleStepperButtonMouseDown,
onClick: handleStep('up'),
};
};
const isDecrementDisabled =
disabledProp || (isNumber(value) ? value <= (min ?? Number.MIN_SAFE_INTEGER) : false);
const getDecrementButtonProps = <ExternalProps extends Record<string, unknown> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseNumberInputDecrementButtonSlotProps<ExternalProps> => {
return {
...externalProps,
...stepperButtonCommonProps,
disabled: isDecrementDisabled,
'aria-disabled': isDecrementDisabled,
onMouseDown: handleStepperButtonMouseDown,
onClick: handleStep('down'),
};
};
return {
disabled: disabledProp,
error: errorProp,
focused,
formControlContext,
getInputProps,
getIncrementButtonProps,
getDecrementButtonProps,
getRootProps,
required: requiredProp,
value: focused ? dirtyValue : value,
isIncrementDisabled,
isDecrementDisabled,
inputValue: dirtyValue,
};
}
| 6,281 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/useNumberInput.types.ts | import * as React from 'react';
import { FormControlState } from '../FormControl';
import { NumberInputAction } from './numberInputAction.types';
import { ActionWithContext } from '../utils/useControllableReducer.types';
export type StepDirection = 'up' | 'down';
/**
* The internal state of the NumberInput.
* Modify via the reducer only.
*/
export interface NumberInputState {
/**
* The clamped `value` of the `input` element.
*/
value?: number | '';
/**
* The dirty `value` of the `input` element when it is in focus.
*/
inputValue?: string;
}
/**
* Additional props passed to the number input reducer actions.
*/
export type NumberInputActionContext = {
min?: number;
max?: number;
step?: number;
shiftMultiplier: number;
/**
* A function that parses the raw input value
*/
getInputValueAsString: (val: string) => string;
};
export type NumberInputReducerAction<CustomActionContext = {}> = ActionWithContext<
NumberInputAction,
NumberInputActionContext & CustomActionContext
>;
export interface UseNumberInputParameters {
/**
* The minimum value.
*/
min?: number;
/**
* The maximum value.
*/
max?: number;
/**
* The amount that the value changes on each increment or decrement.
*/
step?: number;
/**
* Multiplier applied to `step` if the shift key is held while incrementing
* or decrementing the value. Defaults to `10`.
*/
shiftMultiplier?: number;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: unknown;
/**
* If `true`, the component is disabled.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
disabled?: boolean;
/**
* If `true`, the `input` will indicate an error by setting the `aria-invalid` attribute.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
error?: boolean;
onBlur?: (event?: React.FocusEvent<HTMLInputElement>) => void;
onClick?: React.MouseEventHandler;
/**
* Callback fired when the `input` value changes after each keypress, before clamping is applied.
* Note that `event.target.value` may contain values that fall outside of `min` and `max` or
* are otherwise "invalid".
*
* @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
*/
onInputChange?: React.ChangeEventHandler<HTMLInputElement>;
onFocus?: React.FocusEventHandler;
/**
* Callback fired after the value is clamped and changes - when the `input` is blurred or when
* the stepper buttons are triggered.
* Called with `undefined` when the value is unset.
*
* @param {React.FocusEvent<HTMLInputElement>|React.PointerEvent|React.KeyboardEvent} event The event source of the callback
* @param {number|undefined} value The new value of the component
*/
onChange?: (
event: React.FocusEvent<HTMLInputElement> | React.PointerEvent | React.KeyboardEvent,
value: number | undefined,
) => void;
/**
* The `id` attribute of the input element.
*/
inputId?: string;
/**
* The ref of the input element.
*/
inputRef?: React.Ref<HTMLInputElement>;
/**
* If `true`, the `input` element is required.
* The prop defaults to the value (`false`) inherited from the parent FormControl component.
*/
required?: boolean;
/**
* If `true`, the `input` element becomes read-only. The stepper buttons remain active,
* with the addition that they are now keyboard focusable.
* @default false
*/
readOnly?: boolean;
/**
* The current value. Use when the component is controlled.
*/
value?: number;
}
export interface UseNumberInputRootSlotOwnProps {
onClick: React.MouseEventHandler | undefined;
}
export type UseNumberInputRootSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseNumberInputRootSlotOwnProps | 'onBlur' | 'onInputChange' | 'onFocus'
> &
UseNumberInputRootSlotOwnProps;
export interface UseNumberInputInputSlotOwnProps {
defaultValue: number | undefined;
id: string | undefined;
ref: React.RefCallback<HTMLInputElement> | null;
value: number | undefined;
role?: React.AriaRole;
'aria-disabled': React.AriaAttributes['aria-disabled'];
'aria-valuemax': React.AriaAttributes['aria-valuemax'];
'aria-valuemin': React.AriaAttributes['aria-valuemin'];
'aria-valuenow': React.AriaAttributes['aria-valuenow'];
'aria-valuetext': React.AriaAttributes['aria-valuetext'];
tabIndex?: number;
onBlur: React.FocusEventHandler;
onChange: React.ChangeEventHandler<HTMLInputElement>;
onFocus: React.FocusEventHandler;
required: boolean;
disabled: boolean;
}
export type UseNumberInputInputSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseNumberInputInputSlotOwnProps
> &
UseNumberInputInputSlotOwnProps;
export interface UseNumberInputIncrementButtonSlotOwnProps {
'aria-controls': React.AriaAttributes['aria-controls'];
'aria-disabled': React.AriaAttributes['aria-disabled'];
disabled: boolean;
tabIndex?: number;
}
export type UseNumberInputIncrementButtonSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseNumberInputIncrementButtonSlotOwnProps
> &
UseNumberInputIncrementButtonSlotOwnProps;
export interface UseNumberInputDecrementButtonSlotOwnProps {
'aria-controls': React.AriaAttributes['aria-controls'];
'aria-disabled': React.AriaAttributes['aria-disabled'];
disabled: boolean;
tabIndex?: number;
}
export type UseNumberInputDecrementButtonSlotProps<ExternalProps = {}> = Omit<
ExternalProps,
keyof UseNumberInputDecrementButtonSlotOwnProps
> &
UseNumberInputDecrementButtonSlotOwnProps;
export interface UseNumberInputReturnValue {
/**
* If `true`, the component will be disabled.
* @default false
*/
disabled: boolean;
/**
* If `true`, the `input` will indicate an error by setting the `aria-invalid` attribute.
* @default false
*/
error: boolean;
/**
* If `true`, the `input` will be focused.
* @default false
*/
focused: boolean;
/**
* Return value from the `useFormControlContext` hook.
*/
formControlContext: FormControlState | undefined;
/**
* Resolver for the decrement button slot's props.
* @param externalProps props for the decrement button slot
* @returns props that should be spread on the decrement button slot
*/
getDecrementButtonProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseNumberInputDecrementButtonSlotProps<ExternalProps>;
/**
* Resolver for the increment button slot's props.
* @param externalProps props for the increment button slot
* @returns props that should be spread on the increment button slot
*/
getIncrementButtonProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseNumberInputIncrementButtonSlotProps<ExternalProps>;
/**
* Resolver for the input slot's props.
* @param externalProps props for the input slot
* @returns props that should be spread on the input slot
*/
getInputProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseNumberInputInputSlotProps<ExternalProps>;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(
externalProps?: ExternalProps,
) => UseNumberInputRootSlotProps<ExternalProps>;
/**
* If `true`, the `input` will indicate that it's required.
* @default false
*/
required: boolean;
/**
* The clamped `value` of the `input` element.
*/
value: unknown;
/**
* The dirty `value` of the `input` element when it is in focus.
*/
inputValue: string | undefined;
/**
* If `true`, the increment button will be disabled.
* e.g. when the `value` is already at `max`
* @default false
*/
isIncrementDisabled: boolean;
/**
* If `true`, the decrement button will be disabled.
* e.g. when the `value` is already at `min`
* @default false
*/
isDecrementDisabled: boolean;
}
| 6,282 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/utils.test.ts | import { expect } from 'chai';
import { clamp, isNumber } from './utils';
describe('utils', () => {
it('clamp: clamps a value based on min and max', () => {
expect(clamp(1, 2, 4)).to.equal(2);
expect(clamp(5, 2, 4)).to.equal(4);
expect(clamp(-5, -1, 5)).to.equal(-1);
});
it('clamp: clamps a value between min and max and on a valid step', () => {
expect(clamp(2, -15, 15, 3)).to.equal(3);
expect(clamp(-1, -15, 15, 3)).to.equal(0);
expect(clamp(5, -15, 15, 3)).to.equal(6);
expect(clamp(-5, -15, 15, 3)).to.equal(-6);
expect(clamp(-55, -15, 15, 3)).to.equal(-15);
expect(clamp(57, -15, 15, 3)).to.equal(15);
expect(clamp(3, -20, 20, 5)).to.equal(5);
expect(clamp(2, -20, 20, 5)).to.equal(0);
expect(clamp(8, -20, 20, 5)).to.equal(10);
expect(clamp(-7, -20, 20, 5)).to.equal(-5);
});
it('isNumber: rejects NaN', () => {
expect(isNumber(NaN)).to.equal(false);
});
it('isNumber: rejects Infinity', () => {
expect(isNumber(Infinity)).to.equal(false);
expect(isNumber(-Infinity)).to.equal(false);
});
it('isNumber: rejects falsy values', () => {
expect(isNumber('')).to.equal(false);
expect(isNumber(undefined)).to.equal(false);
expect(isNumber(null)).to.equal(false);
});
it('isNumber: accepts positive and negative integers', () => {
expect(isNumber(10)).to.equal(true);
expect(isNumber(7)).to.equal(true);
expect(isNumber(-20)).to.equal(true);
expect(isNumber(-333)).to.equal(true);
});
it('isNumber: accepts 0', () => {
expect(isNumber(0)).to.equal(true);
expect(isNumber(-0)).to.equal(true);
});
});
| 6,283 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/unstable_useNumberInput/utils.ts | function simpleClamp(
val: number,
min: number = Number.MIN_SAFE_INTEGER,
max: number = Number.MAX_SAFE_INTEGER,
): number {
return Math.max(min, Math.min(val, max));
}
export function clamp(
val: number,
min: number = Number.MIN_SAFE_INTEGER,
max: number = Number.MAX_SAFE_INTEGER,
stepProp: number = NaN,
): number {
if (Number.isNaN(stepProp)) {
return simpleClamp(val, min, max);
}
const step = stepProp || 1;
const remainder = val % step;
const positivity = Math.sign(remainder);
if (Math.abs(remainder) > step / 2) {
return simpleClamp(val + positivity * (step - Math.abs(remainder)), min, max);
}
return simpleClamp(val - positivity * Math.abs(remainder), min, max);
}
export function isNumber(val: unknown): val is number {
return typeof val === 'number' && !Number.isNaN(val) && Number.isFinite(val);
}
| 6,284 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useAutocomplete/index.d.ts | export { useAutocomplete } from './useAutocomplete';
export * from './useAutocomplete';
| 6,285 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useAutocomplete/index.js | 'use client';
export * from './useAutocomplete';
| 6,286 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useAutocomplete/useAutocomplete.d.ts | import * as React from 'react';
export interface CreateFilterOptionsConfig<Value> {
ignoreAccents?: boolean;
ignoreCase?: boolean;
limit?: number;
matchFrom?: 'any' | 'start';
stringify?: (option: Value) => string;
trim?: boolean;
}
export interface FilterOptionsState<Value> {
inputValue: string;
getOptionLabel: (option: Value) => string;
}
export interface AutocompleteGroupedOption<Value = string> {
key: number;
index: number;
group: string;
options: Value[];
}
export function createFilterOptions<Value>(
config?: CreateFilterOptionsConfig<Value>,
): (options: Value[], state: FilterOptionsState<Value>) => Value[];
export type AutocompleteFreeSoloValueMapping<FreeSolo> = FreeSolo extends true ? string : never;
export type AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo> = Multiple extends true
? Array<Value | AutocompleteFreeSoloValueMapping<FreeSolo>>
: DisableClearable extends true
? NonNullable<Value | AutocompleteFreeSoloValueMapping<FreeSolo>>
: Value | null | AutocompleteFreeSoloValueMapping<FreeSolo>;
export interface UseAutocompleteProps<
Value,
Multiple extends boolean | undefined,
DisableClearable extends boolean | undefined,
FreeSolo extends boolean | undefined,
> {
/**
* @internal The prefix of the state class name, temporary for Joy UI
* @default 'Mui'
*/
unstable_classNamePrefix?: string;
/**
* @internal
* Temporary for Joy UI because the parent listbox is the document object
* TODO v6: Normalize the logic and remove this param.
*/
unstable_isActiveElementInListbox?: (listbox: React.RefObject<HTMLElement>) => boolean;
/**
* If `true`, the portion of the selected suggestion that has not been typed by the user,
* known as the completion string, appears inline after the input cursor in the textbox.
* The inline completion string is visually highlighted and has a selected state.
* @default false
*/
autoComplete?: boolean;
/**
* If `true`, the first option is automatically highlighted.
* @default false
*/
autoHighlight?: boolean;
/**
* If `true`, the selected option becomes the value of the input
* when the Autocomplete loses focus unless the user chooses
* a different option or changes the character string in the input.
*
* When using `freeSolo` mode, the typed value will be the input value
* if the Autocomplete loses focus without highlighting an option.
* @default false
*/
autoSelect?: boolean;
/**
* Control if the input should be blurred when an option is selected:
*
* - `false` the input is not blurred.
* - `true` the input is always blurred.
* - `touch` the input is blurred after a touch event.
* - `mouse` the input is blurred after a mouse event.
* @default false
*/
blurOnSelect?: 'touch' | 'mouse' | true | false;
/**
* If `true`, the input's text is cleared on blur if no value is selected.
*
* Set to `true` if you want to help the user enter a new value.
* Set to `false` if you want to help the user resume their search.
* @default !props.freeSolo
*/
clearOnBlur?: boolean;
/**
* If `true`, clear all values when the user presses escape and the popup is closed.
* @default false
*/
clearOnEscape?: boolean;
/**
* The component name that is using this hook. Used for warnings.
*/
componentName?: string;
/**
* The default value. Use when the component is not controlled.
* @default props.multiple ? [] : null
*/
defaultValue?: AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo>;
/**
* If `true`, the input can't be cleared.
* @default false
*/
disableClearable?: DisableClearable;
/**
* If `true`, the popup won't close when a value is selected.
* @default false
*/
disableCloseOnSelect?: boolean;
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
/**
* If `true`, will allow focus on disabled items.
* @default false
*/
disabledItemsFocusable?: boolean;
/**
* If `true`, the list box in the popup will not wrap focus.
* @default false
*/
disableListWrap?: boolean;
/**
* A function that determines the filtered options to be rendered on search.
*
* @default createFilterOptions()
* @param {Value[]} options The options to render.
* @param {object} state The state of the component.
* @returns {Value[]}
*/
filterOptions?: (options: Value[], state: FilterOptionsState<Value>) => Value[];
/**
* If `true`, hide the selected options from the list box.
* @default false
*/
filterSelectedOptions?: boolean;
/**
* If `true`, the Autocomplete is free solo, meaning that the user input is not bound to provided options.
* @default false
*/
freeSolo?: FreeSolo;
/**
* Used to determine the disabled state for a given option.
*
* @param {Value} option The option to test.
* @returns {boolean}
*/
getOptionDisabled?: (option: Value) => boolean;
/**
* Used to determine the string value for a given option.
* It's used to fill the input (and the list box options if `renderOption` is not provided).
*
* If used in free solo mode, it must accept both the type of the options and a string.
*
* @param {Value} option
* @returns {string}
* @default (option) => option.label ?? option
*/
getOptionLabel?: (option: Value | AutocompleteFreeSoloValueMapping<FreeSolo>) => string;
/**
* If provided, the options will be grouped under the returned string.
* The groupBy value is also used as the text for group headings when `renderGroup` is not provided.
*
* @param {Value} options The options to group.
* @returns {string}
*/
groupBy?: (option: Value) => string;
/**
* If `true`, the component handles the "Home" and "End" keys when the popup is open.
* It should move focus to the first option and last option, respectively.
* @default !props.freeSolo
*/
handleHomeEndKeys?: boolean;
/**
* This prop is used to help implement the accessibility logic.
* If you don't provide an id it will fall back to a randomly generated one.
*/
id?: string;
/**
* If `true`, the highlight can move to the input.
* @default false
*/
includeInputInList?: boolean;
/**
* The input value.
*/
inputValue?: string;
/**
* Used to determine if the option represents the given value.
* Uses strict equality by default.
* ⚠️ Both arguments need to be handled, an option can only match with one value.
*
* @param {Value} option The option to test.
* @param {Value} value The value to test against.
* @returns {boolean}
*/
isOptionEqualToValue?: (option: Value, value: Value) => boolean;
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
* @default false
*/
multiple?: Multiple;
/**
* Callback fired when the value changes.
*
* @param {React.SyntheticEvent} event The event source of the callback.
* @param {Value|Value[]} value The new value of the component.
* @param {string} reason One of "createOption", "selectOption", "removeOption", "blur" or "clear".
* @param {string} [details]
*/
onChange?: (
event: React.SyntheticEvent,
value: AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo>,
reason: AutocompleteChangeReason,
details?: AutocompleteChangeDetails<Value>,
) => void;
/**
* Callback fired when the popup requests to be closed.
* Use in controlled mode (see open).
*
* @param {React.SyntheticEvent} event The event source of the callback.
* @param {string} reason Can be: `"toggleInput"`, `"escape"`, `"selectOption"`, `"removeOption"`, `"blur"`.
*/
onClose?: (event: React.SyntheticEvent, reason: AutocompleteCloseReason) => void;
/**
* Callback fired when the highlight option changes.
*
* @param {React.SyntheticEvent} event The event source of the callback.
* @param {Value} option The highlighted option.
* @param {string} reason Can be: `"keyboard"`, `"auto"`, `"mouse"`, `"touch"`.
*/
onHighlightChange?: (
event: React.SyntheticEvent,
option: Value | null,
reason: AutocompleteHighlightChangeReason,
) => void;
/**
* Callback fired when the input value changes.
*
* @param {React.SyntheticEvent} event The event source of the callback.
* @param {string} value The new value of the text input.
* @param {string} reason Can be: `"input"` (user input), `"reset"` (programmatic change), `"clear"`.
*/
onInputChange?: (
event: React.SyntheticEvent,
value: string,
reason: AutocompleteInputChangeReason,
) => void;
/**
* Callback fired when the popup requests to be opened.
* Use in controlled mode (see open).
*
* @param {React.SyntheticEvent} event The event source of the callback.
*/
onOpen?: (event: React.SyntheticEvent) => void;
/**
* If `true`, the component is shown.
*/
open?: boolean;
/**
* If `true`, the popup will open on input focus.
* @default false
*/
openOnFocus?: boolean;
/**
* Array of options.
*/
options: ReadonlyArray<Value>;
/**
* If `true`, the component becomes readonly. It is also supported for multiple tags where the tag cannot be deleted.
* @default false
*/
readOnly?: boolean;
/**
* If `true`, the input's text is selected on focus.
* It helps the user clear the selected value.
* @default !props.freeSolo
*/
selectOnFocus?: boolean;
/**
* The value of the autocomplete.
*
* The value must have reference equality with the option in order to be selected.
* You can customize the equality behavior with the `isOptionEqualToValue` prop.
*/
value?: AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo>;
}
export interface UseAutocompleteParameters<
Value,
Multiple extends boolean | undefined,
DisableClearable extends boolean | undefined,
FreeSolo extends boolean | undefined,
> extends UseAutocompleteProps<Value, Multiple, DisableClearable, FreeSolo> {}
export type AutocompleteHighlightChangeReason = 'keyboard' | 'mouse' | 'auto' | 'touch';
export type AutocompleteChangeReason =
| 'createOption'
| 'selectOption'
| 'removeOption'
| 'clear'
| 'blur';
export interface AutocompleteChangeDetails<Value = string> {
option: Value;
}
export type AutocompleteCloseReason =
| 'createOption'
| 'toggleInput'
| 'escape'
| 'selectOption'
| 'removeOption'
| 'blur';
export type AutocompleteInputChangeReason = 'input' | 'reset' | 'clear';
export type AutocompleteGetTagProps = ({ index }: { index: number }) => {
key: number;
'data-tag-index': number;
tabIndex: -1;
onDelete: (event: any) => void;
};
/**
*
* Demos:
*
* - [Autocomplete](https://mui.com/base-ui/react-autocomplete/#hook)
*
* API:
*
* - [useAutocomplete API](https://mui.com/base-ui/react-autocomplete/hooks-api/#use-autocomplete)
*/
export function useAutocomplete<
Value,
Multiple extends boolean | undefined = false,
DisableClearable extends boolean | undefined = false,
FreeSolo extends boolean | undefined = false,
>(
props: UseAutocompleteProps<Value, Multiple, DisableClearable, FreeSolo>,
): UseAutocompleteReturnValue<Value, Multiple, DisableClearable, FreeSolo>;
export interface UseAutocompleteRenderedOption<Value> {
option: Value;
index: number;
}
export interface UseAutocompleteReturnValue<
Value,
Multiple extends boolean | undefined = false,
DisableClearable extends boolean | undefined = false,
FreeSolo extends boolean | undefined = false,
> {
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: (externalProps?: any) => React.HTMLAttributes<HTMLDivElement>;
/**
* Resolver for the input element's props.
* @returns props that should be spread on the input element
*/
getInputProps: () => React.InputHTMLAttributes<HTMLInputElement> & {
ref: React.Ref<HTMLInputElement>;
};
/**
* Resolver for the input label element's props.
* @returns props that should be spread on the input label element
*/
getInputLabelProps: () => Omit<React.HTMLAttributes<HTMLLabelElement>, 'color'>;
/**
* Resolver for the `clear` button element's props.
* @returns props that should be spread on the *clear* button element
*/
getClearProps: () => React.HTMLAttributes<HTMLButtonElement>;
/**
* Resolver for the popup icon's props.
* @returns props that should be spread on the popup icon
*/
getPopupIndicatorProps: () => React.HTMLAttributes<HTMLButtonElement>;
/**
* A tag props getter.
*/
getTagProps: AutocompleteGetTagProps;
/**
* Resolver for the listbox component's props.
* @returns props that should be spread on the listbox component
*/
getListboxProps: () => React.HTMLAttributes<HTMLUListElement>;
/**
* Resolver for the rendered option element's props.
* @param renderedOption option rendered on the Autocomplete
* @returns props that should be spread on the li element
*/
getOptionProps: (
renderedOption: UseAutocompleteRenderedOption<Value>,
) => React.HTMLAttributes<HTMLLIElement>;
/**
* Id for the Autocomplete.
*/
id: string;
/**
* The input value.
*/
inputValue: string;
/**
* The value of the autocomplete.
*/
value: AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo>;
/**
* If `true`, the component input has some values.
*/
dirty: boolean;
/**
* If `true`, the listbox is being displayed.
*/
expanded: boolean;
/**
* If `true`, the popup is open on the component.
*/
popupOpen: boolean;
/**
* If `true`, the component is focused.
*/
focused: boolean;
/**
* An HTML element that is used to set the position of the component.
*/
anchorEl: null | HTMLElement;
/**
* Setter for the component `anchorEl`.
* @returns function for setting `anchorEl`
*/
setAnchorEl: () => void;
/**
* Index of the focused tag for the component.
*/
focusedTag: number;
/**
* The options to render. It's either `Value[]` or `AutocompleteGroupedOption<Value>[]` if the groupBy prop is provided.
*/
groupedOptions: Value[] | Array<AutocompleteGroupedOption<Value>>;
}
| 6,287 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useAutocomplete/useAutocomplete.js | 'use client';
/* eslint-disable no-constant-condition */
import * as React from 'react';
import {
unstable_setRef as setRef,
unstable_useEventCallback as useEventCallback,
unstable_useControlled as useControlled,
unstable_useId as useId,
usePreviousProps,
} from '@mui/utils';
// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
// Give up on IE11 support for this feature
function stripDiacritics(string) {
return typeof string.normalize !== 'undefined'
? string.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
: string;
}
export function createFilterOptions(config = {}) {
const {
ignoreAccents = true,
ignoreCase = true,
limit,
matchFrom = 'any',
stringify,
trim = false,
} = config;
return (options, { inputValue, getOptionLabel }) => {
let input = trim ? inputValue.trim() : inputValue;
if (ignoreCase) {
input = input.toLowerCase();
}
if (ignoreAccents) {
input = stripDiacritics(input);
}
const filteredOptions = !input
? options
: options.filter((option) => {
let candidate = (stringify || getOptionLabel)(option);
if (ignoreCase) {
candidate = candidate.toLowerCase();
}
if (ignoreAccents) {
candidate = stripDiacritics(candidate);
}
return matchFrom === 'start'
? candidate.indexOf(input) === 0
: candidate.indexOf(input) > -1;
});
return typeof limit === 'number' ? filteredOptions.slice(0, limit) : filteredOptions;
};
}
// To replace with .findIndex() once we stop IE11 support.
function findIndex(array, comp) {
for (let i = 0; i < array.length; i += 1) {
if (comp(array[i])) {
return i;
}
}
return -1;
}
const defaultFilterOptions = createFilterOptions();
// Number of options to jump in list box when `Page Up` and `Page Down` keys are used.
const pageSize = 5;
const defaultIsActiveElementInListbox = (listboxRef) =>
listboxRef.current !== null && listboxRef.current.parentElement?.contains(document.activeElement);
export function useAutocomplete(props) {
const {
// eslint-disable-next-line @typescript-eslint/naming-convention
unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,
// eslint-disable-next-line @typescript-eslint/naming-convention
unstable_classNamePrefix = 'Mui',
autoComplete = false,
autoHighlight = false,
autoSelect = false,
blurOnSelect = false,
clearOnBlur = !props.freeSolo,
clearOnEscape = false,
componentName = 'useAutocomplete',
defaultValue = props.multiple ? [] : null,
disableClearable = false,
disableCloseOnSelect = false,
disabled: disabledProp,
disabledItemsFocusable = false,
disableListWrap = false,
filterOptions = defaultFilterOptions,
filterSelectedOptions = false,
freeSolo = false,
getOptionDisabled,
getOptionLabel: getOptionLabelProp = (option) => option.label ?? option,
groupBy,
handleHomeEndKeys = !props.freeSolo,
id: idProp,
includeInputInList = false,
inputValue: inputValueProp,
isOptionEqualToValue = (option, value) => option === value,
multiple = false,
onChange,
onClose,
onHighlightChange,
onInputChange,
onOpen,
open: openProp,
openOnFocus = false,
options,
readOnly = false,
selectOnFocus = !props.freeSolo,
value: valueProp,
} = props;
const id = useId(idProp);
let getOptionLabel = getOptionLabelProp;
getOptionLabel = (option) => {
const optionLabel = getOptionLabelProp(option);
if (typeof optionLabel !== 'string') {
if (process.env.NODE_ENV !== 'production') {
const erroneousReturn =
optionLabel === undefined ? 'undefined' : `${typeof optionLabel} (${optionLabel})`;
console.error(
`MUI: The \`getOptionLabel\` method of ${componentName} returned ${erroneousReturn} instead of a string for ${JSON.stringify(
option,
)}.`,
);
}
return String(optionLabel);
}
return optionLabel;
};
const ignoreFocus = React.useRef(false);
const firstFocus = React.useRef(true);
const inputRef = React.useRef(null);
const listboxRef = React.useRef(null);
const [anchorEl, setAnchorEl] = React.useState(null);
const [focusedTag, setFocusedTag] = React.useState(-1);
const defaultHighlighted = autoHighlight ? 0 : -1;
const highlightedIndexRef = React.useRef(defaultHighlighted);
const [value, setValueState] = useControlled({
controlled: valueProp,
default: defaultValue,
name: componentName,
});
const [inputValue, setInputValueState] = useControlled({
controlled: inputValueProp,
default: '',
name: componentName,
state: 'inputValue',
});
const [focused, setFocused] = React.useState(false);
const resetInputValue = React.useCallback(
(event, newValue) => {
// retain current `inputValue` if new option isn't selected and `clearOnBlur` is false
// When `multiple` is enabled, `newValue` is an array of all selected items including the newly selected item
const isOptionSelected = multiple ? value.length < newValue.length : newValue !== null;
if (!isOptionSelected && !clearOnBlur) {
return;
}
let newInputValue;
if (multiple) {
newInputValue = '';
} else if (newValue == null) {
newInputValue = '';
} else {
const optionLabel = getOptionLabel(newValue);
newInputValue = typeof optionLabel === 'string' ? optionLabel : '';
}
if (inputValue === newInputValue) {
return;
}
setInputValueState(newInputValue);
if (onInputChange) {
onInputChange(event, newInputValue, 'reset');
}
},
[getOptionLabel, inputValue, multiple, onInputChange, setInputValueState, clearOnBlur, value],
);
const [open, setOpenState] = useControlled({
controlled: openProp,
default: false,
name: componentName,
state: 'open',
});
const [inputPristine, setInputPristine] = React.useState(true);
const inputValueIsSelectedValue =
!multiple && value != null && inputValue === getOptionLabel(value);
const popupOpen = open && !readOnly;
const filteredOptions = popupOpen
? filterOptions(
options.filter((option) => {
if (
filterSelectedOptions &&
(multiple ? value : [value]).some(
(value2) => value2 !== null && isOptionEqualToValue(option, value2),
)
) {
return false;
}
return true;
}),
// we use the empty string to manipulate `filterOptions` to not filter any options
// i.e. the filter predicate always returns true
{
inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
getOptionLabel,
},
)
: [];
const previousProps = usePreviousProps({
filteredOptions,
value,
inputValue,
});
React.useEffect(() => {
const valueChange = value !== previousProps.value;
if (focused && !valueChange) {
return;
}
// Only reset the input's value when freeSolo if the component's value changes.
if (freeSolo && !valueChange) {
return;
}
resetInputValue(null, value);
}, [value, resetInputValue, focused, previousProps.value, freeSolo]);
const listboxAvailable = open && filteredOptions.length > 0 && !readOnly;
if (process.env.NODE_ENV !== 'production') {
if (value !== null && !freeSolo && options.length > 0) {
const missingValue = (multiple ? value : [value]).filter(
(value2) => !options.some((option) => isOptionEqualToValue(option, value2)),
);
if (missingValue.length > 0) {
console.warn(
[
`MUI: The value provided to ${componentName} is invalid.`,
`None of the options match with \`${
missingValue.length > 1
? JSON.stringify(missingValue)
: JSON.stringify(missingValue[0])
}\`.`,
'You can use the `isOptionEqualToValue` prop to customize the equality test.',
].join('\n'),
);
}
}
}
const focusTag = useEventCallback((tagToFocus) => {
if (tagToFocus === -1) {
inputRef.current.focus();
} else {
anchorEl.querySelector(`[data-tag-index="${tagToFocus}"]`).focus();
}
});
// Ensure the focusedTag is never inconsistent
React.useEffect(() => {
if (multiple && focusedTag > value.length - 1) {
setFocusedTag(-1);
focusTag(-1);
}
}, [value, multiple, focusedTag, focusTag]);
function validOptionIndex(index, direction) {
if (!listboxRef.current || index < 0 || index >= filteredOptions.length) {
return -1;
}
let nextFocus = index;
while (true) {
const option = listboxRef.current.querySelector(`[data-option-index="${nextFocus}"]`);
// Same logic as MenuList.js
const nextFocusDisabled = disabledItemsFocusable
? false
: !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
if (option && option.hasAttribute('tabindex') && !nextFocusDisabled) {
// The next option is available
return nextFocus;
}
// The next option is disabled, move to the next element.
// with looped index
if (direction === 'next') {
nextFocus = (nextFocus + 1) % filteredOptions.length;
} else {
nextFocus = (nextFocus - 1 + filteredOptions.length) % filteredOptions.length;
}
// We end up with initial index, that means we don't have available options.
// All of them are disabled
if (nextFocus === index) {
return -1;
}
}
}
const setHighlightedIndex = useEventCallback(({ event, index, reason = 'auto' }) => {
highlightedIndexRef.current = index;
// does the index exist?
if (index === -1) {
inputRef.current.removeAttribute('aria-activedescendant');
} else {
inputRef.current.setAttribute('aria-activedescendant', `${id}-option-${index}`);
}
if (onHighlightChange) {
onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);
}
if (!listboxRef.current) {
return;
}
const prev = listboxRef.current.querySelector(
`[role="option"].${unstable_classNamePrefix}-focused`,
);
if (prev) {
prev.classList.remove(`${unstable_classNamePrefix}-focused`);
prev.classList.remove(`${unstable_classNamePrefix}-focusVisible`);
}
let listboxNode = listboxRef.current;
if (listboxRef.current.getAttribute('role') !== 'listbox') {
listboxNode = listboxRef.current.parentElement.querySelector('[role="listbox"]');
}
// "No results"
if (!listboxNode) {
return;
}
if (index === -1) {
listboxNode.scrollTop = 0;
return;
}
const option = listboxRef.current.querySelector(`[data-option-index="${index}"]`);
if (!option) {
return;
}
option.classList.add(`${unstable_classNamePrefix}-focused`);
if (reason === 'keyboard') {
option.classList.add(`${unstable_classNamePrefix}-focusVisible`);
}
// Scroll active descendant into view.
// Logic copied from https://www.w3.org/WAI/content-assets/wai-aria-practices/patterns/combobox/examples/js/select-only.js
// In case of mouse clicks and touch (in mobile devices) we avoid scrolling the element and keep both behaviors same.
// Consider this API instead once it has a better browser support:
// .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });
if (
listboxNode.scrollHeight > listboxNode.clientHeight &&
reason !== 'mouse' &&
reason !== 'touch'
) {
const element = option;
const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
const elementBottom = element.offsetTop + element.offsetHeight;
if (elementBottom > scrollBottom) {
listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;
} else if (
element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) <
listboxNode.scrollTop
) {
listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);
}
}
});
const changeHighlightedIndex = useEventCallback(
({ event, diff, direction = 'next', reason = 'auto' }) => {
if (!popupOpen) {
return;
}
const getNextIndex = () => {
const maxIndex = filteredOptions.length - 1;
if (diff === 'reset') {
return defaultHighlighted;
}
if (diff === 'start') {
return 0;
}
if (diff === 'end') {
return maxIndex;
}
const newIndex = highlightedIndexRef.current + diff;
if (newIndex < 0) {
if (newIndex === -1 && includeInputInList) {
return -1;
}
if ((disableListWrap && highlightedIndexRef.current !== -1) || Math.abs(diff) > 1) {
return 0;
}
return maxIndex;
}
if (newIndex > maxIndex) {
if (newIndex === maxIndex + 1 && includeInputInList) {
return -1;
}
if (disableListWrap || Math.abs(diff) > 1) {
return maxIndex;
}
return 0;
}
return newIndex;
};
const nextIndex = validOptionIndex(getNextIndex(), direction);
setHighlightedIndex({ index: nextIndex, reason, event });
// Sync the content of the input with the highlighted option.
if (autoComplete && diff !== 'reset') {
if (nextIndex === -1) {
inputRef.current.value = inputValue;
} else {
const option = getOptionLabel(filteredOptions[nextIndex]);
inputRef.current.value = option;
// The portion of the selected suggestion that has not been typed by the user,
// a completion string, appears inline after the input cursor in the textbox.
const index = option.toLowerCase().indexOf(inputValue.toLowerCase());
if (index === 0 && inputValue.length > 0) {
inputRef.current.setSelectionRange(inputValue.length, option.length);
}
}
}
},
);
const checkHighlightedOptionExists = () => {
const isSameValue = (value1, value2) => {
const label1 = value1 ? getOptionLabel(value1) : '';
const label2 = value2 ? getOptionLabel(value2) : '';
return label1 === label2;
};
if (
highlightedIndexRef.current !== -1 &&
previousProps.filteredOptions &&
previousProps.filteredOptions.length !== filteredOptions.length &&
previousProps.inputValue === inputValue &&
(multiple
? value.length === previousProps.value.length &&
previousProps.value.every((val, i) => getOptionLabel(value[i]) === getOptionLabel(val))
: isSameValue(previousProps.value, value))
) {
const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current];
if (previousHighlightedOption) {
const previousHighlightedOptionExists = filteredOptions.some((option) => {
return getOptionLabel(option) === getOptionLabel(previousHighlightedOption);
});
if (previousHighlightedOptionExists) {
return true;
}
}
}
return false;
};
const syncHighlightedIndex = React.useCallback(() => {
if (!popupOpen) {
return;
}
// Check if the previously highlighted option still exists in the updated filtered options list and if the value and inputValue haven't changed
// If it exists and the value and the inputValue haven't changed, return, otherwise continue execution
if (checkHighlightedOptionExists()) {
return;
}
const valueItem = multiple ? value[0] : value;
// The popup is empty, reset
if (filteredOptions.length === 0 || valueItem == null) {
changeHighlightedIndex({ diff: 'reset' });
return;
}
if (!listboxRef.current) {
return;
}
// Synchronize the value with the highlighted index
if (valueItem != null) {
const currentOption = filteredOptions[highlightedIndexRef.current];
// Keep the current highlighted index if possible
if (
multiple &&
currentOption &&
findIndex(value, (val) => isOptionEqualToValue(currentOption, val)) !== -1
) {
return;
}
const itemIndex = findIndex(filteredOptions, (optionItem) =>
isOptionEqualToValue(optionItem, valueItem),
);
if (itemIndex === -1) {
changeHighlightedIndex({ diff: 'reset' });
} else {
setHighlightedIndex({ index: itemIndex });
}
return;
}
// Prevent the highlighted index to leak outside the boundaries.
if (highlightedIndexRef.current >= filteredOptions.length - 1) {
setHighlightedIndex({ index: filteredOptions.length - 1 });
return;
}
// Restore the focus to the previous index.
setHighlightedIndex({ index: highlightedIndexRef.current });
// Ignore filteredOptions (and options, isOptionEqualToValue, getOptionLabel) not to break the scroll position
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
// Only sync the highlighted index when the option switch between empty and not
filteredOptions.length,
// Don't sync the highlighted index with the value when multiple
// eslint-disable-next-line react-hooks/exhaustive-deps
multiple ? false : value,
filterSelectedOptions,
changeHighlightedIndex,
setHighlightedIndex,
popupOpen,
inputValue,
multiple,
]);
const handleListboxRef = useEventCallback((node) => {
setRef(listboxRef, node);
if (!node) {
return;
}
syncHighlightedIndex();
});
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (!inputRef.current || inputRef.current.nodeName !== 'INPUT') {
if (inputRef.current && inputRef.current.nodeName === 'TEXTAREA') {
console.warn(
[
`A textarea element was provided to ${componentName} where input was expected.`,
`This is not a supported scenario but it may work under certain conditions.`,
`A textarea keyboard navigation may conflict with Autocomplete controls (e.g. enter and arrow keys).`,
`Make sure to test keyboard navigation and add custom event handlers if necessary.`,
].join('\n'),
);
} else {
console.error(
[
`MUI: Unable to find the input element. It was resolved to ${inputRef.current} while an HTMLInputElement was expected.`,
`Instead, ${componentName} expects an input element.`,
'',
componentName === 'useAutocomplete'
? 'Make sure you have bound getInputProps correctly and that the normal ref/effect resolutions order is guaranteed.'
: 'Make sure you have customized the input component correctly.',
].join('\n'),
);
}
}
}, [componentName]);
}
React.useEffect(() => {
syncHighlightedIndex();
}, [syncHighlightedIndex]);
const handleOpen = (event) => {
if (open) {
return;
}
setOpenState(true);
setInputPristine(true);
if (onOpen) {
onOpen(event);
}
};
const handleClose = (event, reason) => {
if (!open) {
return;
}
setOpenState(false);
if (onClose) {
onClose(event, reason);
}
};
const handleValue = (event, newValue, reason, details) => {
if (multiple) {
if (value.length === newValue.length && value.every((val, i) => val === newValue[i])) {
return;
}
} else if (value === newValue) {
return;
}
if (onChange) {
onChange(event, newValue, reason, details);
}
setValueState(newValue);
};
const isTouch = React.useRef(false);
const selectNewValue = (event, option, reasonProp = 'selectOption', origin = 'options') => {
let reason = reasonProp;
let newValue = option;
if (multiple) {
newValue = Array.isArray(value) ? value.slice() : [];
if (process.env.NODE_ENV !== 'production') {
const matches = newValue.filter((val) => isOptionEqualToValue(option, val));
if (matches.length > 1) {
console.error(
[
`MUI: The \`isOptionEqualToValue\` method of ${componentName} does not handle the arguments correctly.`,
`The component expects a single value to match a given option but found ${matches.length} matches.`,
].join('\n'),
);
}
}
const itemIndex = findIndex(newValue, (valueItem) => isOptionEqualToValue(option, valueItem));
if (itemIndex === -1) {
newValue.push(option);
} else if (origin !== 'freeSolo') {
newValue.splice(itemIndex, 1);
reason = 'removeOption';
}
}
resetInputValue(event, newValue);
handleValue(event, newValue, reason, { option });
if (!disableCloseOnSelect && (!event || (!event.ctrlKey && !event.metaKey))) {
handleClose(event, reason);
}
if (
blurOnSelect === true ||
(blurOnSelect === 'touch' && isTouch.current) ||
(blurOnSelect === 'mouse' && !isTouch.current)
) {
inputRef.current.blur();
}
};
function validTagIndex(index, direction) {
if (index === -1) {
return -1;
}
let nextFocus = index;
while (true) {
// Out of range
if (
(direction === 'next' && nextFocus === value.length) ||
(direction === 'previous' && nextFocus === -1)
) {
return -1;
}
const option = anchorEl.querySelector(`[data-tag-index="${nextFocus}"]`);
// Same logic as MenuList.js
if (
!option ||
!option.hasAttribute('tabindex') ||
option.disabled ||
option.getAttribute('aria-disabled') === 'true'
) {
nextFocus += direction === 'next' ? 1 : -1;
} else {
return nextFocus;
}
}
}
const handleFocusTag = (event, direction) => {
if (!multiple) {
return;
}
if (inputValue === '') {
handleClose(event, 'toggleInput');
}
let nextTag = focusedTag;
if (focusedTag === -1) {
if (inputValue === '' && direction === 'previous') {
nextTag = value.length - 1;
}
} else {
nextTag += direction === 'next' ? 1 : -1;
if (nextTag < 0) {
nextTag = 0;
}
if (nextTag === value.length) {
nextTag = -1;
}
}
nextTag = validTagIndex(nextTag, direction);
setFocusedTag(nextTag);
focusTag(nextTag);
};
const handleClear = (event) => {
ignoreFocus.current = true;
setInputValueState('');
if (onInputChange) {
onInputChange(event, '', 'clear');
}
handleValue(event, multiple ? [] : null, 'clear');
};
const handleKeyDown = (other) => (event) => {
if (other.onKeyDown) {
other.onKeyDown(event);
}
if (event.defaultMuiPrevented) {
return;
}
if (focusedTag !== -1 && ['ArrowLeft', 'ArrowRight'].indexOf(event.key) === -1) {
setFocusedTag(-1);
focusTag(-1);
}
// Wait until IME is settled.
if (event.which !== 229) {
switch (event.key) {
case 'Home':
if (popupOpen && handleHomeEndKeys) {
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({ diff: 'start', direction: 'next', reason: 'keyboard', event });
}
break;
case 'End':
if (popupOpen && handleHomeEndKeys) {
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({
diff: 'end',
direction: 'previous',
reason: 'keyboard',
event,
});
}
break;
case 'PageUp':
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({
diff: -pageSize,
direction: 'previous',
reason: 'keyboard',
event,
});
handleOpen(event);
break;
case 'PageDown':
// Prevent scroll of the page
event.preventDefault();
changeHighlightedIndex({ diff: pageSize, direction: 'next', reason: 'keyboard', event });
handleOpen(event);
break;
case 'ArrowDown':
// Prevent cursor move
event.preventDefault();
changeHighlightedIndex({ diff: 1, direction: 'next', reason: 'keyboard', event });
handleOpen(event);
break;
case 'ArrowUp':
// Prevent cursor move
event.preventDefault();
changeHighlightedIndex({ diff: -1, direction: 'previous', reason: 'keyboard', event });
handleOpen(event);
break;
case 'ArrowLeft':
handleFocusTag(event, 'previous');
break;
case 'ArrowRight':
handleFocusTag(event, 'next');
break;
case 'Enter':
if (highlightedIndexRef.current !== -1 && popupOpen) {
const option = filteredOptions[highlightedIndexRef.current];
const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
// Avoid early form validation, let the end-users continue filling the form.
event.preventDefault();
if (disabled) {
return;
}
selectNewValue(event, option, 'selectOption');
// Move the selection to the end.
if (autoComplete) {
inputRef.current.setSelectionRange(
inputRef.current.value.length,
inputRef.current.value.length,
);
}
} else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
if (multiple) {
// Allow people to add new values before they submit the form.
event.preventDefault();
}
selectNewValue(event, inputValue, 'createOption', 'freeSolo');
}
break;
case 'Escape':
if (popupOpen) {
// Avoid Opera to exit fullscreen mode.
event.preventDefault();
// Avoid the Modal to handle the event.
event.stopPropagation();
handleClose(event, 'escape');
} else if (clearOnEscape && (inputValue !== '' || (multiple && value.length > 0))) {
// Avoid Opera to exit fullscreen mode.
event.preventDefault();
// Avoid the Modal to handle the event.
event.stopPropagation();
handleClear(event);
}
break;
case 'Backspace':
if (multiple && !readOnly && inputValue === '' && value.length > 0) {
const index = focusedTag === -1 ? value.length - 1 : focusedTag;
const newValue = value.slice();
newValue.splice(index, 1);
handleValue(event, newValue, 'removeOption', {
option: value[index],
});
}
break;
case 'Delete':
if (multiple && !readOnly && inputValue === '' && value.length > 0 && focusedTag !== -1) {
const index = focusedTag;
const newValue = value.slice();
newValue.splice(index, 1);
handleValue(event, newValue, 'removeOption', {
option: value[index],
});
}
break;
default:
}
}
};
const handleFocus = (event) => {
setFocused(true);
if (openOnFocus && !ignoreFocus.current) {
handleOpen(event);
}
};
const handleBlur = (event) => {
// Ignore the event when using the scrollbar with IE11
if (unstable_isActiveElementInListbox(listboxRef)) {
inputRef.current.focus();
return;
}
setFocused(false);
firstFocus.current = true;
ignoreFocus.current = false;
if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');
} else if (autoSelect && freeSolo && inputValue !== '') {
selectNewValue(event, inputValue, 'blur', 'freeSolo');
} else if (clearOnBlur) {
resetInputValue(event, value);
}
handleClose(event, 'blur');
};
const handleInputChange = (event) => {
const newValue = event.target.value;
if (inputValue !== newValue) {
setInputValueState(newValue);
setInputPristine(false);
if (onInputChange) {
onInputChange(event, newValue, 'input');
}
}
if (newValue === '') {
if (!disableClearable && !multiple) {
handleValue(event, null, 'clear');
}
} else {
handleOpen(event);
}
};
const handleOptionMouseMove = (event) => {
const index = Number(event.currentTarget.getAttribute('data-option-index'));
if (highlightedIndexRef.current !== index) {
setHighlightedIndex({
event,
index,
reason: 'mouse',
});
}
};
const handleOptionTouchStart = (event) => {
setHighlightedIndex({
event,
index: Number(event.currentTarget.getAttribute('data-option-index')),
reason: 'touch',
});
isTouch.current = true;
};
const handleOptionClick = (event) => {
const index = Number(event.currentTarget.getAttribute('data-option-index'));
selectNewValue(event, filteredOptions[index], 'selectOption');
isTouch.current = false;
};
const handleTagDelete = (index) => (event) => {
const newValue = value.slice();
newValue.splice(index, 1);
handleValue(event, newValue, 'removeOption', {
option: value[index],
});
};
const handlePopupIndicator = (event) => {
if (open) {
handleClose(event, 'toggleInput');
} else {
handleOpen(event);
}
};
// Prevent input blur when interacting with the combobox
const handleMouseDown = (event) => {
// Prevent focusing the input if click is anywhere outside the Autocomplete
if (!event.currentTarget.contains(event.target)) {
return;
}
if (event.target.getAttribute('id') !== id) {
event.preventDefault();
}
};
// Focus the input when interacting with the combobox
const handleClick = (event) => {
// Prevent focusing the input if click is anywhere outside the Autocomplete
if (!event.currentTarget.contains(event.target)) {
return;
}
inputRef.current.focus();
if (
selectOnFocus &&
firstFocus.current &&
inputRef.current.selectionEnd - inputRef.current.selectionStart === 0
) {
inputRef.current.select();
}
firstFocus.current = false;
};
const handleInputMouseDown = (event) => {
if (!disabledProp && (inputValue === '' || !open)) {
handlePopupIndicator(event);
}
};
let dirty = freeSolo && inputValue.length > 0;
dirty = dirty || (multiple ? value.length > 0 : value !== null);
let groupedOptions = filteredOptions;
if (groupBy) {
// used to keep track of key and indexes in the result array
const indexBy = new Map();
let warn = false;
groupedOptions = filteredOptions.reduce((acc, option, index) => {
const group = groupBy(option);
if (acc.length > 0 && acc[acc.length - 1].group === group) {
acc[acc.length - 1].options.push(option);
} else {
if (process.env.NODE_ENV !== 'production') {
if (indexBy.get(group) && !warn) {
console.warn(
`MUI: The options provided combined with the \`groupBy\` method of ${componentName} returns duplicated headers.`,
'You can solve the issue by sorting the options with the output of `groupBy`.',
);
warn = true;
}
indexBy.set(group, true);
}
acc.push({
key: index,
index,
group,
options: [option],
});
}
return acc;
}, []);
}
if (disabledProp && focused) {
handleBlur();
}
return {
getRootProps: (other = {}) => ({
'aria-owns': listboxAvailable ? `${id}-listbox` : null,
...other,
onKeyDown: handleKeyDown(other),
onMouseDown: handleMouseDown,
onClick: handleClick,
}),
getInputLabelProps: () => ({
id: `${id}-label`,
htmlFor: id,
}),
getInputProps: () => ({
id,
value: inputValue,
onBlur: handleBlur,
onFocus: handleFocus,
onChange: handleInputChange,
onMouseDown: handleInputMouseDown,
// if open then this is handled imperatively so don't let react override
// only have an opinion about this when closed
'aria-activedescendant': popupOpen ? '' : null,
'aria-autocomplete': autoComplete ? 'both' : 'list',
'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,
'aria-expanded': listboxAvailable,
// Disable browser's suggestion that might overlap with the popup.
// Handle autocomplete but not autofill.
autoComplete: 'off',
ref: inputRef,
autoCapitalize: 'none',
spellCheck: 'false',
role: 'combobox',
disabled: disabledProp,
}),
getClearProps: () => ({
tabIndex: -1,
type: 'button',
onClick: handleClear,
}),
getPopupIndicatorProps: () => ({
tabIndex: -1,
type: 'button',
onClick: handlePopupIndicator,
}),
getTagProps: ({ index }) => ({
key: index,
'data-tag-index': index,
tabIndex: -1,
...(!readOnly && { onDelete: handleTagDelete(index) }),
}),
getListboxProps: () => ({
role: 'listbox',
id: `${id}-listbox`,
'aria-labelledby': `${id}-label`,
ref: handleListboxRef,
onMouseDown: (event) => {
// Prevent blur
event.preventDefault();
},
}),
getOptionProps: ({ index, option }) => {
const selected = (multiple ? value : [value]).some(
(value2) => value2 != null && isOptionEqualToValue(option, value2),
);
const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
return {
key: getOptionLabel(option),
tabIndex: -1,
role: 'option',
id: `${id}-option-${index}`,
onMouseMove: handleOptionMouseMove,
onClick: handleOptionClick,
onTouchStart: handleOptionTouchStart,
'data-option-index': index,
'aria-disabled': disabled,
'aria-selected': selected,
};
},
id,
inputValue,
value,
dirty,
expanded: popupOpen && anchorEl,
popupOpen,
focused: focused || focusedTag !== -1,
anchorEl,
setAnchorEl,
focusedTag,
groupedOptions,
};
}
| 6,288 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useAutocomplete/useAutocomplete.spec.ts | import { expectType } from '@mui/types';
import { useAutocomplete, FilterOptionsState } from '@mui/base/useAutocomplete';
interface Person {
id: string;
name: string;
}
const persons: Person[] = [
{ id: '1', name: 'Chris' },
{ id: '2', name: 'Kim' },
{ id: '3', name: 'Ben' },
{ id: '4', name: 'Matt' },
];
function Component() {
// value type is inferred correctly when multiple is undefined
useAutocomplete({
options: ['1', '2', '3'],
onChange(event, value) {
expectType<string | null, typeof value>(value);
},
});
// value type is inferred correctly when multiple is false
useAutocomplete({
options: ['1', '2', '3'],
multiple: false,
onChange(event, value) {
expectType<string | null, typeof value>(value);
},
});
// value type is inferred correctly for type unions
useAutocomplete({
options: ['1', '2', '3', 4, true],
onChange(event, value) {
expectType<string | number | boolean | null, typeof value>(value);
},
});
// value type is inferred correctly for interface
useAutocomplete({
options: persons,
onChange(event, value) {
expectType<Person | null, typeof value>(value);
},
});
// value type is inferred correctly when value is set
useAutocomplete({
options: ['1', '2', '3'],
onChange(event, value) {
expectType<string | null, typeof value>(value);
value;
},
filterOptions(options, state) {
expectType<FilterOptionsState<string>, typeof state>(state);
expectType<string[], typeof options>(options);
return options;
},
getOptionLabel(option) {
expectType<string, typeof option>(option);
return option;
},
value: null,
});
// Multiple selection mode
// value type is inferred correctly for simple type
useAutocomplete({
options: ['1', '2', '3'],
multiple: true,
onChange(event, value) {
expectType<string[], typeof value>(value);
value;
},
});
// value type is inferred correctly for union type
useAutocomplete({
options: ['1', '2', '3', 4, true],
multiple: true,
onChange(event, value) {
expectType<Array<string | number | boolean>, typeof value>(value);
},
});
// value type is inferred correctly for interface
useAutocomplete({
options: persons,
multiple: true,
onChange(event, value) {
expectType<Person[], typeof value>(value);
value;
},
});
// no type inference conflict when value type is set explicitly
useAutocomplete({
options: persons,
multiple: true,
onChange(event, value: Person[]) {},
});
// options accepts const and value has correct type
useAutocomplete({
options: ['1', '2', '3'] as const,
onChange(event, value) {
expectType<'1' | '2' | '3' | null, typeof value>(value);
},
});
// Disable clearable
useAutocomplete({
options: ['1', '2', '3'],
disableClearable: true,
onChange(event, value) {
expectType<string, typeof value>(value);
},
});
useAutocomplete({
options: ['1', '2', '3'],
disableClearable: false,
onChange(event, value) {
expectType<string | null, typeof value>(value);
},
});
useAutocomplete({
options: ['1', '2', '3'],
onChange(event, value) {
expectType<string | null, typeof value>(value);
},
});
// Free solo
useAutocomplete({
options: persons,
onChange(event, value) {
expectType<string | Person | null, typeof value>(value);
},
freeSolo: true,
});
useAutocomplete({
options: persons,
disableClearable: true,
onChange(event, value) {
expectType<string | Person, typeof value>(value);
},
freeSolo: true,
});
useAutocomplete({
options: persons,
multiple: true,
onChange(event, value) {
expectType<Array<string | Person>, typeof value>(value);
},
freeSolo: true,
});
useAutocomplete({
options: persons,
getOptionLabel(option) {
expectType<string | Person, typeof option>(option);
return '';
},
freeSolo: true,
});
}
| 6,289 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useAutocomplete/useAutocomplete.test.js | import * as React from 'react';
import { expect } from 'chai';
import { createRenderer, screen, ErrorBoundary, act, fireEvent } from '@mui-internal/test-utils';
import { spy } from 'sinon';
import { useAutocomplete, createFilterOptions } from '@mui/base/useAutocomplete';
describe('useAutocomplete', () => {
const { render } = createRenderer();
it('should preserve DOM nodes of options when re-ordering', () => {
function Test(props) {
const { options } = props;
const {
groupedOptions,
getRootProps,
getInputLabelProps,
getInputProps,
getListboxProps,
getOptionProps,
} = useAutocomplete({
options,
open: true,
});
return (
<div>
<div {...getRootProps()}>
<label {...getInputLabelProps()}>useAutocomplete</label>
<input {...getInputProps()} />
</div>
{groupedOptions.length > 0 ? (
<ul {...getListboxProps()}>
{groupedOptions.map((option, index) => {
return <li {...getOptionProps({ option, index })}>{option}</li>;
})}
</ul>
) : null}
</div>
);
}
const { rerender } = render(<Test options={['foo', 'bar']} />);
const [fooOptionAsFirst, barOptionAsSecond] = screen.getAllByRole('option');
rerender(<Test options={['bar', 'foo']} />);
const [barOptionAsFirst, fooOptionAsSecond] = screen.getAllByRole('option');
// If the DOM nodes are not preserved VO will not read the first option again since it thinks it didn't change.
expect(fooOptionAsFirst).to.equal(fooOptionAsSecond);
expect(barOptionAsFirst).to.equal(barOptionAsSecond);
});
describe('createFilterOptions', () => {
it('defaults to getOptionLabel for text filtering', () => {
const filterOptions = createFilterOptions();
const getOptionLabel = (option) => option.name;
const options = [
{
id: '1234',
name: 'cat',
},
{
id: '5678',
name: 'dog',
},
{
id: '9abc',
name: 'emu',
},
];
expect(filterOptions(options, { inputValue: 'a', getOptionLabel })).to.deep.equal([
options[0],
]);
});
it('filters without error with empty option set', () => {
const filterOptions = createFilterOptions();
const getOptionLabel = (option) => option.name;
const options = [];
expect(filterOptions(options, { inputValue: 'a', getOptionLabel })).to.deep.equal([]);
});
describe('option: limit', () => {
it('limits the number of suggested options to be shown', () => {
const filterOptions = createFilterOptions({ limit: 2 });
const getOptionLabel = (option) => option.name;
const options = [
{
id: '1234',
name: 'a1',
},
{
id: '5678',
name: 'a2',
},
{
id: '9abc',
name: 'a3',
},
{
id: '9abc',
name: 'a4',
},
];
expect(filterOptions(options, { inputValue: 'a', getOptionLabel })).to.deep.equal([
options[0],
options[1],
]);
});
});
describe('option: matchFrom', () => {
let filterOptions;
let getOptionLabel;
let options;
beforeEach(() => {
filterOptions = createFilterOptions({ matchFrom: 'any' });
getOptionLabel = (option) => option.name;
options = [
{
id: '1234',
name: 'ab',
},
{
id: '5678',
name: 'ba',
},
{
id: '9abc',
name: 'ca',
},
];
});
describe('any', () => {
it('show all results that match', () => {
expect(filterOptions(options, { inputValue: 'a', getOptionLabel })).to.deep.equal(
options,
);
});
});
describe('empty', () => {
it('does not call getOptionLabel if filter is empty', () => {
const getOptionLabelSpy = spy(getOptionLabel);
expect(
filterOptions(options, { inputValue: '', getOptionLabel: getOptionLabelSpy }),
).to.deep.equal(options);
expect(getOptionLabelSpy.callCount).to.equal(0);
});
});
describe('start', () => {
it('show only results that start with search', () => {
expect(filterOptions(options, { inputValue: 'a', getOptionLabel })).to.deep.equal(
options,
);
});
});
});
describe('option: ignoreAccents', () => {
it('does not ignore accents', () => {
const filterOptions = createFilterOptions({ ignoreAccents: false });
const getOptionLabel = (option) => option.name;
const options = [
{
id: '1234',
name: 'áb',
},
{
id: '5678',
name: 'ab',
},
{
id: '9abc',
name: 'áe',
},
{
id: '9abc',
name: 'ae',
},
];
expect(filterOptions(options, { inputValue: 'á', getOptionLabel })).to.deep.equal([
options[0],
options[2],
]);
});
});
describe('option: ignoreCase', () => {
it('matches results with case insensitive', () => {
const filterOptions = createFilterOptions({ ignoreCase: false });
const getOptionLabel = (option) => option.name;
const options = [
{
id: '1234',
name: 'Ab',
},
{
id: '5678',
name: 'ab',
},
{
id: '9abc',
name: 'Ae',
},
{
id: '9abc',
name: 'ae',
},
];
expect(filterOptions(options, { inputValue: 'A', getOptionLabel })).to.deep.equal([
options[0],
options[2],
]);
});
});
});
it('should warn if the input is not binded', function test() {
// TODO is this fixed?
if (!/jsdom/.test(window.navigator.userAgent)) {
// can't catch render errors in the browser for unknown reason
// tried try-catch + error boundary + window onError preventDefault
this.skip();
}
function Test(props) {
const { options } = props;
const {
groupedOptions,
getRootProps,
getInputLabelProps,
// getInputProps,
getListboxProps,
getOptionProps,
} = useAutocomplete({
options,
open: true,
});
return (
<div>
<div {...getRootProps()}>
<label {...getInputLabelProps()}>useAutocomplete</label>
</div>
{groupedOptions.length > 0 ? (
<ul {...getListboxProps()}>
{groupedOptions.map((option, index) => {
return <li {...getOptionProps({ option, index })}>{option}</li>;
})}
</ul>
) : null}
</div>
);
}
const node16ErrorMessage =
"Error: Uncaught [TypeError: Cannot read properties of null (reading 'removeAttribute')]";
const olderNodeErrorMessage =
"Error: Uncaught [TypeError: Cannot read property 'removeAttribute' of null]";
const nodeVersion = Number(process.versions.node.split('.')[0]);
const errorMessage = nodeVersion >= 16 ? node16ErrorMessage : olderNodeErrorMessage;
const devErrorMessages = [
errorMessage,
'MUI: Unable to find the input element.',
errorMessage,
// strict effects runs effects twice
React.version.startsWith('18') && 'MUI: Unable to find the input element.',
React.version.startsWith('18') && errorMessage,
'The above error occurred in the <ul> component',
React.version.startsWith('16') && 'The above error occurred in the <ul> component',
'The above error occurred in the <Test> component',
// strict effects runs effects twice
React.version.startsWith('18') && 'The above error occurred in the <Test> component',
React.version.startsWith('16') && 'The above error occurred in the <Test> component',
];
expect(() => {
render(
<ErrorBoundary>
<Test options={['foo', 'bar']} />
</ErrorBoundary>,
);
}).toErrorDev(devErrorMessages);
});
describe('prop: freeSolo', () => {
it('should not reset if the component value does not change on blur', () => {
function Test(props) {
const { options } = props;
const { getInputProps } = useAutocomplete({ options, open: true, freeSolo: true });
return <input {...getInputProps()} />;
}
render(<Test options={['foo', 'bar']} />);
const input = screen.getByRole('combobox');
act(() => {
fireEvent.change(input, { target: { value: 'free' } });
input.blur();
});
expect(input.value).to.equal('free');
});
});
describe('getInputProps', () => {
it('should disable input element', () => {
function Test(props) {
const { options } = props;
const { getInputProps } = useAutocomplete({ options, disabled: true });
return <input {...getInputProps()} />;
}
render(<Test options={['foo', 'bar']} />);
const input = screen.getByRole('combobox');
expect(input).to.have.attribute('disabled');
});
});
it('should allow tuples or arrays as value when multiple=false', () => {
function Test() {
const defaultValue = ['bar'];
const { getClearProps, getInputProps } = useAutocomplete({
defaultValue,
disableClearable: false,
getOptionLabel: ([val]) => val,
isOptionEqualToValue: (option, value) => {
if (option === value) {
return true;
}
return option[0] === value[0];
},
multiple: false,
options: [['foo'], defaultValue, ['baz']],
});
return (
<div>
<input {...getInputProps()} />
<button data-testid="button" {...getClearProps()} />;
</div>
);
}
const { getByTestId } = render(<Test />);
const button = getByTestId('button');
expect(() => {
fireEvent.click(button);
}).not.to.throw();
});
});
| 6,290 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useBadge/index.ts | 'use client';
export { useBadge } from './useBadge';
export * from './useBadge.types';
| 6,291 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useBadge/useBadge.ts | 'use client';
import * as React from 'react';
import { usePreviousProps } from '@mui/utils';
import { UseBadgeParameters, UseBadgeReturnValue } from './useBadge.types';
/**
*
* Demos:
*
* - [Badge](https://mui.com/base-ui/react-badge/#hook)
*
* API:
*
* - [useBadge API](https://mui.com/base-ui/react-badge/hooks-api/#use-badge)
*/
export function useBadge(parameters: UseBadgeParameters): UseBadgeReturnValue {
const {
badgeContent: badgeContentProp,
invisible: invisibleProp = false,
max: maxProp = 99,
showZero = false,
} = parameters;
const prevProps = usePreviousProps({
badgeContent: badgeContentProp,
max: maxProp,
});
let invisible = invisibleProp;
if (invisibleProp === false && badgeContentProp === 0 && !showZero) {
invisible = true;
}
const { badgeContent, max = maxProp } = invisible ? prevProps : parameters;
const displayValue: React.ReactNode =
badgeContent && Number(badgeContent) > max ? `${max}+` : badgeContent;
return {
badgeContent,
invisible,
max,
displayValue,
};
}
| 6,292 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useBadge/useBadge.types.ts | export interface UseBadgeParameters {
/**
* The content rendered within the badge.
*/
badgeContent?: React.ReactNode;
/**
* If `true`, the badge is invisible.
* @default false
*/
invisible?: boolean;
/**
* Max count to show.
* @default 99
*/
max?: number;
/**
* Controls whether the badge is hidden when `badgeContent` is zero.
* @default false
*/
showZero?: boolean;
}
export interface UseBadgeReturnValue {
/**
* Defines the content that's displayed inside the badge.
*/
badgeContent: React.ReactNode;
/**
* If `true`, the component will not be visible.
*/
invisible: boolean;
/**
* Maximum number to be displayed in the badge.
*/
max: number;
/**
* Value to be displayed in the badge. If `badgeContent` is greater than `max`, it will return `max+`.
*/
displayValue: React.ReactNode;
}
| 6,293 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useButton/index.ts | 'use client';
export { useButton } from './useButton';
export * from './useButton.types';
| 6,294 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useButton/useButton.test.tsx | import * as React from 'react';
import { act, createRenderer, fireEvent } from '@mui-internal/test-utils';
import { expect } from 'chai';
import { spy } from 'sinon';
import { useButton } from '@mui/base/useButton';
describe('useButton', () => {
const { render } = createRenderer();
describe('state: active', () => {
describe('when using a button element', () => {
it('is set when triggered by mouse', () => {
function TestComponent() {
const buttonRef = React.useRef(null);
const { active, getRootProps } = useButton({ rootRef: buttonRef });
return <button {...getRootProps()} className={active ? 'active' : ''} />;
}
const { getByRole } = render(<TestComponent />);
const button = getByRole('button');
fireEvent.mouseDown(button);
expect(button).to.have.class('active');
fireEvent.mouseUp(button);
expect(button).not.to.have.class('active');
});
it('is set when triggered by keyboard', () => {
function TestComponent() {
const buttonRef = React.useRef(null);
const { active, getRootProps } = useButton({ rootRef: buttonRef });
return <button {...getRootProps()} className={active ? 'active' : ''} />;
}
const { getByRole } = render(<TestComponent />);
const button = getByRole('button');
button.focus();
fireEvent.keyDown(button, { key: ' ' });
expect(button).to.have.class('active');
fireEvent.keyUp(button, { key: ' ' });
expect(button).not.to.have.class('active');
});
it('is set when clicked on an element inside the button', () => {
function TestComponent() {
const buttonRef = React.useRef(null);
const { active, getRootProps } = useButton({ rootRef: buttonRef });
return (
<button {...getRootProps()} className={active ? 'active' : ''}>
<span>Click here</span>
</button>
);
}
const { getByText, getByRole } = render(<TestComponent />);
const span = getByText('Click here');
const button = getByRole('button');
fireEvent.mouseDown(span);
expect(button).to.have.class('active');
});
it('is unset when mouse button is released above another element', () => {
function TestComponent() {
const buttonRef = React.useRef(null);
const { active, getRootProps } = useButton({ rootRef: buttonRef });
return (
<div data-testid="parent">
<button {...getRootProps()} className={active ? 'active' : ''} />
</div>
);
}
const { getByRole, getByTestId } = render(<TestComponent />);
const button = getByRole('button');
const background = getByTestId('parent');
fireEvent.mouseDown(button);
expect(button).to.have.class('active');
fireEvent.mouseUp(background);
expect(button).not.to.have.class('active');
});
});
describe('when using a span element', () => {
it('is set when triggered by mouse', () => {
function TestComponent() {
const buttonRef = React.useRef(null);
const { active, getRootProps } = useButton({ rootRef: buttonRef });
return <span {...getRootProps()} className={active ? 'active' : ''} />;
}
const { getByRole } = render(<TestComponent />);
const button = getByRole('button');
fireEvent.mouseDown(button);
expect(button).to.have.class('active');
fireEvent.mouseUp(button);
expect(button).not.to.have.class('active');
});
it('is set when triggered by keyboard', () => {
function TestComponent() {
const buttonRef = React.useRef(null);
const { active, getRootProps } = useButton({ rootRef: buttonRef });
return <span {...getRootProps()} className={active ? 'active' : ''} />;
}
const { getByRole } = render(<TestComponent />);
const button = getByRole('button');
button.focus();
fireEvent.keyDown(button, { key: ' ' });
expect(button).to.have.class('active');
fireEvent.keyUp(button, { key: ' ' });
expect(button).not.to.have.class('active');
});
});
describe('event handlers', () => {
interface WithClickHandler {
onClick: React.MouseEventHandler;
}
it('calls them when provided in props', () => {
function TestComponent(props: WithClickHandler) {
const ref = React.useRef(null);
const { getRootProps } = useButton({ ...props, rootRef: ref });
return <button {...getRootProps()} />;
}
const handleClick = spy();
const { getByRole } = render(<TestComponent onClick={handleClick} />);
fireEvent.click(getByRole('button'));
expect(handleClick.callCount).to.equal(1);
});
it('calls them when provided in getRootProps()', () => {
const handleClick = spy();
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref });
return <button {...getRootProps({ onClick: handleClick })} />;
}
const { getByRole } = render(<TestComponent />);
fireEvent.click(getByRole('button'));
expect(handleClick.callCount).to.equal(1);
});
it('calls the one provided in getRootProps() when both props and getRootProps have ones', () => {
const handleClickExternal = spy();
const handleClickInternal = spy();
function TestComponent(props: WithClickHandler) {
const ref = React.useRef(null);
const { getRootProps } = useButton({ ...props, rootRef: ref });
return <button {...getRootProps({ onClick: handleClickInternal })} />;
}
const { getByRole } = render(<TestComponent onClick={handleClickExternal} />);
fireEvent.click(getByRole('button'));
expect(handleClickInternal.callCount).to.equal(1);
expect(handleClickExternal.callCount).to.equal(0);
});
it('handles onFocusVisible and does not include it in the root props', () => {
interface WithFocusVisibleHandler {
onFocusVisible: React.FocusEventHandler;
}
function TestComponent(props: WithFocusVisibleHandler) {
const ref = React.useRef(null);
const { getRootProps } = useButton({ ...props, rootRef: ref });
// @ts-expect-error onFocusVisible is removed from props
expect(getRootProps().onFocusVisible).to.equal(undefined);
return <button {...getRootProps()} />;
}
const handleFocusVisible = spy();
const { getByRole } = render(<TestComponent onFocusVisible={handleFocusVisible} />);
act(() => {
getByRole('button').focus();
});
expect(handleFocusVisible.callCount).to.equal(1);
});
});
});
describe('tabIndex', () => {
it('does not return tabIndex in getRootProps when host component is BUTTON', () => {
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref });
expect(getRootProps().tabIndex).to.equal(undefined);
return <button {...getRootProps()} />;
}
const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.property('tabIndex', 0);
});
it('returns tabIndex in getRootProps when host component is not BUTTON', () => {
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref });
expect(getRootProps().tabIndex).to.equal(ref.current ? 0 : undefined);
return <span {...getRootProps()} />;
}
const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.property('tabIndex', 0);
});
it('returns tabIndex in getRootProps if it is explicitly provided', () => {
const customTabIndex = 3;
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref, tabIndex: customTabIndex });
return <button {...getRootProps()} />;
}
const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.property('tabIndex', customTabIndex);
});
});
describe('arbitrary props', () => {
it('are passed to the host component', () => {
const buttonTestId = 'button-test-id';
function TestComponent() {
const { getRootProps } = useButton({});
return <button {...getRootProps({ 'data-testid': buttonTestId })} />;
}
const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.attribute('data-testid', buttonTestId);
});
});
});
| 6,295 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useButton/useButton.ts | 'use client';
import * as React from 'react';
import {
unstable_useForkRef as useForkRef,
unstable_useIsFocusVisible as useIsFocusVisible,
} from '@mui/utils';
import {
UseButtonParameters,
UseButtonReturnValue,
UseButtonRootSlotProps,
} from './useButton.types';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { EventHandlers } from '../utils/types';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
/**
*
* Demos:
*
* - [Button](https://mui.com/base-ui/react-button/#hook)
*
* API:
*
* - [useButton API](https://mui.com/base-ui/react-button/hooks-api/#use-button)
*/
export function useButton(parameters: UseButtonParameters = {}): UseButtonReturnValue {
const {
disabled = false,
focusableWhenDisabled,
href,
rootRef: externalRef,
tabIndex,
to,
type,
} = parameters;
const buttonRef = React.useRef<HTMLButtonElement | HTMLAnchorElement | HTMLElement>();
const [active, setActive] = React.useState<boolean>(false);
const {
isFocusVisibleRef,
onFocus: handleFocusVisible,
onBlur: handleBlurVisible,
ref: focusVisibleRef,
} = useIsFocusVisible();
const [focusVisible, setFocusVisible] = React.useState(false);
if (disabled && !focusableWhenDisabled && focusVisible) {
setFocusVisible(false);
}
React.useEffect(() => {
isFocusVisibleRef.current = focusVisible;
}, [focusVisible, isFocusVisibleRef]);
const [hostElementName, setHostElementName] = React.useState<string>('');
const createHandleMouseLeave = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
if (focusVisible) {
event.preventDefault();
}
otherHandlers.onMouseLeave?.(event);
};
const createHandleBlur = (otherHandlers: EventHandlers) => (event: React.FocusEvent) => {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setFocusVisible(false);
}
otherHandlers.onBlur?.(event);
};
const createHandleFocus =
(otherHandlers: EventHandlers) => (event: React.FocusEvent<HTMLButtonElement>) => {
// Fix for https://github.com/facebook/react/issues/7769
if (!buttonRef.current) {
buttonRef.current = event.currentTarget;
}
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setFocusVisible(true);
otherHandlers.onFocusVisible?.(event);
}
otherHandlers.onFocus?.(event);
};
const isNativeButton = () => {
const button = buttonRef.current;
return (
hostElementName === 'BUTTON' ||
(hostElementName === 'INPUT' &&
['button', 'submit', 'reset'].includes((button as HTMLInputElement)?.type)) ||
(hostElementName === 'A' && (button as HTMLAnchorElement)?.href)
);
};
const createHandleClick = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
if (!disabled) {
otherHandlers.onClick?.(event);
}
};
const createHandleMouseDown = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
if (!disabled) {
setActive(true);
document.addEventListener(
'mouseup',
() => {
setActive(false);
},
{ once: true },
);
}
otherHandlers.onMouseDown?.(event);
};
const createHandleKeyDown =
(otherHandlers: EventHandlers) => (event: React.KeyboardEvent & MuiCancellableEvent) => {
otherHandlers.onKeyDown?.(event);
if (event.defaultMuiPrevented) {
return;
}
if (event.target === event.currentTarget && !isNativeButton() && event.key === ' ') {
event.preventDefault();
}
if (event.target === event.currentTarget && event.key === ' ' && !disabled) {
setActive(true);
}
// Keyboard accessibility for non interactive elements
if (
event.target === event.currentTarget &&
!isNativeButton() &&
event.key === 'Enter' &&
!disabled
) {
otherHandlers.onClick?.(event);
event.preventDefault();
}
};
const createHandleKeyUp =
(otherHandlers: EventHandlers) => (event: React.KeyboardEvent & MuiCancellableEvent) => {
// calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
// https://codesandbox.io/s/button-keyup-preventdefault-dn7f0
if (event.target === event.currentTarget) {
setActive(false);
}
otherHandlers.onKeyUp?.(event);
// Keyboard accessibility for non interactive elements
if (
event.target === event.currentTarget &&
!isNativeButton() &&
!disabled &&
event.key === ' ' &&
!event.defaultMuiPrevented
) {
otherHandlers.onClick?.(event);
}
};
const updateHostElementName = React.useCallback((instance: HTMLElement | null) => {
setHostElementName(instance?.tagName ?? '');
}, []);
const handleRef = useForkRef(updateHostElementName, externalRef, focusVisibleRef, buttonRef);
interface AdditionalButtonProps {
type?: React.ButtonHTMLAttributes<HTMLButtonElement>['type'];
disabled?: boolean;
role?: React.AriaRole;
'aria-disabled'?: React.AriaAttributes['aria-disabled'];
tabIndex?: number;
}
const buttonProps: AdditionalButtonProps = {};
if (tabIndex !== undefined) {
buttonProps.tabIndex = tabIndex;
}
if (hostElementName === 'BUTTON') {
buttonProps.type = type ?? 'button';
if (focusableWhenDisabled) {
buttonProps['aria-disabled'] = disabled;
} else {
buttonProps.disabled = disabled;
}
} else if (hostElementName !== '') {
if (!href && !to) {
buttonProps.role = 'button';
buttonProps.tabIndex = tabIndex ?? 0;
}
if (disabled) {
buttonProps['aria-disabled'] = disabled as boolean;
buttonProps.tabIndex = focusableWhenDisabled ? tabIndex ?? 0 : -1;
}
}
const getRootProps = <ExternalProps extends Record<string, any> = {}>(
externalProps: ExternalProps = {} as ExternalProps,
): UseButtonRootSlotProps<ExternalProps> => {
const externalEventHandlers = {
...extractEventHandlers(parameters),
...extractEventHandlers(externalProps),
};
const props = {
type,
...externalEventHandlers,
...buttonProps,
...externalProps,
onBlur: createHandleBlur(externalEventHandlers),
onClick: createHandleClick(externalEventHandlers),
onFocus: createHandleFocus(externalEventHandlers),
onKeyDown: createHandleKeyDown(externalEventHandlers),
onKeyUp: createHandleKeyUp(externalEventHandlers),
onMouseDown: createHandleMouseDown(externalEventHandlers),
onMouseLeave: createHandleMouseLeave(externalEventHandlers),
ref: handleRef,
};
// onFocusVisible can be present on the props or parameters,
// but it's not a valid React event handler so it must not be forwarded to the inner component.
// If present, it will be handled by the focus handler.
delete props.onFocusVisible;
return props;
};
return {
getRootProps,
focusVisible,
setFocusVisible,
active,
rootRef: handleRef,
};
}
| 6,296 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useButton/useButton.types.ts | import * as React from 'react';
import { MuiCancellableEventHandler } from '../utils/MuiCancellableEvent';
export interface UseButtonParameters {
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
/**
* If `true`, allows a disabled button to receive focus.
* @default false
*/
focusableWhenDisabled?: boolean;
href?: string;
onFocusVisible?: React.FocusEventHandler;
rootRef?: React.Ref<Element>;
tabIndex?: NonNullable<React.HTMLAttributes<any>['tabIndex']>;
to?: string;
/**
* Type attribute applied when the `component` is `button`.
* @default 'button'
*/
type?: React.ButtonHTMLAttributes<HTMLButtonElement>['type'];
}
export interface UseButtonRootSlotOwnProps {
'aria-disabled'?: React.AriaAttributes['aria-disabled'];
disabled?: boolean;
tabIndex?: number;
type?: React.ButtonHTMLAttributes<HTMLButtonElement>['type'];
role?: React.AriaRole;
onBlur: React.FocusEventHandler;
onFocus: React.FocusEventHandler;
onKeyDown: MuiCancellableEventHandler<React.KeyboardEvent>;
onKeyUp: MuiCancellableEventHandler<React.KeyboardEvent>;
onMouseDown: React.MouseEventHandler;
onMouseLeave: React.MouseEventHandler;
ref: React.RefCallback<Element> | null;
}
export type UseButtonRootSlotProps<ExternalProps = {}> = ExternalProps & UseButtonRootSlotOwnProps;
export interface UseButtonReturnValue {
/**
* Resolver for the root slot's props.
* @param externalProps additional props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, any> = {}>(
externalProps?: ExternalProps,
) => UseButtonRootSlotProps<ExternalProps>;
/**
* If `true`, the component is being focused using keyboard.
*/
focusVisible: boolean;
/**
* Callback for setting the `focusVisible` param.
*/
setFocusVisible: React.Dispatch<React.SetStateAction<boolean>>;
/**
* If `true`, the component is active (pressed).
*/
active: boolean;
/**
* A ref to the component's root DOM element.
*/
rootRef: React.RefCallback<Element> | null;
}
| 6,297 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useCompound/index.ts | 'use client';
export * from './useCompoundParent';
export * from './useCompoundItem';
| 6,298 |
0 | petrpan-code/mui/material-ui/packages/mui-base/src | petrpan-code/mui/material-ui/packages/mui-base/src/useCompound/useCompound.test.tsx | import * as React from 'react';
import { expect } from 'chai';
import { render } from '@mui-internal/test-utils';
import { CompoundComponentContext, useCompoundParent } from './useCompoundParent';
import { useCompoundItem } from './useCompoundItem';
type ItemValue = { value: string; ref: React.RefObject<HTMLSpanElement> };
describe('compound components', () => {
describe('useCompoundParent', () => {
it('knows about children from the whole subtree', () => {
let parentSubitems: Map<string, ItemValue>;
function Parent(props: React.PropsWithChildren<{}>) {
const { children } = props;
const { subitems, contextValue } = useCompoundParent<string, ItemValue>();
parentSubitems = subitems;
return (
<CompoundComponentContext.Provider value={contextValue}>
{children}
</CompoundComponentContext.Provider>
);
}
function Child(props: React.PropsWithChildren<{ id: string; value: string }>) {
const { id, value, children } = props;
const ref = React.useRef<HTMLSpanElement>(null);
useCompoundItem(
id,
React.useMemo(() => ({ value, ref }), [value]),
);
return <span ref={ref}>{children}</span>;
}
render(
<Parent>
<Child id="1" value="one" />
<Child id="2" value="two">
<Child id="2.1" value="two.one" />
<Child id="2.2" value="two.two" />
</Child>
<Child id="3" value="three">
<Child id="3.1" value="three.one">
<Child id="3.1.1" value="three.one.one" />
</Child>
</Child>
</Parent>,
);
expect(Array.from(parentSubitems!.keys())).to.deep.equal([
'1',
'2',
'2.1',
'2.2',
'3',
'3.1',
'3.1.1',
]);
expect(Array.from(parentSubitems!.values()).map((v) => v.value)).to.deep.equal([
'one',
'two',
'two.one',
'two.two',
'three',
'three.one',
'three.one.one',
]);
});
it('knows about children rendered by other components', () => {
let parentSubitems: Map<string, ItemValue>;
function Parent(props: React.PropsWithChildren<{}>) {
const { children } = props;
const { subitems, contextValue } = useCompoundParent<string, ItemValue>();
parentSubitems = subitems;
return (
<CompoundComponentContext.Provider value={contextValue}>
{children}
</CompoundComponentContext.Provider>
);
}
function Child(props: { id: string; value: string }) {
const { id, value } = props;
const ref = React.useRef<HTMLSpanElement>(null);
useCompoundItem(
id,
React.useMemo(() => ({ value, ref }), [value]),
);
return <span ref={ref} />;
}
function Wrapper() {
return (
<React.Fragment>
<Child id="1" value="one" />
<Child id="2" value="two" />
<Child id="3" value="three" />
</React.Fragment>
);
}
render(
<Parent>
<Child id="0" value="zero" />
<Wrapper />
<Child id="4" value="four" />
</Parent>,
);
expect(Array.from(parentSubitems!.keys())).to.deep.equal(['0', '1', '2', '3', '4']);
expect(Array.from(parentSubitems!.values()).map((v) => v.value)).to.deep.equal([
'zero',
'one',
'two',
'three',
'four',
]);
});
// https://github.com/mui/material-ui/issues/36800
it('maintains the correct order of children when they are inserted in the middle', () => {
let parentSubitems: Map<string, ItemValue>;
let subitemsToRender = ['1', '4', '5'];
function Parent(props: React.PropsWithChildren<{}>) {
const { children } = props;
const { subitems, contextValue } = useCompoundParent<string, ItemValue>();
parentSubitems = subitems;
return (
<CompoundComponentContext.Provider value={contextValue}>
{children}
</CompoundComponentContext.Provider>
);
}
function Child(props: React.PropsWithChildren<{ id: string; value: string }>) {
const { id, value, children } = props;
const ref = React.useRef<HTMLSpanElement>(null);
useCompoundItem(
id,
React.useMemo(() => ({ value, ref }), [value]),
);
return <span ref={ref}>{children}</span>;
}
const { rerender } = render(
<Parent>
{subitemsToRender.map((item) => (
<Child key={item} id={item} value={item} />
))}
</Parent>,
);
subitemsToRender = ['1', '2', '3', '4', '5'];
rerender(
<Parent>
{subitemsToRender.map((item) => (
<Child key={item} id={item} value={item} />
))}
</Parent>,
);
expect(Array.from(parentSubitems!.keys())).to.deep.equal(['1', '2', '3', '4', '5']);
});
// TODO: test if removed children are removed from the map
// TODO: test if parent is notified about updated metadata
});
describe('useCompoundItem', () => {
it('knows its position within the parent and total number of registered items', () => {
function Parent(props: React.PropsWithChildren<{}>) {
const { children } = props;
const { contextValue } = useCompoundParent<
string,
{ ref: React.RefObject<HTMLSpanElement> }
>();
return (
<CompoundComponentContext.Provider value={contextValue}>
{children}
</CompoundComponentContext.Provider>
);
}
function Child() {
const id = React.useId();
const ref = React.useRef<HTMLSpanElement>(null);
const { index, totalItemCount } = useCompoundItem(
id,
React.useMemo(() => ({ ref }), []),
);
return (
<span data-testid="child" ref={ref}>
{index + 1} of {totalItemCount}
</span>
);
}
const { getAllByTestId } = render(
<Parent>
<Child />
<Child />
<React.Fragment>
<p>Unrelated element 1</p>
<Child />
</React.Fragment>
<p>Unrelated element 2</p>
<div>
<Child />
</div>
</Parent>,
);
const children = getAllByTestId('child');
children.forEach((child, index) => {
expect(child.innerHTML).to.equal(`${index + 1} of 4`);
});
});
it('gets assigned a generated id if none is provided', () => {
function Parent(props: React.PropsWithChildren<{}>) {
const { children } = props;
const { contextValue } = useCompoundParent<
number,
{ ref: React.RefObject<HTMLLIElement> }
>();
return (
<CompoundComponentContext.Provider value={contextValue}>
<ul>{children}</ul>
</CompoundComponentContext.Provider>
);
}
function idGenerator(existingIds: Set<string>) {
return `item-${existingIds.size}`;
}
function Child() {
const ref = React.useRef<HTMLLIElement>(null);
const { id } = useCompoundItem<string, { ref: React.RefObject<HTMLLIElement> }>(
idGenerator,
React.useMemo(() => ({ ref }), []),
);
return <li ref={ref}>{id}</li>;
}
const { getAllByRole } = render(
<Parent>
<Child />
<Child />
<Child />
</Parent>,
);
const children = getAllByRole('listitem');
expect(children[0].innerHTML).to.equal('item-0');
expect(children[1].innerHTML).to.equal('item-1');
expect(children[2].innerHTML).to.equal('item-2');
});
});
});
| 6,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.