2020-03-15 13:26:52 -04:00
|
|
|
import React, { useLayoutEffect, useRef, useEffect } from "react";
|
2020-01-15 20:42:02 +05:00
|
|
|
import "./Popover.css";
|
2020-03-16 19:07:47 -07:00
|
|
|
import { unstable_batchedUpdates } from "react-dom";
|
2020-01-07 07:50:59 +05:00
|
|
|
|
|
|
|
type Props = {
|
|
|
|
top?: number;
|
|
|
|
left?: number;
|
|
|
|
children?: React.ReactNode;
|
|
|
|
onCloseRequest?(): void;
|
2020-01-14 09:44:18 +01:00
|
|
|
fitInViewport?: boolean;
|
2020-01-07 07:50:59 +05:00
|
|
|
};
|
|
|
|
|
2020-01-14 09:44:18 +01:00
|
|
|
export function Popover({
|
|
|
|
children,
|
|
|
|
left,
|
|
|
|
top,
|
|
|
|
onCloseRequest,
|
2020-01-24 12:04:54 +02:00
|
|
|
fitInViewport = false,
|
2020-01-14 09:44:18 +01:00
|
|
|
}: Props) {
|
|
|
|
const popoverRef = useRef<HTMLDivElement>(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) {
|
2020-02-02 20:04:35 +02:00
|
|
|
element.style.left = `${viewportWidth - width}px`;
|
2020-01-14 09:44:18 +01:00
|
|
|
}
|
|
|
|
const viewportHeight = window.innerHeight;
|
|
|
|
if (y + height > viewportHeight) {
|
2020-02-02 20:04:35 +02:00
|
|
|
element.style.top = `${viewportHeight - height}px`;
|
2020-01-14 09:44:18 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [fitInViewport]);
|
|
|
|
|
2020-03-15 13:26:52 -04:00
|
|
|
useEffect(() => {
|
|
|
|
if (onCloseRequest) {
|
|
|
|
const handler = (e: Event) => {
|
|
|
|
if (!popoverRef.current?.contains(e.target as Node)) {
|
2020-03-16 19:07:47 -07:00
|
|
|
unstable_batchedUpdates(() => onCloseRequest());
|
2020-03-15 13:26:52 -04:00
|
|
|
}
|
|
|
|
};
|
|
|
|
document.addEventListener("pointerdown", handler, false);
|
|
|
|
return () => document.removeEventListener("pointerdown", handler, false);
|
|
|
|
}
|
|
|
|
}, [onCloseRequest]);
|
|
|
|
|
2020-01-07 07:50:59 +05:00
|
|
|
return (
|
2020-01-14 09:44:18 +01:00
|
|
|
<div className="popover" style={{ top: top, left: left }} ref={popoverRef}>
|
2020-01-07 07:50:59 +05:00
|
|
|
{children}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|