| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- import { JSX } from "preact";
- import { useEffect, useState } from "preact/hooks";
- import Button from "../components/form/Button.tsx";
- interface ModalAction {
- text: string;
- onClick?: (text: string) => void | Promise<void>;
- }
- interface ModalGlobalHook {
- show: (
- title: string,
- content: string | JSX.Element,
- actions: ModalAction[],
- ) => void;
- hide: () => void;
- }
- declare global {
- var $modal: ModalGlobalHook | undefined;
- }
- export default function Modal() {
- const [visible, setVisible] = useState(false);
- const [title, setTitle] = useState("");
- const [content, setContent] = useState<string | JSX.Element>("");
- const [actions, setActions] = useState<ModalAction[]>([]);
- const showModal = (
- newTitle: string,
- newContent: string | JSX.Element,
- newActions: ModalAction[],
- ) => {
- setTitle(newTitle || "");
- setContent(newContent || "");
- setActions(newActions || []);
- setVisible(true);
- };
- const hideModal = () => {
- setVisible(false);
- };
- useEffect(() => {
- globalThis.$modal = {
- show: (
- title: string,
- content: string | JSX.Element,
- actions: ModalAction[],
- ) => showModal(title, content, actions),
- hide: () => hideModal(),
- };
- return () => {
- delete globalThis.$modal;
- };
- }, []);
- return (
- <>
- <div
- className={`fixed inset-0 bg-black/60 z-[8] flex items-center justify-center ${
- !visible ? "hidden" : ""
- }`}
- >
- <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg w-[500px] max-w-[90%] max-h-[60%] relative text-base cursor-pointer">
- <i
- className="bi bi-x absolute right-4 top-3 text-2xl"
- onClick={() => {
- hideModal();
- }}
- />
- {title
- ? (
- <div className="p-4 border-b border-gray-200 dark:border-gray-700 font-medium">
- {title}
- </div>
- )
- : null}
- <div className="p-4">{content}</div>
- {actions.length > 0
- ? (
- <div className="flex justify-end border-t border-gray-200 dark:border-gray-700 p-4">
- {actions.map((action, index) => (
- <Button
- type="button"
- key={index}
- className="ml-2 first:ml-0"
- onClick={() => {
- action.onClick
- ? action.onClick(action.text)
- : hideModal();
- }}
- >
- {action.text}
- </Button>
- ))}
- </div>
- )
- : null}
- </div>
- </div>
- </>
- );
- }
|