UNPKG

2.56 kBJavaScriptView Raw
1import _extends from "@babel/runtime/helpers/esm/extends";
2import * as React from 'react';
3import { unstable_useId as useId, unstable_useForkRef as useForkRef } from '@mui/utils';
4import useButton from '../useButton';
5import { useListItem } from '../useList';
6import { useCompoundItem } from '../utils/useCompoundItem';
7function idGenerator(existingKeys) {
8 return `menu-item-${existingKeys.size}`;
9}
10
11/**
12 *
13 * Demos:
14 *
15 * - [Menu](https://mui.com/base/react-menu/#hooks)
16 *
17 * API:
18 *
19 * - [useMenuItem API](https://mui.com/base/react-menu/hooks-api/#use-menu-item)
20 */
21export default function useMenuItem(params) {
22 const {
23 disabled = false,
24 id: idParam,
25 rootRef: externalRef,
26 label
27 } = params;
28 const id = useId(idParam);
29 const itemRef = React.useRef(null);
30 const itemMetadata = React.useMemo(() => ({
31 disabled,
32 id: id != null ? id : '',
33 label,
34 ref: itemRef
35 }), [disabled, id, label]);
36 const {
37 getRootProps: getListRootProps,
38 highlighted,
39 rootRef: listItemRefHandler
40 } = useListItem({
41 item: id
42 });
43 const {
44 index,
45 totalItemCount
46 } = useCompoundItem(id != null ? id : idGenerator, itemMetadata);
47 const {
48 getRootProps: getButtonProps,
49 focusVisible,
50 rootRef: buttonRefHandler
51 } = useButton({
52 disabled,
53 focusableWhenDisabled: true
54 });
55 const handleRef = useForkRef(listItemRefHandler, buttonRefHandler, externalRef, itemRef);
56 React.useDebugValue({
57 id,
58 highlighted,
59 disabled,
60 label
61 });
62
63 // If `id` is undefined (during SSR in React < 18), we fall back to rendering a simplified menu item
64 // which does not have access to infortmation about its position or highlighted state.
65 if (id === undefined) {
66 return {
67 getRootProps: (otherHandlers = {}) => _extends({}, otherHandlers, getButtonProps(otherHandlers), {
68 role: 'menuitem'
69 }),
70 disabled: false,
71 focusVisible,
72 highlighted: false,
73 index: -1,
74 totalItemCount: 0,
75 rootRef: handleRef
76 };
77 }
78 const getRootProps = (otherHandlers = {}) => {
79 const resolvedButtonProps = _extends({}, otherHandlers, getButtonProps(otherHandlers));
80 const resolvedMenuItemProps = _extends({}, resolvedButtonProps, getListRootProps(resolvedButtonProps));
81 return _extends({}, otherHandlers, resolvedButtonProps, resolvedMenuItemProps, {
82 role: 'menuitem',
83 ref: handleRef
84 });
85 };
86 return {
87 getRootProps,
88 disabled,
89 focusVisible,
90 highlighted,
91 index,
92 totalItemCount,
93 rootRef: handleRef
94 };
95}
\No newline at end of file