| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- /** @jsx h */
- /** @jsxFrag Fragment */
- import { JSX, Fragment, h } from "preact";
- import { useState, useEffect } 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>
- </>
- );
- }
|