Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions docs/PWA.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ This is an **online-first app shell**, not an offline radio player.
- The worker pre-caches **only** `offline.html`, a small static, noindex,
self-contained explanation. Navigation requests go to the network first.
On a network failure, the worker displays the translated offline explanation.
The fallback page listens for browser connectivity changes and also probes the
same-origin, deployment-scoped web manifest with a 5-second timeout and
backoff (3 to 15 seconds). It reloads the **original URL** only after a valid
network response, does not loop-refresh while offline, and pauses background
probes while hidden. The manual Retry button uses the same verification.
- There is **no audio cache**: MP3/AAC, .m3u8 playlists, HLS segments, provider
requests, API, JS, CSS, search index JSON and all real station HTML stay
network-only. A stream always requires a current online connection.
Expand Down Expand Up @@ -41,13 +46,19 @@ tabs; test on the actual device before marking #340 or #346 complete.
- [ ] Install on Android Chrome and open the app from its launcher.
- [ ] Add to Home Screen on Safari iOS, test lock-screen/audio interruptions.
- [ ] With the app open, go offline then navigate: see the offline explanation;
retry after restoring connection should fetch a fresh live page.
restore connection and verify automatic recovery to the same page without
pressing Retry. Also verify Retry works and no repeated reloads occur
while disconnected, including when the browser omits an online event.
- [ ] Repeat the recovery test on a station deep link and on a
`/pr-preview/pr-N/` deployment: its connectivity probe must stay within
the active Pages scope. A browser reload must leave the player paused.
- [ ] Use DevTools Application → Cache Storage: **only** `offline.html` is
precached; no station catalog, stream segments or signed URLs.
- [ ] Update the worker: no forced reload, old audio continues, next visits
fetch fresh HTML and JSON rather than replaying stale caches.
- [ ] `npm test`, `npm run generate:site`, SEO/GA4 noindex and GitHub Pages
subpath validations, mobile light/dark and safe-area smoke tests.

