Modal.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { JSX } from "preact";
  2. import { useEffect, useState } from "preact/hooks";
  3. import Button from "../components/form/Button.tsx";
  4. interface ModalAction {
  5. text: string;
  6. onClick?: (text: string) => void | Promise<void>;
  7. }
  8. interface ModalGlobalHook {
  9. show: (
  10. title: string,
  11. content: string | JSX.Element,
  12. actions: ModalAction[],
  13. ) => void;
  14. hide: () => void;
  15. }
  16. declare global {
  17. var $modal: ModalGlobalHook | undefined;
  18. }
  19. export default function Modal() {
  20. const [visible, setVisible] = useState(false);
  21. const [title, setTitle] = useState("");
  22. const [content, setContent] = useState<string | JSX.Element>("");
  23. const [actions, setActions] = useState<ModalAction[]>([]);
  24. const showModal = (
  25. newTitle: string,
  26. newContent: string | JSX.Element,
  27. newActions: ModalAction[],
  28. ) => {
  29. setTitle(newTitle || "");
  30. setContent(newContent || "");
  31. setActions(newActions || []);
  32. setVisible(true);
  33. };
  34. const hideModal = () => {
  35. setVisible(false);
  36. };
  37. useEffect(() => {
  38. globalThis.$modal = {
  39. show: (
  40. title: string,
  41. content: string | JSX.Element,
  42. actions: ModalAction[],
  43. ) => showModal(title, content, actions),
  44. hide: () => hideModal(),
  45. };
  46. return () => {
  47. delete globalThis.$modal;
  48. };
  49. }, []);
  50. return (
  51. <>
  52. <div className={`fixed inset-0 bg-black/60 z-[8] flex items-center justify-center ${!visible ? "hidden" : ""}`}>
  53. <div className="bg-white border border-gray-200 rounded-lg w-[500px] max-w-[90%] max-h-[60%] relative text-base cursor-pointer">
  54. <i
  55. className="bi bi-x absolute right-4 top-3 text-2xl"
  56. onClick={() => {
  57. hideModal();
  58. }}
  59. />
  60. {title ? <div className="p-4 border-b border-gray-200 font-medium">{title}</div> : null}
  61. <div className="p-4">{content}</div>
  62. {actions.length > 0
  63. ? (
  64. <div className="flex justify-end border-t border-gray-200 p-4">
  65. {actions.map((action, index) => (
  66. <Button
  67. type="button"
  68. key={index}
  69. className="ml-2 first:ml-0"
  70. onClick={() => {
  71. action.onClick
  72. ? action.onClick(action.text)
  73. : hideModal();
  74. }}
  75. >
  76. {action.text}
  77. </Button>
  78. ))}
  79. </div>
  80. )
  81. : null}
  82. </div>
  83. </div>
  84. </>
  85. );
  86. }