import { createRoot, type Root } from 'react-dom/client'; import { StrictMode, useEffect, useState } from 'react'; import { App } from './App'; import type { ModalOpenOptions } from './types'; import './modal.css'; type ModalApi = { open: ( nextOptions?: ModalOpenOptions ) => void; close: () => void; }; function ModalHost( { onReady }: { onReady: ( api: ModalApi ) => void } ) { const [ isOpen, setIsOpen ] = useState( false ); const [ options, setOptions ] = useState( {} ); useEffect( () => { onReady( { open( nextOptions = {} ) { setOptions( nextOptions ); setIsOpen( true ); }, close() { setIsOpen( false ); }, } ); }, [ onReady ] ); return setIsOpen( false ) } />; } let reactRoot: Root | null = null; let modalApi: ModalApi | null = null; let pendingOpen: ModalOpenOptions | null = null; function flushPendingOpen() { if ( modalApi && pendingOpen ) { modalApi.open( pendingOpen ); pendingOpen = null; } } function ensureModalRoot() { let rootElement = document.getElementById( 'voltax-vms-modal-root' ); if ( ! rootElement ) { rootElement = document.createElement( 'div' ); rootElement.id = 'voltax-vms-modal-root'; document.body.appendChild( rootElement ); return rootElement; } if ( rootElement.parentElement !== document.body ) { document.body.appendChild( rootElement ); } return rootElement; } function mountModal() { if ( reactRoot ) { return true; } const rootElement = ensureModalRoot(); if ( ! rootElement ) { return false; } reactRoot = createRoot( rootElement ); reactRoot.render( { modalApi = api; flushPendingOpen(); } } /> ); return true; } function schedulePendingOpen() { let attempts = 0; const maxAttempts = 40; function tryFlush() { if ( modalApi && pendingOpen ) { modalApi.open( pendingOpen ); pendingOpen = null; return; } attempts += 1; if ( attempts < maxAttempts ) { window.setTimeout( tryFlush, 25 ); } } tryFlush(); } window.voltaxModal = { open( nextOptions = {} ) { if ( ! mountModal() ) { pendingOpen = nextOptions; return; } if ( modalApi ) { modalApi.open( nextOptions ); return; } pendingOpen = nextOptions; schedulePendingOpen(); }, close() { if ( modalApi ) { modalApi.close(); } }, }; mountModal(); if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', mountModal ); } else { window.setTimeout( mountModal, 0 ); }