diff --git a/docs/data/material/components/number-field/demos/adornments/NumberFieldAdornments.tsx b/docs/data/material/components/number-field/demos/adornments/NumberFieldAdornments.tsx new file mode 100644 index 00000000000000..f6dc64d088097e --- /dev/null +++ b/docs/data/material/components/number-field/demos/adornments/NumberFieldAdornments.tsx @@ -0,0 +1,46 @@ +import * as React from 'react'; +import ClearIcon from '@mui/icons-material/Clear'; +import Box from '@mui/material/Box'; +import IconButton from '@mui/material/IconButton'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldAdornments() { + const [value, setValue] = React.useState(5); + const inputRef = React.useRef(null); + + return ( + + {/* @focus-start */} + + { + setValue(null); + inputRef.current?.focus(); + }} + > + + + } + /> + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/spinner-demo/client.ts b/docs/data/material/components/number-field/demos/adornments/client.ts similarity index 52% rename from docs/data/material/components/number-field/demos/spinner-demo/client.ts rename to docs/data/material/components/number-field/demos/adornments/client.ts index c874a2038b3efd..47671215a56433 100644 --- a/docs/data/material/components/number-field/demos/spinner-demo/client.ts +++ b/docs/data/material/components/number-field/demos/adornments/client.ts @@ -2,6 +2,4 @@ import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; -const ClientProvider = createDemoClient(import.meta.url); - -export default ClientProvider; +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/adornments/index.ts b/docs/data/material/components/number-field/demos/adornments/index.ts new file mode 100644 index 00000000000000..7f85578ae60b1a --- /dev/null +++ b/docs/data/material/components/number-field/demos/adornments/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldAdornments from './NumberFieldAdornments'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldAdornments, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/basic/BasicNumberFields.tsx b/docs/data/material/components/number-field/demos/basic/BasicNumberFields.tsx new file mode 100644 index 00000000000000..d6214bbb4544dd --- /dev/null +++ b/docs/data/material/components/number-field/demos/basic/BasicNumberFields.tsx @@ -0,0 +1,21 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function BasicNumberFields() { + return ( + .MuiNumberField-root': { width: '25ch' }, + }} + > + {/* @focus-start */} + + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/field-demo/client.ts b/docs/data/material/components/number-field/demos/basic/client.ts similarity index 52% rename from docs/data/material/components/number-field/demos/field-demo/client.ts rename to docs/data/material/components/number-field/demos/basic/client.ts index c874a2038b3efd..47671215a56433 100644 --- a/docs/data/material/components/number-field/demos/field-demo/client.ts +++ b/docs/data/material/components/number-field/demos/basic/client.ts @@ -2,6 +2,4 @@ import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; -const ClientProvider = createDemoClient(import.meta.url); - -export default ClientProvider; +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/basic/index.ts b/docs/data/material/components/number-field/demos/basic/index.ts new file mode 100644 index 00000000000000..31e371cac69daa --- /dev/null +++ b/docs/data/material/components/number-field/demos/basic/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import BasicNumberFields from './BasicNumberFields'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, BasicNumberFields, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/color/NumberFieldColors.tsx b/docs/data/material/components/number-field/demos/color/NumberFieldColors.tsx new file mode 100644 index 00000000000000..9fa5dc23d8ca1c --- /dev/null +++ b/docs/data/material/components/number-field/demos/color/NumberFieldColors.tsx @@ -0,0 +1,13 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldColors() { + return ( + + {/* @focus-start */} + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/color/client.ts b/docs/data/material/components/number-field/demos/color/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/color/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/color/index.ts b/docs/data/material/components/number-field/demos/color/index.ts new file mode 100644 index 00000000000000..ce027d35ebe859 --- /dev/null +++ b/docs/data/material/components/number-field/demos/color/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldColors from './NumberFieldColors'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldColors, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/constraints/NumberFieldConstraints.tsx b/docs/data/material/components/number-field/demos/constraints/NumberFieldConstraints.tsx new file mode 100644 index 00000000000000..62ae7313a92068 --- /dev/null +++ b/docs/data/material/components/number-field/demos/constraints/NumberFieldConstraints.tsx @@ -0,0 +1,26 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldConstraints() { + return ( + + {/* @focus-start */} + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/constraints/client.ts b/docs/data/material/components/number-field/demos/constraints/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/constraints/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/constraints/index.ts b/docs/data/material/components/number-field/demos/constraints/index.ts new file mode 100644 index 00000000000000..d8e2c88f8ff32f --- /dev/null +++ b/docs/data/material/components/number-field/demos/constraints/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldConstraints from './NumberFieldConstraints'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldConstraints, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/controls-position/NumberFieldControlPositions.tsx b/docs/data/material/components/number-field/demos/controls-position/NumberFieldControlPositions.tsx new file mode 100644 index 00000000000000..2abc7bd3373672 --- /dev/null +++ b/docs/data/material/components/number-field/demos/controls-position/NumberFieldControlPositions.tsx @@ -0,0 +1,51 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldControlPositions() { + return ( + + {/* @focus-start */} + {(['outlined', 'filled', 'standard'] as const).map((variant) => ( + + + + + + + ))} + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/controls-position/client.ts b/docs/data/material/components/number-field/demos/controls-position/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/controls-position/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/controls-position/index.ts b/docs/data/material/components/number-field/demos/controls-position/index.ts new file mode 100644 index 00000000000000..f5048fac6eb349 --- /dev/null +++ b/docs/data/material/components/number-field/demos/controls-position/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldControlPositions from './NumberFieldControlPositions'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldControlPositions, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/field-demo/FieldDemo.tsx b/docs/data/material/components/number-field/demos/field-demo/FieldDemo.tsx deleted file mode 100644 index 62dc22caa81308..00000000000000 --- a/docs/data/material/components/number-field/demos/field-demo/FieldDemo.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import * as React from 'react'; -import Box from '@mui/material/Box'; -import NumberField from './NumberField'; - -export default function FieldDemo() { - return ( - - {/* @focus-start */} - - - - {/* @focus-end */} - - ); -} diff --git a/docs/data/material/components/number-field/demos/field-demo/NumberField.tsx b/docs/data/material/components/number-field/demos/field-demo/NumberField.tsx deleted file mode 100644 index 9cbc887160a992..00000000000000 --- a/docs/data/material/components/number-field/demos/field-demo/NumberField.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import * as React from 'react'; -import { NumberField as BaseNumberField } from '@base-ui/react/number-field'; -import IconButton from '@mui/material/IconButton'; -import FormControl from '@mui/material/FormControl'; -import FormHelperText from '@mui/material/FormHelperText'; -import OutlinedInput from '@mui/material/OutlinedInput'; -import InputAdornment from '@mui/material/InputAdornment'; -import InputLabel from '@mui/material/InputLabel'; -import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp'; -import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'; - -/** - * This component is a placeholder for FormControl to correctly set the shrink label state on SSR. - */ -function SSRInitialFilled(_: BaseNumberField.Root.Props) { - return null; -} -SSRInitialFilled.muiName = 'Input'; - -export default function NumberField({ - id: idProp, - label, - error, - size = 'medium', - ...other -}: BaseNumberField.Root.Props & { - label?: React.ReactNode; - size?: 'small' | 'medium'; - error?: boolean; -}) { - // @focus-start @padding 1 - let id = React.useId(); - if (idProp) { - id = idProp; - } - return ( - ( - - {props.children} - - )} - > - - {label} - ( - - } - > - - - - } - > - - - - } - sx={{ pr: 0 }} - /> - )} - /> - - Enter value between 10 and 40 - - - ); - // @focus-end -} diff --git a/docs/data/material/components/number-field/demos/field-demo/index.ts b/docs/data/material/components/number-field/demos/field-demo/index.ts deleted file mode 100644 index a1924670cb03cb..00000000000000 --- a/docs/data/material/components/number-field/demos/field-demo/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; - -import FieldDemo from './FieldDemo'; -import ClientProvider from './client'; - -export default createDemo(import.meta.url, FieldDemo, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/form-props/FormPropsNumberFields.tsx b/docs/data/material/components/number-field/demos/form-props/FormPropsNumberFields.tsx new file mode 100644 index 00000000000000..4b8355d98061c8 --- /dev/null +++ b/docs/data/material/components/number-field/demos/form-props/FormPropsNumberFields.tsx @@ -0,0 +1,19 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function FormPropsNumberFields() { + return ( + + {/* @focus-start */} + + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/form-props/client.ts b/docs/data/material/components/number-field/demos/form-props/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/form-props/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/form-props/index.ts b/docs/data/material/components/number-field/demos/form-props/index.ts new file mode 100644 index 00000000000000..1b5fc6c56de5ab --- /dev/null +++ b/docs/data/material/components/number-field/demos/form-props/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import FormPropsNumberFields from './FormPropsNumberFields'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, FormPropsNumberFields, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/form/NumberFieldForm.tsx b/docs/data/material/components/number-field/demos/form/NumberFieldForm.tsx new file mode 100644 index 00000000000000..6247fecbb30fb3 --- /dev/null +++ b/docs/data/material/components/number-field/demos/form/NumberFieldForm.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import Button from '@mui/material/Button'; +import NumberField from '@mui/material/NumberField'; +import Stack from '@mui/material/Stack'; +import Typography from '@mui/material/Typography'; + +export default function NumberFieldForm() { + // @focus-start @padding 1 + const [value, setValue] = React.useState(5); + const [submitted, setSubmitted] = React.useState(null); + + return ( + { + event.preventDefault(); + setSubmitted(String(new FormData(event.currentTarget).get('price'))); + }} + onReset={() => { + setValue(5); + setSubmitted(null); + }} + sx={{ width: 320, maxWidth: '100%' }} + > + + + + + + {submitted !== null && Submitted price: {submitted}} + + ); + // @focus-end +} diff --git a/docs/data/material/components/number-field/demos/form/client.ts b/docs/data/material/components/number-field/demos/form/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/form/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/form/index.ts b/docs/data/material/components/number-field/demos/form/index.ts new file mode 100644 index 00000000000000..c9c38cd270b64f --- /dev/null +++ b/docs/data/material/components/number-field/demos/form/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldForm from './NumberFieldForm'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldForm, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/format/FormattedNumberFields.tsx b/docs/data/material/components/number-field/demos/format/FormattedNumberFields.tsx new file mode 100644 index 00000000000000..9fba28f186091d --- /dev/null +++ b/docs/data/material/components/number-field/demos/format/FormattedNumberFields.tsx @@ -0,0 +1,32 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function FormattedNumberFields() { + return ( + + {/* @focus-start */} + + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/format/client.ts b/docs/data/material/components/number-field/demos/format/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/format/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/format/index.ts b/docs/data/material/components/number-field/demos/format/index.ts new file mode 100644 index 00000000000000..f975d2061486a6 --- /dev/null +++ b/docs/data/material/components/number-field/demos/format/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import FormattedNumberFields from './FormattedNumberFields'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, FormattedNumberFields, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/full-width/FullWidthNumberField.tsx b/docs/data/material/components/number-field/demos/full-width/FullWidthNumberField.tsx new file mode 100644 index 00000000000000..713b44248e3846 --- /dev/null +++ b/docs/data/material/components/number-field/demos/full-width/FullWidthNumberField.tsx @@ -0,0 +1,11 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function FullWidthNumberField() { + return ( + + {/* @focus */} + + + ); +} diff --git a/docs/data/material/components/number-field/demos/full-width/client.ts b/docs/data/material/components/number-field/demos/full-width/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/full-width/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/full-width/index.ts b/docs/data/material/components/number-field/demos/full-width/index.ts new file mode 100644 index 00000000000000..61c26effd2d398 --- /dev/null +++ b/docs/data/material/components/number-field/demos/full-width/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import FullWidthNumberField from './FullWidthNumberField'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, FullWidthNumberField, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/margin/NumberFieldMargin.tsx b/docs/data/material/components/number-field/demos/margin/NumberFieldMargin.tsx new file mode 100644 index 00000000000000..ddf2265ac501f3 --- /dev/null +++ b/docs/data/material/components/number-field/demos/margin/NumberFieldMargin.tsx @@ -0,0 +1,38 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +function RedBar() { + return ( + ({ + height: 20, + backgroundColor: 'rgba(255, 0, 0, 0.1)', + ...theme.applyStyles('dark', { + backgroundColor: 'rgb(255 132 132 / 25%)', + }), + })} + /> + ); +} + +export default function NumberFieldMargin() { + return ( + + {/* @focus-start */} + + + + + + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/margin/client.ts b/docs/data/material/components/number-field/demos/margin/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/margin/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/margin/index.ts b/docs/data/material/components/number-field/demos/margin/index.ts new file mode 100644 index 00000000000000..6198374fe3920e --- /dev/null +++ b/docs/data/material/components/number-field/demos/margin/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldMargin from './NumberFieldMargin'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldMargin, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/render/NumberFieldRender.tsx b/docs/data/material/components/number-field/demos/render/NumberFieldRender.tsx new file mode 100644 index 00000000000000..26fe2817cbabaf --- /dev/null +++ b/docs/data/material/components/number-field/demos/render/NumberFieldRender.tsx @@ -0,0 +1,25 @@ +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldRender() { + return ( + // @focus-start @padding 2 + } + slotProps={{ + formHelperText: { + render: (props, state) => ( +

+ {props.children} {state.value ?? 0} +

+ ), + }, + }} + /> + // @focus-end + ); +} diff --git a/docs/data/material/components/number-field/demos/render/client.ts b/docs/data/material/components/number-field/demos/render/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/render/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/render/index.ts b/docs/data/material/components/number-field/demos/render/index.ts new file mode 100644 index 00000000000000..7f33f9baca2d02 --- /dev/null +++ b/docs/data/material/components/number-field/demos/render/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldRender from './NumberFieldRender'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldRender, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/scrub-area-customization/CustomizedNumberFieldScrubArea.tsx b/docs/data/material/components/number-field/demos/scrub-area-customization/CustomizedNumberFieldScrubArea.tsx new file mode 100644 index 00000000000000..ca24495af3a6f1 --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-customization/CustomizedNumberFieldScrubArea.tsx @@ -0,0 +1,30 @@ +import DragIndicatorIcon from '@mui/icons-material/DragIndicator'; +import SwapHorizIcon from '@mui/icons-material/SwapHoriz'; +import NumberField from '@mui/material/NumberField'; + +export default function CustomizedNumberFieldScrubArea() { + return ( + // @focus-start @padding 2 + ({ + children: , + sx: { + color: 'primary.main', + bgcolor: scrubbing ? 'action.selected' : 'transparent', + }, + }), + scrubAreaCursor: { + children: , + sx: { + color: 'primary.main', + }, + }, + }} + /> + // @focus-end + ); +} diff --git a/docs/data/material/components/number-field/demos/scrub-area-customization/client.ts b/docs/data/material/components/number-field/demos/scrub-area-customization/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-customization/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/scrub-area-customization/index.ts b/docs/data/material/components/number-field/demos/scrub-area-customization/index.ts new file mode 100644 index 00000000000000..5555cb8ca287ee --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-customization/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import CustomizedNumberFieldScrubArea from './CustomizedNumberFieldScrubArea'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, CustomizedNumberFieldScrubArea, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/scrub-area-options/NumberFieldScrubAreaOptions.tsx b/docs/data/material/components/number-field/demos/scrub-area-options/NumberFieldScrubAreaOptions.tsx new file mode 100644 index 00000000000000..3f50c2eb2e3908 --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-options/NumberFieldScrubAreaOptions.tsx @@ -0,0 +1,25 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldScrubAreaOptions() { + return ( + + {/* @focus-start */} + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/scrub-area-options/client.ts b/docs/data/material/components/number-field/demos/scrub-area-options/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-options/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/scrub-area-options/index.ts b/docs/data/material/components/number-field/demos/scrub-area-options/index.ts new file mode 100644 index 00000000000000..c420a83a6b88eb --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-options/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldScrubAreaOptions from './NumberFieldScrubAreaOptions'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldScrubAreaOptions, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/scrub-area-placement/NumberFieldScrubAreaPlacement.tsx b/docs/data/material/components/number-field/demos/scrub-area-placement/NumberFieldScrubAreaPlacement.tsx new file mode 100644 index 00000000000000..2553c2fec39c3f --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-placement/NumberFieldScrubAreaPlacement.tsx @@ -0,0 +1,25 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldScrubAreaPlacement() { + return ( + .MuiNumberField-root': { width: '25ch' }, + }} + > + {/* @focus-start */} + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/scrub-area-placement/client.ts b/docs/data/material/components/number-field/demos/scrub-area-placement/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-placement/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/scrub-area-placement/index.ts b/docs/data/material/components/number-field/demos/scrub-area-placement/index.ts new file mode 100644 index 00000000000000..bc381f7f2b3b95 --- /dev/null +++ b/docs/data/material/components/number-field/demos/scrub-area-placement/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldScrubAreaPlacement from './NumberFieldScrubAreaPlacement'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldScrubAreaPlacement, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/sizes/NumberFieldSizes.tsx b/docs/data/material/components/number-field/demos/sizes/NumberFieldSizes.tsx new file mode 100644 index 00000000000000..6fdb246c56018e --- /dev/null +++ b/docs/data/material/components/number-field/demos/sizes/NumberFieldSizes.tsx @@ -0,0 +1,31 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldSizes() { + return ( + + {/* @focus-start */} + {(['outlined', 'filled', 'standard'] as const).map((variant) => ( + .MuiNumberField-root': { width: '25ch' }, + }} + > + + + + ))} + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/sizes/client.ts b/docs/data/material/components/number-field/demos/sizes/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/sizes/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/sizes/index.ts b/docs/data/material/components/number-field/demos/sizes/index.ts new file mode 100644 index 00000000000000..76b8632df9deaa --- /dev/null +++ b/docs/data/material/components/number-field/demos/sizes/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldSizes from './NumberFieldSizes'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldSizes, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/spinner-demo/NumberSpinner.tsx b/docs/data/material/components/number-field/demos/spinner-demo/NumberSpinner.tsx deleted file mode 100644 index 5b0adc303809f3..00000000000000 --- a/docs/data/material/components/number-field/demos/spinner-demo/NumberSpinner.tsx +++ /dev/null @@ -1,153 +0,0 @@ -import * as React from 'react'; -import { NumberField as BaseNumberField } from '@base-ui/react/number-field'; -import Box from '@mui/material/Box'; -import Button from '@mui/material/Button'; -import FormControl from '@mui/material/FormControl'; -import FormLabel from '@mui/material/FormLabel'; -import AddIcon from '@mui/icons-material/Add'; -import RemoveIcon from '@mui/icons-material/Remove'; -import OutlinedInput from '@mui/material/OutlinedInput'; -import OpenInFullIcon from '@mui/icons-material/OpenInFull'; - -export default function NumberSpinner({ - id: idProp, - label, - error, - size = 'medium', - ...other -}: BaseNumberField.Root.Props & { - label?: React.ReactNode; - size?: 'small' | 'medium'; - error?: boolean; -}) { - // @focus-start @padding 1 - let id = React.useId(); - if (idProp) { - id = idProp; - } - return ( - ( - - {props.children} - - )} - > - - } - > - - {label} - - - - - - - - } - > - - - - ( - - )} - /> - - - } - > - - - - - ); - // @focus-end -} diff --git a/docs/data/material/components/number-field/demos/spinner-demo/SpinnerDemo.tsx b/docs/data/material/components/number-field/demos/spinner-demo/SpinnerDemo.tsx deleted file mode 100644 index baca92b9bdae9c..00000000000000 --- a/docs/data/material/components/number-field/demos/spinner-demo/SpinnerDemo.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import * as React from 'react'; -import Box from '@mui/material/Box'; -import NumberSpinner from './NumberSpinner'; - -export default function SpinnerDemo() { - return ( - - {/* @focus-start */} - - - - {/* @focus-end */} - - ); -} diff --git a/docs/data/material/components/number-field/demos/spinner-demo/index.ts b/docs/data/material/components/number-field/demos/spinner-demo/index.ts deleted file mode 100644 index 40955eb00d546d..00000000000000 --- a/docs/data/material/components/number-field/demos/spinner-demo/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; - -import SpinnerDemo from './SpinnerDemo'; -import ClientProvider from './client'; - -export default createDemo(import.meta.url, SpinnerDemo, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/state/NumberFieldState.tsx b/docs/data/material/components/number-field/demos/state/NumberFieldState.tsx new file mode 100644 index 00000000000000..418683e5933e6a --- /dev/null +++ b/docs/data/material/components/number-field/demos/state/NumberFieldState.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; +import Typography from '@mui/material/Typography'; + +export default function NumberFieldState() { + const [value, setValue] = React.useState(0); + const [committed, setCommitted] = React.useState(0); + + return ( +
+ + {/* @focus-start */} + + + {/* @focus-end */} + + + Value: {String(value)} · Last committed: {String(committed)} + +
+ ); +} diff --git a/docs/data/material/components/number-field/demos/state/client.ts b/docs/data/material/components/number-field/demos/state/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/state/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/state/index.ts b/docs/data/material/components/number-field/demos/state/index.ts new file mode 100644 index 00000000000000..2802eb21f5e2eb --- /dev/null +++ b/docs/data/material/components/number-field/demos/state/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldState from './NumberFieldState'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldState, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/steps/NumberFieldSteps.tsx b/docs/data/material/components/number-field/demos/steps/NumberFieldSteps.tsx new file mode 100644 index 00000000000000..5e5e54ae32d61c --- /dev/null +++ b/docs/data/material/components/number-field/demos/steps/NumberFieldSteps.tsx @@ -0,0 +1,32 @@ +import Box from '@mui/material/Box'; +import NumberField from '@mui/material/NumberField'; + +export default function NumberFieldSteps() { + return ( + + {/* @focus-start */} + + + + {/* @focus-end */} + + ); +} diff --git a/docs/data/material/components/number-field/demos/steps/client.ts b/docs/data/material/components/number-field/demos/steps/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/steps/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/steps/index.ts b/docs/data/material/components/number-field/demos/steps/index.ts new file mode 100644 index 00000000000000..a195243af57d4e --- /dev/null +++ b/docs/data/material/components/number-field/demos/steps/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldSteps from './NumberFieldSteps'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldSteps, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/theme/NumberFieldTheme.tsx b/docs/data/material/components/number-field/demos/theme/NumberFieldTheme.tsx new file mode 100644 index 00000000000000..8a118bc62f176d --- /dev/null +++ b/docs/data/material/components/number-field/demos/theme/NumberFieldTheme.tsx @@ -0,0 +1,49 @@ +import NumberField, { numberFieldClasses } from '@mui/material/NumberField'; +import { ThemeProvider, useTheme } from '@mui/material/styles'; +import type { Theme } from '@mui/material/styles'; + +// @focus-start +const customTheme = (outerTheme: Theme): Theme => ({ + ...outerTheme, + components: { + ...outerTheme.components, + MuiNumberField: { + defaultProps: { + size: 'small', + controlsPosition: 'stacked', + scrubAreaPosition: 'start', + }, + styleOverrides: { + root: { + [`&.${numberFieldClasses.scrubbing}`]: { + outline: `2px solid ${(outerTheme.vars ?? outerTheme).palette.primary.main}`, + outlineOffset: 4, + borderRadius: (outerTheme.vars ?? outerTheme).shape.borderRadius, + }, + }, + incrementButton: { + color: (outerTheme.vars ?? outerTheme).palette.success.main, + }, + decrementButton: { + color: (outerTheme.vars ?? outerTheme).palette.warning.main, + }, + }, + }, + }, +}); +// @focus-end + +export default function NumberFieldTheme() { + const outerTheme = useTheme(); + return ( + + + + ); +} diff --git a/docs/data/material/components/number-field/demos/theme/client.ts b/docs/data/material/components/number-field/demos/theme/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/theme/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/theme/index.ts b/docs/data/material/components/number-field/demos/theme/index.ts new file mode 100644 index 00000000000000..e9e892a711dc5d --- /dev/null +++ b/docs/data/material/components/number-field/demos/theme/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import NumberFieldTheme from './NumberFieldTheme'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, NumberFieldTheme, { ClientProvider }); diff --git a/docs/data/material/components/number-field/demos/validation/ValidationNumberField.tsx b/docs/data/material/components/number-field/demos/validation/ValidationNumberField.tsx new file mode 100644 index 00000000000000..f6c6b197aa5f1a --- /dev/null +++ b/docs/data/material/components/number-field/demos/validation/ValidationNumberField.tsx @@ -0,0 +1,21 @@ +import * as React from 'react'; +import NumberField from '@mui/material/NumberField'; + +export default function ValidationNumberField() { + // @focus-start @padding 1 + const [value, setValue] = React.useState(5); + const error = value === null || value < 10; + + return ( + + ); + // @focus-end +} diff --git a/docs/data/material/components/number-field/demos/validation/client.ts b/docs/data/material/components/number-field/demos/validation/client.ts new file mode 100644 index 00000000000000..47671215a56433 --- /dev/null +++ b/docs/data/material/components/number-field/demos/validation/client.ts @@ -0,0 +1,5 @@ +'use client'; + +import { createDemoClient } from '@mui/internal-core-docs/utils/createDemoClient'; + +export default createDemoClient(import.meta.url); diff --git a/docs/data/material/components/number-field/demos/validation/index.ts b/docs/data/material/components/number-field/demos/validation/index.ts new file mode 100644 index 00000000000000..4e7da946f9725e --- /dev/null +++ b/docs/data/material/components/number-field/demos/validation/index.ts @@ -0,0 +1,5 @@ +import { createDemo } from '@mui/internal-core-docs/utils/createDemo'; +import ValidationNumberField from './ValidationNumberField'; +import ClientProvider from './client'; + +export default createDemo(import.meta.url, ValidationNumberField, { ClientProvider }); diff --git a/docs/data/material/components/number-field/number-field.md b/docs/data/material/components/number-field/number-field.md index 1aa586d72421ca..71cba20220542a 100644 --- a/docs/data/material/components/number-field/number-field.md +++ b/docs/data/material/components/number-field/number-field.md @@ -1,73 +1,291 @@ --- productId: material-ui -title: Number field React component -components: Button, IconButton, InputLabel, FormControl, FormLabel, FormHelperText, OutlinedInput +title: React Number Field component +components: NumberField, FormControl, Input, FilledInput, OutlinedInput, InputLabel, FormHelperText, InputAdornment, IconButton +githubLabel: 'scope: number field' +githubSource: packages/mui-material/src/NumberField --- # Number Field -

