| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @flow |
| 8 | */ |
| 9 | |
| 10 | import * as React from 'react'; |
| 11 | import {useState, useEffect, useCallback} from 'react'; |
| 12 | |
| 13 | import type {ContextMenuPosition} from './types'; |
| 14 | |
| 15 | type Payload = { |
| 16 | shouldShow: boolean, |
| 17 | position: ContextMenuPosition | null, |
| 18 | hide: () => void, |
| 19 | }; |
| 20 | |
| 21 | export default function useContextMenu(anchorElementRef: { |
| 22 | current: React.ElementRef<any> | null, |
| 23 | }): Payload { |
| 24 | const [shouldShow, setShouldShow] = useState(false); |
| 25 | const [position, setPosition] = React.useState<ContextMenuPosition | null>( |
| 26 | null, |
| 27 | ); |
| 28 | |
| 29 | const hide = useCallback(() => { |
| 30 | setShouldShow(false); |
| 31 | setPosition(null); |
| 32 | }, []); |
| 33 | |
| 34 | useEffect(() => { |
| 35 | const anchor = anchorElementRef.current; |
| 36 | if (anchor == null) return; |
| 37 | |
| 38 | function handleAnchorContextMenu(e: MouseEvent) { |
| 39 | e.preventDefault(); |
| 40 | e.stopPropagation(); |
| 41 | |
| 42 | const {pageX, pageY} = e; |
| 43 | |
| 44 | const ownerDocument = anchor?.ownerDocument; |
| 45 | const portalContainer = ownerDocument?.querySelector( |
| 46 | '[data-react-devtools-portal-root]', |
| 47 | ); |
| 48 | |
| 49 | if (portalContainer == null) { |
| 50 | throw new Error( |
| 51 | "DevTools tooltip root node not found: can't display the context menu", |
| 52 | ); |
| 53 | } |
| 54 | |
| 55 | // `x` and `y` should be relative to the container, to which these context menus will be portaled |
| 56 | // we can't use just `pageX` or `pageY` for Fusebox integration, because RDT frontend is inlined with the whole document |
| 57 | // meaning that `pageY` will have an offset of 27, which is the tab bar height |
| 58 | // for the browser extension, these will equal to 0 |
| 59 | const {top: containerTop, left: containerLeft} = |
| 60 | portalContainer.getBoundingClientRect(); |
| 61 | |
| 62 | setShouldShow(true); |
| 63 | setPosition({x: pageX - containerLeft, y: pageY - containerTop}); |
| 64 | } |
| 65 | |
| 66 | anchor.addEventListener('contextmenu', handleAnchorContextMenu); |
| 67 | return () => { |
| 68 | anchor.removeEventListener('contextmenu', handleAnchorContextMenu); |
| 69 | }; |
| 70 | }, [anchorElementRef]); |
| 71 | |
| 72 | return {shouldShow, position, hide}; |
| 73 | } |