BlueGit

projects-timfalken-com microchess

Files

microchess / web / assets / pwa.js

pwa.js

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