winzik/engine/web/jumphp-pwa.js
David Nurdin 070aece6b4 PWA: offline bar and "new version" bar of the page, the cached build really starts offline
- jumphp-pwa.js (pwa on, not framed by a portal): a small bar while the network is gone (also when the
  worker had to answer from its cache while navigator.onLine says true; a probe takes it away when the
  network is back) and a "new version, reload" bar when a newer build waits (Pwa::applyUpdate()),
  14 languages
- sw.js: tells the page it was opened from the cache (to the new page of a navigation, and on request:
  {type: 'jumphp:offline?'}), an unversioned file falls back to the cached one, redirects never kept
- jumphp.js hears the worker from the start (window.JUMPHP_OFFLINE, event 'jumphp:offline')
- package-web.sh: jumphp.js was missing from version.json, so the worker never cached it and a
  normal build with pwa on did not start offline
- AGENTS.md: the bars, and the playground's games installed as apps of their own and played offline

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JkYTqsvYu6AYr9yQ3Q4Nt6
2026-11-15 20:34:33 +01:00

165 lines
8.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Installable / offline game (JumPHP\Device\Pwa), when game.yaml `pwa` is on: registers sw.js, keeps the
// browser's install question for later, tells PHP (JsBridge 'pwa' events) and runs its requests
// ({do: 'install' | 'update'}).
// Embedded in a portal page (the JumPHP playground frames the game): the game itself cannot be installed from a frame, but its
// page can. The page answers {type: 'jumphp:install-info', installable, installed, downloads: [{platform, name, url, size}]};
// PHP gets it as a 'pwa' event {portal: {...}} and asks {do: 'portal-install'} (the page's prompt) or {do: 'portal-menu'} (its menu).
function portal(api) {
if (window.parent === window) return;
addEventListener('message', (event) => {
if (event.source !== window.parent || event.data?.type !== 'jumphp:install-info') return;
const d = event.data;
if (typeof d.choice === 'boolean') api.send('pwa', { choice: d.choice }); // the answer to {do: 'portal-install'}
api.send('pwa', { portal: { installable: !!d.installable, installed: !!d.installed, downloads: Array.isArray(d.downloads) ? d.downloads : [] } });
});
api.on('pwa', (msg) => {
if (msg.do === 'portal-install') window.parent.postMessage({ type: 'jumphp:install' }, '*');
else if (msg.do === 'portal-menu') window.parent.postMessage({ type: 'jumphp:install-menu' }, '*');
});
window.parent.postMessage({ type: 'jumphp:install-query' }, '*');
setTimeout(() => window.parent.postMessage({ type: 'jumphp:install-query' }, '*'), 4000); // the page's prompt may come later
}
// The page's own small bars (an installable game of its own, not framed by a portal: the portal page shows its own): "offline, the
// game runs from its cache" while the network is gone, and "new version, reload" when a newer build waits (the same as
// Pwa::applyUpdate()). They never take the touches meant for the game and shrink / go away by themselves. Texts: the 14 languages.
const WORDS = {
fr: ['Hors ligne — l\'application fonctionne avec les données en cache', 'Hors ligne', 'Nouvelle version disponible', 'Recharger'],
en: ['Offline — the app runs with cached data', 'Offline', 'New version available', 'Reload'],
es: ['Sin conexión — la aplicación funciona con los datos en caché', 'Sin conexión', 'Nueva versión disponible', 'Recargar'],
de: ['Offline — die App läuft mit den zwischengespeicherten Daten', 'Offline', 'Neue Version verfügbar', 'Neu laden'],
it: ['Offline — l\'app funziona con i dati in cache', 'Offline', 'Nuova versione disponibile', 'Ricarica'],
pt: ['Offline — o aplicativo funciona com os dados em cache', 'Offline', 'Nova versão disponível', 'Recarregar'],
nl: ['Offline — de app werkt met de gegevens in de cache', 'Offline', 'Nieuwe versie beschikbaar', 'Herladen'],
pl: ['Offline — aplikacja działa na danych z pamięci podręcznej', 'Offline', 'Dostępna nowa wersja', 'Odśwież'],
ru: ['Нет сети — приложение работает с данными из кэша', 'Нет сети', 'Доступна новая версия', 'Обновить'],
uk: ['Немає мережі — застосунок працює з даними з кешу', 'Немає мережі', 'Доступна нова версія', 'Оновити'],
tr: ['Çevrimdışı — uygulama önbellekteki verilerle çalışıyor', 'Çevrimdışı', 'Yeni sürüm hazır', 'Yeniden yükle'],
ja: ['オフライン — アプリはキャッシュのデータで動作しています', 'オフライン', '新しいバージョンがあります', '再読み込み'],
zh: ['离线 — 应用正在使用缓存的数据运行', '离线', '有新版本可用', '重新加载'],
ko: ['오프라인 — 앱이 캐시된 데이터로 실행 중입니다', '오프라인', '새 버전이 있습니다', '새로고침'],
};
function pageBars(onReload) {
const params = new URLSearchParams(location.search);
const w = WORDS[(params.get('lang') || navigator.language || 'en').slice(0, 2).toLowerCase()] || WORDS.en;
const css = 'position:fixed;z-index:99999;left:50%;transform:translateX(-50%);max-width:calc(100% - 24px);box-sizing:border-box;display:flex;gap:10px;align-items:center;padding:6px 12px;border-radius:10px;background:#0b0e1fe6;color:#fff;font:13px/1.3 system-ui,sans-serif;box-shadow:0 2px 12px #000a;pointer-events:none;';
let offline = null;
let shrink = null;
const show = () => {
if (!offline) {
offline = document.createElement('div');
offline.setAttribute('role', 'status');
offline.style.cssText = css + 'bottom:max(8px, env(safe-area-inset-bottom));';
document.body.appendChild(offline);
}
offline.textContent = '⚡ ' + w[0];
clearTimeout(shrink);
shrink = setTimeout(() => { if (offline) offline.textContent = '⚡ ' + w[1]; }, 8000);
};
const hide = () => { offline?.remove(); offline = null; };
addEventListener('offline', show);
addEventListener('online', hide);
if (navigator.onLine === false) show();
// answered from the cache while navigator.onLine says true (no answer, the server down): the bar, and the network tried now and
// then (the worker's own address is never answered from a cache) to take it away
let probe = null;
const cached = () => {
show();
clearInterval(probe);
probe = setInterval(() => fetch('sw.js?probe=' + Date.now(), { cache: 'no-store', method: 'HEAD' })
.then((r) => { if (r.ok) { clearInterval(probe); hide(); } }).catch(() => {}), 15000);
};
addEventListener('jumphp:offline', cached);
if (window.JUMPHP_OFFLINE) cached();
let update = null;
return {
update() {
if (update) return;
update = document.createElement('div');
update.setAttribute('role', 'status');
update.style.cssText = css + 'top:6px;pointer-events:auto;';
update.textContent = w[2];
const button = document.createElement('button');
button.textContent = w[3];
button.style.cssText = 'font:inherit;font-weight:600;padding:6px 14px;border:0;border-radius:8px;background:#ffd23f;color:#111;cursor:pointer';
button.onclick = (e) => { e.stopPropagation(); update?.remove(); update = null; onReload(); };
update.appendChild(button);
document.body.appendChild(update);
},
};
}
export function install(api) {
portal(api);
if (!api.GAME.pwa || !('serviceWorker' in navigator) || !isSecureContext) return {};
const bars = window.parent === window ? pageBars(() => api.applyUpdate?.()) : null;
let deferred = null;
let registration = null;
addEventListener('beforeinstallprompt', (e) => {
e.preventDefault(); // no mini-infobar: the game offers it in its own menu
deferred = e;
api.send('pwa', { installable: true }, 'pwa-installable');
});
addEventListener('appinstalled', () => {
deferred = null;
api.send('pwa', { installed: true });
});
const watch = (worker) => {
if (!worker) return;
const check = () => {
// a worker waiting while another one controls the page: a newer build
if (worker.state === 'installed' && navigator.serviceWorker.controller) { api.send('pwa', { update: true }); bars?.update(); }
};
worker.addEventListener('statechange', check);
check();
};
navigator.serviceWorker.register('sw.js').then((reg) => {
registration = reg;
watch(reg.waiting);
watch(reg.installing);
reg.addEventListener('updatefound', () => watch(reg.installing));
// look for a newer build now and then (a long session, a phone app kept open for days)
// (not at once: the registration job may still run and the check would be dropped)
const check = () => { if (navigator.serviceWorker.controller) reg.update().catch(() => {}); };
setTimeout(check, 3000);
setInterval(check, 30 * 60 * 1000);
document.addEventListener('visibilitychange', () => { if (!document.hidden) check(); });
return navigator.serviceWorker.ready;
}).then(() => api.send('pwa', { offline: true })).catch((e) => console.warn('[pwa]', e));
let reloading = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (reloading || !api.updating) return;
reloading = true;
Promise.resolve(window.saveUserFiles?.()).finally(() => location.reload());
});
api.on('pwa', (msg) => {
if (msg.do === 'install') {
const ask = () => {
if (!deferred) { api.send('pwa', { choice: false }); return; }
const e = deferred;
deferred = null;
api.send('pwa', { installable: false }, 'pwa-installable');
e.prompt().then(() => e.userChoice)
.then((choice) => api.send('pwa', { choice: choice.outcome === 'accepted' }))
.catch(() => api.gesture(() => { deferred = e; ask(); })); // no recent gesture: at the next tap / key
};
ask();
} else if (msg.do === 'update') {
api.applyUpdate();
}
});
// the newer build takes over, the page reloads into it (var/ saved first: controllerchange)
api.applyUpdate = () => {
if (!registration || !registration.waiting) return;
api.updating = true;
registration.waiting.postMessage('skipWaiting');
};
return {};
}