From 8104c8525d6fb86f50f27035d01f8e58b8e7c9bd Mon Sep 17 00:00:00 2001 From: David Luzar Date: Tue, 14 Jan 2020 09:44:18 +0100 Subject: [PATCH] ensure contextMenu doesn't overflow viewport (#364) --- src/components/ContextMenu.tsx | 7 ++++++- src/components/Popover.tsx | 32 +++++++++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/components/ContextMenu.tsx b/src/components/ContextMenu.tsx index c367d824..8053e226 100644 --- a/src/components/ContextMenu.tsx +++ b/src/components/ContextMenu.tsx @@ -18,7 +18,12 @@ type Props = { function ContextMenu({ options, onCloseRequest, top, left }: Props) { return ( - +
    e.preventDefault()}> {options.map((option, idx) => (
  • (null); + + // ensure the popover doesn't overflow the viewport + useLayoutEffect(() => { + if (fitInViewport && popoverRef.current) { + const element = popoverRef.current; + const { x, y, width, height } = element.getBoundingClientRect(); + + const viewportWidth = window.innerWidth; + if (x + width > viewportWidth) { + element.style.left = viewportWidth - width + "px"; + } + const viewportHeight = window.innerHeight; + if (y + height > viewportHeight) { + element.style.top = viewportHeight - height + "px"; + } + } + }, [fitInViewport]); + return ( -
    +