neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
+189
View File
@@ -0,0 +1,189 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { Theme } from "../styles/index.mjs";
import { InternalStandardProps as StandardProps } from "../internal/index.mjs";
import { InputProps } from "../Input/index.mjs";
import { MenuProps } from "../Menu/index.mjs";
import { SelectChangeEvent, SelectInputProps } from "./SelectInput.mjs";
import { SelectClasses } from "./selectClasses.mjs";
import { OutlinedInputProps } from "../OutlinedInput/index.mjs";
import { FilledInputProps } from "../FilledInput/index.mjs";
export { SelectChangeEvent };
export interface BaseSelectProps<Value = unknown> extends StandardProps<InputProps, 'value' | 'onChange' | 'placeholder'> {
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
* @default false
*/
autoWidth?: boolean | undefined;
/**
* The option elements to populate the select with.
* Can be some `MenuItem` when `native` is false and `option` when `native` is true.
*
* ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
*/
children?: React.ReactNode;
/**
* Override or extend the styles applied to the component.
* @default {}
*/
classes?: Partial<SelectClasses> | undefined;
/**
* If `true`, the component is initially open. Use when the component open state is not controlled (i.e. the `open` prop is not defined).
* You can only use it when the `native` prop is `false` (default).
* @default false
*/
defaultOpen?: boolean | undefined;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: Value | undefined;
/**
* If `true`, a value is displayed even if no items are selected.
*
* In order to display a meaningful value, a function can be passed to the `renderValue` prop which
* returns the value to be displayed when no items are selected.
*
* ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value.
* The label should either be hidden or forced to a shrunk state.
* @default false
*/
displayEmpty?: boolean | undefined;
/**
* The icon that displays the arrow.
* @default ArrowDropDownIcon
*/
IconComponent?: React.ElementType | undefined;
/**
* The `id` of the wrapper element or the `select` element when `native`.
*/
id?: string | undefined;
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input?: React.ReactElement<unknown, any> | undefined;
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#attributes) applied to the `input` element.
* When `native` is `true`, the attributes are applied on the `select` element.
*/
inputProps?: InputProps['inputProps'] | undefined;
/**
* See [OutlinedInput#label](https://mui.com/material-ui/api/outlined-input/#props)
*/
label?: React.ReactNode;
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId?: string | undefined;
/**
* Props applied to the [`Menu`](https://mui.com/material-ui/api/menu/) element.
*/
MenuProps?: Partial<MenuProps> | undefined;
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
* @default false
*/
multiple?: boolean | undefined;
/**
* If `true`, the component uses a native `select` element.
* @default false
*/
native?: boolean | undefined;
/**
* Callback fired when a menu item is selected.
*
* @param {SelectChangeEvent<Value>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event, not a change event, unless the change event is caused by browser autofill.
* @param {object} [child] The react element that was selected when `native` is `false` (default).
*/
onChange?: SelectInputProps<Value>['onChange'] | undefined;
/**
* Callback fired when the component requests to be closed.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select collapses).
*
* @param {object} event The event source of the callback.
*/
onClose?: ((event: React.SyntheticEvent) => void) | undefined;
/**
* Callback fired when the component requests to be opened.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select expands).
*
* @param {object} event The event source of the callback.
*/
onOpen?: ((event: React.SyntheticEvent) => void) | undefined;
/**
* If `true`, the component is shown.
* You can only use it when the `native` prop is `false` (default).
*/
open?: boolean | undefined;
/**
* Render the selected value.
* You can only use it when the `native` prop is `false` (default).
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue?: ((value: Value) => React.ReactNode) | undefined;
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps?: React.HTMLAttributes<HTMLDivElement> | undefined;
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps<Theme> | undefined;
/**
* The `input` value. Providing an empty string will select no options.
* Set to an empty string `''` if you don't want any of the available options to be selected.
*
* If the value is an object it must have reference equality with the option in order to be selected.
* If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
*/
value?: Value | '' | undefined;
/**
* The variant to use.
* @default 'outlined'
*/
variant?: SelectVariants | undefined;
}
export interface FilledSelectProps extends Omit<FilledInputProps, 'value' | 'onChange' | 'id' | 'classes' | 'inputProps' | 'placeholder' | 'label'> {
/**
* The variant to use.
* @default 'outlined'
*/
variant: 'filled';
}
export interface StandardSelectProps extends Omit<InputProps, 'value' | 'onChange' | 'id' | 'classes' | 'inputProps' | 'placeholder' | 'label'> {
/**
* The variant to use.
* @default 'outlined'
*/
variant: 'standard';
}
export interface OutlinedSelectProps extends Omit<OutlinedInputProps, 'value' | 'onChange' | 'id' | 'classes' | 'inputProps' | 'placeholder' | 'label'> {
/**
* The variant to use.
* @default 'outlined'
*/
variant?: 'outlined' | undefined;
}
export type SelectVariants = 'outlined' | 'standard' | 'filled';
export type SelectProps<Value = unknown> = (FilledSelectProps & BaseSelectProps<Value>) | (StandardSelectProps & BaseSelectProps<Value>) | (OutlinedSelectProps & BaseSelectProps<Value>);
/**
*
* Demos:
*
* - [Select](https://mui.com/material-ui/react-select/)
*
* API:
*
* - [Select API](https://mui.com/material-ui/api/select/)
* - inherits [OutlinedInput API](https://mui.com/material-ui/api/outlined-input/)
*/
declare const Select: (<Value = unknown>(props: SelectProps<Value>) => React.JSX.Element) & {
muiName: string;
};
export default Select;
+189
View File
@@ -0,0 +1,189 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { Theme } from "../styles/index.js";
import { InternalStandardProps as StandardProps } from "../internal/index.js";
import { InputProps } from "../Input/index.js";
import { MenuProps } from "../Menu/index.js";
import { SelectChangeEvent, SelectInputProps } from "./SelectInput.js";
import { SelectClasses } from "./selectClasses.js";
import { OutlinedInputProps } from "../OutlinedInput/index.js";
import { FilledInputProps } from "../FilledInput/index.js";
export { SelectChangeEvent };
export interface BaseSelectProps<Value = unknown> extends StandardProps<InputProps, 'value' | 'onChange' | 'placeholder'> {
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
* @default false
*/
autoWidth?: boolean | undefined;
/**
* The option elements to populate the select with.
* Can be some `MenuItem` when `native` is false and `option` when `native` is true.
*
* ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
*/
children?: React.ReactNode;
/**
* Override or extend the styles applied to the component.
* @default {}
*/
classes?: Partial<SelectClasses> | undefined;
/**
* If `true`, the component is initially open. Use when the component open state is not controlled (i.e. the `open` prop is not defined).
* You can only use it when the `native` prop is `false` (default).
* @default false
*/
defaultOpen?: boolean | undefined;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: Value | undefined;
/**
* If `true`, a value is displayed even if no items are selected.
*
* In order to display a meaningful value, a function can be passed to the `renderValue` prop which
* returns the value to be displayed when no items are selected.
*
* ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value.
* The label should either be hidden or forced to a shrunk state.
* @default false
*/
displayEmpty?: boolean | undefined;
/**
* The icon that displays the arrow.
* @default ArrowDropDownIcon
*/
IconComponent?: React.ElementType | undefined;
/**
* The `id` of the wrapper element or the `select` element when `native`.
*/
id?: string | undefined;
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input?: React.ReactElement<unknown, any> | undefined;
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#attributes) applied to the `input` element.
* When `native` is `true`, the attributes are applied on the `select` element.
*/
inputProps?: InputProps['inputProps'] | undefined;
/**
* See [OutlinedInput#label](https://mui.com/material-ui/api/outlined-input/#props)
*/
label?: React.ReactNode;
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId?: string | undefined;
/**
* Props applied to the [`Menu`](https://mui.com/material-ui/api/menu/) element.
*/
MenuProps?: Partial<MenuProps> | undefined;
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
* @default false
*/
multiple?: boolean | undefined;
/**
* If `true`, the component uses a native `select` element.
* @default false
*/
native?: boolean | undefined;
/**
* Callback fired when a menu item is selected.
*
* @param {SelectChangeEvent<Value>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event, not a change event, unless the change event is caused by browser autofill.
* @param {object} [child] The react element that was selected when `native` is `false` (default).
*/
onChange?: SelectInputProps<Value>['onChange'] | undefined;
/**
* Callback fired when the component requests to be closed.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select collapses).
*
* @param {object} event The event source of the callback.
*/
onClose?: ((event: React.SyntheticEvent) => void) | undefined;
/**
* Callback fired when the component requests to be opened.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select expands).
*
* @param {object} event The event source of the callback.
*/
onOpen?: ((event: React.SyntheticEvent) => void) | undefined;
/**
* If `true`, the component is shown.
* You can only use it when the `native` prop is `false` (default).
*/
open?: boolean | undefined;
/**
* Render the selected value.
* You can only use it when the `native` prop is `false` (default).
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue?: ((value: Value) => React.ReactNode) | undefined;
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps?: React.HTMLAttributes<HTMLDivElement> | undefined;
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps<Theme> | undefined;
/**
* The `input` value. Providing an empty string will select no options.
* Set to an empty string `''` if you don't want any of the available options to be selected.
*
* If the value is an object it must have reference equality with the option in order to be selected.
* If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
*/
value?: Value | '' | undefined;
/**
* The variant to use.
* @default 'outlined'
*/
variant?: SelectVariants | undefined;
}
export interface FilledSelectProps extends Omit<FilledInputProps, 'value' | 'onChange' | 'id' | 'classes' | 'inputProps' | 'placeholder' | 'label'> {
/**
* The variant to use.
* @default 'outlined'
*/
variant: 'filled';
}
export interface StandardSelectProps extends Omit<InputProps, 'value' | 'onChange' | 'id' | 'classes' | 'inputProps' | 'placeholder' | 'label'> {
/**
* The variant to use.
* @default 'outlined'
*/
variant: 'standard';
}
export interface OutlinedSelectProps extends Omit<OutlinedInputProps, 'value' | 'onChange' | 'id' | 'classes' | 'inputProps' | 'placeholder' | 'label'> {
/**
* The variant to use.
* @default 'outlined'
*/
variant?: 'outlined' | undefined;
}
export type SelectVariants = 'outlined' | 'standard' | 'filled';
export type SelectProps<Value = unknown> = (FilledSelectProps & BaseSelectProps<Value>) | (StandardSelectProps & BaseSelectProps<Value>) | (OutlinedSelectProps & BaseSelectProps<Value>);
/**
*
* Demos:
*
* - [Select](https://mui.com/material-ui/react-select/)
*
* API:
*
* - [Select API](https://mui.com/material-ui/api/select/)
* - inherits [OutlinedInput API](https://mui.com/material-ui/api/outlined-input/)
*/
declare const Select: (<Value = unknown>(props: SelectProps<Value>) => React.JSX.Element) & {
muiName: string;
};
export default Select;
+303
View File
@@ -0,0 +1,303 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _deepmerge = _interopRequireDefault(require("@mui/utils/deepmerge"));
var _composeClasses = _interopRequireDefault(require("@mui/utils/composeClasses"));
var _getReactElementRef = _interopRequireDefault(require("@mui/utils/getReactElementRef"));
var _SelectInput = _interopRequireDefault(require("./SelectInput"));
var _useFormControl = require("../FormControl/useFormControl");
var _ArrowDropDown = _interopRequireDefault(require("../internal/svg-icons/ArrowDropDown"));
var _Input = _interopRequireDefault(require("../Input"));
var _NativeSelectInput = _interopRequireDefault(require("../NativeSelect/NativeSelectInput"));
var _FilledInput = _interopRequireDefault(require("../FilledInput"));
var _OutlinedInput = _interopRequireDefault(require("../OutlinedInput"));
var _DefaultPropsProvider = require("../DefaultPropsProvider");
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _zeroStyled = require("../zero-styled");
var _rootShouldForwardProp = _interopRequireDefault(require("../styles/rootShouldForwardProp"));
var _selectClasses = require("./selectClasses");
var _jsxRuntime = require("react/jsx-runtime");
const useUtilityClasses = ownerState => {
const {
classes
} = ownerState;
const slots = {
root: ['root']
};
const composedClasses = (0, _composeClasses.default)(slots, _selectClasses.getSelectUtilityClasses, classes);
return {
...classes,
...composedClasses
};
};
const styledRootConfig = {
name: 'MuiSelect',
slot: 'Root',
shouldForwardProp: prop => (0, _rootShouldForwardProp.default)(prop) && prop !== 'variant'
};
const StyledInput = (0, _zeroStyled.styled)(_Input.default, styledRootConfig)('');
const StyledOutlinedInput = (0, _zeroStyled.styled)(_OutlinedInput.default, styledRootConfig)('');
const StyledFilledInput = (0, _zeroStyled.styled)(_FilledInput.default, styledRootConfig)('');
const Select = /*#__PURE__*/React.forwardRef(function Select(inProps, ref) {
const props = (0, _DefaultPropsProvider.useDefaultProps)({
name: 'MuiSelect',
props: inProps
});
const {
autoWidth = false,
children,
classes: classesProp = {},
className,
defaultOpen = false,
displayEmpty = false,
IconComponent = _ArrowDropDown.default,
id,
input,
inputProps,
label,
labelId,
MenuProps,
multiple = false,
native = false,
onClose,
onOpen,
open,
renderValue,
SelectDisplayProps,
variant: variantProp = 'outlined',
...other
} = props;
const inputComponent = native ? _NativeSelectInput.default : _SelectInput.default;
const [fcs] = (0, _useFormControl.useFormControlState)({
props,
states: ['variant', 'error']
});
const variant = fcs.variant || variantProp;
const ownerState = {
...props,
variant,
classes: classesProp
};
const classes = useUtilityClasses(ownerState);
const {
root,
...restOfClasses
} = classes;
const InputComponent = input || {
standard: /*#__PURE__*/(0, _jsxRuntime.jsx)(StyledInput, {
ownerState: ownerState
}),
outlined: /*#__PURE__*/(0, _jsxRuntime.jsx)(StyledOutlinedInput, {
label: label,
ownerState: ownerState
}),
filled: /*#__PURE__*/(0, _jsxRuntime.jsx)(StyledFilledInput, {
ownerState: ownerState
})
}[variant];
const inputComponentRef = (0, _useForkRef.default)(ref, (0, _getReactElementRef.default)(InputComponent));
return /*#__PURE__*/(0, _jsxRuntime.jsx)(React.Fragment, {
children: /*#__PURE__*/React.cloneElement(InputComponent, {
// Most of the logic is implemented in `SelectInput`.
// The `Select` component is a simple API wrapper to expose something better to play with.
inputComponent,
inputProps: {
children,
error: fcs.error,
IconComponent,
variant,
type: undefined,
// We render a select. We can ignore the type provided by the `Input`.
multiple,
...(native ? {
id
} : {
autoWidth,
defaultOpen,
displayEmpty,
labelId,
MenuProps,
onClose,
onOpen,
open,
renderValue,
SelectDisplayProps: {
id,
...SelectDisplayProps
}
}),
...inputProps,
classes: inputProps ? (0, _deepmerge.default)(restOfClasses, inputProps.classes) : restOfClasses,
...(input ? input.props.inputProps : {})
},
...((multiple && native || displayEmpty) && variant === 'outlined' ? {
notched: true
} : {}),
ref: inputComponentRef,
className: (0, _clsx.default)(InputComponent.props.className, className, classes.root),
// If a custom input is provided via 'input' prop, do not allow 'variant' to be propagated to it's root element. See https://github.com/mui/material-ui/issues/33894.
...(!input && {
variant
}),
...other
})
});
});
process.env.NODE_ENV !== "production" ? Select.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the d.ts file and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
* @default false
*/
autoWidth: _propTypes.default.bool,
/**
* The option elements to populate the select with.
* Can be some `MenuItem` when `native` is false and `option` when `native` is true.
*
* ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
* @default {}
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* If `true`, the component is initially open. Use when the component open state is not controlled (i.e. the `open` prop is not defined).
* You can only use it when the `native` prop is `false` (default).
* @default false
*/
defaultOpen: _propTypes.default.bool,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: _propTypes.default.any,
/**
* If `true`, a value is displayed even if no items are selected.
*
* In order to display a meaningful value, a function can be passed to the `renderValue` prop which
* returns the value to be displayed when no items are selected.
*
* ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value.
* The label should either be hidden or forced to a shrunk state.
* @default false
*/
displayEmpty: _propTypes.default.bool,
/**
* The icon that displays the arrow.
* @default ArrowDropDownIcon
*/
IconComponent: _propTypes.default.elementType,
/**
* The `id` of the wrapper element or the `select` element when `native`.
*/
id: _propTypes.default.string,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input: _propTypes.default.element,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#attributes) applied to the `input` element.
* When `native` is `true`, the attributes are applied on the `select` element.
*/
inputProps: _propTypes.default.object,
/**
* See [OutlinedInput#label](https://mui.com/material-ui/api/outlined-input/#props)
*/
label: _propTypes.default.node,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: _propTypes.default.string,
/**
* Props applied to the [`Menu`](https://mui.com/material-ui/api/menu/) element.
*/
MenuProps: _propTypes.default.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
* @default false
*/
multiple: _propTypes.default.bool,
/**
* If `true`, the component uses a native `select` element.
* @default false
*/
native: _propTypes.default.bool,
/**
* Callback fired when a menu item is selected.
*
* @param {SelectChangeEvent<Value>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event, not a change event, unless the change event is caused by browser autofill.
* @param {object} [child] The react element that was selected when `native` is `false` (default).
*/
onChange: _propTypes.default.func,
/**
* Callback fired when the component requests to be closed.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select collapses).
*
* @param {object} event The event source of the callback.
*/
onClose: _propTypes.default.func,
/**
* Callback fired when the component requests to be opened.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select expands).
*
* @param {object} event The event source of the callback.
*/
onOpen: _propTypes.default.func,
/**
* If `true`, the component is shown.
* You can only use it when the `native` prop is `false` (default).
*/
open: _propTypes.default.bool,
/**
* Render the selected value.
* You can only use it when the `native` prop is `false` (default).
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: _propTypes.default.func,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: _propTypes.default.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object, _propTypes.default.bool])), _propTypes.default.func, _propTypes.default.object]),
/**
* The `input` value. Providing an empty string will select no options.
* Set to an empty string `''` if you don't want any of the available options to be selected.
*
* If the value is an object it must have reference equality with the option in order to be selected.
* If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
*/
value: _propTypes.default.oneOfType([_propTypes.default.oneOf(['']), _propTypes.default.any]),
/**
* The variant to use.
* @default 'outlined'
*/
variant: _propTypes.default.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
Select.muiName = 'Select';
var _default = exports.default = Select;
+296
View File
@@ -0,0 +1,296 @@
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import deepmerge from '@mui/utils/deepmerge';
import composeClasses from '@mui/utils/composeClasses';
import getReactElementRef from '@mui/utils/getReactElementRef';
import SelectInput from "./SelectInput.mjs";
import { useFormControlState } from "../FormControl/useFormControl.mjs";
import ArrowDropDownIcon from "../internal/svg-icons/ArrowDropDown.mjs";
import Input from "../Input/index.mjs";
import NativeSelectInput from "../NativeSelect/NativeSelectInput.mjs";
import FilledInput from "../FilledInput/index.mjs";
import OutlinedInput from "../OutlinedInput/index.mjs";
import { useDefaultProps } from "../DefaultPropsProvider/index.mjs";
import useForkRef from "../utils/useForkRef.mjs";
import { styled } from "../zero-styled/index.mjs";
import rootShouldForwardProp from "../styles/rootShouldForwardProp.mjs";
import { getSelectUtilityClasses } from "./selectClasses.mjs";
import { jsx as _jsx } from "react/jsx-runtime";
const useUtilityClasses = ownerState => {
const {
classes
} = ownerState;
const slots = {
root: ['root']
};
const composedClasses = composeClasses(slots, getSelectUtilityClasses, classes);
return {
...classes,
...composedClasses
};
};
const styledRootConfig = {
name: 'MuiSelect',
slot: 'Root',
shouldForwardProp: prop => rootShouldForwardProp(prop) && prop !== 'variant'
};
const StyledInput = styled(Input, styledRootConfig)('');
const StyledOutlinedInput = styled(OutlinedInput, styledRootConfig)('');
const StyledFilledInput = styled(FilledInput, styledRootConfig)('');
const Select = /*#__PURE__*/React.forwardRef(function Select(inProps, ref) {
const props = useDefaultProps({
name: 'MuiSelect',
props: inProps
});
const {
autoWidth = false,
children,
classes: classesProp = {},
className,
defaultOpen = false,
displayEmpty = false,
IconComponent = ArrowDropDownIcon,
id,
input,
inputProps,
label,
labelId,
MenuProps,
multiple = false,
native = false,
onClose,
onOpen,
open,
renderValue,
SelectDisplayProps,
variant: variantProp = 'outlined',
...other
} = props;
const inputComponent = native ? NativeSelectInput : SelectInput;
const [fcs] = useFormControlState({
props,
states: ['variant', 'error']
});
const variant = fcs.variant || variantProp;
const ownerState = {
...props,
variant,
classes: classesProp
};
const classes = useUtilityClasses(ownerState);
const {
root,
...restOfClasses
} = classes;
const InputComponent = input || {
standard: /*#__PURE__*/_jsx(StyledInput, {
ownerState: ownerState
}),
outlined: /*#__PURE__*/_jsx(StyledOutlinedInput, {
label: label,
ownerState: ownerState
}),
filled: /*#__PURE__*/_jsx(StyledFilledInput, {
ownerState: ownerState
})
}[variant];
const inputComponentRef = useForkRef(ref, getReactElementRef(InputComponent));
return /*#__PURE__*/_jsx(React.Fragment, {
children: /*#__PURE__*/React.cloneElement(InputComponent, {
// Most of the logic is implemented in `SelectInput`.
// The `Select` component is a simple API wrapper to expose something better to play with.
inputComponent,
inputProps: {
children,
error: fcs.error,
IconComponent,
variant,
type: undefined,
// We render a select. We can ignore the type provided by the `Input`.
multiple,
...(native ? {
id
} : {
autoWidth,
defaultOpen,
displayEmpty,
labelId,
MenuProps,
onClose,
onOpen,
open,
renderValue,
SelectDisplayProps: {
id,
...SelectDisplayProps
}
}),
...inputProps,
classes: inputProps ? deepmerge(restOfClasses, inputProps.classes) : restOfClasses,
...(input ? input.props.inputProps : {})
},
...((multiple && native || displayEmpty) && variant === 'outlined' ? {
notched: true
} : {}),
ref: inputComponentRef,
className: clsx(InputComponent.props.className, className, classes.root),
// If a custom input is provided via 'input' prop, do not allow 'variant' to be propagated to it's root element. See https://github.com/mui/material-ui/issues/33894.
...(!input && {
variant
}),
...other
})
});
});
process.env.NODE_ENV !== "production" ? Select.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the d.ts file and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
* @default false
*/
autoWidth: PropTypes.bool,
/**
* The option elements to populate the select with.
* Can be some `MenuItem` when `native` is false and `option` when `native` is true.
*
* ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* @default {}
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the component is initially open. Use when the component open state is not controlled (i.e. the `open` prop is not defined).
* You can only use it when the `native` prop is `false` (default).
* @default false
*/
defaultOpen: PropTypes.bool,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, a value is displayed even if no items are selected.
*
* In order to display a meaningful value, a function can be passed to the `renderValue` prop which
* returns the value to be displayed when no items are selected.
*
* ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value.
* The label should either be hidden or forced to a shrunk state.
* @default false
*/
displayEmpty: PropTypes.bool,
/**
* The icon that displays the arrow.
* @default ArrowDropDownIcon
*/
IconComponent: PropTypes.elementType,
/**
* The `id` of the wrapper element or the `select` element when `native`.
*/
id: PropTypes.string,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input: PropTypes.element,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#attributes) applied to the `input` element.
* When `native` is `true`, the attributes are applied on the `select` element.
*/
inputProps: PropTypes.object,
/**
* See [OutlinedInput#label](https://mui.com/material-ui/api/outlined-input/#props)
*/
label: PropTypes.node,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: PropTypes.string,
/**
* Props applied to the [`Menu`](https://mui.com/material-ui/api/menu/) element.
*/
MenuProps: PropTypes.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
* @default false
*/
multiple: PropTypes.bool,
/**
* If `true`, the component uses a native `select` element.
* @default false
*/
native: PropTypes.bool,
/**
* Callback fired when a menu item is selected.
*
* @param {SelectChangeEvent<Value>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event, not a change event, unless the change event is caused by browser autofill.
* @param {object} [child] The react element that was selected when `native` is `false` (default).
*/
onChange: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select collapses).
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be opened.
* Use it in either controlled (see the `open` prop), or uncontrolled mode (to detect when the Select expands).
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the component is shown.
* You can only use it when the `native` prop is `false` (default).
*/
open: PropTypes.bool,
/**
* Render the selected value.
* You can only use it when the `native` prop is `false` (default).
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: PropTypes.func,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: PropTypes.object,
/**
* 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 `input` value. Providing an empty string will select no options.
* Set to an empty string `''` if you don't want any of the available options to be selected.
*
* If the value is an object it must have reference equality with the option in order to be selected.
* If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
*/
value: PropTypes.oneOfType([PropTypes.oneOf(['']), PropTypes.any]),
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
Select.muiName = 'Select';
export default Select;
+57
View File
@@ -0,0 +1,57 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { Theme } from "../styles/index.mjs";
import { MenuProps } from "../Menu/index.mjs";
/**
* The change can be caused by different kind of events.
* The type of event depends on what caused the change.
* For example, when the browser auto-fills the `Select` you'll receive a `React.ChangeEvent`.
*/
export type SelectChangeEvent<Value = string> = Value extends (string & {}) | number ? React.ChangeEvent<Omit<HTMLInputElement, 'value'> & {
value: Value;
}> | (Event & {
target: {
value: Value;
name: string;
};
}) : React.ChangeEvent<HTMLInputElement> | (Event & {
target: {
value: Value;
name: string;
};
});
export interface SelectInputProps<Value = unknown> {
autoFocus?: boolean | undefined;
autoWidth: boolean;
defaultOpen?: boolean | undefined;
disabled?: boolean | undefined;
error?: boolean | undefined;
IconComponent?: React.ElementType | undefined;
inputRef?: ((ref: HTMLSelectElement | {
node: HTMLInputElement;
value: SelectInputProps<Value>['value'];
}) => void) | undefined;
MenuProps?: Partial<MenuProps> | undefined;
multiple: boolean;
name?: string | undefined;
native: boolean;
onBlur?: React.FocusEventHandler<any> | undefined;
onChange?: ((event: SelectChangeEvent<Value>, child: React.ReactNode) => void) | undefined;
onClose?: ((event: React.SyntheticEvent) => void) | undefined;
onFocus?: React.FocusEventHandler<any> | undefined;
onKeyDown?: React.KeyboardEventHandler | undefined;
onMouseDown?: React.MouseEventHandler | undefined;
onOpen?: ((event: React.SyntheticEvent) => void) | undefined;
open?: boolean | undefined;
readOnly?: boolean | undefined;
renderValue?: ((value: SelectInputProps<Value>['value']) => React.ReactNode) | undefined;
SelectDisplayProps?: React.HTMLAttributes<HTMLDivElement> | undefined;
sx?: SxProps<Theme> | undefined;
tabIndex?: number | undefined;
value?: Value | undefined;
variant?: 'standard' | 'outlined' | 'filled' | undefined;
}
declare const SelectInput: React.JSXElementConstructor<SelectInputProps>;
export default SelectInput;
+57
View File
@@ -0,0 +1,57 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { Theme } from "../styles/index.js";
import { MenuProps } from "../Menu/index.js";
/**
* The change can be caused by different kind of events.
* The type of event depends on what caused the change.
* For example, when the browser auto-fills the `Select` you'll receive a `React.ChangeEvent`.
*/
export type SelectChangeEvent<Value = string> = Value extends (string & {}) | number ? React.ChangeEvent<Omit<HTMLInputElement, 'value'> & {
value: Value;
}> | (Event & {
target: {
value: Value;
name: string;
};
}) : React.ChangeEvent<HTMLInputElement> | (Event & {
target: {
value: Value;
name: string;
};
});
export interface SelectInputProps<Value = unknown> {
autoFocus?: boolean | undefined;
autoWidth: boolean;
defaultOpen?: boolean | undefined;
disabled?: boolean | undefined;
error?: boolean | undefined;
IconComponent?: React.ElementType | undefined;
inputRef?: ((ref: HTMLSelectElement | {
node: HTMLInputElement;
value: SelectInputProps<Value>['value'];
}) => void) | undefined;
MenuProps?: Partial<MenuProps> | undefined;
multiple: boolean;
name?: string | undefined;
native: boolean;
onBlur?: React.FocusEventHandler<any> | undefined;
onChange?: ((event: SelectChangeEvent<Value>, child: React.ReactNode) => void) | undefined;
onClose?: ((event: React.SyntheticEvent) => void) | undefined;
onFocus?: React.FocusEventHandler<any> | undefined;
onKeyDown?: React.KeyboardEventHandler | undefined;
onMouseDown?: React.MouseEventHandler | undefined;
onOpen?: ((event: React.SyntheticEvent) => void) | undefined;
open?: boolean | undefined;
readOnly?: boolean | undefined;
renderValue?: ((value: SelectInputProps<Value>['value']) => React.ReactNode) | undefined;
SelectDisplayProps?: React.HTMLAttributes<HTMLDivElement> | undefined;
sx?: SxProps<Theme> | undefined;
tabIndex?: number | undefined;
value?: Value | undefined;
variant?: 'standard' | 'outlined' | 'filled' | undefined;
}
declare const SelectInput: React.JSXElementConstructor<SelectInputProps>;
export default SelectInput;
+953
View File
@@ -0,0 +1,953 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _formatMuiErrorMessage = _interopRequireDefault(require("@mui/utils/formatMuiErrorMessage"));
var React = _interopRequireWildcard(require("react"));
var _reactIs = require("react-is");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _composeClasses = _interopRequireDefault(require("@mui/utils/composeClasses"));
var _useId = _interopRequireDefault(require("@mui/utils/useId"));
var _refType = _interopRequireDefault(require("@mui/utils/refType"));
var _useTimeout = _interopRequireDefault(require("@mui/utils/useTimeout"));
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _Menu = _interopRequireDefault(require("../Menu/Menu"));
var _NativeSelectInput = require("../NativeSelect/NativeSelectInput");
var _utils = require("../InputBase/utils");
var _zeroStyled = require("../zero-styled");
var _slotShouldForwardProp = _interopRequireDefault(require("../styles/slotShouldForwardProp"));
var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));
var _useEventCallback = _interopRequireDefault(require("../utils/useEventCallback"));
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _useControlled = _interopRequireDefault(require("../utils/useControlled"));
var _selectClasses = _interopRequireWildcard(require("./selectClasses"));
var _utils2 = require("./utils");
var _closedTypeahead = require("./utils/closedTypeahead");
var _SelectFocusSourceContext = require("./utils/SelectFocusSourceContext");
var _jsxRuntime = require("react/jsx-runtime");
var _span;
const OPENING_MOUSE_UP_BOUNDARY_OFFSET = 2;
// The initial mouseup may land on an item when the menu opens over the trigger.
const SELECTED_MOUSE_UP_DELAY = 400;
const UNSELECTED_MOUSE_UP_DELAY = 200;
const TYPEAHEAD_RESET_MS = 750;
const SPACE = ' ';
const ARROW_UP = 'ArrowUp';
const ARROW_DOWN = 'ArrowDown';
const ENTER = 'Enter';
/**
* Returns true when a native mouse event should be treated as happening inside
* the element, even if a portal or backdrop retargeted the event away from it.
*
* Select uses this for the opening mouseup: when the menu opens over the
* trigger, the release can target the backdrop or portaled menu even though the
* pointer is still inside the trigger or menu bounds.
*/
function isMouseEventInsideElement(event, element) {
if (!element) {
return false;
}
const eventPath = event.composedPath();
if (eventPath.includes(element)) {
return true;
}
if (event.target?.nodeType && element.contains(event.target)) {
return true;
}
const rect = element.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) {
// Hidden or transition-mounted elements do not have useful bounds to hit-test.
return false;
}
return event.clientX >= rect.left - OPENING_MOUSE_UP_BOUNDARY_OFFSET && event.clientX <= rect.right + OPENING_MOUSE_UP_BOUNDARY_OFFSET && event.clientY >= rect.top - OPENING_MOUSE_UP_BOUNDARY_OFFSET && event.clientY <= rect.bottom + OPENING_MOUSE_UP_BOUNDARY_OFFSET;
}
const SelectSelect = (0, _zeroStyled.styled)(_NativeSelectInput.StyledSelectSelect, {
name: 'MuiSelect',
slot: 'Select',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [
// Win specificity over the input base
{
[`&.${_selectClasses.default.select}`]: styles.select
}, {
[`&.${_selectClasses.default.select}`]: styles[ownerState.variant]
}, {
[`&.${_selectClasses.default.error}`]: styles.error
}, {
[`&.${_selectClasses.default.multiple}`]: styles.multiple
}];
}
})({
// Win specificity over the input base
[`&.${_selectClasses.default.select}`]: {
height: 'auto',
// Resets for multiple select with chips
minHeight: '1.4375em',
// Required for select\text-field height consistency
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden'
}
});
const SelectIcon = (0, _zeroStyled.styled)(_NativeSelectInput.StyledSelectIcon, {
name: 'MuiSelect',
slot: 'Icon',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.icon, ownerState.open && styles.iconOpen];
}
})({});
const SelectNativeInput = (0, _zeroStyled.styled)('input', {
shouldForwardProp: prop => (0, _slotShouldForwardProp.default)(prop) && prop !== 'classes',
name: 'MuiSelect',
slot: 'NativeInput'
})({
bottom: 0,
left: 0,
position: 'absolute',
opacity: 0,
pointerEvents: 'none',
width: '100%',
boxSizing: 'border-box'
});
const useUtilityClasses = ownerState => {
const {
classes,
variant,
disabled,
multiple,
open,
error
} = ownerState;
const slots = {
select: ['select', variant, disabled && 'disabled', multiple && 'multiple', error && 'error'],
icon: ['icon', open && 'iconOpen', disabled && 'disabled'],
nativeInput: ['nativeInput']
};
return (0, _composeClasses.default)(slots, _selectClasses.getSelectUtilityClasses, classes);
};
/**
* @ignore - internal component.
*/
const SelectInput = /*#__PURE__*/React.forwardRef(function SelectInput(props, ref) {
const {
'aria-describedby': ariaDescribedby,
'aria-label': ariaLabel,
autoFocus,
autoWidth,
children,
className,
defaultOpen,
defaultValue,
disabled,
displayEmpty,
error = false,
IconComponent,
inputRef: inputRefProp,
labelId,
MenuProps = {},
multiple,
name,
onBlur,
onChange,
onClose,
onFocus,
// eslint-disable-next-line react/prop-types
onKeyDown,
// eslint-disable-next-line react/prop-types
onMouseDown,
onOpen,
open: openProp,
readOnly,
renderValue,
required,
SelectDisplayProps = {},
tabIndex: tabIndexProp,
// catching `type` from Input which makes no sense for SelectInput
type,
value: valueProp,
variant = 'standard',
...other
} = props;
const [value, setValueState] = (0, _useControlled.default)({
controlled: valueProp,
default: defaultValue,
name: 'Select'
});
const [openState, setOpenState] = (0, _useControlled.default)({
controlled: openProp,
default: defaultOpen,
name: 'Select'
});
const inputRef = React.useRef(null);
const displayRef = React.useRef(null);
const paperRef = React.useRef(null);
const openRef = React.useRef(false);
const hasSelectedItemInListRef = React.useRef(false);
const openingMouseUpListenerCleanupRef = React.useRef(null);
const didPointerDownOnItemRef = React.useRef(false);
const selectionRef = React.useRef({
allowSelectedMouseUp: false,
allowUnselectedMouseUp: false
});
const closedTypeaheadRef = React.useRef({
buffer: '',
previousSearchIndex: null,
matchedIndex: null
});
const selectedMouseUpTimer = (0, _useTimeout.default)();
const unselectedMouseUpTimer = (0, _useTimeout.default)();
const typeaheadResetTimer = (0, _useTimeout.default)();
const [displayNode, setDisplayNode] = React.useState(null);
const {
current: isOpenControlled
} = React.useRef(openProp != null);
const [menuMinWidthState, setMenuMinWidthState] = React.useState();
const [openInteractionType, setOpenInteractionType] = React.useState(null);
const handleRef = (0, _useForkRef.default)(ref, inputRefProp);
const handleDisplayRef = React.useCallback(node => {
displayRef.current = node;
if (node) {
setDisplayNode(node);
}
}, []);
const anchorElement = displayNode?.parentNode;
React.useImperativeHandle(handleRef, () => ({
focus: () => {
displayRef.current.focus();
},
node: inputRef.current,
value
}), [value]);
const open = displayNode !== null && openState;
const resetClosedTypeahead = React.useCallback(() => {
typeaheadResetTimer.clear();
closedTypeaheadRef.current.buffer = '';
closedTypeaheadRef.current.previousSearchIndex = null;
closedTypeaheadRef.current.matchedIndex = null;
}, [typeaheadResetTimer]);
(0, _useEnhancedEffect.default)(() => {
openRef.current = open;
if (open) {
resetClosedTypeahead();
}
}, [open, resetClosedTypeahead]);
const clearSelectionTimers = React.useCallback(() => {
selectedMouseUpTimer.clear();
unselectedMouseUpTimer.clear();
}, [selectedMouseUpTimer, unselectedMouseUpTimer]);
const resetMouseUpSelection = React.useCallback(() => {
clearSelectionTimers();
didPointerDownOnItemRef.current = false;
selectionRef.current = {
allowSelectedMouseUp: false,
allowUnselectedMouseUp: false
};
}, [clearSelectionTimers]);
const clearOpeningMouseUpListener = React.useCallback(() => {
if (openingMouseUpListenerCleanupRef.current) {
openingMouseUpListenerCleanupRef.current();
openingMouseUpListenerCleanupRef.current = null;
}
}, []);
React.useEffect(() => {
if (!open) {
resetMouseUpSelection();
clearOpeningMouseUpListener();
}
}, [open, resetMouseUpSelection, clearOpeningMouseUpListener]);
// Keep unmount cleanup separate from the `open` effect. Effect cleanups also run
// before the next effect, which would clear the opening mouseup listener while opening.
React.useEffect(() => {
return () => {
resetMouseUpSelection();
clearOpeningMouseUpListener();
resetClosedTypeahead();
};
}, [resetMouseUpSelection, clearOpeningMouseUpListener, resetClosedTypeahead]);
React.useEffect(() => {
if (!open || !anchorElement || autoWidth) {
return undefined;
}
if (typeof ResizeObserver === 'undefined') {
return undefined;
}
const observer = new ResizeObserver(() => {
setMenuMinWidthState(anchorElement.clientWidth);
});
observer.observe(anchorElement);
return () => {
observer.disconnect();
};
}, [open, anchorElement, autoWidth]);
// Resize menu on `defaultOpen` automatic toggle.
React.useEffect(() => {
if (defaultOpen && openState && displayNode && !isOpenControlled) {
setMenuMinWidthState(autoWidth ? null : anchorElement.clientWidth);
displayRef.current.focus();
}
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [displayNode, autoWidth]);
// `isOpenControlled` is ignored because the component should never switch between controlled and uncontrolled modes.
// `defaultOpen` and `openState` are ignored to avoid unnecessary callbacks.
React.useEffect(() => {
if (autoFocus) {
displayRef.current.focus();
}
}, [autoFocus]);
React.useEffect(() => {
if (!labelId) {
return undefined;
}
const label = (0, _ownerDocument.default)(displayRef.current).getElementById(labelId);
if (label) {
const handler = () => {
if (getSelection().isCollapsed) {
displayRef.current.focus();
}
};
label.addEventListener('click', handler);
return () => {
label.removeEventListener('click', handler);
};
}
return undefined;
}, [labelId]);
const update = (0, _useEventCallback.default)((openParam, event) => {
if (!openParam) {
resetMouseUpSelection();
clearOpeningMouseUpListener();
}
if (openParam) {
resetClosedTypeahead();
setOpenInteractionType((0, _utils2.getOpenInteractionType)(event));
if (onOpen) {
onOpen(event);
}
} else {
setOpenInteractionType(null);
if (onClose) {
onClose(event);
}
}
if (!isOpenControlled) {
openRef.current = openParam;
setMenuMinWidthState(autoWidth ? null : anchorElement.clientWidth);
setOpenState(openParam);
}
});
const scheduleMouseUpSelection = () => {
resetMouseUpSelection();
// When there is no selected item in the list, a mousedown
// on the trigger followed by a quick mouseup over the first option can accidentally select
// within 200ms. Delay unselected mouseup to match the safer 400ms window.
if (!hasSelectedItemInListRef.current) {
selectedMouseUpTimer.start(SELECTED_MOUSE_UP_DELAY, () => {
selectionRef.current.allowSelectedMouseUp = true;
selectionRef.current.allowUnselectedMouseUp = true;
});
} else {
// mousedown -> move to unselected item -> mouseup should not select within 200ms.
unselectedMouseUpTimer.start(UNSELECTED_MOUSE_UP_DELAY, () => {
selectionRef.current.allowUnselectedMouseUp = true;
// mousedown -> mouseup on selected item should not select within 400ms.
selectedMouseUpTimer.start(UNSELECTED_MOUSE_UP_DELAY, () => {
selectionRef.current.allowSelectedMouseUp = true;
});
});
}
};
const handleMouseDown = event => {
onMouseDown?.(event);
// Ignore everything but left-click
if (event.button !== 0) {
return;
}
// Hijack the default focus behavior.
event.preventDefault();
if (!displayRef.current) {
return;
}
displayRef.current.focus();
const doc = (0, _ownerDocument.default)(event.currentTarget);
scheduleMouseUpSelection();
clearOpeningMouseUpListener();
const handleMouseUp = mouseEvent => {
openingMouseUpListenerCleanupRef.current = null;
if (!displayRef.current) {
return;
}
if (isMouseEventInsideElement(mouseEvent, displayRef.current) || isMouseEventInsideElement(mouseEvent, paperRef.current)) {
return;
}
if (!openRef.current && isOpenControlled) {
return;
}
update(false, mouseEvent);
};
doc.addEventListener('mouseup', handleMouseUp, {
capture: true,
once: true
});
openingMouseUpListenerCleanupRef.current = () => {
doc.removeEventListener('mouseup', handleMouseUp, true);
};
update(true, event);
};
const handleClose = event => {
update(false, event);
};
const childrenArray = React.Children.toArray(children);
// Support autofill.
const handleChange = event => {
const child = childrenArray.find(childItem => childItem.props.value === event.target.value);
if (child === undefined) {
return;
}
setValueState(child.props.value);
if (onChange) {
onChange(event, child);
}
};
const handleValueChange = (event, child, newValue) => {
setValueState(newValue);
if (onChange) {
// Redefine target to allow name and value to be read.
// This allows seamless integration with the most popular form libraries.
// https://github.com/mui/material-ui/issues/13485#issuecomment-676048492
// Clone the event to not override `target` of the original event.
const nativeEvent = event.nativeEvent || event;
const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
Object.defineProperty(clonedEvent, 'target', {
writable: true,
value: {
value: newValue,
name
}
});
onChange(clonedEvent, child);
}
};
const handleItemClick = child => event => {
didPointerDownOnItemRef.current = false;
let newValue;
// We use the tabindex attribute to signal the available options.
if (!event.currentTarget.hasAttribute('tabindex')) {
return;
}
if (multiple) {
newValue = Array.isArray(value) ? value.slice() : [];
const itemIndex = value.indexOf(child.props.value);
if (itemIndex === -1) {
newValue.push(child.props.value);
} else {
newValue.splice(itemIndex, 1);
}
} else {
newValue = child.props.value;
}
if (child.props.onClick) {
child.props.onClick(event);
}
if (value !== newValue) {
handleValueChange(event, child, newValue);
}
if (!multiple) {
update(false, event);
}
};
const handleItemMouseUp = (child, selected) => event => {
child.props.onMouseUp?.(event);
if (didPointerDownOnItemRef.current) {
didPointerDownOnItemRef.current = false;
return;
}
const disallowSelectedMouseUp = !selectionRef.current.allowSelectedMouseUp && selected;
const disallowUnselectedMouseUp = !selectionRef.current.allowUnselectedMouseUp && !selected;
if (disallowSelectedMouseUp || disallowUnselectedMouseUp) {
return;
}
event.currentTarget.click();
};
const handleClosedTypeahead = event => {
const state = closedTypeaheadRef.current;
const hasActiveBuffer = state.buffer !== '';
if (open || multiple || disabled || event.defaultPrevented || event.nativeEvent?.isComposing || event.key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey || event.key === SPACE && !hasActiveBuffer) {
return false;
}
if (event.key === SPACE) {
event.preventDefault();
}
const isNewSession = state.buffer === '';
const {
options: searchableOptions,
selectedIndex
} = (0, _closedTypeahead.getTypeaheadOptions)(childrenArray, value);
if (searchableOptions.length === 0) {
if (event.key !== SPACE) {
resetClosedTypeahead();
}
return true;
}
if (isNewSession) {
state.previousSearchIndex = selectedIndex;
}
const key = event.key.toLowerCase();
if (state.buffer === key && (0, _closedTypeahead.canCycleRepeatedCharacter)(searchableOptions, key)) {
state.buffer = '';
state.previousSearchIndex = state.matchedIndex;
}
state.buffer += key;
typeaheadResetTimer.start(TYPEAHEAD_RESET_MS, resetClosedTypeahead);
const matchingIndex = (0, _closedTypeahead.getMatchingOptionIndex)(searchableOptions, state.buffer, (state.previousSearchIndex ?? -1) + 1);
if (matchingIndex !== -1) {
const matchedOption = searchableOptions[matchingIndex];
state.matchedIndex = matchingIndex;
if (!(0, _utils2.areEqualValues)(value, matchedOption.value)) {
handleValueChange(event, matchedOption.child, matchedOption.value);
}
return true;
}
if (event.key !== SPACE) {
resetClosedTypeahead();
}
return true;
};
const handleKeyDown = event => {
if (!readOnly) {
const isClosedTypeaheadHandled = handleClosedTypeahead(event);
// The native select doesn't respond to Enter on macOS, but it's recommended by
// https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/
const isOpenKey = event.key === SPACE || event.key === ARROW_UP || event.key === ARROW_DOWN || event.key === ENTER;
if (!isClosedTypeaheadHandled && isOpenKey) {
event.preventDefault();
update(true, event);
}
onKeyDown?.(event);
}
};
const handleBlur = event => {
resetClosedTypeahead();
// if open event.stopImmediatePropagation
if (!open && onBlur) {
// Preact support, target is read only property on a native event.
Object.defineProperty(event, 'target', {
writable: true,
value: {
value,
name
}
});
onBlur(event);
}
};
const handleItemKeyDown = child => event => {
child?.props?.onKeyDown?.(event);
if (event.key === SPACE && event.target === event.currentTarget && !event.defaultPrevented) {
// Prevent the browser from scrolling the page
event.preventDefault();
// Ignore auto-repeated keydowns to avoid toggling multiple times
if (!event.repeat) {
// Trigger via click so that onClick receives a click event,
// consistent with Enter and pointer interactions.
event.currentTarget.click();
}
}
};
delete other['aria-invalid'];
let display;
let displaySingle;
const displayMultiple = [];
let computeDisplay = false;
let foundMatch = false;
// No need to display any value if the field is empty.
if ((0, _utils.isFilled)({
value
}) || displayEmpty) {
if (renderValue) {
display = renderValue(value);
} else {
computeDisplay = true;
}
}
const items = childrenArray.map(child => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if ((0, _reactIs.isFragment)(child)) {
console.error(["MUI: The Select component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
let selected;
if (multiple) {
if (!Array.isArray(value)) {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI: The `value` prop must be an array ' + 'when using the `Select` component with `multiple`.' : (0, _formatMuiErrorMessage.default)(2));
}
selected = value.some(v => (0, _utils2.areEqualValues)(v, child.props.value));
if (selected && computeDisplay) {
displayMultiple.push(child.props.children);
}
} else {
selected = (0, _utils2.areEqualValues)(value, child.props.value);
if (selected && computeDisplay) {
displaySingle = child.props.children;
}
}
if (selected) {
foundMatch = true;
}
return /*#__PURE__*/React.cloneElement(child, {
'aria-selected': selected ? 'true' : 'false',
onMouseDown: event => {
didPointerDownOnItemRef.current = true;
child.props.onMouseDown?.(event);
},
onPointerDown: event => {
didPointerDownOnItemRef.current = true;
child.props.onPointerDown?.(event);
},
onClick: handleItemClick(child),
onMouseUp: handleItemMouseUp(child, selected),
onKeyUp: event => {
if (event.key === SPACE) {
// otherwise our MenuItems dispatches a click event
// it's not behavior of the native <option> and causes
// the select to close immediately since we open on space keydown
event.preventDefault();
}
if (child.props.onKeyUp) {
child.props.onKeyUp(event);
}
},
onKeyDown: handleItemKeyDown(child),
role: 'option',
selected,
value: undefined,
// The value is most likely not a valid HTML attribute.
'data-value': child.props.value // Instead, we provide it as a data attribute.
});
});
// Keep the opening mouseup guard current without mutating refs during render.
(0, _useEnhancedEffect.default)(() => {
hasSelectedItemInListRef.current = foundMatch;
if (!open && !multiple && !foundMatch) {
resetClosedTypeahead();
}
}, [foundMatch, multiple, open, resetClosedTypeahead]);
if (process.env.NODE_ENV !== 'production') {
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (!foundMatch && !multiple && value !== '') {
const values = childrenArray.map(child => child.props.value);
console.warn([`MUI: You have provided an out-of-range value \`${value}\` for the select ${name ? `(name="${name}") ` : ''}component.`, "Consider providing a value that matches one of the available options or ''.", `The available values are ${values.filter(x => x != null).map(x => `\`${x}\``).join(', ') || '""'}.`].join('\n'));
}
}, [foundMatch, childrenArray, multiple, name, value]);
}
if (computeDisplay) {
if (multiple) {
if (displayMultiple.length === 0) {
display = null;
} else {
display = displayMultiple.reduce((output, child, index) => {
output.push(child);
if (index < displayMultiple.length - 1) {
output.push(', ');
}
return output;
}, []);
}
} else {
display = displaySingle;
}
}
// Avoid performing a layout computation in the render method.
let menuMinWidth = menuMinWidthState;
if (!autoWidth && isOpenControlled && displayNode) {
menuMinWidth = anchorElement.clientWidth;
}
let tabIndex;
if (typeof tabIndexProp !== 'undefined') {
tabIndex = tabIndexProp;
} else {
tabIndex = disabled ? null : 0;
}
const buttonId = SelectDisplayProps.id || (name ? `mui-component-select-${name}` : undefined);
const ownerState = {
...props,
variant,
value,
open,
error
};
const classes = useUtilityClasses(ownerState);
const menuPaperSlotProps = typeof MenuProps.slotProps?.paper === 'function' ? MenuProps.slotProps.paper(ownerState) : MenuProps.slotProps?.paper;
const handlePaperRef = (0, _useForkRef.default)(menuPaperSlotProps?.ref, paperRef);
const menuListSlotProps = typeof MenuProps.slotProps?.list === 'function' ? MenuProps.slotProps.list(ownerState) : MenuProps.slotProps?.list;
const listboxId = (0, _useId.default)();
const nativeInputId = (0, _useId.default)();
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SelectSelect, {
as: "div",
ref: handleDisplayRef,
tabIndex: tabIndex,
role: "combobox",
"aria-controls": open ? listboxId : undefined,
"aria-disabled": disabled ? 'true' : undefined,
"aria-expanded": open ? 'true' : 'false',
"aria-haspopup": "listbox",
"aria-readonly": readOnly ? 'true' : undefined,
"aria-label": ariaLabel,
"aria-labelledby": labelId,
"aria-describedby": ariaDescribedby,
"aria-required": required ? 'true' : undefined,
"aria-invalid": error ? 'true' : undefined,
onKeyDown: handleKeyDown,
onMouseDown: disabled || readOnly ? null : handleMouseDown,
onBlur: handleBlur,
onFocus: onFocus,
...SelectDisplayProps,
ownerState: ownerState,
className: (0, _clsx.default)(SelectDisplayProps.className, classes.select, className)
// The id is required for proper a11y
,
id: buttonId,
children: (0, _utils2.isEmpty)(display) ? // notranslate needed while Google Translate will not fix zero-width space issue
_span || (_span = /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
className: "notranslate",
"aria-hidden": true,
children: "\u200B"
})) : display
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(SelectNativeInput, {
"aria-invalid": error,
value: Array.isArray(value) ? value.join(',') : value,
name: name,
ref: inputRef,
"aria-hidden": true,
onChange: handleChange,
tabIndex: -1,
disabled: disabled,
readOnly: readOnly,
className: classes.nativeInput,
autoFocus: autoFocus,
required: required,
...other,
id: other.id ?? nativeInputId,
ownerState: ownerState
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(SelectIcon, {
as: IconComponent,
className: classes.icon,
ownerState: ownerState
}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_SelectFocusSourceContext.SelectFocusSourceProvider, {
value: openInteractionType,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.default, {
id: `menu-${name || ''}`,
anchorEl: anchorElement,
open: open,
onClose: handleClose,
anchorOrigin: {
vertical: 'bottom',
horizontal: 'center'
},
transformOrigin: {
vertical: 'top',
horizontal: 'center'
},
...MenuProps,
slotProps: {
...MenuProps.slotProps,
list: {
'aria-labelledby': labelId,
role: 'listbox',
'aria-multiselectable': multiple ? 'true' : undefined,
disableListWrap: true,
id: listboxId,
...menuListSlotProps
},
paper: {
...menuPaperSlotProps,
ref: handlePaperRef,
style: {
minWidth: menuMinWidth,
...menuPaperSlotProps?.style
}
}
},
children: items
})
})]
});
});
process.env.NODE_ENV !== "production" ? SelectInput.propTypes = {
/**
* @ignore
*/
'aria-describedby': _propTypes.default.string,
/**
* @ignore
*/
'aria-label': _propTypes.default.string,
/**
* @ignore
*/
autoFocus: _propTypes.default.bool,
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
*/
autoWidth: _propTypes.default.bool,
/**
* The option elements to populate the select with.
* Can be some `<MenuItem>` elements.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* The CSS class name of the select element.
*/
className: _propTypes.default.string,
/**
* If `true`, the component is toggled on mount. Use when the component open state is not controlled.
* You can only use it when the `native` prop is `false` (default).
*/
defaultOpen: _propTypes.default.bool,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: _propTypes.default.any,
/**
* If `true`, the select is disabled.
*/
disabled: _propTypes.default.bool,
/**
* If `true`, the selected item is displayed even if its value is empty.
*/
displayEmpty: _propTypes.default.bool,
/**
* If `true`, the `select input` will indicate an error.
*/
error: _propTypes.default.bool,
/**
* The icon that displays the arrow.
*/
IconComponent: _propTypes.default.elementType.isRequired,
/**
* Imperative handle implementing `{ value: T, node: HTMLElement, focus(): void }`
* Equivalent to `ref`
*/
inputRef: _refType.default,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: _propTypes.default.string,
/**
* Props applied to the [`Menu`](/material-ui/api/menu/) element.
*/
MenuProps: _propTypes.default.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
*/
multiple: _propTypes.default.bool,
/**
* Name attribute of the `select` or hidden `input` element.
*/
name: _propTypes.default.string,
/**
* @ignore
*/
onBlur: _propTypes.default.func,
/**
* Callback fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* @param {object} [child] The react element that was selected.
*/
onChange: _propTypes.default.func,
/**
* Callback fired when the component requests to be closed.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onClose: _propTypes.default.func,
/**
* @ignore
*/
onFocus: _propTypes.default.func,
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onOpen: _propTypes.default.func,
/**
* If `true`, the component is shown.
*/
open: _propTypes.default.bool,
/**
* @ignore
*/
readOnly: _propTypes.default.bool,
/**
* Render the selected value.
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: _propTypes.default.func,
/**
* If `true`, the component is required.
*/
required: _propTypes.default.bool,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: _propTypes.default.object,
/**
* @ignore
*/
tabIndex: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),
/**
* @ignore
*/
type: _propTypes.default.any,
/**
* The input value.
*/
value: _propTypes.default.any,
/**
* The variant to use.
*/
variant: _propTypes.default.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
var _default = exports.default = SelectInput;
+946
View File
@@ -0,0 +1,946 @@
'use client';
import _formatErrorMessage from "@mui/utils/formatMuiErrorMessage";
var _span;
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import composeClasses from '@mui/utils/composeClasses';
import useId from '@mui/utils/useId';
import refType from '@mui/utils/refType';
import useTimeout from '@mui/utils/useTimeout';
import ownerDocument from "../utils/ownerDocument.mjs";
import Menu from "../Menu/Menu.mjs";
import { StyledSelectSelect, StyledSelectIcon } from "../NativeSelect/NativeSelectInput.mjs";
import { isFilled } from "../InputBase/utils.mjs";
import { styled } from "../zero-styled/index.mjs";
import slotShouldForwardProp from "../styles/slotShouldForwardProp.mjs";
import useEnhancedEffect from "../utils/useEnhancedEffect.mjs";
import useEventCallback from "../utils/useEventCallback.mjs";
import useForkRef from "../utils/useForkRef.mjs";
import useControlled from "../utils/useControlled.mjs";
import selectClasses, { getSelectUtilityClasses } from "./selectClasses.mjs";
import { areEqualValues, isEmpty, getOpenInteractionType } from "./utils/index.mjs";
import { canCycleRepeatedCharacter, getMatchingOptionIndex, getTypeaheadOptions } from "./utils/closedTypeahead.mjs";
import { SelectFocusSourceProvider } from "./utils/SelectFocusSourceContext.mjs";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const OPENING_MOUSE_UP_BOUNDARY_OFFSET = 2;
// The initial mouseup may land on an item when the menu opens over the trigger.
const SELECTED_MOUSE_UP_DELAY = 400;
const UNSELECTED_MOUSE_UP_DELAY = 200;
const TYPEAHEAD_RESET_MS = 750;
const SPACE = ' ';
const ARROW_UP = 'ArrowUp';
const ARROW_DOWN = 'ArrowDown';
const ENTER = 'Enter';
/**
* Returns true when a native mouse event should be treated as happening inside
* the element, even if a portal or backdrop retargeted the event away from it.
*
* Select uses this for the opening mouseup: when the menu opens over the
* trigger, the release can target the backdrop or portaled menu even though the
* pointer is still inside the trigger or menu bounds.
*/
function isMouseEventInsideElement(event, element) {
if (!element) {
return false;
}
const eventPath = event.composedPath();
if (eventPath.includes(element)) {
return true;
}
if (event.target?.nodeType && element.contains(event.target)) {
return true;
}
const rect = element.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) {
// Hidden or transition-mounted elements do not have useful bounds to hit-test.
return false;
}
return event.clientX >= rect.left - OPENING_MOUSE_UP_BOUNDARY_OFFSET && event.clientX <= rect.right + OPENING_MOUSE_UP_BOUNDARY_OFFSET && event.clientY >= rect.top - OPENING_MOUSE_UP_BOUNDARY_OFFSET && event.clientY <= rect.bottom + OPENING_MOUSE_UP_BOUNDARY_OFFSET;
}
const SelectSelect = styled(StyledSelectSelect, {
name: 'MuiSelect',
slot: 'Select',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [
// Win specificity over the input base
{
[`&.${selectClasses.select}`]: styles.select
}, {
[`&.${selectClasses.select}`]: styles[ownerState.variant]
}, {
[`&.${selectClasses.error}`]: styles.error
}, {
[`&.${selectClasses.multiple}`]: styles.multiple
}];
}
})({
// Win specificity over the input base
[`&.${selectClasses.select}`]: {
height: 'auto',
// Resets for multiple select with chips
minHeight: '1.4375em',
// Required for select\text-field height consistency
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden'
}
});
const SelectIcon = styled(StyledSelectIcon, {
name: 'MuiSelect',
slot: 'Icon',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.icon, ownerState.open && styles.iconOpen];
}
})({});
const SelectNativeInput = styled('input', {
shouldForwardProp: prop => slotShouldForwardProp(prop) && prop !== 'classes',
name: 'MuiSelect',
slot: 'NativeInput'
})({
bottom: 0,
left: 0,
position: 'absolute',
opacity: 0,
pointerEvents: 'none',
width: '100%',
boxSizing: 'border-box'
});
const useUtilityClasses = ownerState => {
const {
classes,
variant,
disabled,
multiple,
open,
error
} = ownerState;
const slots = {
select: ['select', variant, disabled && 'disabled', multiple && 'multiple', error && 'error'],
icon: ['icon', open && 'iconOpen', disabled && 'disabled'],
nativeInput: ['nativeInput']
};
return composeClasses(slots, getSelectUtilityClasses, classes);
};
/**
* @ignore - internal component.
*/
const SelectInput = /*#__PURE__*/React.forwardRef(function SelectInput(props, ref) {
const {
'aria-describedby': ariaDescribedby,
'aria-label': ariaLabel,
autoFocus,
autoWidth,
children,
className,
defaultOpen,
defaultValue,
disabled,
displayEmpty,
error = false,
IconComponent,
inputRef: inputRefProp,
labelId,
MenuProps = {},
multiple,
name,
onBlur,
onChange,
onClose,
onFocus,
// eslint-disable-next-line react/prop-types
onKeyDown,
// eslint-disable-next-line react/prop-types
onMouseDown,
onOpen,
open: openProp,
readOnly,
renderValue,
required,
SelectDisplayProps = {},
tabIndex: tabIndexProp,
// catching `type` from Input which makes no sense for SelectInput
type,
value: valueProp,
variant = 'standard',
...other
} = props;
const [value, setValueState] = useControlled({
controlled: valueProp,
default: defaultValue,
name: 'Select'
});
const [openState, setOpenState] = useControlled({
controlled: openProp,
default: defaultOpen,
name: 'Select'
});
const inputRef = React.useRef(null);
const displayRef = React.useRef(null);
const paperRef = React.useRef(null);
const openRef = React.useRef(false);
const hasSelectedItemInListRef = React.useRef(false);
const openingMouseUpListenerCleanupRef = React.useRef(null);
const didPointerDownOnItemRef = React.useRef(false);
const selectionRef = React.useRef({
allowSelectedMouseUp: false,
allowUnselectedMouseUp: false
});
const closedTypeaheadRef = React.useRef({
buffer: '',
previousSearchIndex: null,
matchedIndex: null
});
const selectedMouseUpTimer = useTimeout();
const unselectedMouseUpTimer = useTimeout();
const typeaheadResetTimer = useTimeout();
const [displayNode, setDisplayNode] = React.useState(null);
const {
current: isOpenControlled
} = React.useRef(openProp != null);
const [menuMinWidthState, setMenuMinWidthState] = React.useState();
const [openInteractionType, setOpenInteractionType] = React.useState(null);
const handleRef = useForkRef(ref, inputRefProp);
const handleDisplayRef = React.useCallback(node => {
displayRef.current = node;
if (node) {
setDisplayNode(node);
}
}, []);
const anchorElement = displayNode?.parentNode;
React.useImperativeHandle(handleRef, () => ({
focus: () => {
displayRef.current.focus();
},
node: inputRef.current,
value
}), [value]);
const open = displayNode !== null && openState;
const resetClosedTypeahead = React.useCallback(() => {
typeaheadResetTimer.clear();
closedTypeaheadRef.current.buffer = '';
closedTypeaheadRef.current.previousSearchIndex = null;
closedTypeaheadRef.current.matchedIndex = null;
}, [typeaheadResetTimer]);
useEnhancedEffect(() => {
openRef.current = open;
if (open) {
resetClosedTypeahead();
}
}, [open, resetClosedTypeahead]);
const clearSelectionTimers = React.useCallback(() => {
selectedMouseUpTimer.clear();
unselectedMouseUpTimer.clear();
}, [selectedMouseUpTimer, unselectedMouseUpTimer]);
const resetMouseUpSelection = React.useCallback(() => {
clearSelectionTimers();
didPointerDownOnItemRef.current = false;
selectionRef.current = {
allowSelectedMouseUp: false,
allowUnselectedMouseUp: false
};
}, [clearSelectionTimers]);
const clearOpeningMouseUpListener = React.useCallback(() => {
if (openingMouseUpListenerCleanupRef.current) {
openingMouseUpListenerCleanupRef.current();
openingMouseUpListenerCleanupRef.current = null;
}
}, []);
React.useEffect(() => {
if (!open) {
resetMouseUpSelection();
clearOpeningMouseUpListener();
}
}, [open, resetMouseUpSelection, clearOpeningMouseUpListener]);
// Keep unmount cleanup separate from the `open` effect. Effect cleanups also run
// before the next effect, which would clear the opening mouseup listener while opening.
React.useEffect(() => {
return () => {
resetMouseUpSelection();
clearOpeningMouseUpListener();
resetClosedTypeahead();
};
}, [resetMouseUpSelection, clearOpeningMouseUpListener, resetClosedTypeahead]);
React.useEffect(() => {
if (!open || !anchorElement || autoWidth) {
return undefined;
}
if (typeof ResizeObserver === 'undefined') {
return undefined;
}
const observer = new ResizeObserver(() => {
setMenuMinWidthState(anchorElement.clientWidth);
});
observer.observe(anchorElement);
return () => {
observer.disconnect();
};
}, [open, anchorElement, autoWidth]);
// Resize menu on `defaultOpen` automatic toggle.
React.useEffect(() => {
if (defaultOpen && openState && displayNode && !isOpenControlled) {
setMenuMinWidthState(autoWidth ? null : anchorElement.clientWidth);
displayRef.current.focus();
}
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [displayNode, autoWidth]);
// `isOpenControlled` is ignored because the component should never switch between controlled and uncontrolled modes.
// `defaultOpen` and `openState` are ignored to avoid unnecessary callbacks.
React.useEffect(() => {
if (autoFocus) {
displayRef.current.focus();
}
}, [autoFocus]);
React.useEffect(() => {
if (!labelId) {
return undefined;
}
const label = ownerDocument(displayRef.current).getElementById(labelId);
if (label) {
const handler = () => {
if (getSelection().isCollapsed) {
displayRef.current.focus();
}
};
label.addEventListener('click', handler);
return () => {
label.removeEventListener('click', handler);
};
}
return undefined;
}, [labelId]);
const update = useEventCallback((openParam, event) => {
if (!openParam) {
resetMouseUpSelection();
clearOpeningMouseUpListener();
}
if (openParam) {
resetClosedTypeahead();
setOpenInteractionType(getOpenInteractionType(event));
if (onOpen) {
onOpen(event);
}
} else {
setOpenInteractionType(null);
if (onClose) {
onClose(event);
}
}
if (!isOpenControlled) {
openRef.current = openParam;
setMenuMinWidthState(autoWidth ? null : anchorElement.clientWidth);
setOpenState(openParam);
}
});
const scheduleMouseUpSelection = () => {
resetMouseUpSelection();
// When there is no selected item in the list, a mousedown
// on the trigger followed by a quick mouseup over the first option can accidentally select
// within 200ms. Delay unselected mouseup to match the safer 400ms window.
if (!hasSelectedItemInListRef.current) {
selectedMouseUpTimer.start(SELECTED_MOUSE_UP_DELAY, () => {
selectionRef.current.allowSelectedMouseUp = true;
selectionRef.current.allowUnselectedMouseUp = true;
});
} else {
// mousedown -> move to unselected item -> mouseup should not select within 200ms.
unselectedMouseUpTimer.start(UNSELECTED_MOUSE_UP_DELAY, () => {
selectionRef.current.allowUnselectedMouseUp = true;
// mousedown -> mouseup on selected item should not select within 400ms.
selectedMouseUpTimer.start(UNSELECTED_MOUSE_UP_DELAY, () => {
selectionRef.current.allowSelectedMouseUp = true;
});
});
}
};
const handleMouseDown = event => {
onMouseDown?.(event);
// Ignore everything but left-click
if (event.button !== 0) {
return;
}
// Hijack the default focus behavior.
event.preventDefault();
if (!displayRef.current) {
return;
}
displayRef.current.focus();
const doc = ownerDocument(event.currentTarget);
scheduleMouseUpSelection();
clearOpeningMouseUpListener();
const handleMouseUp = mouseEvent => {
openingMouseUpListenerCleanupRef.current = null;
if (!displayRef.current) {
return;
}
if (isMouseEventInsideElement(mouseEvent, displayRef.current) || isMouseEventInsideElement(mouseEvent, paperRef.current)) {
return;
}
if (!openRef.current && isOpenControlled) {
return;
}
update(false, mouseEvent);
};
doc.addEventListener('mouseup', handleMouseUp, {
capture: true,
once: true
});
openingMouseUpListenerCleanupRef.current = () => {
doc.removeEventListener('mouseup', handleMouseUp, true);
};
update(true, event);
};
const handleClose = event => {
update(false, event);
};
const childrenArray = React.Children.toArray(children);
// Support autofill.
const handleChange = event => {
const child = childrenArray.find(childItem => childItem.props.value === event.target.value);
if (child === undefined) {
return;
}
setValueState(child.props.value);
if (onChange) {
onChange(event, child);
}
};
const handleValueChange = (event, child, newValue) => {
setValueState(newValue);
if (onChange) {
// Redefine target to allow name and value to be read.
// This allows seamless integration with the most popular form libraries.
// https://github.com/mui/material-ui/issues/13485#issuecomment-676048492
// Clone the event to not override `target` of the original event.
const nativeEvent = event.nativeEvent || event;
const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
Object.defineProperty(clonedEvent, 'target', {
writable: true,
value: {
value: newValue,
name
}
});
onChange(clonedEvent, child);
}
};
const handleItemClick = child => event => {
didPointerDownOnItemRef.current = false;
let newValue;
// We use the tabindex attribute to signal the available options.
if (!event.currentTarget.hasAttribute('tabindex')) {
return;
}
if (multiple) {
newValue = Array.isArray(value) ? value.slice() : [];
const itemIndex = value.indexOf(child.props.value);
if (itemIndex === -1) {
newValue.push(child.props.value);
} else {
newValue.splice(itemIndex, 1);
}
} else {
newValue = child.props.value;
}
if (child.props.onClick) {
child.props.onClick(event);
}
if (value !== newValue) {
handleValueChange(event, child, newValue);
}
if (!multiple) {
update(false, event);
}
};
const handleItemMouseUp = (child, selected) => event => {
child.props.onMouseUp?.(event);
if (didPointerDownOnItemRef.current) {
didPointerDownOnItemRef.current = false;
return;
}
const disallowSelectedMouseUp = !selectionRef.current.allowSelectedMouseUp && selected;
const disallowUnselectedMouseUp = !selectionRef.current.allowUnselectedMouseUp && !selected;
if (disallowSelectedMouseUp || disallowUnselectedMouseUp) {
return;
}
event.currentTarget.click();
};
const handleClosedTypeahead = event => {
const state = closedTypeaheadRef.current;
const hasActiveBuffer = state.buffer !== '';
if (open || multiple || disabled || event.defaultPrevented || event.nativeEvent?.isComposing || event.key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey || event.key === SPACE && !hasActiveBuffer) {
return false;
}
if (event.key === SPACE) {
event.preventDefault();
}
const isNewSession = state.buffer === '';
const {
options: searchableOptions,
selectedIndex
} = getTypeaheadOptions(childrenArray, value);
if (searchableOptions.length === 0) {
if (event.key !== SPACE) {
resetClosedTypeahead();
}
return true;
}
if (isNewSession) {
state.previousSearchIndex = selectedIndex;
}
const key = event.key.toLowerCase();
if (state.buffer === key && canCycleRepeatedCharacter(searchableOptions, key)) {
state.buffer = '';
state.previousSearchIndex = state.matchedIndex;
}
state.buffer += key;
typeaheadResetTimer.start(TYPEAHEAD_RESET_MS, resetClosedTypeahead);
const matchingIndex = getMatchingOptionIndex(searchableOptions, state.buffer, (state.previousSearchIndex ?? -1) + 1);
if (matchingIndex !== -1) {
const matchedOption = searchableOptions[matchingIndex];
state.matchedIndex = matchingIndex;
if (!areEqualValues(value, matchedOption.value)) {
handleValueChange(event, matchedOption.child, matchedOption.value);
}
return true;
}
if (event.key !== SPACE) {
resetClosedTypeahead();
}
return true;
};
const handleKeyDown = event => {
if (!readOnly) {
const isClosedTypeaheadHandled = handleClosedTypeahead(event);
// The native select doesn't respond to Enter on macOS, but it's recommended by
// https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/
const isOpenKey = event.key === SPACE || event.key === ARROW_UP || event.key === ARROW_DOWN || event.key === ENTER;
if (!isClosedTypeaheadHandled && isOpenKey) {
event.preventDefault();
update(true, event);
}
onKeyDown?.(event);
}
};
const handleBlur = event => {
resetClosedTypeahead();
// if open event.stopImmediatePropagation
if (!open && onBlur) {
// Preact support, target is read only property on a native event.
Object.defineProperty(event, 'target', {
writable: true,
value: {
value,
name
}
});
onBlur(event);
}
};
const handleItemKeyDown = child => event => {
child?.props?.onKeyDown?.(event);
if (event.key === SPACE && event.target === event.currentTarget && !event.defaultPrevented) {
// Prevent the browser from scrolling the page
event.preventDefault();
// Ignore auto-repeated keydowns to avoid toggling multiple times
if (!event.repeat) {
// Trigger via click so that onClick receives a click event,
// consistent with Enter and pointer interactions.
event.currentTarget.click();
}
}
};
delete other['aria-invalid'];
let display;
let displaySingle;
const displayMultiple = [];
let computeDisplay = false;
let foundMatch = false;
// No need to display any value if the field is empty.
if (isFilled({
value
}) || displayEmpty) {
if (renderValue) {
display = renderValue(value);
} else {
computeDisplay = true;
}
}
const items = childrenArray.map(child => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(["MUI: The Select component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
let selected;
if (multiple) {
if (!Array.isArray(value)) {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI: The `value` prop must be an array ' + 'when using the `Select` component with `multiple`.' : _formatErrorMessage(2));
}
selected = value.some(v => areEqualValues(v, child.props.value));
if (selected && computeDisplay) {
displayMultiple.push(child.props.children);
}
} else {
selected = areEqualValues(value, child.props.value);
if (selected && computeDisplay) {
displaySingle = child.props.children;
}
}
if (selected) {
foundMatch = true;
}
return /*#__PURE__*/React.cloneElement(child, {
'aria-selected': selected ? 'true' : 'false',
onMouseDown: event => {
didPointerDownOnItemRef.current = true;
child.props.onMouseDown?.(event);
},
onPointerDown: event => {
didPointerDownOnItemRef.current = true;
child.props.onPointerDown?.(event);
},
onClick: handleItemClick(child),
onMouseUp: handleItemMouseUp(child, selected),
onKeyUp: event => {
if (event.key === SPACE) {
// otherwise our MenuItems dispatches a click event
// it's not behavior of the native <option> and causes
// the select to close immediately since we open on space keydown
event.preventDefault();
}
if (child.props.onKeyUp) {
child.props.onKeyUp(event);
}
},
onKeyDown: handleItemKeyDown(child),
role: 'option',
selected,
value: undefined,
// The value is most likely not a valid HTML attribute.
'data-value': child.props.value // Instead, we provide it as a data attribute.
});
});
// Keep the opening mouseup guard current without mutating refs during render.
useEnhancedEffect(() => {
hasSelectedItemInListRef.current = foundMatch;
if (!open && !multiple && !foundMatch) {
resetClosedTypeahead();
}
}, [foundMatch, multiple, open, resetClosedTypeahead]);
if (process.env.NODE_ENV !== 'production') {
// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (!foundMatch && !multiple && value !== '') {
const values = childrenArray.map(child => child.props.value);
console.warn([`MUI: You have provided an out-of-range value \`${value}\` for the select ${name ? `(name="${name}") ` : ''}component.`, "Consider providing a value that matches one of the available options or ''.", `The available values are ${values.filter(x => x != null).map(x => `\`${x}\``).join(', ') || '""'}.`].join('\n'));
}
}, [foundMatch, childrenArray, multiple, name, value]);
}
if (computeDisplay) {
if (multiple) {
if (displayMultiple.length === 0) {
display = null;
} else {
display = displayMultiple.reduce((output, child, index) => {
output.push(child);
if (index < displayMultiple.length - 1) {
output.push(', ');
}
return output;
}, []);
}
} else {
display = displaySingle;
}
}
// Avoid performing a layout computation in the render method.
let menuMinWidth = menuMinWidthState;
if (!autoWidth && isOpenControlled && displayNode) {
menuMinWidth = anchorElement.clientWidth;
}
let tabIndex;
if (typeof tabIndexProp !== 'undefined') {
tabIndex = tabIndexProp;
} else {
tabIndex = disabled ? null : 0;
}
const buttonId = SelectDisplayProps.id || (name ? `mui-component-select-${name}` : undefined);
const ownerState = {
...props,
variant,
value,
open,
error
};
const classes = useUtilityClasses(ownerState);
const menuPaperSlotProps = typeof MenuProps.slotProps?.paper === 'function' ? MenuProps.slotProps.paper(ownerState) : MenuProps.slotProps?.paper;
const handlePaperRef = useForkRef(menuPaperSlotProps?.ref, paperRef);
const menuListSlotProps = typeof MenuProps.slotProps?.list === 'function' ? MenuProps.slotProps.list(ownerState) : MenuProps.slotProps?.list;
const listboxId = useId();
const nativeInputId = useId();
return /*#__PURE__*/_jsxs(React.Fragment, {
children: [/*#__PURE__*/_jsx(SelectSelect, {
as: "div",
ref: handleDisplayRef,
tabIndex: tabIndex,
role: "combobox",
"aria-controls": open ? listboxId : undefined,
"aria-disabled": disabled ? 'true' : undefined,
"aria-expanded": open ? 'true' : 'false',
"aria-haspopup": "listbox",
"aria-readonly": readOnly ? 'true' : undefined,
"aria-label": ariaLabel,
"aria-labelledby": labelId,
"aria-describedby": ariaDescribedby,
"aria-required": required ? 'true' : undefined,
"aria-invalid": error ? 'true' : undefined,
onKeyDown: handleKeyDown,
onMouseDown: disabled || readOnly ? null : handleMouseDown,
onBlur: handleBlur,
onFocus: onFocus,
...SelectDisplayProps,
ownerState: ownerState,
className: clsx(SelectDisplayProps.className, classes.select, className)
// The id is required for proper a11y
,
id: buttonId,
children: isEmpty(display) ? // notranslate needed while Google Translate will not fix zero-width space issue
_span || (_span = /*#__PURE__*/_jsx("span", {
className: "notranslate",
"aria-hidden": true,
children: "\u200B"
})) : display
}), /*#__PURE__*/_jsx(SelectNativeInput, {
"aria-invalid": error,
value: Array.isArray(value) ? value.join(',') : value,
name: name,
ref: inputRef,
"aria-hidden": true,
onChange: handleChange,
tabIndex: -1,
disabled: disabled,
readOnly: readOnly,
className: classes.nativeInput,
autoFocus: autoFocus,
required: required,
...other,
id: other.id ?? nativeInputId,
ownerState: ownerState
}), /*#__PURE__*/_jsx(SelectIcon, {
as: IconComponent,
className: classes.icon,
ownerState: ownerState
}), /*#__PURE__*/_jsx(SelectFocusSourceProvider, {
value: openInteractionType,
children: /*#__PURE__*/_jsx(Menu, {
id: `menu-${name || ''}`,
anchorEl: anchorElement,
open: open,
onClose: handleClose,
anchorOrigin: {
vertical: 'bottom',
horizontal: 'center'
},
transformOrigin: {
vertical: 'top',
horizontal: 'center'
},
...MenuProps,
slotProps: {
...MenuProps.slotProps,
list: {
'aria-labelledby': labelId,
role: 'listbox',
'aria-multiselectable': multiple ? 'true' : undefined,
disableListWrap: true,
id: listboxId,
...menuListSlotProps
},
paper: {
...menuPaperSlotProps,
ref: handlePaperRef,
style: {
minWidth: menuMinWidth,
...menuPaperSlotProps?.style
}
}
},
children: items
})
})]
});
});
process.env.NODE_ENV !== "production" ? SelectInput.propTypes = {
/**
* @ignore
*/
'aria-describedby': PropTypes.string,
/**
* @ignore
*/
'aria-label': PropTypes.string,
/**
* @ignore
*/
autoFocus: PropTypes.bool,
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
*/
autoWidth: PropTypes.bool,
/**
* The option elements to populate the select with.
* Can be some `<MenuItem>` elements.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* The CSS class name of the select element.
*/
className: PropTypes.string,
/**
* If `true`, the component is toggled on mount. Use when the component open state is not controlled.
* You can only use it when the `native` prop is `false` (default).
*/
defaultOpen: PropTypes.bool,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the select is disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the selected item is displayed even if its value is empty.
*/
displayEmpty: PropTypes.bool,
/**
* If `true`, the `select input` will indicate an error.
*/
error: PropTypes.bool,
/**
* The icon that displays the arrow.
*/
IconComponent: PropTypes.elementType.isRequired,
/**
* Imperative handle implementing `{ value: T, node: HTMLElement, focus(): void }`
* Equivalent to `ref`
*/
inputRef: refType,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: PropTypes.string,
/**
* Props applied to the [`Menu`](/material-ui/api/menu/) element.
*/
MenuProps: PropTypes.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
*/
multiple: PropTypes.bool,
/**
* Name attribute of the `select` or hidden `input` element.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* @param {object} [child] The react element that was selected.
*/
onChange: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* @ignore
*/
readOnly: PropTypes.bool,
/**
* Render the selected value.
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: PropTypes.func,
/**
* If `true`, the component is required.
*/
required: PropTypes.bool,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: PropTypes.object,
/**
* @ignore
*/
tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* @ignore
*/
type: PropTypes.any,
/**
* The input value.
*/
value: PropTypes.any,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
export default SelectInput;
+5
View File
@@ -0,0 +1,5 @@
export { default } from "./Select.mjs";
export * from "./Select.mjs";
export * from "./utils/index.mjs";
export { default as selectClasses } from "./selectClasses.mjs";
export * from "./selectClasses.mjs";
+5
View File
@@ -0,0 +1,5 @@
export { default } from "./Select.js";
export * from "./Select.js";
export * from "./utils/index.js";
export { default as selectClasses } from "./selectClasses.js";
export * from "./selectClasses.js";
+47
View File
@@ -0,0 +1,47 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
selectClasses: true
};
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _Select.default;
}
});
Object.defineProperty(exports, "selectClasses", {
enumerable: true,
get: function () {
return _selectClasses.default;
}
});
var _Select = _interopRequireDefault(require("./Select"));
var _utils = require("./utils");
Object.keys(_utils).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _utils[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _utils[key];
}
});
});
var _selectClasses = _interopRequireWildcard(require("./selectClasses"));
Object.keys(_selectClasses).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _selectClasses[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _selectClasses[key];
}
});
});
+4
View File
@@ -0,0 +1,4 @@
export { default } from "./Select.mjs";
export * from "./utils/index.mjs";
export { default as selectClasses } from "./selectClasses.mjs";
export * from "./selectClasses.mjs";
+30
View File
@@ -0,0 +1,30 @@
export interface SelectClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the select component `select` class. */
select: string;
/** Styles applied to the select component if `multiple={true}`. */
multiple: string;
/** Styles applied to the select component if `variant="filled"`. */
filled: string;
/** Styles applied to the select component if it is focused. */
focused: string;
/** Styles applied to the select component if `variant="outlined"`. */
outlined: string;
/** Styles applied to the select component if `variant="standard"`. */
standard: string;
/** State class applied to the select component `disabled` class. */
disabled: string;
/** Styles applied to the icon component. */
icon: string;
/** Styles applied to the icon component if the popup is open. */
iconOpen: string;
/** Styles applied to the underlying native input component. */
nativeInput: string;
/** State class applied to the root element if `error={true}`. */
error: string;
}
export type SelectClassKey = keyof SelectClasses;
export declare function getSelectUtilityClasses(slot: string): string;
declare const selectClasses: SelectClasses;
export default selectClasses;
+30
View File
@@ -0,0 +1,30 @@
export interface SelectClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the select component `select` class. */
select: string;
/** Styles applied to the select component if `multiple={true}`. */
multiple: string;
/** Styles applied to the select component if `variant="filled"`. */
filled: string;
/** Styles applied to the select component if it is focused. */
focused: string;
/** Styles applied to the select component if `variant="outlined"`. */
outlined: string;
/** Styles applied to the select component if `variant="standard"`. */
standard: string;
/** State class applied to the select component `disabled` class. */
disabled: string;
/** Styles applied to the icon component. */
icon: string;
/** Styles applied to the icon component if the popup is open. */
iconOpen: string;
/** Styles applied to the underlying native input component. */
nativeInput: string;
/** State class applied to the root element if `error={true}`. */
error: string;
}
export type SelectClassKey = keyof SelectClasses;
export declare function getSelectUtilityClasses(slot: string): string;
declare const selectClasses: SelectClasses;
export default selectClasses;
+15
View File
@@ -0,0 +1,15 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.getSelectUtilityClasses = getSelectUtilityClasses;
var _generateUtilityClasses = _interopRequireDefault(require("@mui/utils/generateUtilityClasses"));
var _generateUtilityClass = _interopRequireDefault(require("@mui/utils/generateUtilityClass"));
function getSelectUtilityClasses(slot) {
return (0, _generateUtilityClass.default)('MuiSelect', slot);
}
const selectClasses = (0, _generateUtilityClasses.default)('MuiSelect', ['root', 'select', 'multiple', 'filled', 'outlined', 'standard', 'disabled', 'focused', 'icon', 'iconOpen', 'nativeInput', 'error']);
var _default = exports.default = selectClasses;
+7
View File
@@ -0,0 +1,7 @@
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
import generateUtilityClass from '@mui/utils/generateUtilityClass';
export function getSelectUtilityClasses(slot) {
return generateUtilityClass('MuiSelect', slot);
}
const selectClasses = generateUtilityClasses('MuiSelect', ['root', 'select', 'multiple', 'filled', 'outlined', 'standard', 'disabled', 'focused', 'icon', 'iconOpen', 'nativeInput', 'error']);
export default selectClasses;
@@ -0,0 +1,4 @@
import * as React from 'react';
declare function useSelectFocusSource(): "keyboard" | "mouse" | "touch" | null;
declare const SelectFocusSourceProvider: React.Provider<"keyboard" | "mouse" | "touch" | null>;
export { useSelectFocusSource, SelectFocusSourceProvider };
@@ -0,0 +1,4 @@
import * as React from 'react';
declare function useSelectFocusSource(): "keyboard" | "mouse" | "touch" | null;
declare const SelectFocusSourceProvider: React.Provider<"keyboard" | "mouse" | "touch" | null>;
export { useSelectFocusSource, SelectFocusSourceProvider };
@@ -0,0 +1,19 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SelectFocusSourceProvider = void 0;
exports.useSelectFocusSource = useSelectFocusSource;
var React = _interopRequireWildcard(require("react"));
const SelectFocusSourceContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== 'production') {
SelectFocusSourceContext.displayName = 'SelectFocusSourceContext';
}
function useSelectFocusSource() {
const context = React.useContext(SelectFocusSourceContext);
return context;
}
const SelectFocusSourceProvider = exports.SelectFocusSourceProvider = SelectFocusSourceContext.Provider;
@@ -0,0 +1,13 @@
'use client';
import * as React from 'react';
const SelectFocusSourceContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== 'production') {
SelectFocusSourceContext.displayName = 'SelectFocusSourceContext';
}
function useSelectFocusSource() {
const context = React.useContext(SelectFocusSourceContext);
return context;
}
const SelectFocusSourceProvider = SelectFocusSourceContext.Provider;
export { useSelectFocusSource, SelectFocusSourceProvider };
+1
View File
@@ -0,0 +1 @@
export default function areEqualValues(a: unknown, b: unknown): boolean;
+1
View File
@@ -0,0 +1 @@
export default function areEqualValues(a: unknown, b: unknown): boolean;
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = areEqualValues;
function areEqualValues(a, b) {
if (typeof b === 'object' && b !== null) {
return a === b;
}
// The value could be a number, the DOM will stringify it anyway.
return String(a) === String(b);
}
+8
View File
@@ -0,0 +1,8 @@
export default function areEqualValues(a, b) {
if (typeof b === 'object' && b !== null) {
return a === b;
}
// The value could be a number, the DOM will stringify it anyway.
return String(a) === String(b);
}
+73
View File
@@ -0,0 +1,73 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.canCycleRepeatedCharacter = canCycleRepeatedCharacter;
exports.getMatchingOptionIndex = getMatchingOptionIndex;
exports.getTypeaheadOptions = getTypeaheadOptions;
var React = _interopRequireWildcard(require("react"));
var _areEqualValues = _interopRequireDefault(require("./areEqualValues"));
function hasOwnValueProp(child) {
return Object.prototype.hasOwnProperty.call(child.props, 'value');
}
function getTextFromReactNode(node) {
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
let text = '';
React.Children.forEach(node, child => {
if (typeof child === 'string' || typeof child === 'number') {
text += String(child);
} else if (/*#__PURE__*/React.isValidElement(child)) {
text += getTextFromReactNode(child.props.children);
}
});
return text;
}
function getMatchingOptionIndex(options, search, startIndex = 0) {
if (options.length === 0) {
return -1;
}
const normalizedStartIndex = (startIndex % options.length + options.length) % options.length;
for (let offset = 0; offset < options.length; offset += 1) {
const index = (normalizedStartIndex + offset) % options.length;
if (options[index].label.startsWith(search)) {
return index;
}
}
return -1;
}
function canCycleRepeatedCharacter(options, key) {
return !options.some(option => option.label[0] === key && option.label[1] === key);
}
function getTypeaheadOptions(childrenArray, value) {
const options = [];
let selectedIndex = -1;
for (let index = 0; index < childrenArray.length; index += 1) {
const child = childrenArray[index];
if (! /*#__PURE__*/React.isValidElement(child) || !hasOwnValueProp(child) || child.props.disabled) {
continue;
}
// Closed typeahead cannot exclude CSS-hidden text because no option DOM is mounted.
const label = getTextFromReactNode(child.props.children).trim().toLowerCase();
if (label === '') {
continue;
}
if (selectedIndex === -1 && (0, _areEqualValues.default)(value, child.props.value)) {
selectedIndex = options.length;
}
options.push({
child,
label,
value: child.props.value
});
}
return {
options,
selectedIndex
};
}
+63
View File
@@ -0,0 +1,63 @@
import * as React from 'react';
import areEqualValues from "./areEqualValues.mjs";
function hasOwnValueProp(child) {
return Object.prototype.hasOwnProperty.call(child.props, 'value');
}
function getTextFromReactNode(node) {
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
let text = '';
React.Children.forEach(node, child => {
if (typeof child === 'string' || typeof child === 'number') {
text += String(child);
} else if (/*#__PURE__*/React.isValidElement(child)) {
text += getTextFromReactNode(child.props.children);
}
});
return text;
}
export function getMatchingOptionIndex(options, search, startIndex = 0) {
if (options.length === 0) {
return -1;
}
const normalizedStartIndex = (startIndex % options.length + options.length) % options.length;
for (let offset = 0; offset < options.length; offset += 1) {
const index = (normalizedStartIndex + offset) % options.length;
if (options[index].label.startsWith(search)) {
return index;
}
}
return -1;
}
export function canCycleRepeatedCharacter(options, key) {
return !options.some(option => option.label[0] === key && option.label[1] === key);
}
export function getTypeaheadOptions(childrenArray, value) {
const options = [];
let selectedIndex = -1;
for (let index = 0; index < childrenArray.length; index += 1) {
const child = childrenArray[index];
if (! /*#__PURE__*/React.isValidElement(child) || !hasOwnValueProp(child) || child.props.disabled) {
continue;
}
// Closed typeahead cannot exclude CSS-hidden text because no option DOM is mounted.
const label = getTextFromReactNode(child.props.children).trim().toLowerCase();
if (label === '') {
continue;
}
if (selectedIndex === -1 && areEqualValues(value, child.props.value)) {
selectedIndex = options.length;
}
options.push({
child,
label,
value: child.props.value
});
}
return {
options,
selectedIndex
};
}
@@ -0,0 +1 @@
export default function getOpenInteractionType(event: MouseEvent | KeyboardEvent | TouchEvent | PointerEvent | null): 'keyboard' | 'pointer' | null;
@@ -0,0 +1 @@
export default function getOpenInteractionType(event: MouseEvent | KeyboardEvent | TouchEvent | PointerEvent | null): 'keyboard' | 'pointer' | null;
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getOpenInteractionType;
function getOpenInteractionType(event) {
if (!event) {
return null;
}
if (event.type === 'mousedown' || event.type === 'pointerdown' || event.type === 'touchstart') {
return 'pointer';
}
if (event.type === 'keydown' || event.type === 'click' && event.detail === 0) {
return 'keyboard';
}
return null;
}
@@ -0,0 +1,12 @@
export default function getOpenInteractionType(event) {
if (!event) {
return null;
}
if (event.type === 'mousedown' || event.type === 'pointerdown' || event.type === 'touchstart') {
return 'pointer';
}
if (event.type === 'keydown' || event.type === 'click' && event.detail === 0) {
return 'keyboard';
}
return null;
}
+4
View File
@@ -0,0 +1,4 @@
export { default as getOpenInteractionType } from "./getOpenInteractionType.mjs";
export { default as isEmpty } from "./isEmpty.mjs";
export { default as areEqualValues } from "./areEqualValues.mjs";
export { useSelectFocusSource, SelectFocusSourceProvider } from "./SelectFocusSourceContext.mjs";
+4
View File
@@ -0,0 +1,4 @@
export { default as getOpenInteractionType } from "./getOpenInteractionType.js";
export { default as isEmpty } from "./isEmpty.js";
export { default as areEqualValues } from "./areEqualValues.js";
export { useSelectFocusSource, SelectFocusSourceProvider } from "./SelectFocusSourceContext.js";
+40
View File
@@ -0,0 +1,40 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "SelectFocusSourceProvider", {
enumerable: true,
get: function () {
return _SelectFocusSourceContext.SelectFocusSourceProvider;
}
});
Object.defineProperty(exports, "areEqualValues", {
enumerable: true,
get: function () {
return _areEqualValues.default;
}
});
Object.defineProperty(exports, "getOpenInteractionType", {
enumerable: true,
get: function () {
return _getOpenInteractionType.default;
}
});
Object.defineProperty(exports, "isEmpty", {
enumerable: true,
get: function () {
return _isEmpty.default;
}
});
Object.defineProperty(exports, "useSelectFocusSource", {
enumerable: true,
get: function () {
return _SelectFocusSourceContext.useSelectFocusSource;
}
});
var _getOpenInteractionType = _interopRequireDefault(require("./getOpenInteractionType"));
var _isEmpty = _interopRequireDefault(require("./isEmpty"));
var _areEqualValues = _interopRequireDefault(require("./areEqualValues"));
var _SelectFocusSourceContext = require("./SelectFocusSourceContext");
+4
View File
@@ -0,0 +1,4 @@
export { default as getOpenInteractionType } from "./getOpenInteractionType.mjs";
export { default as isEmpty } from "./isEmpty.mjs";
export { default as areEqualValues } from "./areEqualValues.mjs";
export { useSelectFocusSource, SelectFocusSourceProvider } from "./SelectFocusSourceContext.mjs";
+1
View File
@@ -0,0 +1 @@
export default function isEmpty(display: unknown): boolean;
+1
View File
@@ -0,0 +1 @@
export default function isEmpty(display: unknown): boolean;
+9
View File
@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEmpty;
function isEmpty(display) {
return display == null || typeof display === 'string' && !display.trim();
}
+3
View File
@@ -0,0 +1,3 @@
export default function isEmpty(display) {
return display == null || typeof display === 'string' && !display.trim();
}