(() => { const root = document.documentElement; const installItem = document.querySelector('[data-pwa-install-item]'); const installButton = document.querySelector('[data-pwa-install]'); const status = document.querySelector('[data-pwa-status]'); const standalone = window.matchMedia('(display-mode: standalone)'); let installPrompt = null; let installedThisSession = false; function updateMode() { const installed = standalone.matches || navigator.standalone === true; root.dataset.standalone = String(installed); if (installItem) installItem.hidden = installed || installedThisSession; if (installButton) { installButton.textContent = installPrompt ? 'Install PlotDirector…' : 'App installation…'; if (installPrompt) installButton.removeAttribute('aria-haspopup'); else installButton.setAttribute('aria-haspopup', 'dialog'); } } function updateTheme() { // The shell's tokens remain the only palette; theme changes include save rollback. const color = getComputedStyle(root).getPropertyValue('--pd-chrome').trim(); if (color) document.querySelector('meta[name="theme-color"]')?.setAttribute('content', color); } window.addEventListener('plotdirector:theme-changed', updateTheme); standalone.addEventListener('change', updateMode); window.addEventListener('beforeinstallprompt', event => { if (!installButton) return; event.preventDefault(); installPrompt = event; updateMode(); }); window.addEventListener('appinstalled', () => { installedThisSession = true; installPrompt = null; updateMode(); if (status) status.textContent = 'PlotDirector installed'; }); installButton?.addEventListener('click', async () => { if (!installPrompt) { const help = document.getElementById('pwaInstallationHelp'); if (help && window.bootstrap) { help.addEventListener('hidden.bs.modal', () => document.getElementById('accountMenuButton')?.focus(), { once: true }); bootstrap.Modal.getOrCreateInstance(help).show(); } return; } const prompt = installPrompt; installPrompt = null; updateMode(); try { await prompt.prompt(); await prompt.userChoice; } catch { if (status) status.textContent = 'Installation could not be opened. Use your browser’s app installation menu.'; } }); updateMode(); updateTheme(); if ('serviceWorker' in navigator && window.isSecureContext) { navigator.serviceWorker.register('/service-worker.js', { scope: '/', updateViaCache: 'none' }) .then(registration => { // Each full navigation checks for updates; long-lived editors check on return. // No controllerchange reload: unsaved work must remain undisturbed. let checkedAt = Date.now(); registration.update().catch(() => {}); document.addEventListener('visibilitychange', () => { if (!document.hidden && Date.now() - checkedAt > 60 * 60 * 1000) { checkedAt = Date.now(); registration.update().catch(() => {}); } }); }) .catch(() => { /* Installation enhancement must never block authoring. */ }); } })();