@base-ui/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.
66 lines (64 loc) • 2.31 kB
JavaScript
'use client';
import * as React from 'react';
import { REASONS } from "../../utils/reasons.js";
import { useContextMenuRootContext } from "../../context-menu/root/ContextMenuRootContext.js";
/**
* Returns common props shared by all menu item types.
* This hook extracts the shared logic for id, role, tabIndex, onMouseMove, onClick, and onMouseUp handlers.
*/
export function useMenuItemCommonProps(params) {
const {
closeOnClick,
highlighted,
id,
nodeId,
store,
itemRef,
itemMetadata
} = params;
const {
events: menuEvents
} = store.useState('floatingTreeRoot');
const contextMenuContext = useContextMenuRootContext(true);
const isContextMenu = contextMenuContext !== undefined;
return React.useMemo(() => ({
id,
role: 'menuitem',
tabIndex: highlighted ? 0 : -1,
onMouseMove(event) {
if (!nodeId) {
return;
}
// Inform the floating tree that a menu item within this menu was hovered/moved over
// so unrelated descendant submenus can be closed.
menuEvents.emit('itemhover', {
nodeId,
target: event.currentTarget
});
},
onClick(event) {
if (closeOnClick) {
menuEvents.emit('close', {
domEvent: event,
reason: REASONS.itemPress
});
}
},
onMouseUp(event) {
if (contextMenuContext) {
const initialCursorPoint = contextMenuContext.initialCursorPointRef.current;
contextMenuContext.initialCursorPointRef.current = null;
if (isContextMenu && initialCursorPoint && Math.abs(event.clientX - initialCursorPoint.x) <= 1 && Math.abs(event.clientY - initialCursorPoint.y) <= 1) {
return;
}
}
if (itemRef.current && store.context.allowMouseUpTriggerRef.current && (!isContextMenu || event.button === 2)) {
// 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.
if (!itemMetadata || itemMetadata.type === 'regular-item') {
itemRef.current.click();
}
}
}
}), [closeOnClick, highlighted, id, menuEvents, nodeId, store, itemRef, contextMenuContext, isContextMenu, itemMetadata]);
}