import { FeedbackDialog } from '../feedback/feedback-dialog'; import './update-notice.css'; interface UpdateConfig { version: string; installed: string; compatible: boolean; nativeOnly: boolean; updating: boolean; ajaxUrl: string; nonce: string; updatesNonce: string; plugin: string; pluginsUrl: string; releaseUrl: string; } interface UpdateReply { success: boolean; data?: { message?: string; errorMessage?: string; html?: string; version?: string; installed?: string; targetInstalled?: boolean; updating?: boolean } } type Phase = 'available' | 'updating' | 'uncertain' | 'updated' | 'failed'; const i18n = (window as typeof window & { wp?: { i18n?: { __: (text: string, domain: string) => string } } }).wp?.i18n; const t = (text: string): string => i18n?.__(text, 'fotogenic-ai') ?? text; function mount(root: HTMLElement): void { const raw = root.querySelector('script')?.textContent; if (!raw) return; const config: UpdateConfig = JSON.parse(raw); const install = root.querySelector('[data-update-install]')!; const notes = root.querySelector('[data-update-notes]')!; const dismiss = root.querySelector('[data-update-dismiss]')!; const message = root.querySelector('[data-update-message]')!; const status = document.createElement('span'); status.className = 'screen-reader-text'; status.setAttribute('role', 'status'); root.append(status); const initialMessage = message.textContent; const dialog = new FeedbackDialog(); let phase: Phase = 'available'; let notesPending = false; let notesHtml: string | null = null; const nativeLink = document.createElement('a'); nativeLink.href = config.pluginsUrl; nativeLink.textContent = t('Open WordPress Plugins'); nativeLink.className = 'fotogenic-ai-update-native'; nativeLink.hidden = true; root.append(nativeLink); message.tabIndex = -1; const action = (label: string, name: string) => ({ label, action: name, url: '', newTab: false }); const post = async (name: string): Promise => { const body = new URLSearchParams({ action: `fotogenic_ai_update_${name}`, nonce: config.nonce, _ajax_nonce: config.updatesNonce, version: config.version }); const controller = new AbortController(); const timer = window.setTimeout(() => controller.abort(), name === 'install' ? 120000 : 20000); try { const response = await fetch(config.ajaxUrl, { method: 'POST', credentials: 'same-origin', body, signal: controller.signal }); const result: unknown = await response.json(); if (!result || typeof result !== 'object' || !('success' in result) || typeof result.success !== 'boolean') throw new Error('invalid_update_response'); return result as UpdateReply; } finally { window.clearTimeout(timer); } }; const beforeUnload = (event: BeforeUnloadEvent): void => { event.preventDefault(); event.returnValue = ''; }; const preventNavigation = (event: Event): void => { const target = event.target; if (!(target instanceof Element) || root.contains(target)) return; if (event.type === 'submit' || target.closest('a,button,input,select,[role="button"]')) { event.preventDefault(); event.stopImmediatePropagation(); message.focus(); } }; const guard = (enabled: boolean): void => { for (const type of ['click', 'submit']) { if (enabled) document.addEventListener(type, preventNavigation, true); else document.removeEventListener(type, preventNavigation, true); } if (enabled) window.addEventListener('beforeunload', beforeUnload); else window.removeEventListener('beforeunload', beforeUnload); }; const setPhase = (next: Phase, detail = ''): void => { phase = next; const busy = phase === 'updating'; guard(busy || phase === 'uncertain'); nativeLink.hidden = phase !== 'failed'; root.setAttribute('aria-busy', String(busy)); notes.disabled = busy || phase === 'uncertain'; dismiss.disabled = busy || phase === 'uncertain'; install.disabled = busy || phase === 'updated'; install.textContent = busy ? t('Updating…') : phase === 'updated' ? t('Reloading…') : phase === 'uncertain' ? t('Check status') : t('Update now'); if (busy) { const spinner = document.createElement('span'); spinner.className = 'fotogenic-ai-icon fotogenic-ai-icon--arrows-clockwise fotogenic-ai-icon--spin fotogenic-ai-icon--size-14'; spinner.setAttribute('aria-hidden', 'true'); install.prepend(spinner); } message.textContent = phase === 'failed' || phase === 'uncertain' ? detail : initialMessage; status.textContent = busy ? t('Updating. Please keep this page open until the update finishes.') : phase === 'updated' ? t('Updated successfully. Reloading Fotogenic AI.') : detail; }; const verify = async (): Promise => { install.disabled = true; try { const reply = await post('status'); if (!reply.success || !reply.data?.installed) throw new Error('update_status_unavailable'); if (reply.data.targetInstalled && !reply.data.updating) { setPhase('updated'); window.location.reload(); } else if (reply.data.updating) { setPhase('uncertain', t('WordPress is still updating. Keep this page open and check again shortly.')); } else { setPhase('failed', t('The update did not finish. You can try again or manage it in WordPress Plugins.')); } } catch { setPhase('uncertain', t('We could not confirm the update status. Check again before trying another update.')); } }; const start = async (): Promise => { if (phase === 'updating') return; if (phase === 'updated') return; if (phase === 'uncertain') { await verify(); return; } if (!config.compatible || config.nativeOnly) { window.location.assign(config.pluginsUrl); return; } dialog.close(false, true); setPhase('updating'); try { const reply = await post('install'); if (reply.success) { await verify(); return; } setPhase(reply.data?.updating ? 'uncertain' : 'failed', reply.data?.message || reply.data?.errorMessage || t('The update could not be completed. Open WordPress Plugins for more details.')); } catch { await verify(); } }; install.addEventListener('click', () => { void start(); }); dismiss.addEventListener('click', async () => { dismiss.disabled = true; try { const reply = await post('dismiss'); if (!reply.success) throw new Error('dismiss_failed'); if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) { await root.animate([{ opacity: 1, transform: 'translateY(0)' }, { opacity: 0, transform: 'translateY(-4px)' }], { duration: 160, easing: 'ease-in' }).finished; } root.hidden = true; } catch { message.textContent = t('The notice could not be dismissed. Please try again.'); } finally { dismiss.disabled = false; } }); const openNotes = async (): Promise => { if (notesPending) return; notesPending = true; notes.disabled = true; notes.setAttribute('aria-busy', 'true'); status.textContent = t('Loading release notes.'); const content = document.createElement('div'); content.className = 'fotogenic-ai-update-notes'; content.setAttribute('aria-live', 'polite'); try { if (notesHtml === null) { const reply = await post('notes'); if (!reply.success || typeof reply.data?.html !== 'string') throw new Error('notes_unavailable'); notesHtml = reply.data.html; } // Server strips all attributes and permits only static changelog typography. content.innerHTML = notesHtml; } catch { content.classList.add('is-unavailable'); const explanation = document.createElement('p'); explanation.textContent = t('Release notes are temporarily unavailable. Please check again later.'); content.replaceChildren(explanation); } finally { notesPending = false; notes.removeAttribute('aria-busy'); notes.disabled = phase === 'updating' || phase === 'uncertain'; } if (root.hidden || phase === 'updating' || phase === 'uncertain' || phase === 'updated') return; status.textContent = ''; dialog.show({ icon: 'arrows-clockwise', title: `${t('What’s new in Fotogenic AI')} ${config.version}`, description: '', content, closeOnEscape: true, primary: action(t('Update now'), 'update'), secondary: action(t('Close'), 'close'), returnFocus: notes, onAction: (selected) => { if (selected.action === 'update') void start(); }, }); }; notes.addEventListener('click', () => { void openNotes(); }); if (config.updating) { setPhase('uncertain', t('WordPress is still updating. Keep this page open and check again shortly.')); return; } if (!config.compatible || config.nativeOnly) { install.classList.add('is-native-link'); install.textContent = t('Open WordPress Plugins'); message.textContent = config.nativeOnly ? t('Your network administrator can install this update.') : t('Review the WordPress or PHP requirements before updating.'); } } const initialize = (): void => { document.querySelectorAll('[data-fa-update]').forEach(mount); }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initialize, { once: true }); else initialize();