mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
77 lines
1.6 KiB
TypeScript
77 lines
1.6 KiB
TypeScript
'use client';
|
|
|
|
import {
|
|
ReactNode,
|
|
RefObject,
|
|
useCallback,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
} from 'react';
|
|
import { cn } from '@/lib/helper';
|
|
|
|
export const useModal = () => {
|
|
const ref = useRef<HTMLDialogElement>(null);
|
|
const [open, setOpen] = useState(false);
|
|
|
|
const openModal = useCallback(() => {
|
|
if (!ref.current) return;
|
|
ref.current.show();
|
|
setOpen(true);
|
|
}, []);
|
|
|
|
const closeModal = useCallback(() => {
|
|
if (!ref.current) return;
|
|
ref.current.close();
|
|
setOpen(false);
|
|
}, []);
|
|
|
|
const toggle = useCallback(() => {
|
|
open ? closeModal() : openModal();
|
|
}, [open, closeModal, openModal]);
|
|
|
|
useEffect(() => {
|
|
const dialog = ref.current;
|
|
if (!dialog) return;
|
|
|
|
const handleClose = () => setOpen(false);
|
|
dialog.addEventListener('close', handleClose);
|
|
|
|
return () => {
|
|
dialog.removeEventListener('close', handleClose);
|
|
};
|
|
}, []);
|
|
|
|
return { ref, open, openModal, closeModal, toggle } as const;
|
|
};
|
|
|
|
interface ModalProps {
|
|
ref: RefObject<HTMLDialogElement | null>;
|
|
children?: ReactNode;
|
|
closeOnBackdrop?: boolean;
|
|
className?: {
|
|
modal?: string;
|
|
modalBox?: string;
|
|
};
|
|
}
|
|
|
|
const Modal = ({ ref, children, closeOnBackdrop, className }: ModalProps) => {
|
|
const handleBackdropClick = (e: React.MouseEvent<HTMLDialogElement>) => {
|
|
if (closeOnBackdrop && e.target === ref.current) {
|
|
ref.current?.close();
|
|
}
|
|
};
|
|
|
|
return (
|
|
<dialog
|
|
ref={ref}
|
|
className={cn('modal', className?.modal)}
|
|
onClick={handleBackdropClick}
|
|
>
|
|
<div className={cn('modal-box', className?.modalBox)}>{children}</div>
|
|
</dialog>
|
|
);
|
|
};
|
|
|
|
export default Modal;
|