2020-03-13 15:32:47 -04:00
|
|
|
import "./Modal.scss";
|
2020-01-15 20:42:02 +05:00
|
|
|
|
|
|
|
import React, { useEffect, useState } from "react";
|
|
|
|
import { createPortal } from "react-dom";
|
2020-01-25 19:37:58 -03:00
|
|
|
import { KEYS } from "../keys";
|
2020-01-15 20:42:02 +05:00
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const Modal = (props: {
|
2020-03-13 15:32:47 -04:00
|
|
|
className?: string;
|
2020-01-15 20:42:02 +05:00
|
|
|
children: React.ReactNode;
|
|
|
|
maxWidth?: number;
|
|
|
|
onCloseRequest(): void;
|
2020-01-25 19:37:58 -03:00
|
|
|
labelledBy: string;
|
2020-05-20 16:21:37 +03:00
|
|
|
}) => {
|
2020-01-15 20:42:02 +05:00
|
|
|
const modalRoot = useBodyRoot();
|
2020-01-25 19:37:58 -03:00
|
|
|
|
2020-02-28 23:03:53 +01:00
|
|
|
const handleKeydown = (event: React.KeyboardEvent) => {
|
|
|
|
if (event.key === KEYS.ESCAPE) {
|
|
|
|
event.nativeEvent.stopImmediatePropagation();
|
2020-01-25 19:37:58 -03:00
|
|
|
props.onCloseRequest();
|
|
|
|
}
|
|
|
|
};
|
2020-01-15 20:42:02 +05:00
|
|
|
return createPortal(
|
2020-01-25 19:37:58 -03:00
|
|
|
<div
|
2020-03-13 15:32:47 -04:00
|
|
|
className={`Modal ${props.className ?? ""}`}
|
2020-01-25 19:37:58 -03:00
|
|
|
role="dialog"
|
|
|
|
aria-modal="true"
|
|
|
|
onKeyDown={handleKeydown}
|
|
|
|
aria-labelledby={props.labelledBy}
|
2020-04-08 21:31:40 +09:00
|
|
|
tabIndex={-1}
|
2020-01-25 19:37:58 -03:00
|
|
|
>
|
2020-01-15 20:42:02 +05:00
|
|
|
<div className="Modal__background" onClick={props.onCloseRequest}></div>
|
2020-04-05 15:58:00 +03:00
|
|
|
<div
|
|
|
|
className="Modal__content"
|
2020-04-10 11:13:31 -04:00
|
|
|
style={
|
|
|
|
{
|
|
|
|
"--max-width": `${props.maxWidth}px`,
|
|
|
|
maxHeight: "100%",
|
|
|
|
overflowY: "scroll",
|
|
|
|
} as any
|
|
|
|
}
|
2020-04-05 15:58:00 +03:00
|
|
|
>
|
2020-01-15 20:42:02 +05:00
|
|
|
{props.children}
|
|
|
|
</div>
|
|
|
|
</div>,
|
2020-01-24 12:04:54 +02:00
|
|
|
modalRoot,
|
2020-01-15 20:42:02 +05:00
|
|
|
);
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|
2020-01-15 20:42:02 +05:00
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
const useBodyRoot = () => {
|
|
|
|
const createDiv = () => {
|
2020-01-15 20:42:02 +05:00
|
|
|
const div = document.createElement("div");
|
|
|
|
document.body.appendChild(div);
|
|
|
|
return div;
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|
2020-01-15 20:42:02 +05:00
|
|
|
const [div] = useState(createDiv);
|
|
|
|
useEffect(() => {
|
|
|
|
return () => {
|
|
|
|
document.body.removeChild(div);
|
|
|
|
};
|
|
|
|
}, [div]);
|
|
|
|
return div;
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|