import styles from './toast.module.css'; type ToastType = 'success' | 'info' | 'warning' | 'danger' | 'error'; interface ToastActionInput { label?: unknown; onClick?: unknown; dismiss?: unknown; } interface ToastOptions { title?: unknown; actions?: readonly ToastActionInput[]; ttlMs?: unknown; dedupeKey?: unknown; activity?: unknown; episode?: unknown; onDismiss?: unknown; } interface ToastAction { label: string; onClick: (() => void) | null; dismiss: boolean; } interface Toast { id: string; type: ToastType; title: string; message: string; actions: ToastAction[]; ttlMs: number; dedupeKey: string; activity: boolean; episode: string; createdAt: number; onDismiss: (() => void) | null; } interface NotifyContext { i18n?: { __?: (text: string, domain?: string) => string; }; restUrl?: unknown; restNonce?: unknown; } interface RestResult { ok: boolean; data?: unknown; } type RestFetch = ( path: string, options?: { method?: string; body?: unknown; signal?: AbortSignal }, ) => Promise; interface IconApi { create: ( name: string, options: { weight: 'regular' | 'fill'; size: number }, ) => HTMLElement; } interface SharedNamespace { api?: { restFetch?: { createRestFetch?: (restUrl: string, nonce: string) => RestFetch; }; }; ui: { icon?: IconApi; notifications?: Record; }; } interface FotogenicWindow extends Window { FotogenicAI?: { Shared?: SharedNamespace; }; } interface ToastUi { show: (toast: Toast) => boolean; dismiss: (id: string) => void; clear: () => void; destroy: () => void; } interface NotifySystem { success: (message: string, options?: ToastOptions) => string | undefined; info: (message: string, options?: ToastOptions) => string | undefined; warning: (message: string, options?: ToastOptions) => string | undefined; danger: (message: string, options?: ToastOptions) => string | undefined; error: (message: string, options?: ToastOptions) => string | undefined; dismiss: (id: string) => void; clear: () => void; destroy: () => void; } const MAX_VISIBLE_NOTIFICATIONS = 3; let toastSequence = 0; const css = (name: string): string => { const value = styles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} toast style.`); return value; }; const text = (value: unknown, maximum: number): string => ( typeof value === 'string' ? value.trim().slice(0, maximum) : '' ); const createToast = (type: ToastType, message: string, options: ToastOptions = {}): Toast => { const title = text(options.title, 160); const safeMessage = text(message, 500); const requestedDuration = Number(options.ttlMs); const ttlMs = Number.isFinite(requestedDuration) ? Math.max(0, Math.min(60_000, Math.floor(requestedDuration))) : (['warning', 'danger', 'error'].includes(type) ? 7_200 : 5_200); const actions = (Array.isArray(options.actions) ? options.actions : []) .slice(0, 3) .map((action): ToastAction => ({ label: text(action?.label, 60), onClick: typeof action?.onClick === 'function' ? action.onClick as () => void : null, dismiss: action?.dismiss !== false, })) .filter((action) => action.label !== ''); const dedupeKey = text(options.dedupeKey, 180) || `${type}:${title}:${safeMessage}`; toastSequence += 1; return { id: `studio-notification-${Date.now()}-${toastSequence}`, type, title, message: safeMessage, actions, ttlMs, dedupeKey, activity: options.activity !== false, episode: text(options.episode, 80), createdAt: Date.now(), onDismiss: typeof options.onDismiss === 'function' ? options.onDismiss as () => void : null, }; }; const notificationText = (toast: Toast): string => ( [toast.title, toast.message].filter(Boolean).join('. ') ); const iconForType = (type: ToastType): { name: string; weight: 'regular' | 'fill' } => { if (type === 'success') return { name: 'check-circle', weight: 'fill' }; if (['warning', 'danger', 'error'].includes(type)) return { name: 'warning', weight: 'fill' }; return { name: 'info', weight: 'regular' }; }; const createLiveRegion = (role: 'status' | 'alert'): HTMLDivElement => { const region = document.createElement('div'); region.className = css('screenReader'); region.setAttribute('role', role); region.setAttribute('aria-live', role === 'alert' ? 'assertive' : 'polite'); region.setAttribute('aria-atomic', 'true'); return region; }; const createToastUi = ( root: HTMLElement, icons: IconApi, translate: (text: string) => string, ): ToastUi => { root.classList.add(css('stack')); root.setAttribute('aria-label', translate('Studio notifications')); root.removeAttribute('aria-live'); const politeRegion = createLiveRegion('status'); const assertiveRegion = createLiveRegion('alert'); root.append(politeRegion, assertiveRegion); const entries = new Map(); const activeDedupeKeys = new Set(); const closing = new Map(); const announce = (toast: Toast): void => { const region = ['warning', 'danger', 'error'].includes(toast.type) ? assertiveRegion : politeRegion; region.textContent = ''; window.requestAnimationFrame(() => { if (region.isConnected) region.textContent = notificationText(toast); }); }; const dismiss = (id: string, notify = true, immediate = false): void => { const entry = entries.get(id); if (!entry) return; window.clearTimeout(entry.timer); entries.delete(id); activeDedupeKeys.delete(entry.toast.dedupeKey); if (notify) entry.toast.onDismiss?.(); const restoreFocus = entry.element.contains(document.activeElement); const finish = (): void => { entry.element.remove(); closing.delete(id); if (restoreFocus) { const fallback = [...entries.values()].at(-1)?.element.querySelector('button:not(:disabled)') ?? document.querySelector('[data-fa-notification-toggle]'); fallback?.focus({ preventScroll: true }); } }; const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true; if (immediate || reducedMotion) { finish(); return; } entry.element.classList.add(css('is-closing')); closing.set(id, { element: entry.element, timer: window.setTimeout(finish, 160), }); }; const buildToast = (toast: Toast): HTMLElement => { const card = document.createElement('section'); card.className = [ css('toast'), css(toast.type), ...(toast.ttlMs > 0 ? [] : [css('persistent')]), ].join(' '); card.dataset.toastId = toast.id; card.style.setProperty('--toast-duration', `${toast.ttlMs}ms`); const iconContract = iconForType(toast.type); const icon = document.createElement('span'); icon.className = css('icon'); icon.appendChild(icons.create(iconContract.name, { weight: iconContract.weight, size: 17, })); const copy = document.createElement('div'); copy.className = css('copy'); if (toast.title) { const title = document.createElement('strong'); title.textContent = toast.title; copy.appendChild(title); } if (toast.message) { const message = document.createElement('p'); message.textContent = toast.message; copy.appendChild(message); } if (toast.actions.length > 0) { const actions = document.createElement('div'); actions.className = css('actions'); toast.actions.forEach((action) => { const button = document.createElement('button'); button.type = 'button'; button.textContent = action.label; button.addEventListener('click', () => { if (action.dismiss) dismiss(toast.id, false); action.onClick?.(); }); actions.appendChild(button); }); copy.appendChild(actions); } const close = document.createElement('button'); close.className = css('dismiss'); close.type = 'button'; close.setAttribute( 'aria-label', `${translate('Dismiss')} ${toast.title || toast.message || translate('notification')}`, ); close.appendChild(icons.create('x', { weight: 'regular', size: 16 })); close.addEventListener('click', () => dismiss(toast.id)); card.append(icon, copy, close); if (toast.ttlMs > 0) { const progress = document.createElement('span'); progress.className = css('progress'); progress.setAttribute('aria-hidden', 'true'); card.appendChild(progress); } return card; }; const show = (toast: Toast): boolean => { if (activeDedupeKeys.has(toast.dedupeKey)) return false; while (entries.size >= MAX_VISIBLE_NOTIFICATIONS) { const oldest = entries.keys().next().value as string | undefined; if (!oldest) break; dismiss(oldest, true, true); } const element = buildToast(toast); const timer = toast.ttlMs > 0 ? window.setTimeout(() => dismiss(toast.id), toast.ttlMs) : 0; entries.set(toast.id, { toast, element, timer }); activeDedupeKeys.add(toast.dedupeKey); root.appendChild(element); announce(toast); return true; }; const clear = (): void => { [...entries.keys()].forEach((id) => dismiss(id, false, true)); closing.forEach(({ element, timer }) => { window.clearTimeout(timer); element.remove(); }); closing.clear(); }; const hasVisibleModal = (): boolean => ( [...document.querySelectorAll('[aria-modal="true"]')] .some((element) => element.getClientRects().length > 0 && !element.closest('[hidden]')) ); const onKeyDown = (event: KeyboardEvent): void => { if (event.key !== 'Escape' || event.defaultPrevented || entries.size === 0) return; if (hasVisibleModal()) return; if (document.querySelector('[aria-haspopup][aria-expanded="true"]')) return; const latest = [...entries.keys()].at(-1); if (!latest) return; event.preventDefault(); dismiss(latest); }; document.addEventListener('keydown', onKeyDown); return Object.freeze({ show, dismiss, clear, destroy(): void { document.removeEventListener('keydown', onKeyDown); clear(); politeRegion.remove(); assertiveRegion.remove(); root.classList.remove(css('stack')); }, }); }; const hashMessage = (message: string): string => { let hash = 2_166_136_261; for (let index = 0; index < message.length; index += 1) { hash ^= message.charCodeAt(index); hash = Math.imul(hash, 16_777_619); } return (hash >>> 0).toString(16); }; const activitySemanticKey = (toast: Toast): string => { const requested = toast.dedupeKey.trim().toLowerCase().slice(0, 80); if (/^[a-z0-9][a-z0-9._:-]{0,79}$/.test(requested)) return requested; return `toast-${toast.type}-${hashMessage(`${toast.title}:${toast.message}`)}`; }; const getSharedNamespace = (): SharedNamespace => { const shared = (window as FotogenicWindow).FotogenicAI?.Shared; if (!shared?.ui) throw new Error('Fotogenic AI: shared namespace must load before notifications.'); return shared; }; export const createNotifySystem = (context: NotifyContext = {}): NotifySystem => { const shared = getSharedNamespace(); const icons = shared.ui.icon; if (!icons?.create) throw new Error('Fotogenic AI: icon system must load before notifications.'); const translate = (value: string): string => context.i18n?.__?.(value, 'fotogenic-ai') || value; const root = document.getElementById('fotogenic-ai-notifications-root'); if (!root) throw new Error('Fotogenic AI: notification root is unavailable.'); if (root.parentElement !== document.body) document.body.appendChild(root); const ui = createToastUi(root, icons, translate); const applicationRoot = document.querySelector( '[data-fa-studio-root], [data-fa-home], .fotogenic-ai-settings-shell', ); const header = document.querySelector('[data-fa-shared-toolbar]'); let geometryFrame = 0; let geometryObserver: ResizeObserver | null = null; const syncToastGeometry = (): void => { window.cancelAnimationFrame(geometryFrame); geometryFrame = window.requestAnimationFrame(() => { if (!root?.isConnected || !applicationRoot?.isConnected) return; const shellRect = applicationRoot.getBoundingClientRect(); const headerBottom = header?.getBoundingClientRect().bottom || 0; const adminBottom = document.getElementById('wpadminbar')?.getBoundingClientRect().bottom || 0; const narrow = shellRect.width <= 540; const inset = narrow ? 12 : (shellRect.width <= 820 ? 16 : 24); const width = Math.min(344, Math.max(0, shellRect.width - (inset * 2))); root.classList.add('is-positioned'); const top = Math.max(0, Math.min(window.innerHeight - inset, Math.max(headerBottom, adminBottom))) + inset; root.style.setProperty('--fa-toast-top', `${top}px`); root.style.setProperty('--fa-toast-right', narrow ? '12px' : `${Math.max(0, window.innerWidth - shellRect.right + inset)}px`); root.style.setProperty('--fa-toast-bottom', 'auto'); root.style.setProperty('--fa-toast-max-height', `${Math.max(0, window.innerHeight - top - inset)}px`); root.style.setProperty('--fa-toast-left', narrow ? '12px' : 'auto'); root.style.setProperty('--fa-toast-width', narrow ? 'auto' : `${width}px`); }); }; syncToastGeometry(); window.addEventListener('resize', syncToastGeometry); window.addEventListener('scroll', syncToastGeometry, { passive: true }); if (applicationRoot && typeof ResizeObserver === 'function') { geometryObserver = new ResizeObserver(syncToastGeometry); geometryObserver.observe(applicationRoot); if (header) geometryObserver.observe(header); } const createRestFetch = shared.api?.restFetch?.createRestFetch; const restUrl = text(context.restUrl, 500); const restNonce = text(context.restNonce, 200); const activityFetch = createRestFetch && restUrl && restNonce ? createRestFetch(restUrl, restNonce) : null; const persistActivity = async (toast: Toast): Promise => { if (!activityFetch || !toast.activity) return false; const result = await activityFetch('/notifications/upsert', { method: 'POST', body: { event: { semanticKey: activitySemanticKey(toast), episode: (toast.episode || toast.id).slice(0, 80), type: toast.type, title: toast.title, message: toast.message, }, }, }); if (!result.ok) return false; window.dispatchEvent(new CustomEvent('fotogenic-ai:notification-activity', { detail: { state: result.data }, })); return true; }; const show = (type: ToastType, message: string, options: ToastOptions = {}): string | undefined => { const safeMessage = text(message, 500); if (!safeMessage) return undefined; const toast = createToast(type, safeMessage, options); syncToastGeometry(); if (!ui.show(toast)) return undefined; void persistActivity(toast); return toast.id; }; return Object.freeze({ success: (message: string, options?: ToastOptions) => show('success', message, options), info: (message: string, options?: ToastOptions) => show('info', message, options), warning: (message: string, options?: ToastOptions) => show('warning', message, options), danger: (message: string, options?: ToastOptions) => show('danger', message, options), error: (message: string, options?: ToastOptions) => show('error', message, options), dismiss: ui.dismiss, clear: ui.clear, destroy(): void { ui.destroy(); window.cancelAnimationFrame(geometryFrame); window.removeEventListener('resize', syncToastGeometry); window.removeEventListener('scroll', syncToastGeometry); geometryObserver?.disconnect(); }, }); }; const shared = getSharedNamespace(); const notifications = shared.ui.notifications ?? {}; notifications.createNotifySystem = createNotifySystem; shared.ui.notifications = notifications;