| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import * as stylex from '@stylexjs/stylex'; |
| b69ab31 | | | 9 | import React, {useEffect, useRef} from 'react'; |
| b69ab31 | | | 10 | import ReactDOM from 'react-dom'; |
| b69ab31 | | | 11 | |
| b69ab31 | | | 12 | const styles = stylex.create({ |
| b69ab31 | | | 13 | root: { |
| b69ab31 | | | 14 | position: 'absolute', |
| b69ab31 | | | 15 | width: '100vw', |
| b69ab31 | | | 16 | height: '100vh', |
| b69ab31 | | | 17 | pointerEvents: 'none', |
| b69ab31 | | | 18 | zIndex: 1000, |
| b69ab31 | | | 19 | }, |
| b69ab31 | | | 20 | }); |
| b69ab31 | | | 21 | |
| b69ab31 | | | 22 | /** |
| b69ab31 | | | 23 | * Render `children` as an overlay, in a container that uses absolute positioning. |
| b69ab31 | | | 24 | * Suitable for tooltips, menus, and dragging elements. |
| b69ab31 | | | 25 | */ |
| b69ab31 | | | 26 | export function ViewportOverlay(props: { |
| b69ab31 | | | 27 | children: React.ReactNode; |
| b69ab31 | | | 28 | key?: React.Key | null; |
| b69ab31 | | | 29 | }): React.ReactPortal { |
| b69ab31 | | | 30 | const {key, children} = props; |
| b69ab31 | | | 31 | return ReactDOM.createPortal( |
| b69ab31 | | | 32 | children as Parameters< |
| b69ab31 | | | 33 | typeof ReactDOM.createPortal |
| b69ab31 | | | 34 | >[0] /** ReactDOM's understanding of ReactNode seems wrong here */, |
| b69ab31 | | | 35 | getRootContainer(), |
| b69ab31 | | | 36 | key == null ? null : `overlay-${key}`, |
| b69ab31 | | | 37 | ) as React.ReactPortal; |
| b69ab31 | | | 38 | } |
| b69ab31 | | | 39 | |
| b69ab31 | | | 40 | let cachedRoot: HTMLElement | undefined; |
| b69ab31 | | | 41 | const getRootContainer = (): HTMLElement => { |
| b69ab31 | | | 42 | if (cachedRoot) { |
| b69ab31 | | | 43 | // memoize since our root component won't change |
| b69ab31 | | | 44 | return cachedRoot; |
| b69ab31 | | | 45 | } |
| b69ab31 | | | 46 | throw new Error( |
| b69ab31 | | | 47 | 'ViewportOverlayRoot not found. Make sure you render it at the root of the tree.', |
| b69ab31 | | | 48 | ); |
| b69ab31 | | | 49 | }; |
| b69ab31 | | | 50 | |
| b69ab31 | | | 51 | export function ViewportOverlayRoot() { |
| b69ab31 | | | 52 | const rootRef = useRef<HTMLDivElement | null>(null); |
| b69ab31 | | | 53 | useEffect(() => { |
| b69ab31 | | | 54 | if (rootRef.current) { |
| b69ab31 | | | 55 | cachedRoot = rootRef.current; |
| b69ab31 | | | 56 | } |
| b69ab31 | | | 57 | return () => { |
| b69ab31 | | | 58 | cachedRoot = undefined; |
| b69ab31 | | | 59 | }; |
| b69ab31 | | | 60 | }, []); |
| b69ab31 | | | 61 | return <div ref={rootRef} {...stylex.props(styles.root)} data-testid="viewport-overlay-root" />; |
| b69ab31 | | | 62 | } |