summaryrefslogtreecommitdiff
path: root/packages/prosody-ui/src/hooks/useModal.tsx
blob: 7164bcbbce15b854681f1ba383b6b71a4915af61 (plain)
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
44
45
46
47
48
49
50
51
52
53
import { franc } from "franc-all";
import React, {
  ReactElement,
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";

function useModal() {
  const [achild, setChild] = useState<ReactNode>(null);
  return <Modal close={() => setChild(null)}>{achild}</Modal>;
}
export default useModal;

function Modal({
  children,
  height = "fit-content",
  width = "80%",
  close,
}: {
  children: ReactNode;
  close: () => void;
  width?: any;
  height?: any;
}) {
  function onKey(event: any) {
    if (event.key === "Escape") close();

    useEffect(() => {
      document.addEventListener("keyup", onKey);
      return () => {
        document.removeEventListener("keyup", onKey);
      };
    }, [children]);
  }

  function clickAway(e: React.MouseEvent) {
    e.stopPropagation();
    if (!modalRef.current || !modalRef.current.contains(e.target as any))
      close();
  }
  const modalRef = useRef<HTMLDivElement>(null);
  const style = { width, height };
  return (
    <div id="modal-bg" onClick={clickAway}>
      <div id="modal-fg" style={style} ref={modalRef}>
        {children}
      </div>
    </div>
  );
}