fix: robust SW progress sync and startup delay
This commit is contained in:
83
public/sw.js
83
public/sw.js
@@ -1,10 +1,6 @@
|
|||||||
const CACHE_NAME = 'whisky-vault-v11-offline'; // Professional Offline-Modus v11
|
const CACHE_NAME = 'whisky-vault-v12-offline';
|
||||||
|
|
||||||
// CONFIG: Core Pages & Static Assets
|
|
||||||
const CORE_PAGES = [
|
|
||||||
'/',
|
|
||||||
];
|
|
||||||
|
|
||||||
|
// CONFIG: Assets
|
||||||
const STATIC_ASSETS = [
|
const STATIC_ASSETS = [
|
||||||
'/manifest.webmanifest',
|
'/manifest.webmanifest',
|
||||||
'/icon-192.png',
|
'/icon-192.png',
|
||||||
@@ -12,24 +8,30 @@ const STATIC_ASSETS = [
|
|||||||
'/favicon.ico',
|
'/favicon.ico',
|
||||||
];
|
];
|
||||||
|
|
||||||
// Helper: Broadcast to all clients (including those not yet controlled)
|
const CORE_PAGES = [
|
||||||
|
'/',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Global state to track progress even when UI is not listening
|
||||||
|
let currentProgress = 0;
|
||||||
|
let isPrecacheFinished = false;
|
||||||
|
|
||||||
|
// Helper: Broadcast to all clients
|
||||||
async function broadcast(message) {
|
async function broadcast(message) {
|
||||||
try {
|
try {
|
||||||
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
|
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
|
||||||
clients.forEach(client => client.postMessage(message));
|
clients.forEach(client => client.postMessage(message));
|
||||||
} catch (e) {
|
} catch (e) { }
|
||||||
// Silently fail if no clients found
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper: Fetch with Timeout & AbortController
|
// Helper: Fetch with Timeout & AbortController
|
||||||
async function fetchWithTimeout(url, timeoutMs = 25000) {
|
async function fetchWithTimeout(url, timeoutMs = 30000) {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const id = setTimeout(() => controller.abort(), timeoutMs);
|
const id = setTimeout(() => controller.abort(), timeoutMs);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
cache: 'no-store' // Ensure we get fresh bits
|
cache: 'no-store'
|
||||||
});
|
});
|
||||||
clearTimeout(id);
|
clearTimeout(id);
|
||||||
return response;
|
return response;
|
||||||
@@ -41,20 +43,23 @@ async function fetchWithTimeout(url, timeoutMs = 25000) {
|
|||||||
|
|
||||||
// 🏗️ INSTALL: Build the Offline-Modus
|
// 🏗️ INSTALL: Build the Offline-Modus
|
||||||
self.addEventListener('install', (event) => {
|
self.addEventListener('install', (event) => {
|
||||||
// Immediate takeover
|
|
||||||
self.skipWaiting();
|
self.skipWaiting();
|
||||||
|
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.open(CACHE_NAME).then(async (cache) => {
|
caches.open(CACHE_NAME).then(async (cache) => {
|
||||||
console.log('🏗️ PWA: Building Offline-Modus v11...');
|
console.log('🏗️ PWA: Building Offline-Modus v12...');
|
||||||
// Load small static assets first for instant progress bar feedback
|
|
||||||
|
// 💡 WAIT A MOMENT: Give the UI time to mount and register listeners
|
||||||
|
// In dev mode, the app takes a second to boot up.
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||||
|
|
||||||
const items = [...STATIC_ASSETS, ...CORE_PAGES];
|
const items = [...STATIC_ASSETS, ...CORE_PAGES];
|
||||||
const total = items.length;
|
const total = items.length;
|
||||||
let loaded = 0;
|
let loaded = 0;
|
||||||
|
|
||||||
// Sequential loading to avoid concurrent fetch limits on mobile
|
|
||||||
for (const url of items) {
|
for (const url of items) {
|
||||||
try {
|
try {
|
||||||
|
// Start with manifest and icons (fast) then the app shell (slow in dev)
|
||||||
const res = await fetchWithTimeout(url);
|
const res = await fetchWithTimeout(url);
|
||||||
if (res && res.ok) {
|
if (res && res.ok) {
|
||||||
await cache.put(url, res);
|
await cache.put(url, res);
|
||||||
@@ -63,27 +68,28 @@ self.addEventListener('install', (event) => {
|
|||||||
console.error(`⚠️ PWA: Pre-cache failed for ${url}:`, error);
|
console.error(`⚠️ PWA: Pre-cache failed for ${url}:`, error);
|
||||||
} finally {
|
} finally {
|
||||||
loaded++;
|
loaded++;
|
||||||
|
currentProgress = Math.round((loaded / total) * 100);
|
||||||
broadcast({
|
broadcast({
|
||||||
type: 'PRECACHE_PROGRESS',
|
type: 'OFFLINE_PROGRESS',
|
||||||
progress: Math.round((loaded / total) * 100)
|
progress: currentProgress
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('✅ PWA: Bunker build finished');
|
console.log('✅ PWA: Offline-Modus is ready');
|
||||||
broadcast({ type: 'PRECACHE_COMPLETE', version: CACHE_NAME });
|
isPrecacheFinished = true;
|
||||||
|
broadcast({ type: 'OFFLINE_READY', version: CACHE_NAME });
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 🧹 ACTIVATE: Cleanup old bunkers
|
// 🧹 ACTIVATE: Cleanup old caches
|
||||||
self.addEventListener('activate', (event) => {
|
self.addEventListener('activate', (event) => {
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches.keys().then((cacheNames) => {
|
caches.keys().then((cacheNames) => {
|
||||||
return Promise.all(
|
return Promise.all(
|
||||||
cacheNames.map((cacheName) => {
|
cacheNames.map((cacheName) => {
|
||||||
if (cacheName !== CACHE_NAME) {
|
if (cacheName !== CACHE_NAME) {
|
||||||
console.log('🧹 PWA: Clearing old bunker', cacheName);
|
|
||||||
return caches.delete(cacheName);
|
return caches.delete(cacheName);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -93,66 +99,59 @@ self.addEventListener('activate', (event) => {
|
|||||||
self.clients.claim();
|
self.clients.claim();
|
||||||
});
|
});
|
||||||
|
|
||||||
// 💬 MESSAGE: Handle status checks
|
// 💬 MESSAGE: Handle status queries
|
||||||
self.addEventListener('message', (event) => {
|
self.addEventListener('message', (event) => {
|
||||||
if (event.data?.type === 'CHECK_OFFLINE_STATUS') {
|
if (event.data?.type === 'CHECK_OFFLINE_STATUS') {
|
||||||
event.source.postMessage({
|
event.source.postMessage({
|
||||||
type: 'OFFLINE_STATUS',
|
type: 'OFFLINE_STATUS_RESPONSE',
|
||||||
isReady: true,
|
isReady: isPrecacheFinished,
|
||||||
|
progress: currentProgress,
|
||||||
version: CACHE_NAME
|
version: CACHE_NAME
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 🚀 FETCH: Bunker Strategy
|
// 🚀 FETCH: Offline-First Strategy
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', (event) => {
|
||||||
if (event.request.method !== 'GET') return;
|
if (event.request.method !== 'GET') return;
|
||||||
|
|
||||||
const url = new URL(event.request.url);
|
const url = new URL(event.request.url);
|
||||||
|
|
||||||
// 0. BYPASS for Auth/API/Supabase
|
// Bypass Auth/API
|
||||||
if (url.pathname.includes('/auth/') ||
|
if (url.pathname.includes('/auth/') || url.pathname.includes('/api/') || url.hostname.includes('supabase.co')) {
|
||||||
url.pathname.includes('/api/') ||
|
|
||||||
url.hostname.includes('supabase.co')) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. RSC DATA (_next/data): Bunker with JSON Fallback
|
// RSC Data
|
||||||
if (url.pathname.startsWith('/_next/data/')) {
|
if (url.pathname.startsWith('/_next/data/')) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.match(event.request).then((cached) => {
|
caches.match(event.request).then((cached) => {
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
return fetchWithTimeout(event.request, 3000)
|
return fetchWithTimeout(event.request, 4000)
|
||||||
.catch(() => new Response(JSON.stringify({}), {
|
.catch(() => new Response(JSON.stringify({}), { headers: { 'Content-Type': 'application/json' } }));
|
||||||
headers: { 'Content-Type': 'application/json' }
|
|
||||||
}));
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. NAVIGATION & ASSETS: Bunker + SWR
|
// Navigation & Assets
|
||||||
const isNavigation = event.request.mode === 'navigate';
|
const isNavigation = event.request.mode === 'navigate';
|
||||||
const isAsset = event.request.destination === 'style' ||
|
const isAsset = event.request.destination === 'style' ||
|
||||||
event.request.destination === 'script' ||
|
event.request.destination === 'script' ||
|
||||||
event.request.destination === 'worker' ||
|
|
||||||
event.request.destination === 'font' ||
|
|
||||||
event.request.destination === 'image' ||
|
event.request.destination === 'image' ||
|
||||||
url.pathname.startsWith('/_next/static');
|
url.pathname.startsWith('/_next/static');
|
||||||
|
|
||||||
if (isNavigation || isAsset) {
|
if (isNavigation || isAsset) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.match(event.request).then(async (cachedResponse) => {
|
caches.match(event.request).then(async (cachedResponse) => {
|
||||||
// Background update
|
const fetchPromise = fetchWithTimeout(event.request, 10000)
|
||||||
const fetchPromise = fetchWithTimeout(event.request, 8000)
|
|
||||||
.then(async (networkResponse) => {
|
.then(async (networkResponse) => {
|
||||||
if (networkResponse && networkResponse.status === 200) {
|
if (networkResponse && networkResponse.status === 200) {
|
||||||
const cache = await caches.open(CACHE_NAME);
|
const cache = await caches.open(CACHE_NAME);
|
||||||
cache.put(event.request, networkResponse.clone());
|
cache.put(event.request, networkResponse.clone());
|
||||||
}
|
}
|
||||||
return networkResponse;
|
return networkResponse;
|
||||||
})
|
}).catch(() => { });
|
||||||
.catch(() => { /* Background fail silent */ });
|
|
||||||
|
|
||||||
if (isNavigation) {
|
if (isNavigation) {
|
||||||
if (cachedResponse) return cachedResponse;
|
if (cachedResponse) return cachedResponse;
|
||||||
|
|||||||
@@ -10,19 +10,27 @@ export default function OfflineIndicator() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setIsOffline(!navigator.onLine);
|
setIsOffline(!navigator.onLine);
|
||||||
const savedReady = localStorage.getItem('whisky_bunker_ready') === 'true';
|
const savedReady = localStorage.getItem('whisky_offline_ready') === 'true';
|
||||||
setIsReady(savedReady);
|
setIsReady(savedReady);
|
||||||
|
|
||||||
const handleOnline = () => setIsOffline(false);
|
const handleOnline = () => setIsOffline(false);
|
||||||
const handleOffline = () => setIsOffline(true);
|
const handleOffline = () => setIsOffline(true);
|
||||||
|
|
||||||
const handleMessage = (event: MessageEvent) => {
|
const handleMessage = (event: MessageEvent) => {
|
||||||
if (event.data?.type === 'PRECACHE_PROGRESS') {
|
if (event.data?.type === 'OFFLINE_PROGRESS') {
|
||||||
setProgress(event.data.progress);
|
setProgress(event.data.progress);
|
||||||
}
|
}
|
||||||
if (event.data?.type === 'PRECACHE_COMPLETE' || event.data?.type === 'OFFLINE_STATUS') {
|
if (event.data?.type === 'OFFLINE_READY' || event.data?.type === 'OFFLINE_STATUS_RESPONSE') {
|
||||||
setIsReady(true);
|
if (event.data?.type === 'OFFLINE_STATUS_RESPONSE') {
|
||||||
localStorage.setItem('whisky_bunker_ready', 'true');
|
setProgress(event.data.progress || 0);
|
||||||
|
if (event.data.isReady) {
|
||||||
|
setIsReady(true);
|
||||||
|
localStorage.setItem('whisky_offline_ready', 'true');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setIsReady(true);
|
||||||
|
localStorage.setItem('whisky_offline_ready', 'true');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -31,9 +39,18 @@ export default function OfflineIndicator() {
|
|||||||
|
|
||||||
if ('serviceWorker' in navigator) {
|
if ('serviceWorker' in navigator) {
|
||||||
navigator.serviceWorker.addEventListener('message', handleMessage);
|
navigator.serviceWorker.addEventListener('message', handleMessage);
|
||||||
if (navigator.serviceWorker.controller) {
|
|
||||||
navigator.serviceWorker.controller.postMessage({ type: 'CHECK_OFFLINE_STATUS' });
|
// Proactive status check
|
||||||
}
|
navigator.serviceWorker.ready.then(() => {
|
||||||
|
// If there's an active or installing worker, ask for status
|
||||||
|
const sw = navigator.serviceWorker.controller ||
|
||||||
|
(navigator.serviceWorker as any).installing ||
|
||||||
|
(navigator.serviceWorker as any).waiting;
|
||||||
|
|
||||||
|
if (sw) {
|
||||||
|
sw.postMessage({ type: 'CHECK_OFFLINE_STATUS' });
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -56,11 +73,9 @@ export default function OfflineIndicator() {
|
|||||||
|
|
||||||
if (isReady) {
|
if (isReady) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-1.5 px-2.5 py-1 bg-green-600/10 border border-green-600/20 rounded-full group cursor-help relative">
|
<div className="flex items-center gap-1.5 px-2.5 py-1 bg-green-600/10 border border-green-600/20 rounded-full group cursor-help relative animate-in fade-in zoom-in duration-500">
|
||||||
<ShieldCheck size={10} className="text-green-600" />
|
<ShieldCheck size={10} className="text-green-600" />
|
||||||
<span className="text-[9px] font-black uppercase tracking-widest text-green-600">Offline-Modus aktiv</span>
|
<span className="text-[9px] font-black uppercase tracking-widest text-green-600">Offline-Modus aktiv</span>
|
||||||
|
|
||||||
{/* Tooltip for desktop */}
|
|
||||||
<div className="absolute top-full left-1/2 -translate-x-1/2 mt-2 w-48 p-2 bg-zinc-900 text-[10px] text-zinc-400 rounded-xl border border-white/10 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50 shadow-2xl text-center">
|
<div className="absolute top-full left-1/2 -translate-x-1/2 mt-2 w-48 p-2 bg-zinc-900 text-[10px] text-zinc-400 rounded-xl border border-white/10 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50 shadow-2xl text-center">
|
||||||
Alle Funktionen sind vollständig offline verfügbar.
|
Alle Funktionen sind vollständig offline verfügbar.
|
||||||
</div>
|
</div>
|
||||||
@@ -72,7 +87,7 @@ export default function OfflineIndicator() {
|
|||||||
<div className="flex items-center gap-1.5 px-2.5 py-1 bg-amber-600/10 border border-amber-600/20 rounded-full">
|
<div className="flex items-center gap-1.5 px-2.5 py-1 bg-amber-600/10 border border-amber-600/20 rounded-full">
|
||||||
<Loader2 size={10} className="text-amber-600 animate-spin" />
|
<Loader2 size={10} className="text-amber-600 animate-spin" />
|
||||||
<span className="text-[9px] font-black uppercase tracking-widest text-amber-600">
|
<span className="text-[9px] font-black uppercase tracking-widest text-amber-600">
|
||||||
{progress > 0 ? `Lade Offline-Daten... ${progress}%` : 'Offline-Modus wird vorbereitet...'}
|
{progress > 0 ? `Lade Offline-Daten... ${progress}%` : 'Vorbereiten...'}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user