A React component for capturing numeric input from users.

+

Number Fields let users enter, format, and adjust numeric values.

+ +Use a number field for quantities, prices, and percentages. Users can type a value or adjust it with the stepper buttons or arrow keys. {{"component": "@mui/internal-core-docs/ComponentLinkHeader"}} -A number field is an input with increment and decrement buttons for capturing numeric input from users. +## Basic NumberField -Material UI does not include a number field component out of the box, but this page provides components composed with the [Base UI `NumberField`](https://base-ui.com/react/components/number-field) and styled to align with Material Design (MD2) specifications, so they can be used with Material UI. +Use the `label` prop to describe the value the user should enter. +The default variant is `outlined`. Use `variant="filled"` or `variant="standard"` to change the appearance. -As such, you must install Base UI before proceeding. -The examples that follow can then be copied and pasted directly into your app. -Note that Base UI is tree-shakeable, so the final bundle will only include the components used in your project. +{{"component": "file://./demos/basic/index.ts"}} -## Installation +## Form props - +Set `required` to prevent submitting an empty field. +Use `readOnly` to prevent edits while allowing users to focus the field and copy its value. A `disabled` field is skipped during keyboard navigation and form submission. +Add `helperText` to explain what to enter. -```bash npm -npm install @base-ui/react -``` +{{"component": "file://./demos/form-props/index.ts"}} -```bash pnpm -pnpm add @base-ui/react -``` +## Controlled and uncontrolled values + +Use `defaultValue` to set an initial value and let the field manage subsequent edits. Omit it to start empty. +To control the field, pass `value` and update it in `onValueChange`. Use a number for the value, or `null` for an empty field. + +Use `onValueCommitted` when you need to respond after an adjustment finishes. +For example, type a number in the controlled field below, then leave the field to see the committed value update. +Arrow keys and mouse wheel steps commit immediately. Clicking a stepper button or dragging the scrub handle commits on release. +Both callbacks receive the reason for the change in their second argument (`details.reason`). Call `details.cancel()` in `onValueChange` to reject a change. + +{{"component": "file://./demos/state/index.ts"}} + +## Validation + +Use `error` to display an error state and `helperText` to explain how to correct the value. +In this example, the user must order at least 10 items. + +{{"component": "file://./demos/validation/index.ts"}} + +## Minimum and maximum values + +Use `min` and `max` to limit the value. The decrement button is disabled at the minimum and the increment button at the maximum. +Try typing 11 in the first field below. With `max={10}`, `onValueChange` reports 10 and the field displays 10 when you leave it. + +Set `allowOutOfRange` to keep a value typed or pasted outside the range, as in the second field. Stepping still respects the limits. + +{{"component": "file://./demos/constraints/index.ts"}} + +## Stepping + +Use `step` to set the amount added or subtracted by the buttons and the Arrow Up and Arrow Down keys. +The default step is `1`. +Use `smallStep` and `largeStep` to set the step while holding Alt (Option on macOS) and Shift, respectively. +Their defaults are `0.1` and `10`. + +When bounds are set, Home moves to `min` and End moves to `max`. + +Set `snapOnStep` to snap to step intervals starting at `min`, or `0` if `min` is omitted. + +{{"component": "file://./demos/steps/index.ts"}} + +### Mouse wheel -```bash yarn -yarn add @base-ui/react +Set `allowWheelScrub` to adjust the value with the mouse wheel while the input is focused and hovered. +Wheel stepping is disabled by default. + +```jsx + ``` - +## Formatting and localization + +Use `format` to display currencies, percentages, units, or a specific number of decimal places. +It accepts the options supported by `Intl.NumberFormat`. +Use `locale` to control formatting and parsing independently of the browser's locale. + +The value and value callbacks use unformatted numbers or `null`, regardless of the display format. +For example, a value of `0.125` is displayed as `12.5%` with percent formatting. + +{{"component": "file://./demos/format/index.ts"}} + +## Control placement + +By default, the stepper buttons appear side by side at the end of the input. +Use `controlsPosition="split"` to place one button on each side, or `"stacked"` to stack them at the end. Start and end follow the text direction. +Use `controlsPosition={false}` to hide both buttons. + +{{"component": "file://./demos/controls-position/index.ts"}} + +To style each side of a split field separately, use `ownerState.position` (`'start'` or `'end'`) in the `slotProps.controls` callback. + +## Scrubbing + +Set `scrubAreaPosition` to `"start"` or `"end"` to add a handle that users can drag to adjust the value. +You can place the handle on either side regardless of the stepper button layout. + +{{"component": "file://./demos/scrub-area-placement/index.ts"}} + +### Direction and sensitivity + +Dragging adjusts the value horizontally by default. +Set `slotProps.scrubArea.direction` to `"vertical"` for up/down dragging. +Increase `slotProps.scrubArea.pixelSensitivity` to require more pointer movement before the value changes. +Use `slotProps.scrubArea.teleportDistance` to set how far the cursor can move from the handle's center before wrapping back around. + +{{"component": "file://./demos/scrub-area-options/index.ts"}} + +### Custom handle and cursor + +Use `slotProps.scrubArea` to customize the handle and `slotProps.scrubAreaCursor` to customize the cursor displayed during dragging. +Use `children` to change their icons and `sx` to style them. The example uses `ownerState.scrubbing` to highlight the handle during a drag. +The custom cursor appears during mouse drags in browsers that support pointer lock, except Safari. + +{{"component": "file://./demos/scrub-area-customization/index.ts"}} + +## Input adornments -## Usage +Use `startAdornment` or `endAdornment` to place text, an icon, or a button next to the input. +Pass the content directly, as in `startAdornment="$"` and `endAdornment="/hr"` for an hourly rate. +When the same side also has a scrub handle or stepper buttons, the adornment sits closest to the input. +Adornments sit outside the editable value. To format the value itself according to the locale, use the [`format` prop](#formatting-and-localization). -1. Select one of the demos below that fits your visual design needs. -2. Click **Expand code** in the toolbar. -3. Select the file that starts with `./components/`. -4. Copy the code and paste it into your project. +{{"component": "file://./demos/adornments/index.ts"}} -## Outlined field +## Sizes -The outlined field uses the same building-block components as Material UI's outlined `TextField`—`FormControl`, `OutlinedInput`, `InputLabel`, and `FormHelperText`—with end adornments for the increment and decrement buttons. -See [Text Field—Components](/material-ui/react-text-field/#components) for more details. +Use `size="small"` for a smaller input and stepper buttons. -{{"component": "file://./demos/field-demo/index.ts"}} +{{"component": "file://./demos/sizes/index.ts"}} -## Spinner field +## Margin -For the spinner field component, the increment and decrement buttons are placed next to the outlined input. -This is ideal for touch devices and narrow ranges of values. +The `margin` prop adjusts the vertical spacing of the number field. +The default is `none`. Use `dense` or `normal` to add space above and below the field. -{{"component": "file://./demos/spinner-demo/index.ts"}} +{{"component": "file://./demos/margin/index.ts"}} -## Units and currency +## Full width -Both fields above use the input's end adornment for the increment and decrement buttons, so that slot is not available for a unit or currency symbol. -Use the [`format`](https://base-ui.com/react/components/number-field#NumberFieldRoot-format) prop instead—it accepts [`Intl.NumberFormatOptions`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) and is forwarded to the Base UI `NumberField.Root`: +Use `fullWidth` to fill the width of the field's container. + +{{"component": "file://./demos/full-width/index.ts"}} + +## Color + +The `color` prop changes the highlight color when the field is focused. + +{{"component": "file://./demos/color/index.ts"}} + +## Form submission + +Set `name` on `NumberField` to include its value in the form data. +For example, the field below displays `$5.00` and submits `5` under the name `price`. +If the field is outside the form, pass the form's ID to the `form` prop. + +To support a reset button, use a controlled field and restore its initial value in the form's `onReset` handler. +An uncontrolled Number Field keeps its value when the form resets. + +{{"component": "file://./demos/form/index.ts"}} + +## Controlling the input + +Use `slotProps.htmlInput` to pass attributes and event handlers to the HTML `` element. +Use `slotProps.input` to customize the `OutlinedInput`, `FilledInput`, or `Input` component for the selected variant. For example, `slotProps.input.render` changes the element that groups the input and stepper buttons. +In this example, `borderRadius` rounds the outline and `enterKeyHint` changes the return key label on supported mobile keyboards. ```jsx - + ``` -## Base UI API +Set `value`, `defaultValue`, `disabled`, `readOnly`, and `required` on `NumberField` so they apply to the whole field. +Use `inputRef` to focus the input programmatically. A `ref` on `NumberField` points to the root element. + +To handle an arrow key yourself, call `event.preventBaseUIHandler()` in `slotProps.htmlInput.onKeyDown` to skip the default step for that key. + +## Customization + +### Rendering custom elements + +Use `render` to change the field's root element while keeping its styling and form behavior. +The following example passes `render={
}` to the field and uses `slotProps.formHelperText.render` to show the current value in the helper text. + +{{"component": "file://./demos/render/index.ts"}} + +A `render` callback receives the slot's props and the current field state. Spread the props onto the element to keep its event handlers, styles, and accessibility attributes. +If you render a custom component, forward its ref to the DOM element. +If you render a stepper button as another element, set that slot's `nativeButton` prop to `false`. + +Use `slots` to replace a component entirely. A replacement takes precedence over `render` for that slot. +When replacing `slots.root`, forward its props and ref to a `FormControl` so the label shrinks on focus and both the label and helper text reflect the field's error state. +See the [Number Field slots](/material-ui/api/number-field/#slots) for the available components. + +### Theme overrides + +Use `components.MuiNumberField` in the theme to set defaults for all number fields. +The example uses `defaultProps` to set the field size to `small`, stack the buttons, and add a drag handle. It uses `styleOverrides` to color the buttons and outline the field while the user drags. + +{{"component": "file://./demos/theme/index.ts"}} + +In `styleOverrides.root`, use `& .MuiNumberField-htmlInput` to style the native input and `&.MuiNumberField-scrubbing` to style the field during a drag. + +To add a custom size such as `large`, define a [theme variant](/material-ui/customization/theme-components/#variants). +In TypeScript, add the size to both `NumberFieldPropsSizeOverrides` and `FormControlPropsSizeOverrides`. + +### Data attributes + +Use data attributes such as `data-disabled`, `data-readonly`, `data-required`, and `data-scrubbing` to select slots by state. +For example, `.MuiNumberField-root[data-scrubbing]` matches the field while the user drags its handle. +For use in JavaScript, import the attribute names from `@mui/material/NumberField`. + +| Slot | Export | +| :---------------- | :----------------------------------------- | +| `root` | `NumberFieldRootDataAttributes` | +| `input` | `NumberFieldGroupDataAttributes` | +| `htmlInput` | `NumberFieldInputDataAttributes` | +| `incrementButton` | `NumberFieldIncrementDataAttributes` | +| `decrementButton` | `NumberFieldDecrementDataAttributes` | +| `scrubArea` | `NumberFieldScrubAreaDataAttributes` | +| `scrubAreaCursor` | `NumberFieldScrubAreaCursorDataAttributes` | + +## Anatomy + +The Number Field component renders a root `
` that contains an optional label, the input group, and optional helper text. +The input group wraps the text input and the stepper buttons. +This example includes a drag handle before the input (`scrubAreaPosition="start"`). + +```html +
+ +
+
+ +
+ +
+ + +
+
+

