Files
Ichsan Kurniawan 20b77dc0b7 Add PWA support with offline fallback
Add installable app metadata and icons, register a service worker for asset and page caching, and provide an offline page when navigation fails.
2026-11-04 20:47:26 +07:00

139 lines
5.5 KiB
JavaScript

const CACHE_NAME = 'hats-pwa-v1';
const PRECACHE_ASSETS = [
'/',
'/offline',
'/assets/logo192.png',
'/assets/logo512.png',
'/assets/apple-touch-icon.png',
'/assets/hats-256x256.png',
'/assets/illustrations/maintenance.svg',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
// Attempt to precache essential assets, ignoring individual failures
for (const asset of PRECACHE_ASSETS) {
try {
await cache.add(asset);
} catch (err) {
console.warn(`[PWA SW] Precache failed for ${asset}:`, err);
}
}
})
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.map((key) => {
if (key !== CACHE_NAME) {
return caches.delete(key);
}
})
);
})
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Only handle GET requests
if (request.method !== 'GET') return;
// Do not intercept browser extensions, HMR, or internal telemetry
if (url.protocol !== 'http:' && url.protocol !== 'https:') return;
if (url.pathname.includes('webpack-hmr')) return;
// Do not cache API requests or authentication endpoints
if (
url.pathname.startsWith('/api/') ||
url.hostname.includes('api') ||
url.pathname.startsWith('/auth')
) {
return;
}
// Navigation requests (HTML pages)
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((response) => {
// Only cache successful standard responses
if (response && response.status === 200 && response.type === 'basic') {
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, responseToCache);
});
}
return response;
})
.catch(async () => {
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
const offlineFallback = await caches.match('/offline');
if (offlineFallback) {
return offlineFallback;
}
return new Response(
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Offline - H.A.T.s</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #fafafa; color: #18181b; text-align: center; padding: 20px; }
.card { max-width: 420px; background: white; border: 1px solid #e4e4e7; border-radius: 16px; padding: 32px 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
h1 { font-size: 20px; margin: 16px 0 8px; color: #09090b; }
p { font-size: 14px; color: #71717a; margin-bottom: 24px; line-height: 1.5; }
button { background: #EA512C; color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 500; cursor: pointer; font-size: 14px; }
</style>
</head>
<body>
<div class="card">
<img src="/assets/logo192.png" width="64" height="64" alt="H.A.T.s" style="border-radius: 12px;" />
<h1>You are currently offline</h1>
<p>Please check your internet connection to continue using H.A.T.s.</p>
<button onclick="window.location.reload()">Retry Connection</button>
</div>
</body>
</html>`,
{ headers: { 'Content-Type': 'text/html; charset=utf-8' } }
);
})
);
return;
}
// Static assets (images, icons, fonts) - Cache First, Fallback to Network
if (
url.pathname.startsWith('/assets/') ||
url.pathname.match(/\.(png|jpg|jpeg|svg|webp|gif|ico|woff|woff2|ttf|css)$/)
) {
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request).then((response) => {
if (response && response.status === 200) {
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, clone);
});
}
return response;
});
})
);
}
});