BlueGit

projects-timfalken-com microchess

Files

microchess / web / assets / pwa.js

pwa.js

pwa.js 11.8 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, introRequest = false, pendingIntro;
8 const introHandled = new Set();
9 const notice = document.querySelector('#notification-dialog');
10 let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0;
11 if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null;
12 const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || '';
13 const swUrl = assetVersion ? `sw.js?v=${encodeURIComponent(assetVersion)}` : 'sw.js';
14 const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register(swUrl).catch(() => null) : Promise.resolve(null);
15 async function subscription () { const reg = await registration; return reg?.pushManager ? reg.pushManager.getSubscription() : null; }
16 async function endpoint () { try { return (await subscription())?.endpoint || ''; } catch (_) { return ''; } }
17 async function sync ()
18 {
19 if (!supported || !state || syncedUser === state.user.id) return;
20 syncedUser = state.user.id;
21 try {
22 const sub = await subscription();
23 enabled = !!sub && Notification.permission === 'granted';
24 // A browser subscription follows the signed-in account, including after OAuth.
25 if (enabled) await api({ action: 'push_subscribe', subscription: sub.toJSON() });
26 settings();
27 } catch (_) { enabled = false; settings(); }
28 }
29 function settings ()
30 {
31 const el = document.querySelector('#notification-settings'); if (!el) return;
32 if (ios && !standalone()) { el.innerHTML = '<p>For turn notifications, add Microchess to your home screen, open it there, and enable notifications.</p>'; return; }
33 if (!supported) { el.innerHTML = '<p>This browser does not support turn notifications.</p>'; return; }
34 if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }
35 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>`;
36 }
37 function showNotice (title, content, kind)
38 {
39 if (!notice) return;
40 notice.dataset.kind = kind;
41 document.querySelector('#notification-dialog-content').innerHTML = `<h2 id="notification-dialog-title">${esc(title)}</h2>${content}<div class="actions"><button class="primary" data-close-notification-dialog autofocus>Got it</button></div>`;
42 if (!notice.open) notice.showModal();
43 }
44 async function intro ()
45 {
46 if (!notice || !state || document.hidden || modal?.open || notice.open || introRequest || busy) return;
47 const user = state.user.id;
48 if (pendingIntro === user) {
49 pendingIntro = null;
50 showNotice('Turn notifications', `<p>Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.</p>`, 'intro');
51 return;
52 }
53 if (state.notificationIntroSeen || introHandled.has(user)) return;
54 introRequest = true;
55 try {
56 // An atomic claim prevents the same account seeing this in two tabs/devices.
57 const result = await api({ action: 'claim_notification_intro' });
58 introHandled.add(user);
59 if (result.show) pendingIntro = user;
60 if (state.user.id === user) state.notificationIntroSeen = true;
61 } catch (_) { /* Try again on a later state refresh; game play remains available. */ }
62 finally { introRequest = false; }
63 if (pendingIntro === state?.user.id) intro();
64 }
65 async function notificationFailure (error, phase, disabling)
66 {
67 let advice;
68 if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) {
69 let brave = false;
70 try { brave = await navigator.brave?.isBrave() || false; } catch (_) {}
71 advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Microchess alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;
72 } else if (phase === 'permission' || error.name === 'NotAllowedError') {
73 advice = '<p>Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.</p>';
74 } else if (phase === 'subscribe') {
75 advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Microchess from its home-screen icon.</p>';
76 } else {
77 advice = '<p>Microchess could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';
78 }
79 const details = error.message ? `<details><summary>Error details</summary><p>${esc(error.message)}</p></details>` : '';
80 showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error');
81 }
82 notice?.addEventListener('click', event => {
83 if (event.target.closest('[data-close-notification-dialog]')) notice.close();
84 if (event.target === notice) {
85 const rect = notice.getBoundingClientRect();
86 if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) notice.close();
87 }
88 });
89 // Escape closes only this top dialog, without resetting the game/account behind it.
90 notice?.addEventListener('keydown', event => { if (event.key === 'Escape') event.stopPropagation(); });
91 notice?.addEventListener('close', () => {
92 if (modal?.open) (document.querySelector('[data-toggle-push]') || document.querySelector('#modal-close'))?.focus();
93 intro();
94 });
95 modal?.addEventListener('close', () => intro());
96 document.addEventListener('visibilitychange', () => { if (!document.hidden) intro(); });
97 async function toggle ()
98 {
99 if (operation || !state) return;
100 const disabling = enabled;
101 let phase = disabling ? 'save' : 'permission';
102 operation = true; settings();
103 try {
104 if (enabled) {
105 const sub = await subscription();
106 if (sub) { await api({ action: 'push_unsubscribe', endpoint: sub.endpoint }); await sub.unsubscribe(); }
107 enabled = false;
108 } else {
109 // Call permission directly from the button gesture (required on iOS).
110 const permission = await Notification.requestPermission();
111 if (permission !== 'granted') { await notificationFailure(new Error('Notifications were not enabled.'), phase, false); return; }
112 phase = 'config';
113 const response = await fetch('api.php?action=push_config');
114 const config = await response.json();
115 if (!response.ok) throw new Error(config.error || 'Unable to enable notifications.');
116 phase = 'subscribe';
117 const reg = await registration;
118 if (!reg) throw new Error('Unable to register notifications. Reload and try again.');
119 await navigator.serviceWorker.ready;
120 const key = Uint8Array.from(atob(config.publicKey.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));
121 const sub = await reg.pushManager.getSubscription() || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
122 phase = 'save';
123 await api({ action: 'push_subscribe', subscription: sub.toJSON() });
124 enabled = true;
125 }
126 toast(enabled ? 'Turn notifications enabled on this device.' : 'Turn notifications disabled on this device.');
127 } catch (error) { await notificationFailure(error, phase, disabling); }
128 finally { operation = false; settings(); }
129 }
130 function highlight ()
131 {
132 if (!target || !state) return;
133 const tile = document.querySelector(`#main [data-game="${target}"]`);
134 if (!highlightUntil) {
135 // Only consume the link after authenticated game state has arrived.
136 const url = new URL(location.href); url.searchParams.delete('game'); history.replaceState(null, '', url);
137 if (!tile) { target = null; toast('This game is no longer on your home screen.'); return; }
138 highlightUntil = performance.now() + 3000;
139 tile.scrollIntoView({ block: 'center', behavior: 'instant' });
140 }
141 const remaining = highlightUntil - performance.now();
142 if (remaining <= 0 || !tile) { target = null; return; }
143 const overlay = document.createElement('div'); overlay.className = 'notification-highlight'; overlay.setAttribute('aria-hidden', 'true');
144 if (matchMedia('(prefers-reduced-motion: reduce)').matches) overlay.classList.add('notification-highlight-static');
145 overlay.style.animationDelay = `${remaining - 3000}ms`;
146 tile.append(overlay); setTimeout(() => overlay.remove(), remaining);
147 }
148 window.addEventListener('beforeinstallprompt', event => { event.preventDefault(); installPrompt = event; });
149 window.addEventListener('appinstalled', () => { installPrompt = null; document.querySelectorAll('[data-install-app]').forEach(button => { button.hidden = true; }); });
150 document.addEventListener('click', async event =>
151 {
152 if (event.target.closest('[data-copy-push-settings]')) {
153 const input = document.querySelector('#push-settings-page');
154 try { await navigator.clipboard.writeText(input.value); event.target.textContent = 'Copied ✓'; }
155 catch (_) { input.focus(); input.select(); }
156 return;
157 }
158 if (event.target.closest('[data-toggle-push]')) await toggle();
159 if (!event.target.closest('[data-install-app]')) return;
160 if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }
161 const help = document.querySelector('#install-help');
162 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.'; }
163 });
164 window.microchessPwa = { sync, settings, highlight, endpoint, intro };
165 if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); }
166})();