"use client"; import { useEffect } from "react"; import { type BeforeInstallPromptEvent, setInstallPrompt } from "./install-prompt-store"; import { watchServiceWorkerUpdates } from "./service-worker-updates"; /** * ลงทะเบียน service worker ของแอป + ติดตามอัปเดต (watchServiceWorkerUpdates) + เก็บ `beforeinstallprompt` * ให้ `PwaInstallCard` — วางครั้งเดียวใน layout ที่มี "use client" ได้ (render null) * * * * script ฝั่ง worker ควร: เปลี่ยน byte ทุก deployment (ฝัง deployment id/commit), `self.skipWaiting()` ใน install * โดยไม่ขึ้นกับผล precache, `self.clients.claim()` ใน activate, และเสิร์ฟด้วย `Cache-Control: no-cache` */ export function PwaServiceWorkerRegistration({ url = "/sw.js", scope = "/", }: { url?: string; scope?: string; }) { useEffect(() => { const handleBeforeInstallPrompt = (event: Event) => { event.preventDefault(); setInstallPrompt(event as BeforeInstallPromptEvent); }; const handleAppInstalled = () => setInstallPrompt(null); window.addEventListener("beforeinstallprompt", handleBeforeInstallPrompt); window.addEventListener("appinstalled", handleAppInstalled); let stopWatching: (() => void) | null = null; let isUnmounted = false; const register = async () => { if (!("serviceWorker" in navigator)) return; try { const registration = await navigator.serviceWorker.register(url, { scope, updateViaCache: "none", }); if (isUnmounted) return; stopWatching = watchServiceWorkerUpdates(navigator.serviceWorker, registration); } catch (error) { console.error("Service worker registration failed:", error); } }; if (document.readyState === "complete") { void register(); } else { window.addEventListener("load", register, { once: true }); } return () => { isUnmounted = true; stopWatching?.(); window.removeEventListener("beforeinstallprompt", handleBeforeInstallPrompt); window.removeEventListener("appinstalled", handleAppInstalled); window.removeEventListener("load", register); }; }, [url, scope]); return null; }