UNPKG

@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.

80 lines (77 loc) 2.78 kB
'use client'; import * as React from 'react'; import { isMac } from '@base-ui/utils/detectBrowser'; import { REASONS } from "../../internals/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, onKeyDown, * onMouseMove, onClick, and onMouseUp handlers. */ export function useMenuItemCommonProps(params) { const { closeOnClick, highlighted, id, nodeId, store, typingRef, 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, onKeyDown(event) { if (event.key === ' ' && typingRef?.current) { event.preventDefault(); } }, 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; } // On non-macOS platforms, this mouseup belongs to the right-click gesture // that opened the context menu, so it must not activate an item. if (isContextMenu && !isMac && event.button === 2) { 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, typingRef, itemRef, contextMenuContext, isContextMenu, itemMetadata]); }