UNPKG

2.46 kBJavaScriptView Raw
1'use client';
2
3import _extends from "@babel/runtime/helpers/esm/extends";
4import * as React from 'react';
5import { unstable_useForkRef as useForkRef, unstable_useId as useId } from '@mui/utils';
6import { extractEventHandlers } from '../utils/extractEventHandlers';
7import { useListItem } from '../useList';
8import { useCompoundItem } from '../useCompound';
9import { useButton } from '../useButton';
10import { combineHooksSlotProps } from '../utils/combineHooksSlotProps';
11/**
12 *
13 * Demos:
14 *
15 * - [Select](https://mui.com/base-ui/react-select/#hooks)
16 *
17 * API:
18 *
19 * - [useOption API](https://mui.com/base-ui/react-select/hooks-api/#use-option)
20 */
21export function useOption(params) {
22 const {
23 value,
24 label,
25 disabled,
26 rootRef: optionRefParam,
27 id: idParam
28 } = params;
29 const {
30 getRootProps: getListItemProps,
31 highlighted,
32 selected
33 } = useListItem({
34 item: value
35 });
36 const {
37 getRootProps: getButtonProps,
38 rootRef: buttonRefHandler
39 } = useButton({
40 disabled,
41 focusableWhenDisabled: true
42 });
43 const id = useId(idParam);
44 const optionRef = React.useRef(null);
45 const selectOption = React.useMemo(() => ({
46 disabled,
47 label,
48 value,
49 ref: optionRef,
50 id
51 }), [disabled, label, value, id]);
52 const {
53 index
54 } = useCompoundItem(value, selectOption);
55 const handleRef = useForkRef(optionRefParam, optionRef, buttonRefHandler);
56 const createHandleKeyDown = otherHandlers => event => {
57 var _otherHandlers$onKeyD;
58 (_otherHandlers$onKeyD = otherHandlers.onKeyDown) == null || _otherHandlers$onKeyD.call(otherHandlers, event);
59 if (event.defaultMuiPrevented) {
60 return;
61 }
62 if ([' ', 'Enter'].includes(event.key)) {
63 event.defaultMuiPrevented = true; // prevent listbox onKeyDown
64 }
65 };
66 const getOwnHandlers = (otherHandlers = {}) => ({
67 onKeyDown: createHandleKeyDown(otherHandlers)
68 });
69 return {
70 getRootProps: (externalProps = {}) => {
71 const externalEventHandlers = extractEventHandlers(externalProps);
72 const getCombinedRootProps = combineHooksSlotProps(getListItemProps, combineHooksSlotProps(getButtonProps, getOwnHandlers));
73 return _extends({}, externalProps, externalEventHandlers, getCombinedRootProps(externalEventHandlers), {
74 id,
75 ref: handleRef,
76 role: 'option',
77 'aria-selected': selected
78 });
79 },
80 highlighted,
81 index,
82 selected,
83 rootRef: handleRef
84 };
85}
\No newline at end of file