let overlay: HTMLDivElement | null = null; let input: HTMLInputElement | null = null; let changeHandler: (() => void) | null = null; // Copied from https://github.com/mirainc/raydiant-elements/blob/master/src/presentation/PresentationForm/inputs/FileInput/FileInput.tsx#L18 const acceptTypeMap = { image: [ 'image/png', 'image/jpeg', 'image/svg+xml', 'image/bmp', 'image/tiff', 'image/gif', ], video: [ 'video/mp4', 'video/mpeg', 'video/quicktime', 'video/x-m4v', 'video/webm', ], spreadsheet: [ 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ], pdf: ['application/pdf'], } as const; const createOverlay = () => { const overlay = document.createElement('div'); overlay.style.position = 'fixed'; overlay.style.top = '0'; overlay.style.left = '0'; overlay.style.width = '100%'; overlay.style.height = '100%'; overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'; overlay.style.zIndex = '9999'; // Set text content overlay.innerText = 'Click here to select a file'; overlay.style.fontFamily = '-apple-system, "Segoe UI", Helvetica Neue, Helvetica, Roboto, Arial, sans-serif, system-ui, "Apple Color Emoji", "Segoe UI Emoji"'; overlay.style.fontSize = '32px'; overlay.style.color = '#fff'; overlay.style.display = 'flex'; overlay.style.justifyContent = 'center'; overlay.style.alignItems = 'center'; return overlay; }; const createFileInput = () => { const input = document.createElement('input'); input.type = 'file'; input.multiple = false; // Span width and height of its parent. input.style.position = 'absolute'; input.style.top = '0'; input.style.left = '0'; input.style.width = '100%'; input.style.height = '100%'; input.style.zIndex = '99999'; input.style.cursor = 'pointer'; // Hide the input. input.style.opacity = '0'; return input; }; export async function openFileSelector( type: string ): Promise { return new Promise((resolve) => { overlay = overlay || createOverlay(); input = input || createFileInput(); input.accept = (acceptTypeMap[type] ?? []).join(); // Remove previous change handler if it exists. if (changeHandler) { input.removeEventListener('change', changeHandler); } // Add change handler. changeHandler = () => { // We currently only support selecting a single file in the File Input. if (input?.files?.[0]) { resolve(input.files[0]); } closeFileSelector(); }; input.addEventListener('change', changeHandler); overlay.appendChild(input); // Add overlay to the DOM. document.body.appendChild(overlay); }); } export function closeFileSelector() { if (input) { input.remove(); input = null; } if (overlay) { overlay.remove(); overlay = null; } changeHandler = null; }