import { ModalProviderProps, ModalType } from "./types"; import { useCallback, useState, useMemo } from "react"; import * as React from "react"; import { ModalContext } from "./context"; import { ModalRoot } from "./components"; /** * Provides a context for managing modals within the application. * @param container The DOM element to render modals into. * @param rootComponent The root component to render modal content within. * @param children The child components to render within the modal provider. */ export function ModalProvider({ container, rootComponent, children }: ModalProviderProps) { // State to manage currently active modals const [modals, setModals] = useState>({}); // Function to display a modal const showModal = useCallback( (key: string, modal: ModalType) => setModals(modals => ({ ...modals, [key]: modal })), [] ); // Function to hide a modal const hideModal = useCallback( (key: string) => setModals(modals => { if (!modals[key]) { return modals; } const newModals = { ...modals }; delete newModals[key]; return newModals; }), [] ); // Memoized context value to prevent unnecessary re-renders const contextValue = useMemo(() => ({ showModal, hideModal }), []); // Render modal provider with context and children return ( {children} {/* Render the modal root component */} ); }