Files
web-at-transit/frontend/public/sw.js
T
Bkk1234 4b5a4d33d3 sync from mock: motion, privacy-first search stats, auto-update UX
- frontend/src/lib/ui/motion.ts + components/MotionBoot.tsx: page-enter and
  scroll reveal per pathname change (ported from mock motion.js); IntersectionObserver
  plus sweep fallback for jump-scroll/hidden tabs, maps never transformed
- frontend/src/lib/ui/analytics.ts: cookie-less local-first search analytics
  (localStorage at_stats_v1, DNT/GPC + opt-out, term sanitiser, 900ms debounce,
  caps 300 terms / 200 views / 120 days); optional Umami endpoint via AT_ANALYTICS
- /stats page (StatsView + styles/pages/stats.css): KPIs, 14-day chart, top terms,
  top route/stop pages, no-result terms, JSON export, clear, opt-out
- hooks: stops search apply(), stop detail route filter
- remove footer visitor counter (lib/ui/visitors.ts, .mu-visitor/.mu-vreset, i18n keys)
- remove floating install-app button; PwaBoot keeps SW + guarded version toast
  (sessionStorage guard, silent reload when tab hidden)
- i18n th/en: nav.stats, update.applying, stats.* (public + src/data locales)
- version.json + sw VERSION -> 2026.10.24.3; docs/UI-PORT.md section for this round
2026-11-04 00:53:37 +07:00

125 lines
4.5 KiB
JavaScript

/* ============================================================
Atroute — Service Worker (Next.js)
ทำไมต้องมี:
Chrome/Edge/Samsung Internet จะ "ติดตั้งเป็นแอป" ได้ก็ต่อเมื่อ
1) เสิร์ฟผ่าน HTTPS (หรือ localhost)
2) มี manifest ที่ถูกต้อง (192 + 512 icon, start_url, display)
3) ★ มี service worker ที่มี fetch handler ควบคุมหน้าเว็บ
ข้อ 3 คือสิ่งที่ Next.js ไม่มีให้เอง — ไฟล์นี้คือคำตอบ
กลยุทธ์
- นำทาง (HTML) → network-first (ออนไลน์ได้ของใหม่, ออฟไลน์ใช้ cache)
- /_next/static, /image, /vendor, ฟอนต์ → cache-first (เร็ว + ออฟไลน์ได้)
- /api → ไม่แตะ (ให้ network จัดการ)
- SW ใหม่ → skipWaiting + clients.claim + แจ้งหน้าเว็บ
============================================================ */
const VERSION = "2026.10.24.3"; /* bump เมื่อแก้ UI เพื่อบังคับให้ cache เก่าถูกทิ้ง */
const CACHE = `atroute-${VERSION}`;
const OFFLINE_URL = "/offline.html";
const VERSION_URL = "/version.json";
/* ไฟล์ที่ precache ไว้ใช้ตอนออฟไลน์ (เฉพาะที่ path คงที่) */
const PRECACHE = [
"/",
OFFLINE_URL,
"/ui-manifest.json",
"/image/icons/minibus-192x192.png",
"/image/icons/minibus-512x512.png",
"/image/icons/minibus-maskable-512x512.png",
"/logo.svg",
"/vendor/fonts/k2d.css",
"/vendor/leaflet/leaflet.css",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(CACHE)
.then((cache) => cache.addAll(PRECACHE).catch(() => undefined))
.then(() => self.skipWaiting()),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
.then(() => {
self.clients.matchAll({ type: "window" }).then((cs) => {
cs.forEach((c) => c.postMessage({ type: "SW_ACTIVATED", version: VERSION }));
});
}),
);
});
self.addEventListener("message", (event) => {
if (event.data === "SKIP_WAITING") self.skipWaiting();
});
/** ไฟล์ static ที่ cache-first ได้ (path มี hash หรือไม่เปลี่ยนบ่อย) */
function isStaticAsset(url) {
return (
url.pathname.startsWith("/_next/static/") ||
url.pathname.startsWith("/image/") ||
url.pathname.startsWith("/vendor/") ||
url.pathname.startsWith("/content/") ||
/\.(?:png|jpe?g|webp|avif|svg|ico|woff2?|ttf|css|js)$/i.test(url.pathname)
);
}
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
/* ไม่ยุ่งกับ API และ cross-origin */
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/files/")) return;
/* ---- นำทาง: network-first + offline fallback ---- */
if (req.mode === "navigate") {
event.respondWith(
fetch(req)
.then((res) => {
const copy = res.clone();
caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => undefined);
return res;
})
.catch(async () => {
const cached = await caches.match(req);
return cached || (await caches.match(OFFLINE_URL)) || Response.error();
}),
);
return;
}
/* ---- static: cache-first แล้วค่อยเติม cache ---- */
if (isStaticAsset(url)) {
event.respondWith(
caches.match(req).then((cached) => {
if (cached) return cached;
return fetch(req).then((res) => {
if (res.ok && res.type === "basic") {
const copy = res.clone();
caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => undefined);
}
return res;
});
}),
);
return;
}
/* ---- อื่น ๆ: network-first ---- */
event.respondWith(
fetch(req)
.then((res) => res)
.catch(() => caches.match(req).then((r) => r || Response.error())),
);
});