UNPKG

@carbon/react

Version:

React components for the Carbon Design System

55 lines (53 loc) 1.47 kB
/** * Copyright IBM Corp. 2016, 2026 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ require("../_virtual/_rolldown/runtime.js"); let react = require("react"); //#region src/internal/useAttachedMenu.ts /** * Copyright IBM Corp. 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ /** * This hook contains common code to be used when a menu should be visually attached to an anchor based on a click event. * * @param {Element|object} anchor The element or ref the menu should visually be attached to. * @returns {useAttachedMenuReturn} */ function useAttachedMenu(anchor) { const [open, setOpen] = (0, react.useState)(false); const [position, setPosition] = (0, react.useState)([[-1, -1], [-1, -1]]); function openMenu() { const anchorEl = anchor?.current || anchor; if (anchorEl) { const { left, top, right, bottom } = anchorEl.getBoundingClientRect(); setPosition([[left, right], [top, bottom]]); } setOpen(true); } function closeMenu() { setOpen(false); } function handleClick() { if (open) closeMenu(); else openMenu(); } function handleMousedown(e) { e.preventDefault(); } return { open, x: position[0], y: position[1], handleClick, handleMousedown, handleClose: closeMenu }; } //#endregion exports.useAttachedMenu = useAttachedMenu;