Modal.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import "./Modal.scss";
  2. import React, { useState, useLayoutEffect } from "react";
  3. import { createPortal } from "react-dom";
  4. import clsx from "clsx";
  5. import { KEYS } from "../keys";
  6. export const Modal = (props: {
  7. className?: string;
  8. children: React.ReactNode;
  9. maxWidth?: number;
  10. onCloseRequest(): void;
  11. labelledBy: string;
  12. }) => {
  13. const modalRoot = useBodyRoot();
  14. if (!modalRoot) {
  15. return null;
  16. }
  17. const handleKeydown = (event: React.KeyboardEvent) => {
  18. if (event.key === KEYS.ESCAPE) {
  19. event.nativeEvent.stopImmediatePropagation();
  20. props.onCloseRequest();
  21. }
  22. };
  23. return createPortal(
  24. <div
  25. className={clsx("Modal", props.className)}
  26. role="dialog"
  27. aria-modal="true"
  28. onKeyDown={handleKeydown}
  29. aria-labelledby={props.labelledBy}
  30. >
  31. <div className="Modal__background" onClick={props.onCloseRequest}></div>
  32. <div
  33. className="Modal__content"
  34. style={{ "--max-width": `${props.maxWidth}px` }}
  35. >
  36. {props.children}
  37. </div>
  38. </div>,
  39. modalRoot,
  40. );
  41. };
  42. const useBodyRoot = () => {
  43. const [div, setDiv] = useState<HTMLDivElement | null>(null);
  44. useLayoutEffect(() => {
  45. const isDarkTheme = !!document
  46. .querySelector(".excalidraw")
  47. ?.classList.contains("Appearance_dark");
  48. const div = document.createElement("div");
  49. div.classList.add("excalidraw", "excalidraw-modal-container");
  50. if (isDarkTheme) {
  51. div.classList.add("Appearance_dark");
  52. div.classList.add("Appearance_dark-background-none");
  53. }
  54. document.body.appendChild(div);
  55. setDiv(div);
  56. return () => {
  57. document.body.removeChild(div);
  58. };
  59. }, []);
  60. return div;
  61. };