import React, { useEffect, useCallback } from 'react'; import { X } from 'lucide-react'; import { createPortal } from 'react-dom'; export type ModalSize = 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl' | '5xl' | '6xl' | 'full'; interface ModalProps { isOpen: boolean; onClose: () => void; title?: string | React.ReactNode; children: React.ReactNode; footer?: React.ReactNode; size?: ModalSize; showCloseButton?: boolean; closeOnOverlayClick?: boolean; closeOnEscape?: boolean; className?: string; contentClassName?: string; /** If true, prevents body scroll when modal is open */ preventScroll?: boolean; } const sizeClasses: Record = { sm: 'max-w-sm', md: 'max-w-md', lg: 'max-w-lg', xl: 'max-w-xl', '2xl': 'max-w-2xl', '3xl': 'max-w-3xl', '4xl': 'max-w-4xl', '5xl': 'max-w-5xl', '6xl': 'max-w-6xl', full: 'max-w-full mx-4', }; export const Modal: React.FC = ({ isOpen, onClose, title, children, footer, size = 'md', showCloseButton = true, closeOnOverlayClick = true, closeOnEscape = true, className = '', contentClassName = '', preventScroll = true, }) => { // Handle escape key const handleEscape = useCallback( (e: KeyboardEvent) => { if (closeOnEscape && e.key === 'Escape') { onClose(); } }, [closeOnEscape, onClose] ); useEffect(() => { if (isOpen) { document.addEventListener('keydown', handleEscape); if (preventScroll) { document.body.style.overflow = 'hidden'; } } return () => { document.removeEventListener('keydown', handleEscape); if (preventScroll) { document.body.style.overflow = ''; } }; }, [isOpen, handleEscape, preventScroll]); if (!isOpen) return null; const handleOverlayClick = (e: React.MouseEvent) => { if (closeOnOverlayClick && e.target === e.currentTarget) { onClose(); } }; const modalContent = (
e.stopPropagation()} > {/* Header */} {(title || showCloseButton) && (
{title && (

{title}

)} {showCloseButton && ( )}
)} {/* Content */}
{children}
{/* Footer */} {footer && (
{footer}
)}
); // Use portal to render modal at document body level return createPortal(modalContent, document.body); }; export default Modal;