UNPKG

@carbon/react

Version:

React components for the Carbon Design System

52 lines (50 loc) 1.51 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/components/ContextMenu/useContextMenu.tsx /** * Copyright IBM Corp. 2020, 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. */ /** * @param {TriggerType} [trigger=document] The element or ref which should trigger the Menu on right-click * @returns {ContextMenuProps} Props object to pass onto Menu component */ function useContextMenu(trigger = document) { const [open, setOpen] = (0, react.useState)(false); const [position, setPosition] = (0, react.useState)([0, 0]); function openContextMenu(e) { e.preventDefault(); const { clientX: x, clientY: y } = e; setPosition([x, y]); setOpen(true); } function onClose() { setOpen(false); } (0, react.useEffect)(() => { const el = trigger instanceof Element || trigger instanceof Document || trigger instanceof Window ? trigger : trigger.current; if (el) { const eventListener = (e) => openContextMenu(e); el.addEventListener("contextmenu", eventListener); return () => { el.removeEventListener("contextmenu", eventListener); }; } }, [trigger]); return { open, x: position[0], y: position[1], onClose }; } //#endregion exports.default = useContextMenu;