import { globalState } from '../../../app/global-state'; import PowerduckState from '../../../app/powerduck-state'; import NotificationProvider from '../../ui/notification'; import { ModalUtils } from '../modal-utils'; import './../css/file-manager-dialog.css'; export enum FileManagerModalFileType { Image = 1, All = 2, Media = 3, } interface FileManagerModalResponseArgs { url: string; } interface FileManagerModalArgsBase { fileType?: FileManagerModalFileType; maxWidth?: number; itemId?: number; } interface FileManagerModalArgs extends FileManagerModalArgsBase { callback: (args: FileManagerModalResponseArgs) => void; } /** * File picker dialog. Fixed compared to the previous implementation: * * 1. `.remove()` left the Bootstrap instance, backdrop and scroll lock alive, * so from the SECOND open onwards a click-eating backdrop stayed behind. * 2. Opening while the previous modal faded out let its teardown strip * `body.modal-open`, the scroll lock and the backdrop from under us - BS5 * has no stacked-modal support. * 3. The iframe was attached while the modal was still `display: none`. WebKit * does not load frames in a non-rendered subtree, so the loading overlay * never cleared and swallowed every click. * 4. `showPromise()` never settled on dismiss, hanging `await` callers forever. */ export class FileManagerDialog { static modalIframeUrlBase: string = '/assets/plugins/tinymce/plugins/tinyfilemanager.net/dialog/tfmdialog?callback=onMceDialogCallback&editor=noeditor'; private static readonly DIALOG_ID = 'fileManagerDialog'; /** Upper bound for waiting on a previous modal's fade-out (BS5 fade is ~300 ms). */ private static readonly TEARDOWN_WAIT_MS = 700; /** Safety net in case `hidden.bs.modal` never arrives, so callers cannot hang. */ private static readonly HIDE_FALLBACK_MS = 1500; /** Safety net for WebKit not firing `load` on a re-created frame. */ private static readonly IFRAME_LOAD_TIMEOUT_MS = 10000; /** Resolves with the selected file, or `null` when the dialog was dismissed. */ static showPromise(args: FileManagerModalArgsBase): Promise { return new Promise((resolve) => { this.showInternal(args, resolve); }); } /** `callback` fires only when a file was actually selected. */ static show(args: FileManagerModalArgs): void { this.showInternal(args, (result) => { if (result != null && args.callback != null) { args.callback(result); } }); } private static async showInternal( args: FileManagerModalArgsBase, settle: (result: FileManagerModalResponseArgs | null) => void, ): Promise { if (!globalState.windowExists) { settle(null); return; } // Fix 1 - drop whatever a previous run left behind, instance included. this.disposeDialog(); // Fix 2 - never open on top of a modal that is still tearing down. await this.waitForPendingModalTeardown(); this.sweepOrphanedModalState(); const template = document.createElement('template'); template.innerHTML = this.getModalTemplate().trim(); const dialogEl = template.content.firstElementChild as HTMLElement | null; if (dialogEl == null) { settle(null); return; } document.body.appendChild(dialogEl); let settled = false; let selected: FileManagerModalResponseArgs | null = null; let hideFallbackTimer: any = null; // Fix 4 - a single exit point that always settles, dismiss included. const finish = () => { if (settled) { return; } settled = true; if (hideFallbackTimer != null) { clearTimeout(hideFallbackTimer); } this.removeGlobalCallback(); this.disposeDialog(); settle(selected); }; dialogEl.addEventListener('hidden.bs.modal', finish); globalState.onMceDialogCallback = (cbArgs: FileManagerModalResponseArgs) => { if (settled) { return; } selected = cbArgs; this.removeGlobalCallback(); ModalUtils.hideModal({ modal: dialogEl }); hideFallbackTimer = setTimeout(finish, this.HIDE_FALLBACK_MS); }; // Fix 3 - attach the iframe only once the modal is actually rendered. const attachIframe = () => { if (!settled) { this.attachIframe(dialogEl, args); } }; dialogEl.addEventListener('shown.bs.modal', attachIframe, { once: true }); setTimeout(attachIframe, this.TEARDOWN_WAIT_MS + this.HIDE_FALLBACK_MS); ModalUtils.showModal(null, { modal: dialogEl, }); } private static attachIframe(dialogEl: HTMLElement, args: FileManagerModalArgsBase): void { const context = dialogEl.querySelector('.dialog-frame'); if (context == null || context.querySelector('iframe') != null) { return; } let iframeUrl = `${this.modalIframeUrlBase}&type=${args.fileType || 0}&lang=${PowerduckState.getCurrentLanguage()}`; if (args.maxWidth != null) { iframeUrl += `&maxwidth=${args.maxWidth.toString()}`; } if (args.itemId != null) { iframeUrl += `&itemid=${args.itemId.toString()}`; } let overlayCleared = false; const clearOverlay = () => { if (overlayCleared) { return; } overlayCleared = true; context.querySelector('.holdon-overlay')?.remove(); }; const ifr = document.createElement('iframe'); ifr.setAttribute('style', 'border:0px;height:600px;'); ifr.setAttribute('class', 'file-manager-iframe'); // The overlay covers the whole frame, so a missed `load` would leave the // picker permanently unclickable. Bound it. const loadWatchdog = setTimeout(clearOverlay, this.IFRAME_LOAD_TIMEOUT_MS); ifr.addEventListener('load', () => { clearTimeout(loadWatchdog); setTimeout(clearOverlay, 400); }); ifr.addEventListener('error', () => { clearTimeout(loadWatchdog); clearOverlay(); NotificationProvider.showErrorMessage('Error loading file manager'); }); context.appendChild(ifr); ifr.src = iframeUrl; } /** * Resolves once nothing is fading out. A modal that is legitimately open (the * picker opened from inside one) is not waited for - only a teardown in flight * can pull the body state out from under us. */ private static waitForPendingModalTeardown(): Promise { return new Promise((resolve) => { const startedAt = Date.now(); const isQuiet = (): boolean => { if (document.querySelector('.modal.show') != null) { return true; } // `display: block` lasts the whole fade-out, backdrop and // `body.modal-open` until `hidden.bs.modal`. Wait out both. const stillVisible = Array.from(document.querySelectorAll('.modal')) .some(el => el.style.display === 'block'); return !stillVisible && !document.body.classList.contains('modal-open') && document.querySelector('.modal-backdrop') == null; }; const tick = () => { if (isQuiet() || (Date.now() - startedAt) >= this.TEARDOWN_WAIT_MS) { resolve(); return; } setTimeout(tick, 25); }; tick(); }); } /** * Clears backdrop/body leftovers of modals detached without being disposed. * Only safe - and only needed - while no modal is on screen. */ private static sweepOrphanedModalState(): void { if (document.querySelector('.modal.show') != null) { return; } document.querySelectorAll('.modal-backdrop').forEach(el => el.remove()); document.body.classList.remove('modal-open'); document.body.style.removeProperty('overflow'); document.body.style.removeProperty('padding-right'); } private static disposeDialog(): void { const dialogEl = document.getElementById(this.DIALOG_ID); if (dialogEl == null) { return; } // Dispose first - a bare `.remove()` leaves the Bootstrap instance, its // backdrop and the scroll lock alive. ModalUtils.destroyModalInstance(dialogEl); dialogEl.remove(); } private static removeGlobalCallback(): void { try { delete globalState.onMceDialogCallback; } catch (e) { } } private static getModalTemplate(): string { return ''; } }