UNPKG

2.35 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 otherHandlers.onKeyDown?.(event);
58 if (event.defaultMuiPrevented) {
59 return;
60 }
61 if ([' ', 'Enter'].includes(event.key)) {
62 event.defaultMuiPrevented = true; // prevent listbox onKeyDown
63 }
64 };
65 const getOwnHandlers = (otherHandlers = {}) => ({
66 onKeyDown: createHandleKeyDown(otherHandlers)
67 });
68 return {
69 getRootProps: (externalProps = {}) => {
70 const externalEventHandlers = extractEventHandlers(externalProps);
71 const getCombinedRootProps = combineHooksSlotProps(getListItemProps, combineHooksSlotProps(getButtonProps, getOwnHandlers));
72 return _extends({}, externalProps, externalEventHandlers, getCombinedRootProps(externalEventHandlers), {
73 id,
74 ref: handleRef,
75 role: 'option',
76 'aria-selected': selected
77 });
78 },
79 highlighted,
80 index,
81 selected,
82 rootRef: handleRef
83 };
84}
\No newline at end of file