'use strict'; (() => { const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true; const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1; let installPrompt, syncedUser, enabled = false, operation = false; let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0; if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null; const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register('sw.js').catch(() => null) : Promise.resolve(null); async function subscription () { const reg = await registration; return reg?.pushManager ? reg.pushManager.getSubscription() : null; } async function endpoint () { try { return (await subscription())?.endpoint || ''; } catch (_) { return ''; } } async function sync () { if (!supported || !state || syncedUser === state.user.id) return; syncedUser = state.user.id; try { const sub = await subscription(); enabled = !!sub && Notification.permission === 'granted'; // A browser subscription follows the signed-in account, including after OAuth. if (enabled) await api({ action: 'push_subscribe', subscription: sub.toJSON() }); settings(); } catch (_) { enabled = false; settings(); } } function settings () { const el = document.querySelector('#notification-settings'); if (!el) return; if (ios && !standalone()) { el.innerHTML = '
For turn notifications, add Microchess to your home screen, open it there, and enable notifications.
'; return; } if (!supported) { el.innerHTML = 'This browser does not support turn notifications.
'; return; } if (Notification.permission === 'denied') { el.innerHTML = 'Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.
'; return; } el.innerHTML = `On this device, for turns, challenges and rematch requests.
`; } async function toggle () { if (operation || !state) return; operation = true; settings(); try { if (enabled) { const sub = await subscription(); if (sub) { await api({ action: 'push_unsubscribe', endpoint: sub.endpoint }); await sub.unsubscribe(); } enabled = false; } else { // Call permission directly from the button gesture (required on iOS). const permission = await Notification.requestPermission(); if (permission !== 'granted') { toast('Notifications were not enabled.'); return; } const response = await fetch('api.php?action=push_config'); const config = await response.json(); if (!response.ok) throw new Error(config.error || 'Unable to enable notifications.'); const reg = await registration; if (!reg) throw new Error('Unable to register notifications. Reload and try again.'); await navigator.serviceWorker.ready; const key = Uint8Array.from(atob(config.publicKey.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)); const sub = await reg.pushManager.getSubscription() || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key }); await api({ action: 'push_subscribe', subscription: sub.toJSON() }); enabled = true; } toast(enabled ? 'Turn notifications enabled on this device.' : 'Turn notifications disabled on this device.'); } catch (error) { toast(error.message || 'Unable to change notifications.'); } finally { operation = false; settings(); } } function highlight () { if (!target || !state) return; const tile = document.querySelector(`#main [data-game="${target}"]`); if (!highlightUntil) { // Only consume the link after authenticated game state has arrived. const url = new URL(location.href); url.searchParams.delete('game'); history.replaceState(null, '', url); if (!tile) { target = null; toast('This game is no longer on your home screen.'); return; } highlightUntil = performance.now() + 3000; tile.scrollIntoView({ block: 'center', behavior: 'instant' }); } const remaining = highlightUntil - performance.now(); if (remaining <= 0 || !tile) { target = null; return; } const overlay = document.createElement('div'); overlay.className = 'notification-highlight'; overlay.setAttribute('aria-hidden', 'true'); if (matchMedia('(prefers-reduced-motion: reduce)').matches) overlay.classList.add('notification-highlight-static'); overlay.style.animationDelay = `${remaining - 3000}ms`; tile.append(overlay); setTimeout(() => overlay.remove(), remaining); } window.addEventListener('beforeinstallprompt', event => { event.preventDefault(); installPrompt = event; }); window.addEventListener('appinstalled', () => { installPrompt = null; document.querySelectorAll('[data-install-app]').forEach(button => { button.hidden = true; }); }); document.addEventListener('click', async event => { if (event.target.closest('[data-toggle-push]')) await toggle(); if (!event.target.closest('[data-install-app]')) return; if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; } const help = document.querySelector('#install-help'); if (help) { help.hidden = false; help.textContent = standalone() ? 'Microchess is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Microchess using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Microchess in Chrome or Safari.'; } }); window.microchessPwa = { sync, settings, highlight, endpoint }; if (typeof state !== 'undefined' && state) { sync(); highlight(); } })();