The automated tests verify worker/cache policy and manifest URL resolution.
The automated tests verify worker/cache policy, manifest URL resolution, and
offline-page automatic recovery, polling backoff and preview-scoped probes.
Physical iOS/Android QA remains **not run** until independently documented.
117 changes: 106 additions & 11 deletions public/offline.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
button { appearance: none; border: 0; border-radius: 13px; background: #e11d48; color: white; font: inherit; font-weight: 650; padding: 13px 25px; min-height: 48px; cursor: pointer; }
button:focus-visible { outline: 3px solid #fda4af; outline-offset: 4px; }
button:hover { background: #be123c; }
.note { display: block; margin-top: 18px; color: #aaaab6; font-size: 12px; }
.connection-state { display: block; min-height: 20px; margin-top: 14px; color: #fda4af; font-size: 13px; }
.note { display: block; margin-top: 12px; color: #aaaab6; font-size: 12px; }
button:disabled { cursor: progress; opacity: .75; }
@media (prefers-reduced-motion: no-preference) { button { transition: background .15s ease; } }
</style>
</head>
Expand All @@ -31,31 +33,124 @@
<h1 id="offline-title">You're offline</h1>
<p id="offline-description">Live radio needs an internet connection. Reconnect to keep listening.</p>
<button type="button" id="retry">Try again</button>
<span class="connection-state" id="connection-state" role="status" aria-live="polite">Waiting for a connection…</span>
<small class="note" id="offline-note">Live stations cannot play offline.</small>
</main>
<script>
(() => {
const messages = {
en: ["You're offline", "Live radio needs an internet connection. Reconnect to keep listening.", "Try again", "Live stations cannot play offline."],
vi: ["Bạn đang ngoại tuyến", "Radio trực tiếp cần kết nối Internet. Hãy kết nối lại để tiếp tục nghe.", "Thử lại", "Không thể nghe đài trực tiếp khi ngoại tuyến."],
ja: ["オフラインです", "ライブ配信のラジオにはインターネット接続が必要です。再接続してください。", "再試行", "オフラインではライブ放送を再生できません。"],
"zh-CN": ["当前处于离线状态", "收听直播电台需要网络连接。请重新连接后继续收听。", "重试", "离线时无法播放直播电台。"],
"zh-TW": ["目前處於離線狀態", "收聽直播電台需要網路連線。請重新連線後繼續收聽。", "重試", "離線時無法播放直播電台。"],
fr: ["Vous êtes hors ligne", "Une connexion Internet est nécessaire pour écouter la radio en direct. Reconnectez-vous pour continuer.", "Réessayer", "Les radios en direct ne fonctionnent pas hors ligne."],
ru: ["Вы не в сети", "Для прямого эфира радио требуется интернет. Подключитесь к сети, чтобы продолжить.", "Повторить", "Прямой эфир недоступен без интернета."],
en: ["You're offline", "Live radio needs an internet connection. Reconnect to keep listening.", "Try again", "Live stations cannot play offline.", "Waiting for a connection…", "Checking connection…", "Connection restored. Reopening radio…"],
vi: ["Bạn đang ngoại tuyến", "Radio trực tiếp cần kết nối Internet. Hãy kết nối lại để tiếp tục nghe.", "Thử lại", "Không thể nghe đài trực tiếp khi ngoại tuyến.", "Đang chờ kết nối mạng…", "Đang kiểm tra kết nối…", "Đã có mạng. Đang mở lại radio…"],
ja: ["オフラインです", "ライブ配信のラジオにはインターネット接続が必要です。再接続してください。", "再試行", "オフラインではライブ放送を再生できません。", "接続を待っています…", "接続を確認しています…", "接続が回復しました。ラジオを開き直します…"],
"zh-CN": ["当前处于离线状态", "收听直播电台需要网络连接。请重新连接后继续收听。", "重试", "离线时无法播放直播电台。", "正在等待网络连接…", "正在检查网络连接…", "连接已恢复,正在重新打开电台…"],
"zh-TW": ["目前處於離線狀態", "收聽直播電台需要網路連線。請重新連線後繼續收聽。", "重試", "離線時無法播放直播電台。", "正在等待網路連線…", "正在檢查網路連線…", "連線已恢復,正在重新開啟電台…"],
fr: ["Vous êtes hors ligne", "Une connexion Internet est nécessaire pour écouter la radio en direct. Reconnectez-vous pour continuer.", "Réessayer", "Les radios en direct ne fonctionnent pas hors ligne.", "En attente de connexion…", "Vérification de la connexion…", "Connexion rétablie. Réouverture de la radio…"],
ru: ["Вы не в сети", "Для прямого эфира радио требуется интернет. Подключитесь к сети, чтобы продолжить.", "Повторить", "Прямой эфир недоступен без интернета.", "Ожидание подключения…", "Проверка соединения…", "Соединение восстановлено. Открываем радио…"],
};
const browserLanguage = (navigator.language || 'en').toLowerCase();
const language = browserLanguage.startsWith('zh-tw') || browserLanguage.startsWith('zh-hk') || browserLanguage.startsWith('zh-mo')
? 'zh-TW' : browserLanguage.startsWith('zh') ? 'zh-CN'
: browserLanguage.startsWith('vi') ? 'vi' : browserLanguage.startsWith('ja') ? 'ja'
: browserLanguage.startsWith('fr') ? 'fr' : browserLanguage.startsWith('ru') ? 'ru' : 'en';
document.documentElement.lang = language;
const [title, description, retry, note] = messages[language];
const [title, description, retry, note, waiting, checking, connected] = messages[language];
document.getElementById('offline-title').textContent = title;
document.getElementById('offline-description').textContent = description;
document.getElementById('retry').textContent = retry;
document.getElementById('offline-note').textContent = note;
document.getElementById('retry').addEventListener('click', () => window.location.reload());

const retryButton = document.getElementById('retry');
const connectionState = document.getElementById('connection-state');
retryButton.textContent = retry;
connectionState.textContent = waiting;

let retryTimer = null;
let checkingConnection = false;
let pendingCheck = false;
let restored = false;
let failedAttempts = 0;

const scheduleRetry = () => {
clearTimeout(retryTimer);
if (restored || document.hidden) return;
// Back off while the connection is unavailable; never reload in a loop.
const delay = Math.min(15_000, 3_000 * 2 ** Math.min(Math.max(0, failedAttempts - 1), 3));
retryTimer = setTimeout(() => { void checkConnection(); }, delay);
};

async function checkConnection() {
if (restored || document.hidden) return;
if (checkingConnection) {
pendingCheck = true;
return;
}
checkingConnection = true;
clearTimeout(retryTimer);
retryButton.disabled = true;
connectionState.textContent = checking;

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5_000);
try {
// The active worker gives us the correct deployment scope for deep
// links and /pr-preview/pr-N/ paths, not just the production root.
const registration = await navigator.serviceWorker?.getRegistration?.();
const scope = registration?.scope || new URL('/', window.location.origin).href;
// A non-navigation request bypasses our navigation-only offline
// fallback. Require a real, valid manifest before reloading.
const probeUrl = new URL('brand/site.webmanifest', scope);
const response = await fetch(probeUrl.href, {
cache: 'no-store',
redirect: 'error',
signal: controller.signal,
});
if (!response.ok) throw new Error('Connection unavailable');
const manifest = await response.json();
if (typeof manifest?.name !== 'string' || typeof manifest?.start_url !== 'string') {
throw new Error('Invalid response');
}

restored = true;
connectionState.textContent = connected;
// The address bar still contains the requested station/page URL.
// Do not initiate playback; normal restore-on-reload rules apply.
window.location.reload();
} catch {
failedAttempts += 1;
connectionState.textContent = waiting;
} finally {
clearTimeout(timeout);
checkingConnection = false;
retryButton.disabled = false;
if (!restored) {
if (pendingCheck) {
pendingCheck = false;
void checkConnection();
} else {
scheduleRetry();
}
}
}
}

retryButton.addEventListener('click', () => {
failedAttempts = 0;
void checkConnection();
});
window.addEventListener('online', () => {
failedAttempts = 0;
void checkConnection();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
clearTimeout(retryTimer);
pendingCheck = false;
return;
}
failedAttempts = 0;
void checkConnection();
});
// Also recover when the network returns without firing an online event.
void checkConnection();
})();
</script>
</body>
Expand Down
2 changes: 1 addition & 1 deletion public/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/
const OFFLINE_SCOPE_KEY = encodeURIComponent(new URL(self.registration.scope).pathname);
const OFFLINE_CACHE_PREFIX = 'onair-offline-shell-' + OFFLINE_SCOPE_KEY + '-v';
const OFFLINE_CACHE_NAME = OFFLINE_CACHE_PREFIX + '1';
const OFFLINE_CACHE_NAME = OFFLINE_CACHE_PREFIX + '2';
const OFFLINE_URL = new URL('offline.html', self.registration.scope).href;

self.addEventListener('install', event => {
Expand Down
13 changes: 11 additions & 2 deletions tests/pwa-install-shell.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ function workerHarness(source) {
const cacheKeys = [
'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v0',
'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v1',
'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v2',
'onair-offline-shell-%2Fpr-preview%2Fpr-3%2F-v0',
'some-other-app',
];
Expand All @@ -22,7 +23,7 @@ function workerHarness(source) {
add: async request => { saved.push(request.url || request); },
};
const caches = {
open: async name => { assert.equal(name, 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v1'); return cache; },
open: async name => { assert.equal(name, 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v2'); return cache; },
keys: async () => cacheKeys,
delete: async name => { deleted.push(name); return true; },
match: async url => url === 'https://radio.example/pr-preview/pr-2/offline.html'
Expand Down Expand Up @@ -79,7 +80,10 @@ test('service worker caches only the noindex offline explanation, not stations o
assert.deepEqual(worker.saved, ['https://radio.example/pr-preview/pr-2/offline.html']);
assert.doesNotMatch(source, /self\.skipWaiting\(|self\.clients\.claim\(|cache\.put\(/);
await worker.run('activate');
assert.deepEqual(worker.deleted, ['onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v0']);
assert.deepEqual(worker.deleted, [
'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v0',
'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v1',
]);

for (const request of [
{ mode: 'no-cors', method: 'GET', destination: 'audio', url: 'https://stream.example/live.mp3' },
Expand Down Expand Up @@ -124,4 +128,9 @@ test('offline HTML explicitly refuses offline radio, is noindex and is self-cont
assert.doesNotMatch(html, /<(?:script|link)[^>]+(?:src|href)=["']https?:\/\//i);
assert.match(html, /env\(safe-area-inset-bottom\)/);
assert.match(html, /window\.location\.reload\(\)/);
assert.match(html, /getRegistration\?\.\(\)/);
assert.match(html, /brand\/site\.webmanifest/);
assert.match(html, /aria-live="polite"/);
assert.match(html, /cache: 'no-store'/);
assert.match(html, /document\.addEventListener\('visibilitychange'/);
});
Loading
Loading