| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- import { JSX } from "preact";
- import { useEffect, useState } from "preact/hooks";
- 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 {
- interface Window {
- $modal?: ModalGlobalHook;
- }
- }
- 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(() => {
- window.$modal = {
- show: (
- title: string,
- content: string | JSX.Element,
- actions: ModalAction[],
- ) => showModal(title, content, actions),
- hide: () => hideModal(),
- };
- return () => {
- delete window.$modal;
- };
- }, []);
- return (
- <>
- <div className={`pd-modal${!visible ? " pd-modal-hidden" : ""}`}>
- <div className="pd-modal-content">
- <i
- className="bi bi-x pd-modal-close"
- onClick={() => {
- hideModal();
- }}
- />
- {title ? <div className="pd-modal-title">{title}</div> : null}
- <div className="pd-modal-body">{content}</div>
- {actions.length > 0
- ? (
- <div className="pd-modal-footer">
- {actions.map((action, index) => (
- <button
- key={index}
- onClick={() => {
- action.onClick
- ? action.onClick(action.text)
- : hideModal();
- }}
- >
- {action.text}
- </button>
- ))}
- </div>
- )
- : null}
- </div>
- </div>
- </>
- );
- }
|