-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFloatingBoxAtCursor.tsx
More file actions
43 lines (36 loc) · 1.32 KB
/
FloatingBoxAtCursor.tsx
File metadata and controls
43 lines (36 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { memo, ReactNode, useMemo, useRef } from "react";
import { createPortal } from "react-dom";
import { FloatingBox } from "./FloatingBox";
import useCursorCoords from "./useCursorCoords";
import { Placement } from "@floating-ui/dom";
const DOM_ELEMENT = document.body;
const MemoizedFloatingBox = memo(FloatingBox);
export type FloatingMenuCoords = { x: number; y: number } | undefined;
type CursorFloatingBox = {
isOpen?: boolean;
children:
| ReactNode
| ((props: { isOpen: boolean | undefined; placement?: Placement }) => ReactNode);
};
/**
* FloatingBoxAtCursor component is responsible for rendering a floating menu
* at the cursor position when the isOpen prop is true
*/
export default function FloatingBoxAtCursor({ isOpen = false, children }: CursorFloatingBox) {
const floatingBoxRef = useRef<HTMLDivElement>(null);
const { coords, placement } = useCursorCoords({ isOpen, floatingBoxRef });
const renderChildren = useMemo(
() => (coords ? (typeof children === "function" ? children : () => children) : () => null),
[children, coords],
);
return createPortal(
<MemoizedFloatingBox
ref={floatingBoxRef}
coords={coords}
style={coords ? undefined : { display: "none" }}
>
{renderChildren({ isOpen, placement })}
</MemoizedFloatingBox>,
DOM_ELEMENT,
);
}