import styles from './contained-overlay.module.css'; interface OpenOptions { returnFocus?: HTMLElement | null; initialFocus?: HTMLElement | null; } interface CloseOptions { restoreFocus?: boolean; immediate?: boolean; } interface ReplacePanelOptions { initialFocus?: HTMLElement | null; } interface ContainedOverlayManager { open: (options?: OpenOptions) => boolean; close: (options?: CloseOptions) => boolean; replacePanel: (panel: HTMLElement, options?: ReplacePanelOptions) => boolean; refresh: () => void; isOpen: () => boolean; destroy: () => void; } interface CreateOptions extends OpenOptions { layer: HTMLElement; panel: HTMLElement; onClose?: (manager: ContainedOverlayManager) => void; onClosed?: (manager: ContainedOverlayManager) => void; closeOnBackdrop?: boolean; closeOnEscape?: boolean; modal?: boolean; isolationRoot?: HTMLElement; decorate?: boolean; } interface OverlayEntry { id: symbol; layer: HTMLElement; panel: HTMLElement; modal: boolean; isolationRoot?: HTMLElement; closeOnEscape: boolean; scoped: boolean; initialFocus: HTMLElement | null; returnFocus: HTMLElement | null; open: boolean; closingTimer: number | null; releaseViewport: (() => void) | null; requestClose: () => void; } interface IsolationState { node: HTMLElement; inert: boolean; ariaHidden: string | null; } interface ViewportLockState { htmlOverflow: string; htmlOverscroll: string; bodyOverflow: string; bodyOverscroll: string; bodyPosition: string; bodyTop: string; bodyLeft: string; bodyWidth: string; bodyBoxSizing: string; scrollX: number; scrollY: number; } interface FotogenicWindow extends Window { FotogenicAI?: { Shared?: { ui?: { containedOverlay?: Readonly<{ create: (options: CreateOptions) => ContainedOverlayManager; lockViewport: () => () => void; }>; }; }; }; } const css = (name: string): string => { const value = styles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} contained-overlay style.`); return value; }; const focusableSelector = [ 'button:not(:disabled)', '[href]', 'input:not(:disabled)', 'select:not(:disabled)', 'textarea:not(:disabled)', '[tabindex]:not([tabindex="-1"])', ].join(','); const overlayStack: OverlayEntry[] = []; let isolatedNodes: IsolationState[] = []; let viewportLockCount = 0; let viewportLockState: ViewportLockState | null = null; const focusableElements = (panel: HTMLElement | null): HTMLElement[] => ( panel ? [...panel.querySelectorAll(focusableSelector)].filter((element) => ( element.tabIndex >= 0 && !element.matches(':disabled') && element.getClientRects().length > 0 && !element.closest('[inert]') )) : [] ); const clearIsolation = (): void => { isolatedNodes.forEach(({ node, inert, ariaHidden }) => { // Respect attributes changed by a containing host during its teardown. if (node.hasAttribute('inert')) { if (inert) node.setAttribute('inert', ''); else node.removeAttribute('inert'); } if (node.getAttribute('aria-hidden') === 'true') { if (ariaHidden === null) node.removeAttribute('aria-hidden'); else node.setAttribute('aria-hidden', ariaHidden); } }); isolatedNodes = []; }; const isolationExempt = (node: HTMLElement): boolean => node.matches( '#fotogenic-ai-notifications-root, .fotogenic-ai-global-toast-stack, .fotogenic-ai-studio-sr-only, script, style', ); const refreshIsolation = (): void => { clearIsolation(); const entry = overlayStack.findLast((candidate) => candidate.modal); if (!entry) return; const nestedModal = [...entry.layer.querySelectorAll('[aria-modal="true"]')].at(-1); let activeNode: HTMLElement | null = nestedModal ?? entry.panel; const boundary = nestedModal || !entry.scoped ? document.body : entry.isolationRoot; while (activeNode?.parentElement && activeNode !== boundary) { const parent: HTMLElement = activeNode.parentElement; [...parent.children].forEach((candidate) => { if (!(candidate instanceof HTMLElement) || candidate === activeNode || isolationExempt(candidate)) return; isolatedNodes.push({ node: candidate, inert: candidate.hasAttribute('inert'), ariaHidden: candidate.getAttribute('aria-hidden'), }); candidate.setAttribute('inert', ''); candidate.setAttribute('aria-hidden', 'true'); }); activeNode = parent; } }; const acquireViewportLock = (): void => { viewportLockCount += 1; if (viewportLockCount > 1) return; const bodyStyle = window.getComputedStyle(document.body); const bodyIsFixed = bodyStyle.position === 'fixed'; // A containing host already owns this physical lock and its restoration. if (bodyIsFixed && document.documentElement.style.overflow === 'hidden') return; viewportLockState = { htmlOverflow: document.documentElement.style.overflow, htmlOverscroll: document.documentElement.style.overscrollBehavior, bodyOverflow: document.body.style.overflow, bodyOverscroll: document.body.style.overscrollBehavior, bodyPosition: document.body.style.position, bodyTop: document.body.style.top, bodyLeft: document.body.style.left, bodyWidth: document.body.style.width, bodyBoxSizing: document.body.style.boxSizing, scrollX: window.scrollX, scrollY: window.scrollY, }; if (!bodyIsFixed) { const bodyRect = document.body.getBoundingClientRect(); const top = bodyRect.top - (Number.parseFloat(bodyStyle.marginTop) || 0); const left = bodyRect.left - (Number.parseFloat(bodyStyle.marginLeft) || 0); // Pin the visible page before hiding HTML overflow clamps its scroll range. document.body.style.position = 'fixed'; document.body.style.top = `${top}px`; document.body.style.left = `${left}px`; // Keep the pre-lock scrollbar/margin space while allowing orientation changes. document.body.style.width = `calc(100% - ${window.innerWidth - bodyRect.width}px)`; document.body.style.boxSizing = 'border-box'; } document.documentElement.style.overflow = 'hidden'; document.documentElement.style.overscrollBehavior = 'none'; document.body.style.overflow = 'visible'; document.body.style.overscrollBehavior = 'none'; }; const releaseViewportLock = (): void => { viewportLockCount = Math.max(0, viewportLockCount - 1); if (viewportLockCount || !viewportLockState) return; document.documentElement.style.overflow = viewportLockState.htmlOverflow; document.documentElement.style.overscrollBehavior = viewportLockState.htmlOverscroll; document.body.style.overflow = viewportLockState.bodyOverflow; document.body.style.overscrollBehavior = viewportLockState.bodyOverscroll; document.body.style.position = viewportLockState.bodyPosition; document.body.style.top = viewportLockState.bodyTop; document.body.style.left = viewportLockState.bodyLeft; document.body.style.width = viewportLockState.bodyWidth; document.body.style.boxSizing = viewportLockState.bodyBoxSizing; const { scrollX, scrollY } = viewportLockState; viewportLockState = null; window.scrollTo({ left: scrollX, top: scrollY, behavior: 'instant' }); }; // Each modal host holds one lease until its closing animation finishes. const lockViewport = (): (() => void) => { acquireViewportLock(); let released = false; return () => { if (released) return; released = true; releaseViewportLock(); }; }; const revealFocus = (entry: OverlayEntry, focusTarget: HTMLElement): void => { // Reveal the focused control and its outline within the dialog's own viewport. const clearance = 4; for (let parent = focusTarget.parentElement; parent && entry.panel.contains(parent); parent = parent.parentElement) { if (parent.scrollHeight <= parent.clientHeight) continue; const target = focusTarget.getBoundingClientRect(); const viewport = parent.getBoundingClientRect(); if (target.top - clearance < viewport.top) parent.scrollTop -= viewport.top - target.top + clearance; else if (target.bottom + clearance > viewport.bottom) parent.scrollTop += target.bottom - viewport.bottom + clearance; } }; const focusEntry = (entry: OverlayEntry): void => { const focusTarget = entry.initialFocus?.isConnected ? entry.initialFocus : entry.panel.querySelector('[data-fa-overlay-heading][tabindex="-1"]') ?? focusableElements(entry.panel)[0] ?? entry.panel; focusTarget.focus({ preventScroll: true }); revealFocus(entry, focusTarget); }; let viewportFrame = 0; const syncPresentation = (entry: OverlayEntry): void => { entry.scoped = Boolean(entry.isolationRoot) && window.getComputedStyle(entry.layer).position !== 'fixed'; entry.panel.setAttribute('aria-modal', String(entry.modal && !entry.scoped)); if (entry.modal && !entry.scoped && !entry.releaseViewport) entry.releaseViewport = lockViewport(); else if (entry.scoped && entry.releaseViewport) { entry.releaseViewport(); entry.releaseViewport = null; } }; const handleViewportResize = (): void => { window.cancelAnimationFrame(viewportFrame); viewportFrame = window.requestAnimationFrame(() => { viewportFrame = 0; overlayStack.forEach(syncPresentation); refreshIsolation(); const entry = overlayStack.at(-1); const active = document.activeElement; if (entry?.open && active instanceof HTMLElement && entry.panel.contains(active)) revealFocus(entry, active); }); }; const handleKeyDown = (event: KeyboardEvent): void => { const entry = overlayStack.at(-1); if (!entry?.open) return; if ((!entry.modal || entry.scoped) && !(event.target instanceof HTMLElement && entry.layer.contains(event.target))) return; const nestedNativeDialog = event.target instanceof HTMLElement ? event.target.closest('dialog[open]') : null; const nestedWordPressModal = event.target instanceof HTMLElement ? event.target.closest('#wp-media-modal[role="dialog"]') : null; if (nestedWordPressModal) return; if (event.key === 'Escape' && event.target instanceof HTMLElement && event.target.closest('.fotogenic-ai-custom-select')?.querySelector('[aria-expanded="true"]')) return; if (nestedNativeDialog && entry.layer.contains(nestedNativeDialog) && nestedNativeDialog !== entry.panel) { return; } if (event.key === 'Escape') { event.preventDefault(); event.stopImmediatePropagation(); if (entry.closeOnEscape) entry.requestClose(); return; } if (event.key !== 'Tab' || !entry.modal || entry.scoped) return; event.stopImmediatePropagation(); const focusable = focusableElements(entry.panel); if (!focusable.length) { event.preventDefault(); entry.panel.focus(); return; } const activeElement = document.activeElement; const activeIndex = activeElement instanceof HTMLElement ? focusable.indexOf(activeElement) : -1; const nextIndex = activeIndex < 0 ? (event.shiftKey ? focusable.length - 1 : 0) : (activeIndex + (event.shiftKey ? -1 : 1) + focusable.length) % focusable.length; // Some browser preferences skip buttons during native Tab navigation. // Own each modal step so focus cannot leave the dialog between its endpoints. event.preventDefault(); focusable[nextIndex]?.focus(); }; const register = (entry: OverlayEntry): void => { if (overlayStack.includes(entry)) return; overlayStack.push(entry); if (overlayStack.length === 1) { document.addEventListener('keydown', handleKeyDown, true); window.addEventListener('resize', handleViewportResize); window.visualViewport?.addEventListener('resize', handleViewportResize); } syncPresentation(entry); refreshIsolation(); }; const unregister = (entry: OverlayEntry, restoreFocus: boolean): void => { const index = overlayStack.findIndex((candidate) => candidate.id === entry.id); if (index < 0) return; overlayStack.splice(index, 1); entry.releaseViewport?.(); entry.releaseViewport = null; if (!overlayStack.length) { document.removeEventListener('keydown', handleKeyDown, true); window.removeEventListener('resize', handleViewportResize); window.visualViewport?.removeEventListener('resize', handleViewportResize); window.cancelAnimationFrame(viewportFrame); viewportFrame = 0; } refreshIsolation(); const next = overlayStack.at(-1); window.requestAnimationFrame(() => { if (entry.open || overlayStack.at(-1) !== next) return; if (next?.open) focusEntry(next); else if (!next && restoreFocus && entry.returnFocus?.isConnected) entry.returnFocus.focus({ preventScroll: true }); }); }; const createContainedOverlay = ({ layer, panel, onClose, onClosed, closeOnBackdrop = true, closeOnEscape = true, modal = true, isolationRoot, initialFocus = null, returnFocus = null, decorate = true, }: CreateOptions): ContainedOverlayManager => { if (!(layer instanceof HTMLElement) || !(panel instanceof HTMLElement) || !layer.contains(panel)) { throw new TypeError('Contained overlay requires one layer and a contained panel.'); } if (isolationRoot && !isolationRoot.contains(layer)) throw new TypeError('Overlay isolation root must contain its layer.'); let manager: ContainedOverlayManager; let revision = 0; let destroyed = false; const entry: OverlayEntry = { id: Symbol('fotogenic-contained-overlay'), layer, panel, modal, isolationRoot, scoped: Boolean(isolationRoot), closeOnEscape, initialFocus, returnFocus, open: false, closingTimer: null, releaseViewport: null, requestClose: () => { if (onClose) onClose(manager); else manager.close(); }, }; if (decorate) { layer.classList.add(css('layer'), 'fotogenic-ai-contained-overlay'); panel.classList.add(css('panel'), 'fotogenic-ai-contained-overlay__panel'); } if (panel.tabIndex < 0) panel.tabIndex = -1; panel.setAttribute('aria-modal', String(modal && !isolationRoot)); if (!panel.getAttribute('role')) panel.setAttribute('role', 'dialog'); const handleBackdrop = (event: MouseEvent): void => { if (closeOnBackdrop && event.target === layer) entry.requestClose(); }; layer.addEventListener('mousedown', handleBackdrop); manager = Object.freeze({ open(options: OpenOptions = {}): boolean { if (destroyed) return false; if (entry.open) { refreshIsolation(); return false; } if (entry.closingTimer !== null) { window.clearTimeout(entry.closingTimer); entry.closingTimer = null; } entry.returnFocus = options.returnFocus?.focus ? options.returnFocus : returnFocus?.focus ? returnFocus : document.activeElement instanceof HTMLElement && document.activeElement !== document.body ? document.activeElement : null; entry.initialFocus = options.initialFocus?.focus ? options.initialFocus : initialFocus; entry.open = true; layer.hidden = false; layer.classList.remove('is-closing'); register(entry); const openingRevision = ++revision; // Establish the closed transform before the next paint starts the transition. layer.getBoundingClientRect(); window.requestAnimationFrame(() => { if (!entry.open || destroyed || openingRevision !== revision) return; layer.classList.add('is-open'); focusEntry(entry); }); return true; }, close({ restoreFocus = true, immediate = false }: CloseOptions = {}): boolean { if (!entry.open && entry.closingTimer === null) return false; ++revision; if (entry.closingTimer !== null) window.clearTimeout(entry.closingTimer); entry.open = false; entry.panel.classList.remove(css('panelImmediate')); layer.classList.remove('is-open'); layer.classList.add('is-closing'); const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true; const finish = (): void => { entry.closingTimer = null; layer.classList.remove('is-closing'); layer.hidden = true; unregister(entry, restoreFocus); onClosed?.(manager); }; if (immediate || reducedMotion) finish(); else entry.closingTimer = window.setTimeout(finish, 230); return true; }, replacePanel(nextPanel: HTMLElement, options: ReplacePanelOptions = {}): boolean { if (!(nextPanel instanceof HTMLElement) || !entry.open || !entry.panel.isConnected) return false; const previousPanel = entry.panel; if (decorate) { previousPanel.classList.remove(css('panel'), css('panelImmediate'), 'fotogenic-ai-contained-overlay__panel'); nextPanel.classList.add(css('panel'), css('panelImmediate'), 'fotogenic-ai-contained-overlay__panel'); } if (nextPanel.tabIndex < 0) nextPanel.tabIndex = -1; nextPanel.setAttribute('aria-modal', String(modal && !entry.scoped)); if (!nextPanel.getAttribute('role')) nextPanel.setAttribute('role', 'dialog'); previousPanel.replaceWith(nextPanel); entry.panel = nextPanel; entry.initialFocus = options.initialFocus?.focus ? options.initialFocus : null; refreshIsolation(); const replacementRevision = revision; window.requestAnimationFrame(() => { if (entry.open && !destroyed && replacementRevision === revision) focusEntry(entry); }); return true; }, refresh(): void { if (entry.open) refreshIsolation(); }, isOpen: (): boolean => entry.open, destroy(): void { manager.close({ restoreFocus: false, immediate: true }); destroyed = true; ++revision; layer.removeEventListener('mousedown', handleBackdrop); if (decorate) { layer.classList.remove(css('layer'), 'fotogenic-ai-contained-overlay', 'is-open', 'is-closing'); entry.panel.classList.remove(css('panel'), css('panelImmediate'), 'fotogenic-ai-contained-overlay__panel'); } }, }); layer.hidden = true; return manager; }; const globalWindow = window as FotogenicWindow; globalWindow.FotogenicAI = globalWindow.FotogenicAI ?? {}; globalWindow.FotogenicAI.Shared = globalWindow.FotogenicAI.Shared ?? {}; globalWindow.FotogenicAI.Shared.ui = globalWindow.FotogenicAI.Shared.ui ?? {}; globalWindow.FotogenicAI.Shared.ui.containedOverlay = Object.freeze({ create: createContainedOverlay, lockViewport }); export type { CloseOptions, ContainedOverlayManager, CreateOptions, OpenOptions, ReplacePanelOptions }; export { createContainedOverlay };