UNPKG

10.6 kBJavaScriptView Raw
1'use client';
2
3import _extends from "@babel/runtime/helpers/esm/extends";
4import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
5var _span;
6const _excluded = ["areOptionsEqual", "autoComplete", "autoFocus", "children", "defaultValue", "defaultListboxOpen", "disabled", "getSerializedValue", "listboxId", "listboxOpen", "multiple", "name", "required", "onChange", "onListboxOpenChange", "getOptionAsString", "renderValue", "placeholder", "slotProps", "slots", "value"];
7import * as React from 'react';
8import PropTypes from 'prop-types';
9import { unstable_useForkRef as useForkRef } from '@mui/utils';
10import { useSelect } from '../useSelect';
11import { useSlotProps } from '../utils';
12import { Popup } from '../Unstable_Popup/Popup';
13import { unstable_composeClasses as composeClasses } from '../composeClasses';
14import { getSelectUtilityClass } from './selectClasses';
15import { defaultOptionStringifier } from '../useSelect/defaultOptionStringifier';
16import { useClassNamesOverride } from '../utils/ClassNameConfigurator';
17import { SelectProvider } from '../useSelect/SelectProvider';
18import { jsx as _jsx } from "react/jsx-runtime";
19import { jsxs as _jsxs } from "react/jsx-runtime";
20function defaultRenderValue(selectedOptions) {
21 if (Array.isArray(selectedOptions)) {
22 return /*#__PURE__*/_jsx(React.Fragment, {
23 children: selectedOptions.map(o => o.label).join(', ')
24 });
25 }
26 return selectedOptions?.label ?? null;
27}
28function useUtilityClasses(ownerState) {
29 const {
30 active,
31 disabled,
32 open,
33 focusVisible
34 } = ownerState;
35 const slots = {
36 root: ['root', disabled && 'disabled', focusVisible && 'focusVisible', active && 'active', open && 'expanded'],
37 listbox: ['listbox', disabled && 'disabled'],
38 popup: ['popup']
39 };
40 return composeClasses(slots, useClassNamesOverride(getSelectUtilityClass));
41}
42
43/**
44 * The foundation for building custom-styled select components.
45 *
46 * Demos:
47 *
48 * - [Select](https://mui.com/base-ui/react-select/)
49 *
50 * API:
51 *
52 * - [Select API](https://mui.com/base-ui/react-select/components-api/#select)
53 */
54const Select = /*#__PURE__*/React.forwardRef(function Select(props, forwardedRef) {
55 const {
56 areOptionsEqual,
57 autoComplete,
58 autoFocus,
59 children,
60 defaultValue,
61 defaultListboxOpen = false,
62 disabled: disabledProp,
63 getSerializedValue,
64 listboxId,
65 listboxOpen: listboxOpenProp,
66 multiple = false,
67 name,
68 required = false,
69 onChange,
70 onListboxOpenChange,
71 getOptionAsString = defaultOptionStringifier,
72 renderValue: renderValueProp,
73 placeholder,
74 slotProps = {},
75 slots = {},
76 value: valueProp
77 } = props,
78 other = _objectWithoutPropertiesLoose(props, _excluded);
79 const renderValue = renderValueProp ?? defaultRenderValue;
80 const [buttonDefined, setButtonDefined] = React.useState(false);
81 const buttonRef = React.useRef(null);
82 const listboxRef = React.useRef(null);
83 const Button = slots.root ?? 'button';
84 const ListboxRoot = slots.listbox ?? 'ul';
85 const PopupComponent = slots.popup ?? 'div';
86 const handleButtonRefChange = React.useCallback(element => {
87 setButtonDefined(element != null);
88 }, []);
89 const handleButtonRef = useForkRef(forwardedRef, buttonRef, handleButtonRefChange);
90 React.useEffect(() => {
91 if (autoFocus) {
92 buttonRef.current.focus();
93 }
94 }, [autoFocus]);
95 const {
96 buttonActive,
97 buttonFocusVisible,
98 contextValue,
99 disabled,
100 getButtonProps,
101 getListboxProps,
102 getHiddenInputProps,
103 getOptionMetadata,
104 value,
105 open
106 } = useSelect({
107 name,
108 required,
109 getSerializedValue,
110 areOptionsEqual,
111 buttonRef: handleButtonRef,
112 defaultOpen: defaultListboxOpen,
113 defaultValue,
114 disabled: disabledProp,
115 listboxId,
116 multiple,
117 open: listboxOpenProp,
118 onChange,
119 onOpenChange: onListboxOpenChange,
120 getOptionAsString,
121 value: valueProp,
122 componentName: 'Select'
123 });
124 const ownerState = _extends({}, props, {
125 active: buttonActive,
126 defaultListboxOpen,
127 disabled,
128 focusVisible: buttonFocusVisible,
129 open,
130 multiple,
131 renderValue,
132 value
133 });
134 const classes = useUtilityClasses(ownerState);
135 const buttonProps = useSlotProps({
136 elementType: Button,
137 getSlotProps: getButtonProps,
138 externalSlotProps: slotProps.root,
139 externalForwardedProps: other,
140 ownerState,
141 className: classes.root
142 });
143 const listboxProps = useSlotProps({
144 elementType: ListboxRoot,
145 getSlotProps: getListboxProps,
146 externalSlotProps: slotProps.listbox,
147 additionalProps: {
148 ref: listboxRef
149 },
150 ownerState,
151 className: classes.listbox
152 });
153 const popupProps = useSlotProps({
154 elementType: PopupComponent,
155 externalSlotProps: slotProps.popup,
156 additionalProps: {
157 anchor: buttonRef.current,
158 keepMounted: true,
159 open,
160 placement: 'bottom-start',
161 role: undefined
162 },
163 ownerState,
164 className: classes.popup
165 });
166 let selectedOptionsMetadata;
167 if (multiple) {
168 selectedOptionsMetadata = value.map(v => getOptionMetadata(v)).filter(o => o !== undefined);
169 } else {
170 selectedOptionsMetadata = getOptionMetadata(value) ?? null;
171 }
172 return /*#__PURE__*/_jsxs(React.Fragment, {
173 children: [/*#__PURE__*/_jsx(Button, _extends({}, buttonProps, {
174 children: renderValue(selectedOptionsMetadata) ?? placeholder ?? ( // fall back to a zero-width space to prevent layout shift
175 // from https://github.com/mui/material-ui/pull/24563
176 _span || (_span = /*#__PURE__*/_jsx("span", {
177 className: "notranslate",
178 children: "\u200B"
179 })))
180 })), buttonDefined && /*#__PURE__*/_jsx(Popup, _extends({
181 slots: {
182 root: PopupComponent
183 }
184 }, popupProps, {
185 children: /*#__PURE__*/_jsx(ListboxRoot, _extends({}, listboxProps, {
186 children: /*#__PURE__*/_jsx(SelectProvider, {
187 value: contextValue,
188 children: children
189 })
190 }))
191 })), /*#__PURE__*/_jsx("input", _extends({}, getHiddenInputProps(), {
192 autoComplete: autoComplete
193 }))]
194 });
195});
196process.env.NODE_ENV !== "production" ? Select.propTypes /* remove-proptypes */ = {
197 // ┌────────────────────────────── Warning ──────────────────────────────┐
198 // │ These PropTypes are generated from the TypeScript type definitions. │
199 // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │
200 // └─────────────────────────────────────────────────────────────────────┘
201 /**
202 * A function used to determine if two options' values are equal.
203 * By default, reference equality is used.
204 *
205 * There is a performance impact when using the `areOptionsEqual` prop (proportional to the number of options).
206 * Therefore, it's recommented to use the default reference equality comparison whenever possible.
207 */
208 areOptionsEqual: PropTypes.func,
209 /**
210 * This prop helps users to fill forms faster, especially on mobile devices.
211 * The name can be confusing, as it's more like an autofill.
212 * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
213 */
214 autoComplete: PropTypes.string,
215 /**
216 * If `true`, the select element is focused during the first mount
217 * @default false
218 */
219 autoFocus: PropTypes.bool,
220 /**
221 * @ignore
222 */
223 children: PropTypes.node,
224 /**
225 * @ignore
226 */
227 className: PropTypes.string,
228 /**
229 * If `true`, the select will be initially open.
230 * @default false
231 */
232 defaultListboxOpen: PropTypes.bool,
233 /**
234 * The default selected value. Use when the component is not controlled.
235 */
236 defaultValue: PropTypes.any,
237 /**
238 * If `true`, the select is disabled.
239 * @default false
240 */
241 disabled: PropTypes.bool,
242 /**
243 * A function used to convert the option label to a string.
244 * It's useful when labels are elements and need to be converted to plain text
245 * to enable navigation using character keys on a keyboard.
246 *
247 * @default defaultOptionStringifier
248 */
249 getOptionAsString: PropTypes.func,
250 /**
251 * A function to convert the currently selected value to a string.
252 * Used to set a value of a hidden input associated with the select,
253 * so that the selected value can be posted with a form.
254 */
255 getSerializedValue: PropTypes.func,
256 /**
257 * `id` attribute of the listbox element.
258 */
259 listboxId: PropTypes.string,
260 /**
261 * Controls the open state of the select's listbox.
262 * @default undefined
263 */
264 listboxOpen: PropTypes.bool,
265 /**
266 * If `true`, selecting multiple values is allowed.
267 * This affects the type of the `value`, `defaultValue`, and `onChange` props.
268 *
269 * @default false
270 */
271 multiple: PropTypes.bool,
272 /**
273 * Name of the element. For example used by the server to identify the fields in form submits.
274 */
275 name: PropTypes.string,
276 /**
277 * Callback fired when an option is selected.
278 */
279 onChange: PropTypes.func,
280 /**
281 * Callback fired when the component requests to be opened.
282 * Use in controlled mode (see listboxOpen).
283 */
284 onListboxOpenChange: PropTypes.func,
285 /**
286 * Text to show when there is no selected value.
287 */
288 placeholder: PropTypes.node,
289 /**
290 * Function that customizes the rendering of the selected value.
291 */
292 renderValue: PropTypes.func,
293 /**
294 * If `true`, the Select cannot be empty when submitting form.
295 * @default false
296 */
297 required: PropTypes.bool,
298 /**
299 * The props used for each slot inside the Input.
300 * @default {}
301 */
302 slotProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({
303 listbox: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
304 popup: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
305 root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
306 }),
307 /**
308 * The components used for each slot inside the Select.
309 * Either a string to use a HTML element or a component.
310 * @default {}
311 */
312 slots: PropTypes /* @typescript-to-proptypes-ignore */.shape({
313 listbox: PropTypes.elementType,
314 popup: PropTypes.elementType,
315 root: PropTypes.elementType
316 }),
317 /**
318 * The selected value.
319 * Set to `null` to deselect all options.
320 */
321 value: PropTypes.any
322} : void 0;
323export { Select };
\No newline at end of file