diff options
Diffstat (limited to 'packages/prosody-ui/src/hooks/useModal.tsx')
| -rw-r--r-- | packages/prosody-ui/src/hooks/useModal.tsx | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/packages/prosody-ui/src/hooks/useModal.tsx b/packages/prosody-ui/src/hooks/useModal.tsx new file mode 100644 index 0000000..7164bcb --- /dev/null +++ b/packages/prosody-ui/src/hooks/useModal.tsx @@ -0,0 +1,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> + ); +} |
