@base-ui-components/react
Version:
Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.
56 lines (55 loc) • 1.72 kB
JavaScript
'use client';
import * as React from 'react';
import { useButton } from '../../use-button/index.js';
import { mergeReactProps } from '../../utils/mergeReactProps.js';
import { useForkRef } from '../../utils/useForkRef.js';
export function useMenuItem(params) {
const {
closeOnClick,
disabled = false,
highlighted,
id,
menuEvents,
ref: externalRef,
allowMouseUpTriggerRef,
typingRef
} = params;
const itemRef = React.useRef(null);
const {
getButtonProps,
buttonRef: mergedRef
} = useButton({
disabled,
focusableWhenDisabled: true,
buttonRef: useForkRef(externalRef, itemRef)
});
const getRootProps = React.useCallback(externalProps => {
return getButtonProps(mergeReactProps(externalProps, {
id,
role: 'menuitem',
tabIndex: highlighted ? 0 : -1,
onKeyUp: event => {
if (event.key === ' ' && typingRef.current) {
event.defaultMuiPrevented = true;
}
},
onClick: event => {
if (closeOnClick) {
menuEvents.emit('close', event);
}
},
onMouseUp: event => {
if (itemRef.current && allowMouseUpTriggerRef.current) {
// This fires whenever the user clicks on the trigger, moves the cursor, and releases it over the item.
// We trigger the click and override the `closeOnClick` preference to always close the menu.
itemRef.current.click();
menuEvents.emit('close', event);
}
}
}));
}, [closeOnClick, getButtonProps, highlighted, id, menuEvents, allowMouseUpTriggerRef, typingRef]);
return React.useMemo(() => ({
getRootProps,
rootRef: mergedRef
}), [getRootProps, mergedRef]);
}