import styles from './notification-center.module.css'; import { createAccountController, type AccountController, type AccountNotifier, } from '../account/account-controller'; type ActivityType = 'success' | 'info' | 'warning' | 'danger' | 'error'; interface ActivityItem { id: string; type: ActivityType; semanticKey: string; episode: string; message: string; title: string; createdAt: number; read: boolean; } interface ActivityState { version: 1; unreadCount: number; items: ActivityItem[]; } interface RestResult { ok: boolean; data?: unknown; status?: number; aborted?: boolean; message?: string; } type RestFetch = ( path: string, options?: { method?: string; body?: unknown; signal?: AbortSignal }, ) => Promise; interface IconApi { create: ( name: string, options: { weight: 'regular' | 'fill'; size: number }, ) => HTMLElement; update: ( element: Element, name: string, options: { weight: 'regular' | 'fill'; size: number }, ) => void; } interface OverlayManager { open: (options?: { returnFocus?: HTMLElement; initialFocus?: HTMLElement }) => void; close: (options?: { immediate?: boolean }) => void; isOpen: () => boolean; destroy: () => void; } interface ContainedOverlayApi { create: (options: { layer: HTMLElement; panel: HTMLElement; returnFocus: HTMLElement; onClose: (manager: OverlayManager) => void; decorate?: boolean; }) => OverlayManager; } interface SharedNamespace { ui: { icon?: IconApi; containedOverlay?: ContainedOverlayApi; notifications?: Record; }; } interface FotogenicWindow extends Window { FotogenicAI?: { Shared?: SharedNamespace; }; } interface ActivityCenterContext { root?: HTMLElement | null; restFetch?: RestFetch; i18n?: { __?: (text: string, domain?: string) => string }; notify?: AccountNotifier; onHistory?: () => void; onRun?: (runId: string) => void; onConnect?: () => void; onTopup?: () => void; onPlans?: () => void; isConnected?: () => boolean; onBeforeOpen?: () => void; } interface ActivityCenterController { refresh: () => Promise; close: () => void; getState: () => ActivityState; destroy: () => void; } const css = (name: string): string => { const value = styles[name]; if (!value) throw new Error(`Fotogenic AI: missing ${name} notification-center style.`); return value; }; const createElement = ( tag: K, className = '', content = '', ): HTMLElementTagNameMap[K] => { const element = document.createElement(tag); if (className) element.className = className; if (content) element.textContent = content; return element; }; const normalizeSemanticKey = (value: unknown): string => { const key = String(value ?? '').trim().toLowerCase().slice(0, 80); return /^[a-z0-9][a-z0-9._:-]{0,79}$/.test(key) ? key : ''; }; const record = (value: unknown): Record => ( value !== null && typeof value === 'object' ? value as Record : {} ); const normalizeState = (value: unknown = {}): ActivityState => { const source = record(value); const items = (Array.isArray(source.items) ? source.items : []) .slice(0, 30) .map((candidate): ActivityItem => { const item = record(candidate); const type = ['success', 'info', 'warning', 'danger', 'error'].includes(String(item.type)) ? String(item.type) as ActivityType : 'info'; return { id: String(item.id ?? ''), type, semanticKey: normalizeSemanticKey(item.semanticKey), episode: normalizeSemanticKey(item.episode), message: String(item.message ?? '').trim().slice(0, 240), title: String(item.title ?? '').trim().slice(0, 160), createdAt: Math.max(0, Math.floor(Number(item.createdAt)) || 0), read: item.read === true, }; }) .filter((item) => item.id !== '' && item.message !== ''); return { version: 1, unreadCount: Math.max(0, Math.min(30, Math.floor(Number(source.unreadCount)) || 0)), items, }; }; 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; }; const createNotificationActivityCenter = ( context: ActivityCenterContext = {}, ): ActivityCenterController => { const shared = getSharedNamespace(); const icons = shared.ui.icon; const containedOverlay = shared.ui.containedOverlay; if (!icons?.create || !icons.update) { throw new Error('Fotogenic AI: icon system must load before notifications.'); } if (!containedOverlay?.create) { throw new Error('Fotogenic AI: contained overlay must load before notifications.'); } const translate = (value: string): string => context.i18n?.__?.(value, 'fotogenic-ai') || value; const applicationRoot = context.root instanceof HTMLElement ? context.root : document.querySelector('[data-fa-studio-root], .fotogenic-ai-settings-shell'); const toggle = document.querySelector('[data-fa-notification-toggle]'); const toastRoot = document.getElementById('fotogenic-ai-notifications-root'); if (!applicationRoot || !toggle || !toastRoot) { throw new Error('Fotogenic AI: notification-center anatomy is unavailable.'); } toggle.className = css('trigger'); toggle.setAttribute('aria-haspopup', 'dialog'); toggle.setAttribute('aria-controls', 'studio-notification-center'); toggle.setAttribute('aria-expanded', 'false'); const triggerIcon = toggle.querySelector('[data-fa-notification-icon]'); if (!triggerIcon) throw new Error('Fotogenic AI: notification trigger icon is unavailable.'); const triggerDot = createElement('span', css('triggerDot')); triggerDot.hidden = true; triggerDot.setAttribute('aria-hidden', 'true'); toggle.appendChild(triggerDot); let state = normalizeState(); let stateRevision = 0; let loaded = false; let loading = false; let refreshQueued = false; let loadError = ''; let destroyed = false; const layer = createElement('div', css('layer')); layer.classList.add('fotogenic-ai-contained-overlay'); const panel = createElement('section', css('panel')); panel.id = 'studio-notification-center'; panel.setAttribute('aria-labelledby', 'studio-notification-center-title'); const header = createElement('header', css('heading')); const headingCopy = createElement('div'); const heading = createElement('h2', '', translate('Notifications')); heading.id = 'studio-notification-center-title'; heading.tabIndex = -1; heading.setAttribute('data-fa-overlay-heading', ''); const headerSummary = createElement('p', '', translate('You are all caught up')); headingCopy.append(heading, headerSummary); const closeButton = createElement('button', css('close')); closeButton.type = 'button'; closeButton.setAttribute('aria-label', translate('Close notifications')); closeButton.appendChild(icons.create('x', { weight: 'regular', size: 18 })); header.append(headingCopy, closeButton); const content = createElement('div', css('content')); const footer = createElement('footer', css('footer'), translate('Only you can see this activity.')); panel.append(header, content, footer); layer.appendChild(panel); document.body.appendChild(layer); let overlay: OverlayManager; const syncGeometry = (): void => { if (!applicationRoot.isConnected) return; const viewport = window.visualViewport; const viewportLeft = Math.max(0, Number(viewport?.offsetLeft) || 0); const viewportTop = Math.max(0, Number(viewport?.offsetTop) || 0); const viewportWidth = Math.max(0, Number(viewport?.width) || document.documentElement.clientWidth); const viewportHeight = Math.max(0, Number(viewport?.height) || document.documentElement.clientHeight); const viewportRight = viewportLeft + viewportWidth; const viewportBottom = viewportTop + viewportHeight; const adminBarBottom = Math.max( viewportTop, Number(document.getElementById('wpadminbar')?.getBoundingClientRect().bottom) || 0, ); const rootRect = applicationRoot.getBoundingClientRect(); const headerRect = applicationRoot.querySelector('[data-fa-shared-toolbar]') ?.getBoundingClientRect() || rootRect; const compact = window.matchMedia('(max-width: 782px)').matches; const blockStart = Math.min(viewportBottom, compact ? adminBarBottom : Math.max(adminBarBottom, headerRect.bottom)); const inlineStart = compact ? viewportLeft : Math.min(viewportRight, Math.max(viewportLeft, rootRect.left)); const inlineEnd = compact ? viewportRight : Math.max(inlineStart, Math.min(viewportRight, rootRect.right)); layer.style.setProperty('--fa-notification-layer-top', `${blockStart}px`); layer.style.setProperty('--fa-notification-layer-right', `${Math.max(0, document.documentElement.clientWidth - inlineEnd)}px`); layer.style.setProperty('--fa-notification-layer-bottom', `${Math.max(0, document.documentElement.clientHeight - viewportBottom)}px`); layer.style.setProperty('--fa-notification-layer-left', `${Math.max(0, inlineStart)}px`); }; const close = (): void => { if (!overlay.isOpen()) return; overlay.close(); toggle.setAttribute('aria-expanded', 'false'); toastRoot.classList.remove('fotogenic-ai-notification-stack--center-open'); }; overlay = containedOverlay.create({ layer, panel, returnFocus: toggle, decorate: false, onClose: (manager) => { manager.close(); toggle.setAttribute('aria-expanded', 'false'); toastRoot.classList.remove('fotogenic-ai-notification-stack--center-open'); }, }); const request = async ( path: string, options: { method?: string; body?: unknown; signal?: AbortSignal } = {}, ): Promise => { if (typeof context.restFetch !== 'function') { return { ok: false, data: {}, status: 0, message: 'Notification transport is unavailable.' }; } try { return await context.restFetch(path, options); } catch (error) { return { ok: false, data: {}, status: 0, aborted: options.signal?.aborted === true, message: error instanceof Error ? error.message : String(error), }; } }; const updateTrigger = (): void => { const unread = Math.max(0, state.unreadCount); icons.update(triggerIcon, 'bell', { weight: 'fill', size: 19 }); triggerDot.hidden = unread === 0; const unreadLabel = unread > 0 ? `${unread} ${translate('unread')}` : translate('No unread notifications'); toggle.setAttribute('aria-label', `${translate('Notifications')}. ${unreadLabel}`); }; const relativeTime = (timestamp: number): string => { if (!timestamp) return ''; const elapsed = Math.max(0, Date.now() - (timestamp * 1000)); const minutes = Math.floor(elapsed / 60_000); if (minutes < 1) return translate('Just now'); if (minutes < 60) return `${minutes}${translate('m ago')}`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours}${translate('h ago')}`; return `${Math.floor(hours / 24)}${translate('d ago')}`; }; const notificationTitle = (item: ActivityItem): string => { return item.title || translate('Studio update'); }; const notificationActions = (item: ActivityItem): { label: string; run: () => void }[] => { const semanticKey = item.semanticKey; if (!semanticKey) return []; const connected = context.isConnected?.() === true; const runLifecycle = semanticKey.match(/^generation:(completed|partial|failed|stopped)$/); if (runLifecycle && item.episode && context.onRun) { const lifecycleStatus = runLifecycle[1] || ''; return [{ label: translate(['completed', 'partial'].includes(lifecycleStatus) ? 'View results' : 'View run'), run: () => { close(); context.onRun?.(item.episode); }, }]; } if (/credit|balance|pricing/.test(semanticKey)) { if (!connected && context.onConnect) return [{ label: translate('Connect account'), run: context.onConnect }]; const actions: { label: string; run: () => void }[] = []; if (context.onTopup) actions.push({ label: translate('Add credits'), run: context.onTopup }); if (semanticKey === 'credits:low-episode' && context.onPlans) { actions.push({ label: translate('View plans'), run: context.onPlans }); } return actions; } if (/account|auth|connect|login|logout|session/.test(semanticKey) && !connected && context.onConnect) { return [{ label: translate('Connect account'), run: context.onConnect }]; } if (/generat|image|run|campaign|enhanc/.test(semanticKey) && context.onHistory) { return [{ label: translate('View history'), run: () => { close(); context.onHistory?.(); }, }]; } return []; }; const renderStatus = ( iconName: string, title: string, message: string, options: { weight?: 'regular' | 'fill'; spin?: boolean; retry?: boolean } = {}, ): void => { const status = createElement('div', css('empty')); status.setAttribute('role', 'status'); const icon = icons.create(iconName, { weight: options.weight || 'regular', size: 25 }); icon.classList.toggle('fotogenic-ai-icon--spin', options.spin === true); status.append(icon, createElement('strong', '', title), createElement('p', '', message)); if (options.retry) { const retry = createElement('button', '', translate('Try again')); retry.type = 'button'; retry.addEventListener('click', () => void load()); status.appendChild(retry); } content.appendChild(status); }; const applyServerState = (value: unknown): void => { const nextState = normalizeState(value); const changed = !loaded || !!loadError || JSON.stringify(nextState) !== JSON.stringify(state); state = nextState; loaded = true; loadError = ''; stateRevision += 1; updateTrigger(); if (changed) render(); }; const dismiss = async (id: string): Promise => { const result = await request('/notifications/dismiss', { method: 'POST', body: { id } }); if (result.ok) applyServerState(result.data); else { loadError = translate('Notification activity could not be updated.'); render(); } }; const markRead = async (id: string): Promise => { const item = state.items.find((candidate) => candidate.id === id); if (item && !item.read) { stateRevision += 1; item.read = true; state.unreadCount = Math.max(0, state.unreadCount - 1); updateTrigger(); render(); } const result = await request('/notifications/read', { method: 'POST', body: { ids: [id] } }); if (result.ok) applyServerState(result.data); else void load(); return result; }; const markAllRead = async (button: HTMLButtonElement): Promise => { if (!state.unreadCount) return; button.disabled = true; const result = await request('/notifications/read', { method: 'POST', body: { all: true } }); if (result.ok) applyServerState(result.data); else { button.disabled = false; loadError = translate('Notification activity could not be updated.'); render(); } }; const render = (): void => { content.replaceChildren(); headerSummary.textContent = state.unreadCount > 0 ? `${state.unreadCount} ${state.unreadCount === 1 ? translate('unread update') : translate('unread updates')}` : translate('You are all caught up'); if (loading && !loaded) { renderStatus( 'arrows-clockwise', translate('Loading'), translate('Checking the latest account and Studio updates.'), { spin: true }, ); return; } if (loadError) { renderStatus( 'warning', translate('Notifications unavailable'), loadError, { weight: 'fill', retry: true }, ); return; } if (!state.items.length) { renderStatus( 'bell', translate('No notifications yet'), translate('Account, credit, and generation updates will appear here.'), ); return; } const today = new Date().toDateString(); const groups = [ { label: translate('Today'), key: 'today', items: state.items.filter((item) => new Date(item.createdAt * 1000).toDateString() === today), }, { label: translate('Earlier'), key: 'earlier', items: state.items.filter((item) => new Date(item.createdAt * 1000).toDateString() !== today), }, ].filter((group) => group.items.length > 0); groups.forEach((group, groupIndex) => { const section = createElement('section'); const groupHeading = createElement('div', css('groupHeading')); const title = createElement('h3', '', group.label); title.id = `studio-notification-group-${group.key}`; section.setAttribute('aria-labelledby', title.id); groupHeading.appendChild(title); if (groupIndex === 0) { const markAll = createElement('button', css('markRead'), translate('Mark all read')); markAll.type = 'button'; markAll.disabled = state.unreadCount === 0; markAll.addEventListener('click', () => void markAllRead(markAll)); groupHeading.appendChild(markAll); } const rows = createElement('div', css('rows')); group.items.forEach((item) => { const row = createElement('article', [ css('row'), ...(item.type === 'info' ? [] : [css(item.type)]), ...(item.read ? [css('rowRead')] : []), ].join(' ')); const iconContract = item.type === 'success' ? { name: 'check-circle', weight: 'fill' as const } : (['warning', 'danger', 'error'].includes(item.type) ? { name: 'warning', weight: 'fill' as const } : { name: 'info', weight: 'regular' as const }); const icon = createElement('span', css('activityIcon')); icon.appendChild(icons.create(iconContract.name, { weight: iconContract.weight, size: 17 })); const copy = createElement('div', css('copy')); if (!item.read) copy.appendChild(createElement('span', css('screenReader'), translate('Unread notification.'))); const titleRow = createElement('div', css('titleRow')); const itemTitle = notificationTitle(item); const time = createElement('time', '', relativeTime(item.createdAt)); if (item.createdAt) time.dateTime = new Date(item.createdAt * 1000).toISOString(); const dismissButton = createElement('button', css('dismiss')); dismissButton.type = 'button'; dismissButton.setAttribute('aria-label', `${translate('Dismiss')} ${itemTitle}`); dismissButton.appendChild(icons.create('x', { weight: 'regular', size: 16 })); dismissButton.addEventListener('click', () => void dismiss(item.id)); titleRow.append(createElement('strong', '', itemTitle), time, dismissButton); copy.append(titleRow, createElement('p', '', item.message)); const actionsForItem = notificationActions(item); if (actionsForItem.length > 0) { const actions = createElement('div', css('actions')); actionsForItem.forEach((action) => { const button = createElement('button', '', action.label); button.type = 'button'; button.addEventListener('click', () => { void markRead(item.id); action.run(); }); actions.appendChild(button); }); copy.appendChild(actions); } row.append(icon, copy); rows.appendChild(row); }); section.append(groupHeading, rows); content.appendChild(section); }); }; const load = async (): Promise => { if (destroyed) return; if (loading) { refreshQueued = true; return; } const startedRevision = stateRevision; const showLoading = !loaded || !!loadError; loading = true; loadError = ''; if (showLoading) render(); const result = await request('/notifications'); if (destroyed) return; loading = false; if (result.ok && stateRevision === startedRevision) applyServerState(result.data); else if (!result.ok && stateRevision === startedRevision) { loadError = translate('Notifications are temporarily unavailable.'); render(); } if (refreshQueued) { refreshQueued = false; void load(); } }; const handleToggle = (): void => { if (overlay.isOpen()) { close(); return; } context.onBeforeOpen?.(); syncGeometry(); toggle.setAttribute('aria-expanded', 'true'); toastRoot.classList.add('fotogenic-ai-notification-stack--center-open'); overlay.open({ returnFocus: toggle, initialFocus: heading }); void load(); }; const handleViewport = (): void => { if (overlay.isOpen()) syncGeometry(); }; const geometryObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(handleViewport) : null; geometryObserver?.observe(applicationRoot); const toolbar = applicationRoot.querySelector('[data-fa-shared-toolbar]'); if (toolbar) geometryObserver?.observe(toolbar); const handleActivity = (event: Event): void => { const detail = (event as CustomEvent<{ state?: unknown }>).detail; if (detail?.state) applyServerState(detail.state); else void load(); }; const handleFocus = (): void => { if (document.visibilityState === 'visible') void load(); }; const handleAuthChanged = (): void => { stateRevision += 1; state = normalizeState(); loaded = false; loadError = ''; close(); updateTrigger(); render(); void load(); }; closeButton.addEventListener('click', close); toggle.addEventListener('click', handleToggle); window.addEventListener('fotogenic-ai:notification-activity', handleActivity); window.addEventListener('focus', handleFocus); window.addEventListener('fotogenic-ai:auth-changed', handleAuthChanged); window.addEventListener('resize', handleViewport); window.addEventListener('scroll', handleViewport, true); window.visualViewport?.addEventListener('resize', handleViewport); window.visualViewport?.addEventListener('scroll', handleViewport); updateTrigger(); render(); void load(); return Object.freeze({ refresh: load, close, getState: () => ({ ...state, items: state.items.map((item) => ({ ...item })) }), destroy(): void { if (destroyed) return; destroyed = true; closeButton.removeEventListener('click', close); toggle.removeEventListener('click', handleToggle); window.removeEventListener('fotogenic-ai:notification-activity', handleActivity); window.removeEventListener('focus', handleFocus); window.removeEventListener('fotogenic-ai:auth-changed', handleAuthChanged); window.removeEventListener('resize', handleViewport); window.removeEventListener('scroll', handleViewport, true); window.visualViewport?.removeEventListener('resize', handleViewport); window.visualViewport?.removeEventListener('scroll', handleViewport); geometryObserver?.disconnect(); overlay.destroy(); layer.remove(); toastRoot.classList.remove('fotogenic-ai-notification-stack--center-open'); toggle.classList.remove(css('trigger')); triggerDot.remove(); }, }); }; const shared = getSharedNamespace(); const notifications = shared.ui.notifications ?? {}; export const createNotificationCenter = (context: ActivityCenterContext = {}) => { let account: AccountController | null = null; const activity = createNotificationActivityCenter({ ...context, onBeforeOpen: () => account?.close(), onConnect: () => void account?.startLogin(), onTopup: () => account?.openTopup(), onPlans: () => account?.openPlans(), isConnected: () => account?.isConnected() === true, }); account = createAccountController({ root: context.root, restFetch: context.restFetch, i18n: context.i18n, notify: context.notify, onHistory: context.onHistory, closeNotifications: activity.close, }); return Object.freeze({ refresh: activity.refresh, getState: activity.getState, destroy(): void { account?.destroy(); activity.destroy(); account = null; }, }); }; notifications.notificationCenter = Object.freeze({ create: createNotificationCenter, normalizeState, }); shared.ui.notifications = notifications;