'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, introRequest = false, pendingIntro; const introHandled = new Set(); const notice = document.querySelector('#notification-dialog'); let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0; if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null; const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || ''; const swUrl = assetVersion ? `sw.js?v=${encodeURIComponent(assetVersion)}` : 'sw.js'; const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register(swUrl).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.

`; } function showNotice (title, content, kind) { if (!notice) return; notice.dataset.kind = kind; document.querySelector('#notification-dialog-content').innerHTML = `

${esc(title)}

${content}
`; if (!notice.open) notice.showModal(); } async function intro () { if (!notice || !state || document.hidden || modal?.open || notice.open || introRequest || busy) return; const user = state.user.id; if (pendingIntro === user) { pendingIntro = null; showNotice('Turn notifications', `

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.

`, 'intro'); return; } if (state.notificationIntroSeen || introHandled.has(user)) return; introRequest = true; try { // An atomic claim prevents the same account seeing this in two tabs/devices. const result = await api({ action: 'claim_notification_intro' }); introHandled.add(user); if (result.show) pendingIntro = user; if (state.user.id === user) state.notificationIntroSeen = true; } catch (_) { /* Try again on a later state refresh; game play remains available. */ } finally { introRequest = false; } if (pendingIntro === state?.user.id) intro(); } async function notificationFailure (error, phase, disabling) { let advice; if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) { let brave = false; try { brave = await navigator.brave?.isBrave() || false; } catch (_) {} advice = `

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.'}

${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on Use Google services for push messaging, fully restart Brave, then try enabling notifications again.

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.

`; } else if (phase === 'permission' || error.name === 'NotAllowedError') { advice = '

Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.

'; } else if (phase === 'subscribe') { advice = '

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.

'; } else { advice = '

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.

'; } const details = error.message ? `
Error details

${esc(error.message)}

` : ''; showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error'); } notice?.addEventListener('click', event => { if (event.target.closest('[data-close-notification-dialog]')) notice.close(); if (event.target === notice) { const rect = notice.getBoundingClientRect(); if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) notice.close(); } }); // Escape closes only this top dialog, without resetting the game/account behind it. notice?.addEventListener('keydown', event => { if (event.key === 'Escape') event.stopPropagation(); }); notice?.addEventListener('close', () => { if (modal?.open) (document.querySelector('[data-toggle-push]') || document.querySelector('#modal-close'))?.focus(); intro(); }); modal?.addEventListener('close', () => intro()); document.addEventListener('visibilitychange', () => { if (!document.hidden) intro(); }); async function toggle () { if (operation || !state) return; const disabling = enabled; let phase = disabling ? 'save' : 'permission'; 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') { await notificationFailure(new Error('Notifications were not enabled.'), phase, false); return; } phase = 'config'; 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.'); phase = 'subscribe'; 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 }); phase = 'save'; 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) { await notificationFailure(error, phase, disabling); } 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-copy-push-settings]')) { const input = document.querySelector('#push-settings-page'); try { await navigator.clipboard.writeText(input.value); event.target.textContent = 'Copied ✓'; } catch (_) { input.focus(); input.select(); } return; } 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, intro }; if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); } })();