BlueGit

projects-timfalken-com microchess

Files

microchess / web / assets / pwa.js

pwa.js

pwa.js 6.4 KiB Download Raw
1'use strict';
2(() =>
3{
4 const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
5 const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;
6 const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
7 let installPrompt, syncedUser, enabled = false, operation = false;
8 let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0;
9 if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null;
10 const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register('sw.js').catch(() => null) : Promise.resolve(null);
11 async function subscription () { const reg = await registration; return reg?.pushManager ? reg.pushManager.getSubscription() : null; }
12 async function endpoint () { try { return (await subscription())?.endpoint || ''; } catch (_) { return ''; } }
13 async function sync ()
14 {
15 if (!supported || !state || syncedUser === state.user.id) return;
16 syncedUser = state.user.id;
17 try {
18 const sub = await subscription();
19 enabled = !!sub && Notification.permission === 'granted';
20 // A browser subscription follows the signed-in account, including after OAuth.
21 if (enabled) await api({ action: 'push_subscribe', subscription: sub.toJSON() });
22 settings();
23 } catch (_) { enabled = false; settings(); }
24 }
25 function settings ()
26 {
27 const el = document.querySelector('#notification-settings'); if (!el) return;
28 if (ios && !standalone()) { el.innerHTML = '<p>For turn notifications, add Microchess to your home screen, open it there, and enable notifications.</p>'; return; }
29 if (!supported) { el.innerHTML = '<p>This browser does not support turn notifications.</p>'; return; }
30 if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }
31 el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;
32 }
33 async function toggle ()
34 {
35 if (operation || !state) return;
36 operation = true; settings();
37 try {
38 if (enabled) {
39 const sub = await subscription();
40 if (sub) { await api({ action: 'push_unsubscribe', endpoint: sub.endpoint }); await sub.unsubscribe(); }
41 enabled = false;
42 } else {
43 // Call permission directly from the button gesture (required on iOS).
44 const permission = await Notification.requestPermission();
45 if (permission !== 'granted') { toast('Notifications were not enabled.'); return; }
46 const response = await fetch('api.php?action=push_config');
47 const config = await response.json();
48 if (!response.ok) throw new Error(config.error || 'Unable to enable notifications.');
49 const reg = await registration;
50 if (!reg) throw new Error('Unable to register notifications. Reload and try again.');
51 await navigator.serviceWorker.ready;
52 const key = Uint8Array.from(atob(config.publicKey.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));
53 const sub = await reg.pushManager.getSubscription() || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
54 await api({ action: 'push_subscribe', subscription: sub.toJSON() });
55 enabled = true;
56 }
57 toast(enabled ? 'Turn notifications enabled on this device.' : 'Turn notifications disabled on this device.');
58 } catch (error) { toast(error.message || 'Unable to change notifications.'); }
59 finally { operation = false; settings(); }
60 }
61 function highlight ()
62 {
63 if (!target || !state) return;
64 const tile = document.querySelector(`#main [data-game="${target}"]`);
65 if (!highlightUntil) {
66 // Only consume the link after authenticated game state has arrived.
67 const url = new URL(location.href); url.searchParams.delete('game'); history.replaceState(null, '', url);
68 if (!tile) { target = null; toast('This game is no longer on your home screen.'); return; }
69 highlightUntil = performance.now() + 3000;
70 tile.scrollIntoView({ block: 'center', behavior: 'instant' });
71 }
72 const remaining = highlightUntil - performance.now();
73 if (remaining <= 0 || !tile) { target = null; return; }
74 const overlay = document.createElement('div'); overlay.className = 'notification-highlight'; overlay.setAttribute('aria-hidden', 'true');
75 if (matchMedia('(prefers-reduced-motion: reduce)').matches) overlay.classList.add('notification-highlight-static');
76 overlay.style.animationDelay = `${remaining - 3000}ms`;
77 tile.append(overlay); setTimeout(() => overlay.remove(), remaining);
78 }
79 window.addEventListener('beforeinstallprompt', event => { event.preventDefault(); installPrompt = event; });
80 window.addEventListener('appinstalled', () => { installPrompt = null; document.querySelectorAll('[data-install-app]').forEach(button => { button.hidden = true; }); });
81 document.addEventListener('click', async event =>
82 {
83 if (event.target.closest('[data-toggle-push]')) await toggle();
84 if (!event.target.closest('[data-install-app]')) return;
85 if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }
86 const help = document.querySelector('#install-help');
87 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.'; }
88 });
89 window.microchessPwa = { sync, settings, highlight, endpoint };
90 if (typeof state !== 'undefined' && state) { sync(); highlight(); }
91})();