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.

72 lines (70 loc) 2.59 kB
"use strict"; 'use client'; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default; Object.defineProperty(exports, "__esModule", { value: true }); exports.useMenuItemCommonProps = useMenuItemCommonProps; var React = _interopRequireWildcard(require("react")); var _reasons = require("../../utils/reasons"); var _ContextMenuRootContext = require("../../context-menu/root/ContextMenuRootContext"); /** * Returns common props shared by all menu item types. * This hook extracts the shared logic for id, role, tabIndex, onMouseMove, onClick, and onMouseUp handlers. */ function useMenuItemCommonProps(params) { const { closeOnClick, highlighted, id, nodeId, store, itemRef, itemMetadata } = params; const { events: menuEvents } = store.useState('floatingTreeRoot'); const contextMenuContext = (0, _ContextMenuRootContext.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.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]); }