+ Enter the number of items. +

+
+ + + +``` + +With split controls, the `controls` slot renders once on each side of the input. + +A visually hidden native input follows the `root` slot as a sibling in the DOM. +To space adjacent fields, use `gap` on their flex or grid container. + +## Accessibility + +Give the field a visible `label`. Number Field links the label and any helper text to the native text input, generating an ID if needed. +For a field without a visible label, provide an accessible name through `slotProps.htmlInput`. + +```jsx + +``` -See the documentation below for a complete reference to all of the props. +Keyboard users can tab to the text input and adjust its value with the [stepping shortcuts](#stepping). +The stepper buttons are available to screen readers and are skipped in the default tab order. -- [`NumberField`](https://base-ui.com/react/components/number-field#api-reference) +This component is built on top of Base UI's [NumberField](https://base-ui.com/react/components/number-field) component. diff --git a/docs/data/material/pagesApi.js b/docs/data/material/pagesApi.js index ee76034af9e54a..4f4a8e152a28c8 100644 --- a/docs/data/material/pagesApi.js +++ b/docs/data/material/pagesApi.js @@ -77,6 +77,7 @@ export default [ { pathname: '/material-ui/api/modal' }, { pathname: '/material-ui/api/native-select' }, { pathname: '/material-ui/api/no-ssr' }, + { pathname: '/material-ui/api/number-field' }, { pathname: '/material-ui/api/outlined-input' }, { pathname: '/material-ui/api/pagination' }, { pathname: '/material-ui/api/pagination-item' }, diff --git a/docs/pages/material-ui/api/button.json b/docs/pages/material-ui/api/button.json index de8248eccd8ab1..d7a3f2da3d3b29 100644 --- a/docs/pages/material-ui/api/button.json +++ b/docs/pages/material-ui/api/button.json @@ -233,5 +233,5 @@ "forwardsRefTo": "HTMLButtonElement", "filename": "/packages/mui-material/src/Button/Button.js", "inheritance": { "component": "ButtonBase", "pathname": "/material-ui/api/button-base/" }, - "demos": "" + "demos": "" } diff --git a/docs/pages/material-ui/api/filled-input.json b/docs/pages/material-ui/api/filled-input.json index f8bf89ec493d0b..4967157ab2f957 100644 --- a/docs/pages/material-ui/api/filled-input.json +++ b/docs/pages/material-ui/api/filled-input.json @@ -140,5 +140,5 @@ "forwardsRefTo": "HTMLDivElement", "filename": "/packages/mui-material/src/FilledInput/FilledInput.js", "inheritance": { "component": "InputBase", "pathname": "/material-ui/api/input-base/" }, - "demos": "" + "demos": "" } diff --git a/docs/pages/material-ui/api/form-label.json b/docs/pages/material-ui/api/form-label.json index 8aea963a8963de..7ebe31da28ef6b 100644 --- a/docs/pages/material-ui/api/form-label.json +++ b/docs/pages/material-ui/api/form-label.json @@ -83,5 +83,5 @@ "forwardsRefTo": "HTMLLabelElement", "filename": "/packages/mui-material/src/FormLabel/FormLabel.js", "inheritance": null, - "demos": "" + "demos": "" } diff --git a/docs/pages/material-ui/api/input-adornment.json b/docs/pages/material-ui/api/input-adornment.json index 76154785a55e45..aecfe7e422621a 100644 --- a/docs/pages/material-ui/api/input-adornment.json +++ b/docs/pages/material-ui/api/input-adornment.json @@ -90,5 +90,5 @@ "forwardsRefTo": "HTMLDivElement", "filename": "/packages/mui-material/src/InputAdornment/InputAdornment.js", "inheritance": null, - "demos": "" + "demos": "" } diff --git a/docs/pages/material-ui/api/input.json b/docs/pages/material-ui/api/input.json index 6d0360df0ae25e..94c5ab6ba16c6a 100644 --- a/docs/pages/material-ui/api/input.json +++ b/docs/pages/material-ui/api/input.json @@ -136,5 +136,5 @@ "forwardsRefTo": "HTMLDivElement", "filename": "/packages/mui-material/src/Input/Input.js", "inheritance": { "component": "InputBase", "pathname": "/material-ui/api/input-base/" }, - "demos": "" + "demos": "" } diff --git a/docs/pages/material-ui/api/number-field.js b/docs/pages/material-ui/api/number-field.js new file mode 100644 index 00000000000000..40fe944310ff55 --- /dev/null +++ b/docs/pages/material-ui/api/number-field.js @@ -0,0 +1,8 @@ +import * as React from 'react'; +import { ApiPage } from '@mui/internal-core-docs/ApiPage'; +import descriptions from 'docs/translations/api-docs/number-field/number-field.json'; +import jsonPageContent from './number-field.json'; + +export default function Page() { + return ; +} diff --git a/docs/pages/material-ui/api/number-field.json b/docs/pages/material-ui/api/number-field.json new file mode 100644 index 00000000000000..01f098ec6d9983 --- /dev/null +++ b/docs/pages/material-ui/api/number-field.json @@ -0,0 +1,210 @@ +{ + "props": { + "allowOutOfRange": { "type": { "name": "bool" }, "default": "false" }, + "allowWheelScrub": { "type": { "name": "bool" }, "default": "false" }, + "autoFocus": { "type": { "name": "bool" }, "default": "false" }, + "classes": { "type": { "name": "object" }, "additionalInfo": { "cssApi": true } }, + "color": { + "type": { + "name": "union", + "description": "'primary'
| 'secondary'
| 'error'
| 'info'
| 'success'
| 'warning'
| string" + }, + "default": "'primary'" + }, + "controlsPosition": { + "type": { + "name": "enum", + "description": "'end'
| 'split'
| 'stacked'
| false" + }, + "default": "'end'" + }, + "defaultValue": { "type": { "name": "number" } }, + "disabled": { "type": { "name": "bool" }, "default": "false" }, + "endAdornment": { "type": { "name": "node" } }, + "error": { "type": { "name": "bool" }, "default": "false" }, + "form": { "type": { "name": "string" } }, + "format": { "type": { "name": "object" } }, + "fullWidth": { "type": { "name": "bool" }, "default": "false" }, + "helperText": { "type": { "name": "node" } }, + "id": { "type": { "name": "string" } }, + "inputRef": { + "type": { "name": "union", "description": "func
| { current?: object }" } + }, + "label": { "type": { "name": "node" } }, + "largeStep": { "type": { "name": "number" }, "default": "10" }, + "locale": { + "type": { + "name": "union", + "description": "Array<object
| string>
| object
| string" + } + }, + "margin": { + "type": { + "name": "enum", + "description": "'dense'
| 'none'
| 'normal'" + }, + "default": "'none'" + }, + "max": { "type": { "name": "number" } }, + "min": { "type": { "name": "number" } }, + "name": { "type": { "name": "string" } }, + "onBlur": { "type": { "name": "func" } }, + "onFocus": { "type": { "name": "func" } }, + "onValueChange": { + "type": { "name": "func" }, + "signature": { + "type": "function(value: number | null, eventDetails: NumberFieldChangeEventDetails) => void", + "describedArgs": ["value", "eventDetails"] + } + }, + "onValueCommitted": { + "type": { "name": "func" }, + "signature": { + "type": "function(value: number | null, eventDetails: NumberFieldCommitEventDetails) => void", + "describedArgs": ["value", "eventDetails"] + } + }, + "placeholder": { "type": { "name": "string" } }, + "readOnly": { "type": { "name": "bool" }, "default": "false" }, + "render": { "type": { "name": "union", "description": "element
| func" } }, + "required": { "type": { "name": "bool" }, "default": "false" }, + "scrubAreaPosition": { + "type": { + "name": "enum", + "description": "'end'
| 'start'
| false" + }, + "default": "false" + }, + "size": { + "type": { + "name": "union", + "description": "'medium'
| 'small'
| string" + }, + "default": "'medium'" + }, + "slotProps": { + "type": { + "name": "shape", + "description": "{ controls?: func
| object, decrementButton?: func
| object, formHelperText?: func
| object, htmlInput?: func
| object, incrementButton?: func
| object, input?: func
| object, inputLabel?: func
| object, root?: func
| object, scrubArea?: func
| object, scrubAreaCursor?: func
| object }" + }, + "default": "{}" + }, + "slots": { + "type": { + "name": "shape", + "description": "{ controls?: elementType, decrementButton?: elementType, formHelperText?: elementType, htmlInput?: elementType, incrementButton?: elementType, input?: elementType, inputLabel?: elementType, root?: elementType, scrubArea?: elementType, scrubAreaCursor?: elementType }" + }, + "default": "{}" + }, + "smallStep": { "type": { "name": "number" }, "default": "0.1" }, + "snapOnStep": { "type": { "name": "bool" }, "default": "false" }, + "startAdornment": { "type": { "name": "node" } }, + "step": { + "type": { "name": "union", "description": "'any'
| number" }, + "default": "1" + }, + "sx": { + "type": { + "name": "union", + "description": "Array<func
| object
| bool>
| func
| object" + }, + "additionalInfo": { "sx": true } + }, + "value": { "type": { "name": "number" } }, + "variant": { + "type": { + "name": "enum", + "description": "'filled'
| 'outlined'
| 'standard'" + }, + "default": "'outlined'" + } + }, + "name": "NumberField", + "imports": [ + "import NumberField from '@mui/material/NumberField';", + "import { NumberField } from '@mui/material';" + ], + "slots": [ + { + "name": "controls", + "description": "The component that renders each group of stepper buttons.", + "default": "InputAdornment", + "class": "MuiNumberField-controls" + }, + { + "name": "decrementButton", + "description": "The component that renders the decrement button.", + "default": "IconButton", + "class": "MuiNumberField-decrementButton" + }, + { + "name": "formHelperText", + "description": "The component that renders the helper text.", + "default": "FormHelperText", + "class": "MuiNumberField-formHelperText" + }, + { + "name": "htmlInput", + "description": "The component that renders the native input element.\nUse `& .MuiNumberField-htmlInput` in `styleOverrides.root` to style it.", + "default": "'input'", + "class": "MuiNumberField-htmlInput" + }, + { + "name": "incrementButton", + "description": "The component that renders the increment button.", + "default": "IconButton", + "class": "MuiNumberField-incrementButton" + }, + { + "name": "input", + "description": "The component that renders the Material input wrapper.", + "default": "OutlinedInput", + "class": "MuiNumberField-input" + }, + { + "name": "inputLabel", + "description": "The component that renders the input's label.", + "default": "InputLabel", + "class": "MuiNumberField-inputLabel" + }, + { + "name": "root", + "description": "The component that renders the root.\nWhile scrubbing, the root has the `MuiNumberField-scrubbing` class.\nUse `&.MuiNumberField-scrubbing` in `styleOverrides.root` to style that state.", + "default": "FormControl", + "class": "MuiNumberField-root" + }, + { + "name": "scrubArea", + "description": "The component that renders the drag handle for adjusting the value.", + "default": "'span'", + "class": "MuiNumberField-scrubArea" + }, + { + "name": "scrubAreaCursor", + "description": "The component that renders the custom cursor while dragging the scrub area.", + "default": "'span'", + "class": "MuiNumberField-scrubAreaCursor" + } + ], + "classes": [ + { + "key": "endAdornment", + "className": "MuiNumberField-endAdornment", + "description": "Styles applied to the wrapper around the end adornment content.", + "isGlobal": false + }, + { + "key": "startAdornment", + "className": "MuiNumberField-startAdornment", + "description": "Styles applied to the wrapper around the start adornment content.", + "isGlobal": false + } + ], + "spread": true, + "themeDefaultProps": true, + "muiName": "MuiNumberField", + "forwardsRefTo": "HTMLDivElement", + "filename": "/packages/mui-material/src/NumberField/NumberField.tsx", + "inheritance": { "component": "FormControl", "pathname": "/material-ui/api/form-control/" }, + "demos": "" +} diff --git a/docs/translations/api-docs/number-field/number-field.json b/docs/translations/api-docs/number-field/number-field.json new file mode 100644 index 00000000000000..031743332bace9 --- /dev/null +++ b/docs/translations/api-docs/number-field/number-field.json @@ -0,0 +1,147 @@ +{ + "componentDescription": "Number fields let users enter, format, and adjust numeric values.", + "propDescriptions": { + "allowOutOfRange": { + "description": "If true, values entered by typing or pasting are not clamped to min and max. Stepping with the buttons, keyboard, mouse wheel, or scrub area still respects the bounds." + }, + "allowWheelScrub": { + "description": "If true, the mouse wheel adjusts the value while the input is focused and hovered." + }, + "autoFocus": { + "description": "If true, the input element is focused during the first mount." + }, + "classes": { "description": "Override or extend the styles applied to the component." }, + "color": { + "description": "The color of the component. It supports both default and custom theme colors, which can be added as shown in the palette customization guide." + }, + "controlsPosition": { + "description": "The arrangement of the control buttons. Use 'end' for horizontal minus/plus buttons at the end, 'split' for a minus button at the start and a plus button at the end, 'stacked' for up/down chevrons at the end, or false for no control buttons." + }, + "defaultValue": { + "description": "The initial numeric value for an uncontrolled field. Omit this prop to start with an empty field. Use value for a controlled field." + }, + "disabled": { "description": "If true, the component is disabled." }, + "endAdornment": { + "description": "Content displayed immediately after the input, such as a unit or a clear button." + }, + "error": { "description": "If true, the field is displayed in an error state." }, + "form": { + "description": "The id of the form that owns the field. Use this prop when the field is rendered outside the form." + }, + "format": { + "description": "The Intl.NumberFormat options used to format the displayed value. The value prop and value callbacks use numbers or null, regardless of the display format." + }, + "fullWidth": { + "description": "If true, the input will take up the full width of its container." + }, + "helperText": { "description": "The helper text content." }, + "id": { + "description": "The id of the visible input, used to associate its label and helper text. If omitted, an ID is generated." + }, + "inputRef": { "description": "A ref to the visible <input> element." }, + "label": { "description": "The label content." }, + "largeStep": { + "description": "The amount to increment or decrement while holding the Shift key." + }, + "locale": { + "description": "The locale or locales used to format and parse the value. Defaults to the runtime's locale.
See Intl.NumberFormat." + }, + "margin": { + "description": "If dense or normal, will adjust vertical spacing of this and contained components." + }, + "max": { + "description": "The upper bound for the numeric value. The increment button is disabled at or above this value." + }, + "min": { + "description": "The lower bound for the numeric value. The decrement button is disabled at or below this value." + }, + "name": { + "description": "Identifies the field when a form is submitted. The submitted value is the unformatted number." + }, + "onBlur": { "description": "Callback fired when the input loses focus." }, + "onFocus": { "description": "Callback fired when the input receives focus." }, + "onValueChange": { + "description": "Callback fired when the numeric value changes. Call eventDetails.cancel() to reject the proposed change.", + "typeDescriptions": { + "value": { + "name": "value", + "description": "The new numeric value, or null when the input is empty." + }, + "eventDetails": { + "name": "eventDetails", + "description": "The native event and the reason for the change. Typing a number reports "input-change", clearing the input reports "input-clear", and stepping with Arrow Up or Arrow Down reports "keyboard". Other reasons are "input-blur", "input-paste", "increment-press", "decrement-press", "wheel", "scrub", and "none"." + } + } + }, + "onValueCommitted": { + "description": "Callback fired when the value is committed. Direct text entry commits on blur. Pointer presses on the stepper buttons and scrub interactions commit on pointer release. Keyboard and mouse wheel steps commit immediately.", + "typeDescriptions": { + "value": { + "name": "value", + "description": "The committed numeric value, or null when the input is empty." + }, + "eventDetails": { + "name": "eventDetails", + "description": "The native event and the reason for the commit. Leaving the field after typing a number reports "input-blur". Stepping with Arrow Up or Arrow Down reports "keyboard". Other reasons are "input-clear", "increment-press", "decrement-press", "wheel", "scrub", and "none"." + } + } + }, + "placeholder": { "description": "The short hint displayed in the input when it is empty." }, + "readOnly": { + "description": "If true, the value cannot be changed through user interaction. The input can still receive focus." + }, + "render": { + "description": "Replaces the root element while preserving its styles and behavior. Pass an element or a (props, state) => element callback. Forward the supplied props and ref to the root element. state.value is the current numeric value or null. state.inputValue is the text displayed in the input." + }, + "required": { + "description": "If true, a value is required for form submission and the label is marked as required." + }, + "scrubAreaPosition": { + "description": "The placement of the drag handle used to adjust the value. Use 'start' or 'end' to show the handle, or false to hide it. Its position is independent of controlsPosition." + }, + "size": { "description": "The size of the component." }, + "slotProps": { "description": "The props used for each slot inside." }, + "slots": { "description": "The components used for each slot inside." }, + "smallStep": { + "description": "The amount to increment or decrement while holding the Alt key (Option on macOS)." + }, + "snapOnStep": { + "description": "If true, stepping snaps the value to intervals starting at min, or 0 if min is omitted. Modifier keys use the corresponding smallStep or largeStep intervals." + }, + "startAdornment": { + "description": "Content displayed immediately before the input, such as a currency symbol." + }, + "step": { + "description": "The amount to increment or decrement with the buttons, arrow keys, mouse wheel, or scrub area. Set min explicitly to enable step validation on form submission. Set to "any" to disable step validation; interactive stepping then uses 1, while the Alt and Shift keys still use smallStep and largeStep." + }, + "sx": { + "description": "The system prop that allows defining system overrides as well as additional CSS styles." + }, + "value": { + "description": "The controlled numeric value. Use null to display an empty field and onValueChange to update the value." + }, + "variant": { "description": "The variant to use." } + }, + "classDescriptions": { + "endAdornment": { + "description": "Styles applied to {{nodeName}}.", + "nodeName": "the wrapper around the end adornment content" + }, + "startAdornment": { + "description": "Styles applied to {{nodeName}}.", + "nodeName": "the wrapper around the start adornment content" + } + }, + "slotDescriptions": { + "controls": "The component that renders each group of stepper buttons.", + "decrementButton": "The component that renders the decrement button.", + "formHelperText": "The component that renders the helper text.", + "htmlInput": "The component that renders the native input element. Use & .MuiNumberField-htmlInput in styleOverrides.root to style it.", + "incrementButton": "The component that renders the increment button.", + "input": "The component that renders the Material input wrapper.", + "inputLabel": "The component that renders the input's label.", + "root": "The component that renders the root. While scrubbing, the root has the MuiNumberField-scrubbing class. Use &.MuiNumberField-scrubbing in styleOverrides.root to style that state.", + "scrubArea": "The component that renders the drag handle for adjusting the value.", + "scrubAreaCursor": "The component that renders the custom cursor while dragging the scrub area." + } +} diff --git a/packages/mui-material/package.json b/packages/mui-material/package.json index 4cfaf99b0e896a..627e5c67e863e2 100644 --- a/packages/mui-material/package.json +++ b/packages/mui-material/package.json @@ -34,6 +34,7 @@ }, "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.5", + "@base-ui/react": "^1.9.0", "@mui/core-downloads-tracker": "workspace:^", "@mui/system": "workspace:*", "@mui/types": "workspace:^", @@ -104,6 +105,7 @@ "./internal": "./src/internal/index.ts", "./locale": "./src/locale/index.ts", "./NoSsr": "./src/NoSsr/index.ts", + "./NumberField": "./src/NumberField/index.ts", "./OverridableComponent": "./src/OverridableComponent/index.ts", "./PigmentContainer": "./src/PigmentContainer/index.ts", "./PigmentGrid": "./src/PigmentGrid/index.ts", diff --git a/packages/mui-material/src/Button/Button.d.ts b/packages/mui-material/src/Button/Button.d.ts index 8588998fb51144..b3cf746c29b3c4 100644 --- a/packages/mui-material/src/Button/Button.d.ts +++ b/packages/mui-material/src/Button/Button.d.ts @@ -133,7 +133,6 @@ export type ExtendButton = ExtendButtonBase< * - [Button Group](https://next.mui.com/material-ui/react-button-group/) * - [Button](https://next.mui.com/material-ui/react-button/) * - [Menubar](https://next.mui.com/material-ui/react-menubar/) - * - [Number Field](https://next.mui.com/material-ui/react-number-field/) * - [Transfer List](https://next.mui.com/material-ui/react-transfer-list/) * * API: diff --git a/packages/mui-material/src/FilledInput/FilledInput.d.ts b/packages/mui-material/src/FilledInput/FilledInput.d.ts index 9de7c1a4cdbccd..fe88fa8679638f 100644 --- a/packages/mui-material/src/FilledInput/FilledInput.d.ts +++ b/packages/mui-material/src/FilledInput/FilledInput.d.ts @@ -35,6 +35,7 @@ export interface FilledInputProps extends StandardProps { * * Demos: * + * - [Number Field](https://next.mui.com/material-ui/react-number-field/) * - [Text Field](https://next.mui.com/material-ui/react-text-field/) * * API: diff --git a/packages/mui-material/src/FormLabel/FormLabel.d.ts b/packages/mui-material/src/FormLabel/FormLabel.d.ts index 65059981e28bfa..cfb103180e8ac4 100644 --- a/packages/mui-material/src/FormLabel/FormLabel.d.ts +++ b/packages/mui-material/src/FormLabel/FormLabel.d.ts @@ -71,7 +71,6 @@ export interface FormLabelTypeMap< * Demos: * * - [Checkbox](https://next.mui.com/material-ui/react-checkbox/) - * - [Number Field](https://next.mui.com/material-ui/react-number-field/) * - [Radio Group](https://next.mui.com/material-ui/react-radio-button/) * - [Switch](https://next.mui.com/material-ui/react-switch/) * diff --git a/packages/mui-material/src/Input/Input.d.ts b/packages/mui-material/src/Input/Input.d.ts index e3a34ba43da2a1..37a13a947aab34 100644 --- a/packages/mui-material/src/Input/Input.d.ts +++ b/packages/mui-material/src/Input/Input.d.ts @@ -28,6 +28,7 @@ export interface InputProps extends StandardProps { * * Demos: * + * - [Number Field](https://next.mui.com/material-ui/react-number-field/) * - [Text Field](https://next.mui.com/material-ui/react-text-field/) * * API: diff --git a/packages/mui-material/src/InputAdornment/InputAdornment.d.ts b/packages/mui-material/src/InputAdornment/InputAdornment.d.ts index 2554238b6075b3..d6b5fddf1ee025 100644 --- a/packages/mui-material/src/InputAdornment/InputAdornment.d.ts +++ b/packages/mui-material/src/InputAdornment/InputAdornment.d.ts @@ -51,6 +51,7 @@ export interface InputAdornmentTypeMap< * * Demos: * + * - [Number Field](https://next.mui.com/material-ui/react-number-field/) * - [Text Field](https://next.mui.com/material-ui/react-text-field/) * * API: diff --git a/packages/mui-material/src/NumberField/NumberField.spec.tsx b/packages/mui-material/src/NumberField/NumberField.spec.tsx new file mode 100644 index 00000000000000..602e1c2b5d176f --- /dev/null +++ b/packages/mui-material/src/NumberField/NumberField.spec.tsx @@ -0,0 +1,493 @@ +import * as React from 'react'; +import { expectType } from '@mui/types'; +import type { NumberField as BaseNumberField } from '@base-ui/react/number-field'; +import type { BaseUIEvent } from '@base-ui/react/types'; +import NumberField from '@mui/material/NumberField'; +import type { + NumberFieldChangeEventDetails, + NumberFieldCommitEventDetails, + NumberFieldProps, + NumberFieldVariants, + NumberFieldOwnerState, + StandardNumberFieldProps, + FilledNumberFieldProps, + OutlinedNumberFieldProps, +} from '@mui/material/NumberField'; + +// Wrappers can name the constraint of the public variant generic. +function VariantWrapper(props: NumberFieldProps) { + return ; +} +; + +; +; +; +// @ts-expect-error Placement is separate from the scrubArea slot. +; + +()} />} />; + { + expectType(state); + expectType(state.value); + expectType(state.scrubbing); + return
; + }} +/>; +// @ts-expect-error render takes an element or a callback, not a tag name. +; +// @ts-expect-error Use render to change the root element. +; +// @ts-expect-error Root slot props do not expose component. +; + +// @ts-expect-error Base UI's Group shares the input root and has no public slot. +; +// @ts-expect-error Customize the Material input through slotProps.input. + } }} />; + + }, htmlInput: { render: } }} +/>; + { + expectType(state); + return
; + }, + }, + htmlInput: { + render: (props, state) => { + expectType(state); + return ; + }, + }, + }} +/>; +// @ts-expect-error Use render to change the Material input root. +; +// @ts-expect-error The native input slot does not expose component. +; +// @ts-expect-error render takes an element or callback, not a tag name. +; +// @ts-expect-error render takes an element or callback, not a tag name. +; + +// @ts-expect-error Set the numeric value on NumberField. +; +// @ts-expect-error Set the initial value on NumberField. + ({ defaultValue: '1', inputMode: 'decimal' }) }} />; +// @ts-expect-error Set the form field name on NumberField. +; +// @ts-expect-error Native input slot callbacks also cannot name the visible input. + ({ name: 'price', inputMode: 'decimal' }) }} />; +// @ts-expect-error NumberField formats numbers in a text input. +; + ({ multiline: true, disableUnderline: true }) }} +/>; +// @ts-expect-error The standard input also disallows textarea sizing. +; +// @ts-expect-error Pass native input props through slotProps.htmlInput. +; +// @ts-expect-error Put input keydown handlers on slotProps.htmlInput. + {} } }} />; +// @ts-expect-error The same applies to keyup handlers returned by a slot callback. + ({ onKeyUp: () => {} }) }} />; + ({ slotProps: { input: { placeholder: 'Quantity' } } }) }} +/>; + +// @ts-expect-error NumberField owns its content; use slot props to customize it. +Unsupported content; + +// The default variant exposes OutlinedInput's slots. +; + +; + +; +; + +// A variant cannot use another variant's input slots. +// @ts-expect-error The standard input has no notchedOutline slot. +; +// @ts-expect-error The filled input has no notchedOutline slot. +; +// @ts-expect-error The outlined input has no underline to disable. +; + +// Explicit generic arguments select the corresponding public interface. +const standardProps: NumberFieldProps<'standard'> = { + variant: 'standard', + slotProps: { input: { disableUnderline: true } }, +}; +expectType(standardProps); +; + +const filledProps: NumberFieldProps<'filled'> = { + variant: 'filled', + slotProps: { input: { hiddenLabel: true } }, +}; +expectType(filledProps); +; + +const outlinedProps: NumberFieldProps<'outlined'> = { + slotProps: { input: { slotProps: { notchedOutline: { className: 'outline' } } } }, +}; +expectType(outlinedProps); +; + +// @ts-expect-error A nondefault variant must be selected explicitly. +const missingStandardVariant: NumberFieldProps<'standard'> = {}; +// @ts-expect-error A nondefault variant must be selected explicitly. +const missingFilledVariant: NumberFieldProps<'filled'> = {}; +// @ts-expect-error The generic argument constrains the variant. +const mismatchedVariant: NumberFieldProps<'outlined'> = { variant: 'filled' }; +// @ts-expect-error Only supported variants are accepted. +const invalidVariant: NumberFieldProps<'custom'> = {}; + +// Slot callbacks receive normalized NumberField owner state and retain variant-specific props. + { + expectType(ownerState); + expectType(ownerState.autoFocus); + expectType(ownerState.disabled); + expectType(ownerState.error); + expectType(ownerState.fullWidth); + expectType(ownerState.required); + expectType(ownerState.scrubbing); + return { slotProps: { notchedOutline: { className: 'outline' } } }; + }, + inputLabel: (ownerState) => ({ shrink: ownerState.required }), + }} +/>; + + ({ hiddenLabel: ownerState.disabled }) }} +/>; + +// The public event detail types match the numeric callbacks for every variant. +function ValueCallbacks(props: NumberFieldProps) { + return ( + { + expectType(value); + expectType(details); + }} + onValueCommitted={(value, details) => { + expectType(value); + expectType(details); + }} + /> + ); +} + +; + +; +// @ts-expect-error Numeric values cannot be strings. +; +// @ts-expect-error Numeric default values cannot be strings. +; +// @ts-expect-error Public changes use Base UI's numeric callbacks, not a DOM onChange. +) => {}} />; +// @ts-expect-error onValueChange receives a number or null, not a DOM event. +) => {}} />; +// @ts-expect-error onValueCommitted receives a number or null, not a DOM event. +) => {}} />; + +// The Material input forwards these callbacks to the single-line input. + { + expectType, typeof event>(event); + }, + onChange: (event) => { + expectType, typeof event>(event); + }, + onFocus: (event) => { + expectType, typeof event>(event); + }, + }, + }} +/>; + + { + expectType, typeof event>(event); + }} + onBlur={(event) => { + expectType, typeof event>(event); + }} +/>; + +// Base UI numeric options retain their public input types through the Material wrapper. +; + +// @ts-expect-error Only numeric steps and the "any" keyword are supported. +; +// @ts-expect-error Bounds are numeric values. +; +// @ts-expect-error The uncontrolled default is a number; null is a controlled empty value. +; +// @ts-expect-error Controls have three supported positions. +; +; +// @ts-expect-error Placing both controls at the start is not supported. +; + +$} endAdornment="USD" />; +// @ts-expect-error Set startAdornment directly on NumberField. +; +// @ts-expect-error Set endAdornment directly on NumberField. + ({ title: 'Amount', endAdornment: 'USD' }) }} />; + +// Root and visible-input refs expose different DOM elements. + { + expectType(node); + }} + inputRef={(node) => { + expectType(node); + }} +/>; + +// @ts-expect-error The root ref does not expose a button. +()} />; +// @ts-expect-error inputRef must target the visible native input. +()} />; + +// Slot props expose the corresponding Material component API. Root/button handlers +// need explicit event annotations with the current Material SlotProps types. +} + slotProps={{ + root: { + ref: React.createRef(), + onClick: (event: React.MouseEvent) => event.currentTarget.focus(), + }, + input: { + ref: React.createRef(), + }, + htmlInput: { + ref: (input) => { + expectType(input); + }, + inputMode: 'decimal', + onKeyDown: (event) => { + expectType>, typeof event>(event); + }, + onKeyUp: (event) => { + expectType>, typeof event>(event); + }, + }, + inputLabel: { shrink: true, htmlFor: 'amount', ref: React.createRef() }, + formHelperText: { render:
}, + incrementButton: { + ref: React.createRef(), + children: '+', + size: 'large', + onClick: (event: React.MouseEvent) => event.currentTarget.focus(), + }, + decrementButton: { + render: + {source === 'Base Field context' ? ( + {field} + ) : ( + field + )} + + ); + } + + const { user } = render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const wrapper = input.closest('.MuiInputBase-root')!; + const label = screen.getByText('Amount', { selector: 'label' }); + const buttons = screen.getAllByRole('button', { + name: /Increase|Decrease/, + }); + const toggle = screen.getByRole('button', { name: 'Toggle disabled' }); + const expectDisabledState = (disabled: boolean) => { + expect(input.disabled).to.equal(disabled); + expect(wrapper.classList.contains('Mui-disabled')).to.equal(disabled); + expect(label.classList.contains('Mui-disabled')).to.equal(disabled); + buttons.forEach((button) => expect(button.disabled).to.equal(disabled)); + }; + + expectDisabledState(false); + await user.click(toggle); + expectDisabledState(true); + await user.click(toggle); + expectDisabledState(false); + }); + }); + + it('updates Material input and button availability when readOnly changes', async () => { + function Test() { + const [readOnly, setReadOnly] = React.useState(false); + return ( + + + + + ); + } + + const { user } = render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const wrapper = input.closest('.MuiInputBase-root')!; + const buttons = screen.getAllByRole('button', { + name: /Increase|Decrease/, + }); + const toggle = screen.getByRole('button', { name: 'Toggle read-only' }); + const expectReadOnlyState = (readOnly: boolean) => { + expect(input.readOnly).to.equal(readOnly); + expect(input.disabled).to.equal(false); + expect(wrapper.classList.contains('Mui-readOnly')).to.equal(readOnly); + buttons.forEach((button) => expect(button.disabled).to.equal(readOnly)); + }; + + expectReadOnlyState(false); + await user.click(toggle); + expectReadOnlyState(true); + await user.click(toggle); + expectReadOnlyState(false); + }); + }); + }); + + // Map Base UI availability and field size to the Material buttons and supply icons. + describe('controls', () => { + // The adapter must apply Base UI's resolved availability to IconButton, + // even when consumer props try to re-enable a control. + describe('availability', () => { + it('keeps Material button availability aligned with the value limits', async () => { + const { user } = render( + , + ); + const increment = screen.getByRole('button', { name: 'Increase' }); + const decrement = screen.getByRole('button', { name: 'Decrease' }); + + expect(increment.disabled).to.equal(true); + expect(increment).to.have.class('Mui-disabled'); + expect(decrement.disabled).to.equal(false); + + await user.click(decrement); + expect(increment.disabled).to.equal(false); + expect(increment).not.to.have.class('Mui-disabled'); + expect(decrement.disabled).to.equal(true); + expect(decrement).to.have.class('Mui-disabled'); + + await user.click(increment); + expect(decrement.disabled).to.equal(false); + expect(decrement).not.to.have.class('Mui-disabled'); + }); + + [ + { name: 'disabled', disabled: true, readOnly: false, inheritedDisabled: false }, + { name: 'read-only', disabled: false, readOnly: true, inheritedDisabled: false }, + { name: 'inherited disabled', disabled: false, readOnly: false, inheritedDisabled: true }, + ].forEach(({ name, disabled, readOnly, inheritedDisabled }) => { + it(`cannot re-enable ${name} controls with disabled=false slot props`, () => { + render( + + + , + ); + screen.getAllByRole('button').forEach((button) => { + expect(button.disabled).to.equal(true); + expect(button).to.have.class('Mui-disabled'); + }); + }); + }); + + [ + { disabledSlot: 'incrementButton', disabledName: 'Increase', activeName: 'Decrease' }, + { disabledSlot: 'decrementButton', disabledName: 'Decrease', activeName: 'Increase' }, + ].forEach(({ disabledSlot, disabledName, activeName }) => { + it(`disables ${disabledSlot} independently without blocking the other control`, () => { + render( + , + ); + + expect( + screen.getByRole('button', { name: disabledName }).disabled, + ).to.equal(true); + expect( + screen.getByRole('button', { name: activeName }).disabled, + ).to.equal(false); + }); + }); + }); + + // Supply the appropriate icons and field size without replacing accessible names. + describe('icons and size', () => { + const iconCases = [ + { controlsPosition: 'end', incrementIcon: 'AddIcon', decrementIcon: 'RemoveIcon' }, + { + controlsPosition: 'stacked', + incrementIcon: 'KeyboardArrowUpIcon', + decrementIcon: 'KeyboardArrowDownIcon', + }, + ] as const; + + iconCases.forEach(({ controlsPosition, incrementIcon, decrementIcon }) => { + it(`renders the default ${controlsPosition} icons and forwards the field size to both controls`, () => { + render(); + const increment = screen.getByRole('button', { name: 'Increase' }); + const decrement = screen.getByRole('button', { name: 'Decrease' }); + const incrementIconElement = screen.getByTestId(incrementIcon); + const decrementIconElement = screen.getByTestId(decrementIcon); + + expect(increment).to.contain(incrementIconElement); + expect(decrement).to.contain(decrementIconElement); + for (const button of [increment, decrement]) { + expect(button).to.have.class('MuiIconButton-sizeSmall'); + } + for (const icon of [incrementIconElement, decrementIconElement]) { + expect(icon).to.have.class('MuiSvgIcon-fontSizeInherit'); + } + }); + }); + + it.skipIf(isJsdom())('applies a size override only to the specified button', () => { + render(); + + const increment = screen.getByRole('button', { name: 'Increase' }); + const decrement = screen.getByRole('button', { name: 'Decrease' }); + + expect(getComputedStyle(increment).paddingInlineStart).to.equal('12px'); + expect(getComputedStyle(decrement).paddingInlineStart).to.equal('6px'); + }); + + it('replaces the default icons while preserving the button names', () => { + render( + Plus }, + decrementButton: { children: Minus }, + }} + />, + ); + const increment = screen.getByRole('button', { name: 'Increase' }); + const decrement = screen.getByRole('button', { name: 'Decrease' }); + + expect(increment).to.contain(screen.getByText('Plus')); + expect(decrement).to.contain(screen.getByText('Minus')); + expect(screen.queryByTestId('KeyboardArrowUpIcon')).to.equal(null); + expect(screen.queryByTestId('KeyboardArrowDownIcon')).to.equal(null); + }); + }); + }); + + // Consumer button props must survive both useSlot and the Base UI render adapter. + // Exercise each control's wiring without repeating the shared input variants. + describe('button slot props', () => { + const NativeButton = React.forwardRef< + HTMLButtonElement, + React.ComponentPropsWithoutRef<'button'> + >(function NativeButton(props, ref) { + return } + endAdornment={} + />, + ); + + const wrapper = screen.getByRole('group'); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const scrub = wrapper.querySelector(`.${classes.scrubArea}`); + const getButton = (name: string) => screen.getByRole('button', { name }); + const start = startButtons.map(getButton); + const end = endButtons.map(getButton); + + expect( + Array.from(wrapper.querySelectorAll(`button, input, .${classes.scrubArea}`)), + ).to.deep.equal([ + ...start, + ...(scrubAreaPosition === 'start' ? [scrub] : []), + getButton('Start action'), + input, + getButton('End action'), + ...(scrubAreaPosition === 'end' ? [scrub] : []), + ...end, + ]); + + const groups = wrapper.querySelectorAll(`.${classes.controls}`); + const expectedGroups = [ + { positionClass: 'MuiInputAdornment-positionStart', buttons: start }, + { positionClass: 'MuiInputAdornment-positionEnd', buttons: end }, + ].filter(({ buttons }) => buttons.length > 0); + expect(groups).to.have.length(expectedGroups.length); + expectedGroups.forEach(({ positionClass, buttons }, index) => { + expect(groups[index]).to.have.class(positionClass); + expect(Array.from(groups[index].querySelectorAll('button'))).to.deep.equal(buttons); + }); + + if (scrubAreaPosition) { + expect(scrub!.parentElement).to.have.class( + scrubAreaPosition === 'start' + ? 'MuiInputAdornment-positionStart' + : 'MuiInputAdornment-positionEnd', + ); + expect(scrub!.closest(`.${classes.controls}`)).to.equal(null); + } + }, + ); + }); + + it('preserves the input and its adornments when controls move or are removed', async () => { + function Test({ controlsPosition }: Pick) { + return ( + } + endAdornment={} + /> + ); + } + + const { user, rerender } = render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const prefix = screen.getByRole('textbox', { name: 'Prefix' }); + const suffix = screen.getByRole('textbox', { name: 'Suffix' }); + + await user.clear(input); + await user.keyboard('8'); + await user.type(prefix, '$'); + await user.type(suffix, 'kg'); + + const moveAndCheckControls = async ( + position: NonNullable, + focusedInput: HTMLElement, + ) => { + await user.click(focusedInput); + rerender(); + + expect(focusedInput).toHaveFocus(); + expect(screen.getByRole('textbox', { name: 'Amount' })).to.equal(input); + expect(input).to.have.value('8'); + expect(screen.getByRole('textbox', { name: 'Prefix' })).to.have.value('$'); + expect(screen.getByRole('textbox', { name: 'Suffix' })).to.have.value('kg'); + if (position === false) { + expect(screen.queryByRole('button', { name: 'Increase' })).to.equal(null); + expect(screen.queryByRole('button', { name: 'Decrease' })).to.equal(null); + return; + } + + const increment = screen.getByRole('button', { name: 'Increase' }); + const decrement = screen.getByRole('button', { name: 'Decrease' }); + + expect(increment.closest(`.${classes.controls}`)).to.have.class( + 'MuiInputAdornment-positionEnd', + ); + expect(decrement.closest(`.${classes.controls}`)).to.have.class( + position === 'split' + ? 'MuiInputAdornment-positionStart' + : 'MuiInputAdornment-positionEnd', + ); + expect(increment).to.contain( + screen.getByTestId(position === 'stacked' ? 'KeyboardArrowUpIcon' : 'AddIcon'), + ); + expect(decrement).to.contain( + screen.getByTestId(position === 'stacked' ? 'KeyboardArrowDownIcon' : 'RemoveIcon'), + ); + + await user.click(increment); + expect(input).to.have.value('9'); + await user.click(decrement); + expect(input).to.have.value('8'); + }; + + await moveAndCheckControls('stacked', suffix); + await moveAndCheckControls('split', prefix); + await moveAndCheckControls('end', input); + await moveAndCheckControls(false, suffix); + }); + }); + + // Compare icon edges with an unadorned input's text inset. The cases cover each + // variant/size and outer controls, scrub-only sides, and controls sharing a side. + describe.skipIf(isJsdom())('side padding', () => { + const cases = [ + { + variant: 'outlined', + size: 'medium', + controlsPosition: 'split', + scrubAreaPosition: 'start', + }, + { variant: 'outlined', size: 'small', controlsPosition: 'end', scrubAreaPosition: 'start' }, + { + variant: 'filled', + size: 'medium', + controlsPosition: 'stacked', + scrubAreaPosition: 'start', + }, + { variant: 'filled', size: 'small', controlsPosition: false, scrubAreaPosition: 'end' }, + { variant: 'standard', size: 'medium', controlsPosition: 'split', scrubAreaPosition: 'end' }, + { variant: 'standard', size: 'small', controlsPosition: false, scrubAreaPosition: 'start' }, + ] satisfies Pick< + NumberFieldProps, + 'variant' | 'size' | 'controlsPosition' | 'scrubAreaPosition' + >[]; + + cases.forEach(({ variant, size, controlsPosition, scrubAreaPosition }) => { + it(`aligns ${size} ${variant}, controls=${controlsPosition}, scrub=${scrubAreaPosition}`, () => { + render( + + + + , + ); + const plainInput = screen.getByRole('textbox', { name: 'Plain' }); + const plainRoot = plainInput.closest('.MuiInputBase-root')!.getBoundingClientRect(); + const plainRect = plainInput.getBoundingClientRect(); + const plainStyle = getComputedStyle(plainInput); + const startInset = plainRect.left - plainRoot.left + parseFloat(plainStyle.paddingLeft); + const endInset = plainRoot.right - plainRect.right + parseFloat(plainStyle.paddingRight); + const adornedRoot = screen + .getByRole('textbox', { name: 'Adorned' }) + .closest('.MuiInputBase-root')!; + const adornedRect = adornedRoot.getBoundingClientRect(); + let startSlot = scrubAreaPosition === 'start' ? classes.scrubArea : null; + let endSlot = scrubAreaPosition === 'end' ? classes.scrubArea : null; + if (controlsPosition === 'split') { + startSlot = classes.decrementButton; + } + if (controlsPosition !== false) { + endSlot = classes.incrementButton; + } + + if (startSlot) { + const icon = adornedRoot.querySelector(`.${startSlot} svg`)!.getBoundingClientRect(); + expect(icon.left - adornedRect.left).to.be.closeTo(startInset, 0.5); + } + if (endSlot) { + const icon = adornedRoot.querySelector(`.${endSlot} svg`)!.getBoundingClientRect(); + expect(adornedRect.right - icon.right).to.be.closeTo(endInset, 0.5); + } + }); + }); + }); + + describe('controls slot', () => { + it('resolves refs independently for split controls', () => { + const refs = { + start: React.createRef(), + end: React.createRef(), + }; + render( + ({ ref: refs[position] }) }} + />, + ); + + expect(refs.start.current).not.to.equal(refs.end.current); + expect(refs.start.current).to.contain(screen.getByRole('button', { name: 'Decrease' })); + expect(refs.end.current).to.contain(screen.getByRole('button', { name: 'Increase' })); + }); + + it('preserves styles, ref and live render state for slotProps.controls', async () => { + const ref = React.createRef(); + const renderAdornment: BaseNumberField.Group.Props['render'] = (props, state) => ( +
+ ); + const theme = createTheme({ + components: { MuiNumberField: { styleOverrides: { controls: { paddingBottom: 9 } } } }, + }); + const { user } = render( + + ({ + title: `${position} adornment`, + ref, + sx: { paddingTop: '7px' }, + render: renderAdornment, + }), + }} + /> + , + ); + const adornment = screen.getByTitle('end adornment'); + + expect(adornment.tagName).to.equal('SECTION'); + expect(adornment).to.have.class(classes.controls); + expect(adornment).to.have.class('MuiInputAdornment-positionEnd'); + expect(ref.current).to.equal(adornment); + expect(getComputedStyle(adornment).paddingTop).to.equal('7px'); + expect(getComputedStyle(adornment).paddingBottom).to.equal('9px'); + + await user.click(screen.getByRole('button', { name: 'Increase' })); + expect(adornment).to.have.attribute('data-render-value', '6'); + }); + + it('lets a replacement slot bypass render while preserving the owned buttons', async () => { + const renderControls = vi.fn(() =>
); + const { user } = render( + , + ); + const controls = screen.getByTestId('custom'); + const increment = screen.getByRole('button', { name: 'Increase' }); + + expect(controls).to.contain(increment); + expect(screen.queryByText('Replacement content')).to.equal(null); + expect(renderControls).toHaveBeenCalledTimes(0); + + await user.click(increment); + expect(screen.getByRole('textbox', { name: 'Amount' })).to.have.value('6'); + }); + }); + + // Protect the Base-owned visible input and form input from consumer children, + // which would otherwise break editing, accessibility links, and submission. + describe('root children ownership', () => { + [ + { name: 'top-level children', props: { children: 'Replacement' } }, + { name: 'root slot children', props: { slotProps: { root: { children: 'Replacement' } } } }, + ].forEach(({ name, props }) => { + it(`preserves the owned inputs when passed ${name}`, async () => { + const { user } = render( +
+ + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const form = screen.getByRole('form', { name: 'Number form' }); + + expect(screen.queryByText('Replacement')).to.equal(null); + + await user.click(input); + await user.keyboard('{ArrowUp}'); + + expect(input).to.have.value('6'); + expect(new FormData(form).getAll('amount')).to.deep.equal(['6']); + }); + }); + }); + + // Resolve Material and native consumer configurations before composing Base UI + // behavior, so later InputBase spreads preserve the chosen handlers and refs. + describe('input slot props', () => { + it('preserves the formatted single-line input with conflicting slot props', async () => { + const conflictingProps = { value: '99', defaultValue: '42', type: 'number' }; + const slotProps = { + input: { ...conflictingProps, multiline: true, rows: 3, minRows: 2, maxRows: 4 }, + htmlInput: () => conflictingProps, + }; + const { user } = render( + , + ); + const input = screen.getByRole('textbox'); + expect(input.tagName).to.equal('INPUT'); + expect(input.type).to.equal('text'); + expect(input).not.to.have.attribute('rows'); + expect(input).to.have.value('1,000'); + + await user.type(input, '{ArrowUp}'); + expect(input).to.have.value('1,001'); + }); + + // Replacing the Material wrapper or native input must retain the refs and event + // wiring that connect Base UI editing with Material focus and styling. + describe('input customization', () => { + it('ignores component in input slot props and preserves Material rendering', () => { + const unsupportedComponentProps = { component: 'article' }; + render( + , + }, + htmlInput: { + ...unsupportedComponentProps, + render: , + }, + }} + />, + ); + + expect(screen.getByTestId('material-input')).to.have.class('MuiInputBase-root'); + expect(screen.getByRole('textbox', { name: 'Amount' }).tagName).to.equal('INPUT'); + }); + + // Each variant supplies a different styled native input. Rendering another + // element must keep that layer rather than replace it with an unstyled input. + (['outlined', 'filled', 'standard'] as const).forEach((variant) => { + it(`preserves ${variant} input styles through both render adapters`, () => { + render( + + + }, + htmlInput: { render: }, + }} + /> + , + ); + const reference = screen.getByRole('textbox', { name: 'Reference' }); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + expect(input.closest('.MuiInputBase-root')!.tagName).to.equal('SECTION'); + expect(getComputedStyle(input).padding).to.equal(getComputedStyle(reference).padding); + }); + }); + + it('connects render callbacks to live state and refs even with a themed input root', async () => { + const wrapperRef = React.createRef(); + const inputRef = React.createRef(); + const theme = createTheme({ + components: { + MuiNumberField: { styleOverrides: { input: { paddingRight: 9 } } }, + MuiOutlinedInput: { defaultProps: { slots: { root: 'article' } } }, + }, + }); + const { user } = render( + +
, + }, + htmlInput: { + render: (props, state) => , + }, + }} + /> + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const wrapper = screen.getByRole('group'); + + expect(wrapper.tagName).to.equal('SECTION'); + expect(wrapperRef.current).to.equal(wrapper); + expect(inputRef.current).to.equal(input); + expect(getComputedStyle(wrapper).position).to.equal('relative'); + expect(getComputedStyle(wrapper).paddingRight).to.equal('9px'); + + await user.clear(input); + await user.keyboard('7'); + await user.click(screen.getByRole('button', { name: 'Increase' })); + + expect(input).to.have.value('8'); + expect(document.activeElement).to.equal(input); + expect(wrapper).to.have.attribute('data-render-value', '8'); + expect(input).to.have.attribute('data-render-value', '8'); + }); + + it('preserves click-to-focus and handlers on the shared input root', async () => { + const onClick = vi.fn(); + const onKeyDown = vi.fn((event: React.KeyboardEvent) => { + expect(event.currentTarget).to.equal(screen.getByRole('group')); + }); + const { user } = render( + , + ); + + await user.click(screen.getByRole('group')); + + expect(screen.getByRole('textbox', { name: 'Amount' })).toHaveFocus(); + expect(onClick).toHaveBeenCalledTimes(1); + await user.keyboard('{F2}'); + expect(onKeyDown).toHaveBeenCalledTimes(1); + }); + + const MaterialInputRoot = React.forwardRef< + HTMLElement, + React.ComponentPropsWithoutRef<'section'> & { + ownerState?: { endAdornment?: React.ReactNode }; + } + >(function MaterialInputRoot({ ownerState, ...other }, ref) { + return ( +
+ ); + }); + + (['slotProps', 'theme'] as const).forEach((source) => { + it(`preserves a custom Material input root configured through ${source}`, () => { + const theme = createTheme({ + components: + source === 'theme' + ? { MuiOutlinedInput: { defaultProps: { slots: { root: MaterialInputRoot } } } } + : {}, + }); + render( + + , + }), + slotProps: { root: { id: 'amount-root' } }, + }, + }} + /> + , + ); + const group = screen.getByRole('group'); + + expect(group.tagName).to.equal('SECTION'); + expect(group).to.have.attribute('id', 'amount-root'); + expect(group).to.have.attribute('data-adorned-end', 'true'); + expect(group).to.equal(screen.getByRole('textbox').closest('.MuiInputBase-root')); + }); + }); + + it('uses the themed root of a replacement input and skips the input render callbacks', () => { + const renderInput = vi.fn(() =>
); + const renderHtmlInput = vi.fn(() => ); + const theme = createTheme({ + components: { + MuiOutlinedInput: { defaultProps: { slots: { root: 'article' } } }, + MuiFilledInput: { defaultProps: { slots: { root: MaterialInputRoot } } }, + }, + }); + render( + + + , + ); + + const group = screen.getByRole('group'); + const input = screen.getByRole('textbox'); + expect(group.tagName).to.equal('SECTION'); + expect(group).to.have.attribute('data-adorned-end', 'true'); + expect(group).not.to.have.attribute('required'); + expect(input).to.have.property('required', true); + expect(input).to.equal(screen.getByTestId('custom')); + expect(group).to.contain(input); + expect(renderInput).toHaveBeenCalledTimes(0); + expect(renderHtmlInput).toHaveBeenCalledTimes(0); + }); + + it('preserves editing, handlers and refs with custom Material and native inputs', async () => { + const wrapperRef = React.createRef(); + const inputRef = React.createRef(); + const nativeRef = React.createRef(); + const onValueChange = vi.fn(); + const onChange = vi.fn(); + const keyEvents: [string, HTMLInputElement][] = []; + const recordKey = (event: React.KeyboardEvent) => { + keyEvents.push([event.type, event.currentTarget]); + }; + const wrapperProps = { ref: wrapperRef, 'data-testid': 'material-input' }; + const nativeProps = { + ref: nativeRef, + onKeyDown: recordKey, + onKeyUp: recordKey, + onChange, + 'data-testid': 'native-input', + }; + const { user } = render( + + + + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + const wrapper = screen.getByTestId('material-input'); + expect(screen.getByTestId('native-input')).to.equal(input); + expect(wrapper).to.contain(input); + expect(wrapperRef.current).to.equal(wrapper); + expect(inputRef.current).to.equal(input); + expect(nativeRef.current).to.equal(input); + + await user.click(input); + await user.keyboard('{ArrowUp}'); + expect(input).to.have.value('6'); + expect(keyEvents).to.deep.equal([ + ['keydown', input], + ['keyup', input], + ]); + await user.clear(input); + await user.keyboard('8'); + expect(input).to.have.value('8'); + expect(onChange).toHaveBeenCalledTimes(2); + expect(onValueChange.mock.calls.map(([value]) => value)).to.deep.equal([6, null, 8]); + + // A control press uses Base UI's internal input ref to restore focus. + await user.click(screen.getByRole('button', { name: 'Outside' })); + expect(input).not.to.equal(document.activeElement); + await user.click(screen.getByRole('button', { name: 'Increase' })); + expect(input).to.equal(document.activeElement); + expect(input).to.have.value('9'); + expect(inputRef.current).to.equal(input); + expect(nativeRef.current).to.equal(input); + expect(onValueChange.mock.calls.map(([value]) => value)).to.deep.equal([6, null, 8, 9]); + }); + }); + + describe('native input props', () => { + it('ignores native props and keyboard handlers on the Material wrapper and preserves its root props', async () => { + const ignoredRef = React.createRef(); + const nativeRef = React.createRef(); + const ignoredKeyHandler = vi.fn(); + const wrapperProps = { + onKeyDown: ignoredKeyHandler, + onKeyUp: ignoredKeyHandler, + inputProps: { placeholder: 'Ignored placeholder', ref: ignoredRef }, + slotProps: { + input: { title: 'Ignored title', ref: ignoredRef }, + root: { title: 'Material input' }, + }, + }; + const { user } = render( + wrapperProps, + htmlInput: { ref: nativeRef, 'aria-label': 'Amount' }, + }} + />, + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + expect(input).not.to.have.attribute('placeholder'); + expect(input).not.to.have.attribute('title'); + expect(nativeRef.current).to.equal(input); + expect(ignoredRef.current).to.equal(null); + expect(screen.getByTitle('Material input')).to.contain(input); + + await user.type(input, '{ArrowUp}'); + expect(input).to.have.value('6'); + expect(ignoredKeyHandler).toHaveBeenCalledTimes(0); + }); + + it('lets the Material input override the public placeholder', () => { + render( + , + ); + + expect(screen.getByRole('textbox')).to.have.attribute( + 'placeholder', + 'Material placeholder', + ); + }); + + it('keeps stepping when native keyboard handlers are explicitly undefined', async () => { + const { user } = render( + , + ); + const input = screen.getByRole('textbox'); + await user.type(input, '{ArrowUp}'); + expect(input).to.have.value('6'); + }); + + it('lets the native keydown handler cancel stepping', async () => { + const onValueChange = vi.fn(); + const { user } = render( + { + if (event.key === 'ArrowUp') { + event.preventBaseUIHandler(); + } + }, + }, + }} + />, + ); + + const input = screen.getByRole('textbox'); + await user.type(input, '{ArrowUp}'); + + expect(input).to.have.value('5'); + expect(onValueChange).toHaveBeenCalledTimes(0); + + await user.keyboard('{ArrowDown}'); + expect(input).to.have.value('4'); + }); + }); + }); + + // Keep wrapper events and native input callbacks on their intended elements + // while preserving Material form state and Base UI value commits. + describe('input events', () => { + // The native input, Material wrapper and field root must receive their own + // handlers rather than duplicating forwarded props on the wrong element. + describe('wrapper and native events', () => { + it('preserves handler targets and order from the native input to the field root', async () => { + const calls: { + handler: string; + currentTarget: HTMLElement; + target: EventTarget; + }[] = []; + const record = (handler: string) => (event: React.MouseEvent) => { + calls.push({ handler, currentTarget: event.currentTarget, target: event.target }); + }; + const { user } = render( + , + ); + const input = screen.getByRole('textbox'); + const wrapper = screen.getByTitle('Material input'); + const root = input.closest(`.${classes.root}`)!; + + await user.click(input); + + expect(calls).to.deep.equal([ + { handler: 'native', currentTarget: input, target: input }, + { handler: 'wrapper', currentTarget: wrapper, target: input }, + { handler: 'root', currentTarget: root, target: input }, + ]); + }); + }); + + // Compose public, Material, and native callbacks in the expected order without + // losing FormControl focus/filled state or Base UI editing and commit behavior. + describe('focus, blur and change handlers', () => { + it('lets Material input focus and blur handlers override the public handlers', async () => { + const publicHandler = vi.fn(); + const targets: HTMLElement[] = []; + const slotHandler = (event: React.FocusEvent) => { + targets.push(event.currentTarget); + }; + const { user } = render( + , + ); + const input = screen.getByRole('textbox'); + + await user.click(input); + await user.tab(); + + expect(targets).to.deep.equal([input, input]); + expect(publicHandler).toHaveBeenCalledTimes(0); + }); + + it('composes native callbacks while preserving Material callback order and state', async () => { + const calls: string[] = []; + const targets: HTMLElement[] = []; + const record = (name: string) => (event: React.SyntheticEvent) => { + calls.push(name); + targets.push(event.currentTarget); + }; + const onValueCommitted = vi.fn(); + const { user } = render( + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const label = screen.getByText('Amount', { selector: 'label' }); + + await user.click(input); + expect(label).to.have.class('Mui-focused'); + await user.keyboard('4'); + await user.tab(); + + expect(input).to.have.value('4'); + expect(label).not.to.have.class('Mui-focused'); + expect(label).to.have.attribute('data-shrink', 'true'); + expect(calls).to.deep.equal([ + 'public focus', + 'native focus', + 'native change', + 'Material change', + 'public blur', + 'native blur', + ]); + expect(targets).to.deep.equal(Array(6).fill(input)); + expect(onValueCommitted).toHaveBeenCalledTimes(1); + expect(onValueCommitted.mock.calls[0][0]).to.equal(4); + }); + + it('preserves editing and commits when native callbacks are explicitly undefined', async () => { + const materialChange = vi.fn(); + const onValueChange = vi.fn(); + const onValueCommitted = vi.fn(); + const { user } = render( + , + ); + const input = screen.getByRole('textbox'); + + await user.click(input); + await user.keyboard('4'); + await user.tab(); + + expect(input).to.have.value('4'); + expect(onValueChange).toHaveBeenCalledTimes(1); + expect(onValueChange.mock.calls[0][0]).to.equal(4); + expect(materialChange).toHaveBeenCalledTimes(1); + expect(onValueCommitted).toHaveBeenCalledTimes(1); + expect(onValueCommitted.mock.calls[0][0]).to.equal(4); + }); + }); + }); + + // Base UI supplies the value; NumberField must keep Material's filled state + // aligned with its text, including zero and an empty controlled value. + describe('Material filled state', () => { + it('updates label shrink when the controlled value changes', async () => { + function Test() { + const [value, setValue] = React.useState(5); + return ( + + + + + + + ); + } + + const { user } = render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const label = screen.getByText('Amount', { selector: 'label' }); + const expectValue = (value: string, shrink: boolean) => { + expect(input).to.have.value(value); + expect(label).to.have.attribute('data-shrink', String(shrink)); + }; + + expectValue('5', true); + await user.click(screen.getByRole('button', { name: 'Set zero' })); + expectValue('0', true); + await user.click(screen.getByRole('button', { name: 'Set empty' })); + expectValue('', false); + await user.click(screen.getByRole('button', { name: 'Set number' })); + expectValue('8', true); + }); + + it('clears Material filled state when zero is removed', async () => { + const { user } = render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const label = screen.getByText('Amount', { selector: 'label' }); + + expect(label).to.have.attribute('data-shrink', 'true'); + await user.clear(input); + await user.tab(); + + expect(input).to.have.value(''); + expect(label).to.have.attribute('data-shrink', 'false'); + }); + }); + + // Smoke-test delegated behavior through Material's native input and buttons. + // Base UI owns the parsing, stepping, validation and commit-timing rules. + describe('Base UI integration', () => { + it('reports change and commit reasons for button presses, keyboard steps, and text edits', async () => { + const onValueChange = vi.fn(); + const onValueCommitted = vi.fn(); + const { user } = render( + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + await user.click(screen.getByRole('button', { name: 'Increase' })); + await user.click(screen.getByRole('button', { name: 'Decrease' })); + await user.click(input); + await user.keyboard('{ArrowUp}'); + await user.clear(input); + await user.tab(); + await user.click(input); + await user.paste('1'); + await user.keyboard('7'); + await user.tab(); + + expect( + onValueChange.mock.calls.map(([value, details]) => [value, details.reason]), + ).to.deep.equal([ + [6, 'increment-press'], + [5, 'decrement-press'], + [6, 'keyboard'], + [null, 'input-clear'], + [1, 'input-paste'], + [17, 'input-change'], + ]); + expect( + onValueCommitted.mock.calls.map(([value, details]) => [value, details.reason]), + ).to.deep.equal([ + [6, 'increment-press'], + [5, 'decrement-press'], + [6, 'keyboard'], + [null, 'input-clear'], + [17, 'input-blur'], + ]); + }); + + it('forwards stepping and formatting options through the Material input', async () => { + const onValueChange = vi.fn(); + const { user } = render( + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + expect(input).to.have.value('1,50'); + await user.click(input); + await user.keyboard('{ArrowUp}'); + expect(input).to.have.value('2,00'); + + await user.click(screen.getByRole('button', { name: 'Increase' })); + expect(input).to.have.value('2,50'); + expect(onValueChange.mock.lastCall![0]).to.equal(2.5); + }); + + // Wheel handling attaches a native listener using Base UI's input ref. + it('connects wheel scrubbing to the visible Material input', async () => { + const onValueChange = vi.fn(); + const onValueCommitted = vi.fn(); + const { user } = render( + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + await user.click(input); + // user-event does not expose wheel gestures. + act(() => { + input.dispatchEvent( + new window.WheelEvent('wheel', { + bubbles: true, + cancelable: true, + deltaY: -1, + }), + ); + }); + + expect(input).to.have.value('7'); + expect(onValueChange).toHaveBeenCalledExactlyOnceWith( + 7, + expect.objectContaining({ reason: 'wheel' }), + ); + expect(onValueCommitted).toHaveBeenCalledExactlyOnceWith( + 7, + expect.objectContaining({ reason: 'wheel' }), + ); + }); + }); + + // External forms own the visible input for validation and Enter submission, and + // Base UI's submission input for contributing one raw numeric value. + describe('form submission', () => { + it.each([ + { slot: 'input', slotProps: { input: { name: 'price' } } }, + { slot: 'htmlInput', slotProps: { htmlInput: () => ({ name: 'price' }) } }, + ])('submits only the raw value when slotProps.$slot also supplies name', ({ slotProps }) => { + render( +
+ + , + ); + + expect(screen.getByRole('textbox')).to.have.value('€5.00'); + const form = screen.getByRole('form', { name: 'Order' }); + expect(new FormData(form).getAll('price')).to.deep.equal(['5']); + }); + + it('warns when only an input slot supplies the field name', () => { + expect(() => { + render( +
+ + , + ); + }).toWarnDev('MUI: NumberField ignores `name` on its input slots.'); + + const form = screen.getByRole('form', { name: 'Order' }); + expect(Array.from(new FormData(form).entries())).to.deep.equal([]); + }); + + it('submits one raw numeric value to an external form from a formatted field', async () => { + const submissions: FormData[] = []; + const { user } = render( + +
{ + event.preventDefault(); + submissions.push(new FormData(event.currentTarget)); + }} + > + +
+ +
, + ); + + expect(screen.getByRole('textbox', { name: 'Amount' })).to.have.value('$1,234.50'); + await user.click(screen.getByRole('button', { name: 'Submit' })); + + expect(submissions).to.have.length(1); + expect(Array.from(submissions[0].entries())).to.deep.equal([['amount', '1234.5']]); + }); + + it('uses visible input validation and Enter submission with an external form', async () => { + const submissions: FormData[] = []; + const { user } = render( + +
{ + event.preventDefault(); + submissions.push(new FormData(event.currentTarget)); + }} + > + +
+ +
, + ); + const form = screen.getByRole('form', { name: 'Order' }); + const input = screen.getByRole('textbox', { name: 'Amount' }); + + // The visible input's pattern must participate in the associated form's validation. + expect(form.checkValidity()).to.equal(false); + await user.click(input); + await user.keyboard('{Enter}'); + expect(submissions).to.have.length(0); + + await user.clear(input); + await user.keyboard('7'); + expect(form.checkValidity()).to.equal(true); + await user.keyboard('{Enter}'); + + expect(submissions).to.have.length(1); + expect(Array.from(submissions[0].entries())).to.deep.equal([['amount', '7']]); + }); + }); + + // NumberField owns the label/helper relationships and the visible input's focus + // entry points. Cover that wiring without repeating state styling or SSR checks. + describe('labels, helper text and focus', () => { + it('links an explicit input ID to its label and accessible description', async () => { + const { user } = render( + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const label = screen.getByText('Amount', { selector: 'label' }); + + expect(input).to.have.attribute('id', 'amount'); + expect(input).toHaveAccessibleDescription('Enter the quantity'); + await user.click(label); + expect(document.activeElement).to.equal(input); + }); + + it('uses the native input slot ID for the input, label, and steppers when both IDs are set', async () => { + const { user } = render( + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + expect(input).to.have.attribute('id', 'slot-id'); + for (const button of screen.getAllByRole('button')) { + expect(button).to.have.attribute('aria-controls', 'slot-id'); + } + await user.click(screen.getByText('Amount', { selector: 'label' })); + expect(document.activeElement).to.equal(input); + }); + + it('links the label, helper text, and steppers using the IDs on render elements', () => { + render( + }, + formHelperText: { id: 'slot-help', render:

}, + }} + />, + ); + + const input = screen.getByRole('textbox', { name: 'Quantity' }); + expect(input).to.have.attribute('id', 'quantity'); + expect(input).toHaveAccessibleDescription('Maximum 10'); + expect(input).to.have.attribute('aria-describedby', 'quantity-help'); + for (const button of screen.getAllByRole('button')) { + expect(button).to.have.attribute('aria-controls', input.id); + } + }); + + (['object', 'callback'] as const).forEach((configuration) => { + it(`links the input to a custom helper text ID from ${configuration} slot props`, () => { + render( + ({ id: `${ownerState.id}-help` }) + : { id: 'qty-help' }, + }} + />, + ); + + expect(screen.getByText('Maximum 10')).to.have.attribute('id', 'qty-help'); + expect(screen.getByRole('textbox', { name: 'Quantity' })).toHaveAccessibleDescription( + 'Maximum 10', + ); + }); + }); + + it('renders zero as label and helper content', () => { + render(); + + expect(screen.getByRole('textbox', { name: '0' })).toHaveAccessibleDescription('0'); + }); + + it.each(['', null, undefined, false])( + 'omits the helper text and its input association for helperText=%j', + (helperText) => { + const { container } = render( + , + ); + + expect(container.querySelector(`.${classes.formHelperText}`)).to.equal(null); + expect(screen.getByRole('textbox', { name: 'Amount' })).not.to.have.attribute( + 'aria-describedby', + ); + }, + ); + + it('adds and removes label and helper content without leaving dangling associations', async () => { + function Test() { + const [showContent, setShowContent] = React.useState(false); + + return ( + + + Enter the quantity : ''} + slotProps={{ htmlInput: { 'aria-label': showContent ? undefined : 'Amount' } }} + /> + + ); + } + + const { user } = render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const root = input.closest(`.${classes.root}`)!; + const toggle = screen.getByRole('button', { name: 'Toggle label and helper' }); + const expectNoContent = () => { + expect(root.querySelector('label')).to.equal(null); + expect(root.querySelector('.MuiFormHelperText-root')).to.equal(null); + expect(input).not.to.have.attribute('aria-describedby'); + }; + + expectNoContent(); + await user.click(toggle); + + expect(screen.getByRole('textbox', { name: 'Amount' })).to.equal(input); + expect(input).not.to.have.attribute('aria-label'); + expect(screen.getByText('Amount', { selector: 'label' })).to.have.attribute('for', input.id); + expect(input).toHaveAccessibleDescription('Enter the quantity'); + + await user.click(toggle); + + expect(screen.getByRole('textbox', { name: 'Amount' })).to.equal(input); + expectNoContent(); + expect(input).toHaveAccessibleDescription(''); + }); + + it('autofocuses the visible input', () => { + render(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + expect(document.activeElement).to.equal(input); + }); + + it('provides one tab stop and allows consumer inputRef focus', async () => { + const inputRef = React.createRef(); + const { user } = render( + + + + + , + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const focusButton = screen.getByRole('button', { name: 'Focus amount' }); + + await user.tab(); + expect(document.activeElement).to.equal(focusButton); + await user.tab(); + expect(document.activeElement).to.equal(input); + await user.tab(); + expect(document.activeElement).to.equal(screen.getByRole('button', { name: 'After' })); + await user.tab({ shift: true }); + expect(document.activeElement).to.equal(input); + + await user.click(focusButton); + expect(document.activeElement).to.equal(input); + }); + }); + + // Scrubbing is optional and shares the input adornments with controls and consumer + // content. Cover composition, slot plumbing, and drag interactions through the Material wrapper. + describe('scrub area', () => { + it.skipIf(isJsdom())( + 'aligns the end scrub handle with the split controls in a filled field', + () => { + const { container } = render( + , + ); + const handle = container.querySelector(`.${classes.scrubArea}`)!.getBoundingClientRect(); + const button = screen.getByRole('button', { name: 'Increase' }).getBoundingClientRect(); + expect(handle.top + handle.height / 2).to.be.closeTo(button.top + button.height / 2, 0.5); + }, + ); + + it('resolves scrub slot props only when a scrub area is enabled', () => { + const slotProps = { + scrubArea: vi.fn(() => ({})), + scrubAreaCursor: vi.fn(() => ({})), + }; + const { container, rerender } = render(); + + expect(container.querySelector(`.${classes.scrubArea}`)).to.equal(null); + expect(slotProps.scrubArea).not.toHaveBeenCalled(); + expect(slotProps.scrubAreaCursor).not.toHaveBeenCalled(); + + rerender(); + + expect(slotProps.scrubArea).toHaveBeenCalled(); + expect(slotProps.scrubAreaCursor).toHaveBeenCalled(); + }); + + it('resolves scrub slot callbacks and preserves custom children and refs', () => { + const scrubRef = React.createRef(); + const { container } = render( + ({ + ref: scrubRef, + render:

, + direction: ownerState.size === 'small' ? 'vertical' : 'horizontal', + children: Drag, + }), + }} + />, + ); + const scrub = container.querySelector(`.${classes.scrubArea}`)!; + + expect(scrubRef.current).to.equal(scrub); + expect(scrub).to.equal(screen.getByTestId('render-scrub')); + expect(scrub).to.have.attribute('data-direction', 'vertical'); + expect(scrub).to.contain(screen.getByText('Drag')); + expect(scrub.querySelector('svg')).to.equal(null); + }); + + // Mount the cursor to check Material slot props, render bridges and styling. + // Base UI owns the portal, pointer-lock behavior and ref cleanup. + // Base UI intentionally omits the custom cursor on WebKit. + describe.skipIf(typeof CSS !== 'undefined' && CSS.supports?.('-webkit-backdrop-filter:none'))( + 'cursor slot', + () => { + let originalRequestPointerLock: PropertyDescriptor | undefined; + + const TestCursor = React.forwardRef< + HTMLSpanElement, + React.ComponentPropsWithoutRef<'span'> & TestSlotProps + >(function TestCursor(props, ref) { + const { ownerState, as, ...other } = props; + return ; + }); + + beforeEach(() => { + originalRequestPointerLock = Object.getOwnPropertyDescriptor( + document.body, + 'requestPointerLock', + ); + Object.defineProperty(document.body, 'requestPointerLock', { + configurable: true, + value: vi.fn().mockResolvedValue(undefined), + }); + }); + + afterEach(() => { + if (originalRequestPointerLock) { + Object.defineProperty(document.body, 'requestPointerLock', originalRequestPointerLock); + } else { + Reflect.deleteProperty(document.body, 'requestPointerLock'); + } + }); + + it('resolves callback props through a replacement cursor slot', async () => { + const ref = vi.fn(); + const renderScrub = vi.fn(() =>
); + const renderCursor = vi.fn(() =>
); + const { container, user, unmount } = render( + ({ + ref, + render: renderCursor, + title: `Cursor ${ownerState.label}`, + className: 'custom-cursor', + }), + }} + />, + ); + const scrub = container.querySelector(`.${classes.scrubArea}`)!; + + await user.pointer({ keys: '[MouseLeft>]', target: scrub }); + const cursor = screen.getByTitle('Cursor Amount'); + + expect(cursor).to.equal(screen.getByTestId('custom-cursor')); + expect(cursor).to.have.class(classes.scrubAreaCursor); + expect(cursor).to.have.class('custom-cursor'); + expect(ref).toHaveBeenLastCalledWith(cursor); + expect(renderScrub).toHaveBeenCalledTimes(0); + expect(renderCursor).toHaveBeenCalledTimes(0); + + unmount(); + }); + + it('merges cursor props and refs with theme overrides during scrubbing', async () => { + const ref = React.createRef(); + const theme = createTheme({ + components: { + MuiNumberField: { + styleOverrides: { scrubAreaCursor: { color: 'rgb(255, 0, 0)' } }, + }, + }, + }); + const { container, user } = render( + + ( +
+ ), + title: 'Custom cursor', + className: 'custom-cursor', + style: { opacity: 0.5 }, + children: Drag cursor, + }, + }} + /> + , + ); + const scrub = container.querySelector(`.${classes.scrubArea}`)!; + await user.pointer({ keys: '[MouseLeft>]', target: scrub }); + const cursor = screen.getByTitle('Custom cursor'); + + expect(cursor).to.have.class(classes.scrubAreaCursor); + expect(cursor).to.have.class('custom-cursor'); + expect(cursor.style.opacity).to.equal('0.5'); + expect(cursor).to.have.attribute('data-render-scrubbing', 'true'); + expect(cursor).to.contain(screen.getByText('Drag cursor')); + expect(ref.current).to.equal(cursor); + expect(window.getComputedStyle(cursor).color).to.equal('rgb(255, 0, 0)'); + + await user.pointer({ keys: '[/MouseLeft]', target: scrub }); + await waitFor(() => { + expect(screen.queryByTitle('Custom cursor')).to.equal(null); + }); + }); + }, + ); + + // Keep drag handlers and render state connected through the Material slots. + // Base UI owns drag arithmetic, sensitivity, availability and commit timing. + describe('dragging', () => { + // user-event does not supply the movementX/movementY deltas used for scrubbing. + function movePointer(movementX: number, movementY: number) { + const event = new window.MouseEvent('pointermove', { bubbles: true, cancelable: true }); + Object.defineProperties(event, { + movementX: { value: movementX }, + movementY: { value: movementY }, + }); + act(() => { + window.dispatchEvent(event); + }); + } + + // Check Material customization against the same drag lifecycle as Base UI, + // without repeating its value-calculation behavior here. + it('exposes live scrubbing state to slots, root attributes, classes and theme overrides', async () => { + const callbacks = createSlotCallbacks(); + const theme = createTheme({ + components: { + MuiNumberField: { + styleOverrides: { + root: ({ ownerState }) => ({ + paddingTop: ownerState.scrubbing ? '7px' : '0px', + [`&.${classes.scrubbing}`]: { paddingBottom: 9 }, + }), + }, + }, + }, + }); + const { container, user } = render( + + + , + ); + const root = container.querySelector(`.${classes.root}`)!; + const scrub = container.querySelector(`.${classes.scrubArea}`)!; + const expectScrubbing = (scrubbing: boolean) => { + Object.entries(callbacks).forEach(([slot, callback]) => { + expect(callback.mock.lastCall![0].scrubbing, `slotProps.${slot}`).to.equal(scrubbing); + }); + expect(root.hasAttribute(NumberFieldRootDataAttributes.scrubbing)).to.equal(scrubbing); + expect(root.classList.contains(classes.scrubbing)).to.equal(scrubbing); + expect(root.classList.contains('custom-scrubbing')).to.equal(scrubbing); + expect(getComputedStyle(root).paddingTop).to.equal(scrubbing ? '7px' : '0px'); + expect(getComputedStyle(root).paddingBottom).to.equal(scrubbing ? '9px' : '0px'); + }; + + expectScrubbing(false); + + await user.pointer({ keys: '[MouseLeft>]', target: scrub }); + expectScrubbing(true); + movePointer(4, 0); + + await user.pointer({ keys: '[/MouseLeft]', target: scrub }); + await waitFor(() => expectScrubbing(false)); + }); + + it('preserves scrubbing through a custom handle', async () => { + const onValueChange = vi.fn(); + const onValueCommitted = vi.fn(); + const { container, user } = render( +
, + }, + }} + />, + ); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const scrub = container.querySelector(`.${classes.scrubArea}`)!; + + await user.pointer({ keys: '[MouseLeft>]', target: scrub }); + movePointer(0, -4); + expect(input).to.have.value('9'); + expect(scrub).to.have.attribute('data-render-value', '9'); + expect(onValueChange).toHaveBeenCalledExactlyOnceWith( + 9, + expect.objectContaining({ reason: 'scrub' }), + ); + expect(onValueCommitted).not.toHaveBeenCalled(); + + await user.pointer({ keys: '[/MouseLeft]', target: scrub }); + await waitFor(() => { + expect(onValueCommitted).toHaveBeenCalledExactlyOnceWith( + 9, + expect.objectContaining({ reason: 'scrub' }), + ); + }); + }); + }); + }); + + // FormControl needs the initial filled/adorned state in server markup so labels + // render correctly before effects run and stay stable during hydration. + describe('server rendering', () => { + function expectStableHydration( + hydrate: () => void, + { displayValue, shrink }: { displayValue: string; shrink: boolean }, + ) { + const input = screen.getByRole('textbox', { name: 'Amount' }); + const label = screen.getByText('Amount', { selector: 'label' }); + + // Check server markup before client effects can initialize FormControl. + expect(input).to.have.value(displayValue); + expect(label).to.have.attribute('data-shrink', String(shrink)); + + hydrate(); + + expect(screen.getByRole('textbox', { name: 'Amount' })).to.equal(input); + expect(screen.getByText('Amount', { selector: 'label' })).to.equal(label); + expect(input).to.have.value(displayValue); + expect(label).to.have.attribute('data-shrink', String(shrink)); + } + + it('preserves initial FormControl label state with render through hydration', () => { + const { hydrate } = renderToString( + } />, + ); + expectStableHydration(hydrate, { displayValue: '5', shrink: true }); + }); + + // Initial values, including zero and empty values, must determine label shrink + // before hydration, without relying on client-side FormControl updates. + describe('initial value', () => { + const cases = [ + { name: 'value=0', props: { value: 0 }, displayValue: '0', shrink: true }, + { + name: 'defaultValue=42', + props: { defaultValue: 42 }, + displayValue: '42', + shrink: true, + }, + { + name: 'defaultValue=undefined', + props: { defaultValue: undefined }, + displayValue: '', + shrink: false, + }, + ] satisfies { + name: string; + props: Pick; + displayValue: string; + shrink: boolean; + }[]; + + cases.forEach(({ name, props, displayValue, shrink }) => { + it(`initializes label shrink before hydration with ${name}`, () => { + const { hydrate } = renderToString(); + + expectStableHydration(hydrate, { displayValue, shrink }); + }); + }); + }); + + // Formatting must already appear in server markup, and the same formatted value + // must initialize FormControl's filled state when the client hydrates it. + describe('formatted initial values', () => { + it('preserves formatted initial text through hydration', () => { + const { hydrate } = renderToString( + , + ); + + expectStableHydration(hydrate, { displayValue: '1.234,50', shrink: true }); + }); + }); + + // NumberField's composed start adornments must initialize label shrink on the server. + describe('adornments', () => { + it.each([ + { props: { scrubAreaPosition: 'start' }, shrink: true }, + { props: { scrubAreaPosition: 'end' }, shrink: false }, + { props: { controlsPosition: 'split' }, shrink: true }, + { props: { controlsPosition: 'stacked' }, shrink: false }, + { props: { startAdornment: '' }, shrink: false }, + ] as const)( + 'preserves label shrink=$shrink through hydration with $props', + ({ props, shrink }) => { + const { hydrate } = renderToString(); + expectStableHydration(hydrate, { displayValue: '', shrink }); + }, + ); + + it('resolves slot callbacks once alongside a server-rendered start adornment', () => { + const getInputProps = vi.fn((ownerState: NumberFieldOwnerState) => ({ + className: ownerState.disabled ? 'disabled-input' : undefined, + })); + const getInputLabelProps = vi.fn((ownerState: NumberFieldOwnerState) => ({ + className: ownerState.disabled ? 'disabled-label' : undefined, + })); + const getHelperTextProps = vi.fn(() => ({ id: 'amount-help' })); + const { hydrate } = renderToString( + , + ); + // Assert server evaluation counts before hydration can trigger additional renders. + expect(getInputProps).toHaveBeenCalledTimes(1); + expect(getInputLabelProps).toHaveBeenCalledTimes(1); + expect(getHelperTextProps).toHaveBeenCalledTimes(1); + const adornmentNode = screen.getByText('0'); + const input = screen.getByRole('textbox', { name: 'Amount' }); + expect(input.closest('.disabled-input')).to.contain(adornmentNode); + expect(screen.getByText('Amount', { selector: 'label' })).to.have.class('disabled-label'); + expect(input).toHaveAccessibleDescription('Enter the quantity'); + + expectStableHydration(hydrate, { displayValue: '', shrink: true }); + expect(screen.getByText('0')).to.equal(adornmentNode); + }); + + it('does not shrink an empty server-rendered label with a falsy start and an end adornment', () => { + const { hydrate } = renderToString( + , + ); + const adornmentNode = screen.getByText('kg'); + const group = screen.getByRole('group'); + expect(group.querySelector(`.${classes.startAdornment}`)).to.equal(null); + expect(group.querySelector(`.${classes.endAdornment}`)).to.contain(adornmentNode); + + expectStableHydration(hydrate, { displayValue: '', shrink: false }); + expect(screen.getByText('kg')).to.equal(adornmentNode); + }); + }); + + // Generated IDs must retain their label/helper associations through hydration + // without depending on React's ID format. + describe('generated IDs and associations', () => { + it('preserves input, label and helper IDs through hydration', () => { + const { hydrate } = renderToString(); + const input = screen.getByRole('textbox', { name: 'Amount' }); + const label = screen.getByText('Amount', { selector: 'label' }); + const helper = screen.getByText('Helper text'); + const inputId = input.id; + const labelId = label.id; + const helperId = helper.id; + expect(inputId).not.to.equal(''); + expect(labelId).not.to.equal(''); + expect(helperId).not.to.equal(''); + + const expectAssociations = () => { + expect(screen.getByRole('textbox', { name: 'Amount' })).to.equal(input); + expect(screen.getByText('Amount', { selector: 'label' })).to.equal(label); + expect(screen.getByText('Helper text')).to.equal(helper); + expect(input).to.have.attribute('id', inputId); + expect(label).to.have.attribute('id', labelId); + expect(helper).to.have.attribute('id', helperId); + expect(label).to.have.attribute('for', inputId); + expect(input).to.have.attribute('aria-describedby', helperId); + expect(input).toHaveAccessibleDescription('Helper text'); + }; + + expectAssociations(); + hydrate(); + expectAssociations(); + }); + }); + }); +}); diff --git a/packages/mui-material/src/NumberField/NumberField.tsx b/packages/mui-material/src/NumberField/NumberField.tsx new file mode 100644 index 00000000000000..220d0306a8af89 --- /dev/null +++ b/packages/mui-material/src/NumberField/NumberField.tsx @@ -0,0 +1,507 @@ +'use client'; + +import * as React from 'react'; +import PropTypes from 'prop-types'; + +import { NumberField as BaseNumberField } from '@base-ui/react/number-field'; + +import useId from '@mui/utils/useId'; +import resolveComponentProps from '@mui/utils/resolveComponentProps'; + +import { useDefaultProps } from '../DefaultPropsProvider'; +import type { NumberFieldOwnerState, NumberFieldProps } from './NumberField.types'; +import RootSlot from './NumberFieldRootSlot'; +import InputSlot from './NumberFieldInputSlot'; +import { getUtilityClasses, resolveInputProps, resolveRenderedSlotProps } from './utils'; + +/** + * Number fields let users enter, format, and adjust numeric values. + * + * Demos: + * + * - [Number Field](https://next.mui.com/material-ui/react-number-field/) + * + * API: + * + * - [NumberField API](https://next.mui.com/material-ui/api/number-field/) + * - inherits [FormControl API](https://next.mui.com/material-ui/api/form-control/) + */ +const NumberField = React.forwardRef(function NumberField( + inProps: NumberFieldProps, + ref: React.Ref, +) { + const props = useDefaultProps({ props: inProps, name: 'MuiNumberField' }); + const { + allowOutOfRange = false, + allowWheelScrub = false, + autoFocus = false, + className, + color = 'primary', + controlsPosition = 'end', + defaultValue, + disabled = false, + endAdornment, + error = false, + form, + format, + fullWidth = false, + helperText, + id: idProp, + inputRef, + label, + locale, + largeStep, + max, + min, + name, + onBlur, + onFocus, + onValueChange, + onValueCommitted, + placeholder, + readOnly = false, + render, + required = false, + scrubAreaPosition = false, + size: sizeProp, + slots = {}, + slotProps: slotPropsProp = {}, + smallStep, + step, + snapOnStep = false, + startAdornment, + value, + variant = 'outlined', + ...other + } = props; + + const { size = 'medium' } = useDefaultProps({ + props: { size: sizeProp }, + // eslint-disable-next-line mui/material-ui-name-matches-component-name -- Inherit FormControl's size default. + name: 'MuiFormControl', + }); + const id = useId(idProp); + const hasHelperText = helperText != null && helperText !== '' && helperText !== false; + const defaultHelperTextId = id ? `${id}-helper-text` : undefined; + + // Defer callbacks so split controls receive their own position in ownerState. + // Clear `component` so useSlot preserves the element chosen through `render`. + const slotProps: NonNullable = Object.fromEntries( + Object.entries(slotPropsProp).map(([slotName, slotProp]) => [ + slotName, + (slotOwnerState: NumberFieldOwnerState) => ({ + ...resolveComponentProps(slotProp, slotOwnerState), + component: undefined, + }), + ]), + ); + + const ownerState = { + ...props, + allowOutOfRange, + allowWheelScrub, + autoFocus, + color, + controlsPosition, + disabled, + endAdornment, + error, + fullWidth, + id, + placeholder, + readOnly, + render, + required, + scrubAreaPosition, + size, + snapOnStep, + startAdornment, + variant, + }; + + return ( + { + // Base UI tracks scrubbing and can inherit disabled from Field.Root. Copy its flags + // while keeping the original value and defaultValue props available to slot callbacks. + const resolvedOwnerState = { + ...ownerState, + disabled: baseState.disabled, + required: baseState.required, + readOnly: baseState.readOnly, + scrubbing: baseState.scrubbing, + }; + const classes = getUtilityClasses(resolvedOwnerState); + + // Use the IDs from rendered slots so aria-describedby and htmlFor still point to them. + const helperTextProps = resolveRenderedSlotProps( + resolveComponentProps(slotProps.formHelperText, resolvedOwnerState) ?? {}, + slots.formHelperText, + ); + const helperTextId = hasHelperText + ? (helperTextProps.id ?? defaultHelperTextId) + : undefined; + + // Share slot props used by multiple parts so each callback runs once + // with Base UI's resolved flags. + const { materialInputProps, nativeSlotProps } = resolveInputProps( + slotProps, + resolvedOwnerState, + ); + const { id: nativeInputId, ...htmlInputProps } = resolveRenderedSlotProps( + nativeSlotProps, + slots.htmlInput ?? materialInputProps.slots?.input, + ); + const externalForwardedProps = { + ...other, + component: undefined, + slots, + slotProps: { + ...slotProps, + input: materialInputProps, + htmlInput: htmlInputProps, + inputLabel: { + htmlFor: nativeInputId ?? id, + ...resolveComponentProps(slotProps.inputLabel, resolvedOwnerState), + }, + formHelperText: { ...helperTextProps, id: helperTextId }, + }, + }; + + return ( + + ( + + )} + /> + + ); + }} + smallStep={smallStep} + snapOnStep={snapOnStep} + step={step} + value={value} + /> + ); +}); + +NumberField.propTypes /* remove-proptypes */ = { + // ┌────────────────────────────── Warning ──────────────────────────────┐ + // │ These PropTypes are generated from the TypeScript type definitions. │ + // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │ + // └─────────────────────────────────────────────────────────────────────┘ + /** + * If `true`, values entered by typing or pasting are not clamped to `min` and `max`. + * Stepping with the buttons, keyboard, mouse wheel, or scrub area still respects the bounds. + * @default false + */ + allowOutOfRange: PropTypes.bool, + /** + * If `true`, the mouse wheel adjusts the value while the input is focused and hovered. + * @default false + */ + allowWheelScrub: PropTypes.bool, + /** + * If `true`, the `input` element is focused during the first mount. + * @default false + */ + autoFocus: PropTypes.bool, + /** + * Override or extend the styles applied to the component. + */ + classes: PropTypes.object, + /** + * A CSS class name applied to the root element. + */ + className: PropTypes.string, + /** + * The color of the component. + * It supports both default and custom theme colors, which can be added as shown in the + * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors). + * @default 'primary' + */ + color: PropTypes /* @typescript-to-proptypes-ignore */ + .oneOfType([ + PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), + PropTypes.string, + ]), + /** + * The arrangement of the control buttons. + * Use `'end'` for horizontal minus/plus buttons at the end, `'split'` for a minus button + * at the start and a plus button at the end, `'stacked'` for up/down chevrons at the end, + * or `false` for no control buttons. + * @default 'end' + */ + controlsPosition: PropTypes.oneOf(['end', 'split', 'stacked', false]), + /** + * The initial numeric value for an uncontrolled field. + * Omit this prop to start with an empty field. + * Use `value` for a controlled field. + */ + defaultValue: PropTypes.number, + /** + * If `true`, the component is disabled. + * @default false + */ + disabled: PropTypes.bool, + /** + * Content displayed immediately after the input, such as a unit or a clear button. + */ + endAdornment: PropTypes.node, + /** + * If `true`, the field is displayed in an error state. + * @default false + */ + error: PropTypes.bool, + /** + * The `id` of the form that owns the field. + * Use this prop when the field is rendered outside the form. + */ + form: PropTypes.string, + /** + * The [`Intl.NumberFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) used to format the displayed value. + * The `value` prop and value callbacks use numbers or `null`, regardless of the display format. + */ + format: PropTypes /* @typescript-to-proptypes-ignore */.object, + /** + * If `true`, the input will take up the full width of its container. + * @default false + */ + fullWidth: PropTypes.bool, + /** + * The helper text content. + */ + helperText: PropTypes.node, + /** + * The `id` of the visible input, used to associate its label and helper text. + * If omitted, an ID is generated. + */ + id: PropTypes.string, + /** + * A ref to the visible `` element. + */ + inputRef: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.shape({ + current: PropTypes.object, + }), + ]), + /** + * The label content. + */ + label: PropTypes.node, + /** + * The amount to increment or decrement while holding the Shift key. + * @default 10 + */ + largeStep: PropTypes.number, + /** + * The locale or locales used to format and parse the value. + * Defaults to the runtime's locale. + * + * See [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). + */ + locale: PropTypes /* @typescript-to-proptypes-ignore */ + .oneOfType([ + PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.object, PropTypes.string])), + PropTypes.object, + PropTypes.string, + ]), + /** + * If `dense` or `normal`, will adjust vertical spacing of this and contained components. + * @default 'none' + */ + margin: PropTypes.oneOf(['dense', 'none', 'normal']), + /** + * The upper bound for the numeric value. + * The increment button is disabled at or above this value. + */ + max: PropTypes.number, + /** + * The lower bound for the numeric value. + * The decrement button is disabled at or below this value. + */ + min: PropTypes.number, + /** + * Identifies the field when a form is submitted. + * The submitted value is the unformatted number. + */ + name: PropTypes.string, + /** + * Callback fired when the input loses focus. + */ + onBlur: PropTypes.func, + /** + * Callback fired when the input receives focus. + */ + onFocus: PropTypes.func, + /** + * Callback fired when the numeric value changes. + * Call `eventDetails.cancel()` to reject the proposed change. + * + * @param {number|null} value The new numeric value, or `null` when the input is empty. + * @param {NumberFieldChangeEventDetails} eventDetails The native `event` and the `reason` for the change. + * Typing a number reports `"input-change"`, clearing the input reports `"input-clear"`, + * and stepping with Arrow Up or Arrow Down reports `"keyboard"`. + * Other reasons are `"input-blur"`, `"input-paste"`, `"increment-press"`, `"decrement-press"`, + * `"wheel"`, `"scrub"`, and `"none"`. + */ + onValueChange: PropTypes.func, + /** + * Callback fired when the value is committed. + * Direct text entry commits on blur. + * Pointer presses on the stepper buttons and scrub interactions commit on pointer release. + * Keyboard and mouse wheel steps commit immediately. + * + * @param {number|null} value The committed numeric value, or `null` when the input is empty. + * @param {NumberFieldCommitEventDetails} eventDetails The native `event` and the `reason` for the commit. + * Leaving the field after typing a number reports `"input-blur"`. Stepping with Arrow Up or Arrow Down reports `"keyboard"`. + * Other reasons are `"input-clear"`, `"increment-press"`, `"decrement-press"`, `"wheel"`, `"scrub"`, and `"none"`. + */ + onValueCommitted: PropTypes.func, + /** + * The short hint displayed in the input when it is empty. + */ + placeholder: PropTypes.string, + /** + * If `true`, the value cannot be changed through user interaction. + * The input can still receive focus. + * @default false + */ + readOnly: PropTypes.bool, + /** + * Replaces the root element while preserving its styles and behavior. + * Pass an element or a `(props, state) => element` callback. Forward the supplied props and ref to the root element. + * `state.value` is the current numeric value or `null`. `state.inputValue` is the text displayed in the input. + */ + render: PropTypes.oneOfType([PropTypes.element, PropTypes.func]), + /** + * If `true`, a value is required for form submission and the label is marked as required. + * @default false + */ + required: PropTypes.bool, + /** + * The placement of the drag handle used to adjust the value. + * Use `'start'` or `'end'` to show the handle, or `false` to hide it. + * Its position is independent of `controlsPosition`. + * @default false + */ + scrubAreaPosition: PropTypes.oneOf(['end', 'start', false]), + /** + * The size of the component. + * @default 'medium' + */ + size: PropTypes /* @typescript-to-proptypes-ignore */ + .oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]), + /** + * The props used for each slot inside. + * @default {} + */ + slotProps: PropTypes /* @typescript-to-proptypes-ignore */ + .shape({ + controls: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + decrementButton: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + formHelperText: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + htmlInput: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + incrementButton: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + inputLabel: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + scrubArea: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + scrubAreaCursor: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), + }), + /** + * The components used for each slot inside. + * @default {} + */ + slots: PropTypes.shape({ + controls: PropTypes.elementType, + decrementButton: PropTypes.elementType, + formHelperText: PropTypes.elementType, + htmlInput: PropTypes.elementType, + incrementButton: PropTypes.elementType, + input: PropTypes.elementType, + inputLabel: PropTypes.elementType, + root: PropTypes.elementType, + scrubArea: PropTypes.elementType, + scrubAreaCursor: PropTypes.elementType, + }), + /** + * The amount to increment or decrement while holding the Alt key (Option on macOS). + * @default 0.1 + */ + smallStep: PropTypes.number, + /** + * If `true`, stepping snaps the value to intervals starting at `min`, or `0` if `min` is omitted. + * Modifier keys use the corresponding `smallStep` or `largeStep` intervals. + * @default false + */ + snapOnStep: PropTypes.bool, + /** + * Content displayed immediately before the input, such as a currency symbol. + */ + startAdornment: PropTypes.node, + /** + * The amount to increment or decrement with the buttons, arrow keys, mouse wheel, or scrub area. + * Set `min` explicitly to enable step validation on form submission. + * Set to `"any"` to disable step validation; interactive stepping then uses `1`, + * while the Alt and Shift keys still use `smallStep` and `largeStep`. + * @default 1 + */ + step: PropTypes.oneOfType([PropTypes.oneOf(['any']), PropTypes.number]), + /** + * The system prop that allows defining system overrides as well as additional CSS styles. + */ + sx: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), + PropTypes.func, + PropTypes.object, + ]), + /** + * The controlled numeric value. + * Use `null` to display an empty field and `onValueChange` to update the value. + */ + value: PropTypes.number, + /** + * The variant to use. + * @default 'outlined' + */ + variant: PropTypes.oneOf(['filled', 'outlined', 'standard']), +} as any; + +export default NumberField; diff --git a/packages/mui-material/src/NumberField/NumberField.types.ts b/packages/mui-material/src/NumberField/NumberField.types.ts new file mode 100644 index 00000000000000..00c6f95df154a7 --- /dev/null +++ b/packages/mui-material/src/NumberField/NumberField.types.ts @@ -0,0 +1,521 @@ +import type { NumberField as BaseNumberField } from '@base-ui/react/number-field'; +import type { useRender } from '@base-ui/react/use-render'; + +import type { OverridableStringUnion, Overwrite } from '@mui/types'; +import type { SlotComponentProps } from '@mui/utils/types'; + +import type { InputProps as StandardInputProps } from '../Input'; +import type { InternalStandardProps as StandardProps } from '../internal'; +import type { FormControlProps } from '../FormControl'; +import type { CreateSlotsAndSlotProps } from '../utils/types'; +import type { NumberFieldClasses } from './numberFieldClasses'; +import type { FormHelperTextProps } from '../FormHelperText'; +import type { InputLabelProps } from '../InputLabel'; +import type { Theme } from '../styles/createTheme'; +import type { FilledInputProps } from '../FilledInput'; +import type { IconButtonProps } from '../IconButton'; +import type { InputAdornmentProps } from '../InputAdornment'; +import type { OutlinedInputProps } from '../OutlinedInput'; +import type { SxProps } from '../styles'; + +export type NumberFieldVariants = 'outlined' | 'standard' | 'filled'; + +type ControlsPosition = 'stacked' | 'end' | 'split' | false; + +type OwnedInputProps = Partial>; + +type NativeInputProps = React.ComponentPropsWithRef<'input'>; +type MaterialInputEvents = Pick; +type NativeKeyboardEvents = Pick; + +export interface NumberFieldSlots { + /** + * The component that renders each group of stepper buttons. + * @default InputAdornment + */ + controls: React.ElementType; + /** + * The component that renders the decrement button. + * @default IconButton + */ + decrementButton: React.ElementType; + /** + * The component that renders the helper text. + * @default FormHelperText + */ + formHelperText: React.ElementType; + /** + * The component that renders the native input element. + * Use `& .MuiNumberField-htmlInput` in `styleOverrides.root` to style it. + * @default 'input' + */ + htmlInput: React.ElementType; + /** + * The component that renders the increment button. + * @default IconButton + */ + incrementButton: React.ElementType; + /** + * The component that renders the Material input wrapper. + * @default OutlinedInput + */ + input: React.ElementType; + /** + * The component that renders the input's label. + * @default InputLabel + */ + inputLabel: React.ElementType; + /** + * The component that renders the root. + * While scrubbing, the root has the `MuiNumberField-scrubbing` class. + * Use `&.MuiNumberField-scrubbing` in `styleOverrides.root` to style that state. + * @default FormControl + */ + root: React.ElementType; + /** + * The component that renders the drag handle for adjusting the value. + * @default 'span' + */ + scrubArea: React.ElementType; + /** + * The component that renders the custom cursor while dragging the scrub area. + * @default 'span' + */ + scrubAreaCursor: React.ElementType; +} + +export interface NumberFieldPropsSizeOverrides {} +export interface NumberFieldPropsColorOverrides {} + +export interface NumberFieldRootSlotPropsOverrides {} +export interface NumberFieldControlsSlotPropsOverrides {} +export interface NumberFieldInputSlotPropsOverrides {} +export interface NumberFieldHtmlInputSlotPropsOverrides {} +export interface NumberFieldFormHelperTextSlotPropsOverrides {} +export interface NumberFieldInputLabelSlotPropsOverrides {} +export interface NumberFieldDecrementButtonSlotPropsOverrides {} +export interface NumberFieldIncrementButtonSlotPropsOverrides {} +export interface NumberFieldScrubAreaSlotPropsOverrides {} +export interface NumberFieldScrubAreaCursorSlotPropsOverrides {} + +type NumberFieldInputSlotProps = SlotComponentProps< + React.FunctionComponent, + Overrides & OwnedInputProps, + NumberFieldOwnerState +>; + +export type NumberFieldSlotsAndSlotProps = CreateSlotsAndSlotProps< + NumberFieldSlots, + { + /** + * Props forwarded to each controls adornment. + * Based on the [InputAdornment](https://mui.com/material-ui/api/input-adornment/#props) component. + * NumberField supplies the position and button content. + * With split controls, the callback receives `ownerState.position` for each side. + * Use `render` to change the element while preserving Material styling. + */ + controls: SlotComponentProps< + React.ElementType>, + NumberFieldControlsSlotPropsOverrides & + Pick, 'render'>, + NumberFieldOwnerState & Pick + >; + /** + * Props forwarded to the decrement button slot. + * By default, the available props are based on the [IconButton](https://mui.com/material-ui/api/icon-button/#props) component. + * Use `render` to change the element while preserving Material styling and Base UI behavior. + * Set `nativeButton` to `false` when rendering an element other than a native `