"use client"; import { subscriptionUsesKey, urlBase64ToBytes } from "@suphark/ui/lib/web-push"; import { useCallback, useEffect, useRef, useState } from "react"; export interface UsePushSubscriptionOptions { /** ดึง VAPID public key (null = ระบบแจ้งเตือนยังไม่พร้อม — `available` เป็น false ไม่ throw) */ getPublicKey: () => Promise; /** บันทึก subscription ที่ server — throw = ล้มเหลว (ถอน subscription ของเบราว์เซอร์ให้ ไม่ค้างสองฝั่งไม่ตรงกัน) */ onSubscribe: (subscription: PushSubscriptionJSON) => Promise; /** ลบที่ server ด้วย endpoint */ onUnsubscribe?: (endpoint: string) => Promise; /** path ของ service worker — ค่าเริ่มต้น `/sw.js` */ swPath?: string; } /** * สถานะและคำสั่ง Web Push สำหรับ UI ของแอปเอง (ยกจาก Pi Done / DueBell) — แถวตั้งค่าสำเร็จรูปคือ `WebPushRow` * - `supported` เบราว์เซอร์รองรับ · `available` server พร้อม · `enabled` เปิดอยู่จริง * - `needsRenewal` subscription เดิมสร้างด้วย key เก่า รับอะไรไม่ได้แล้ว ให้ชวนผู้ใช้เปิดใหม่ (`turnOn` ถอนของเก่าให้) * - `turnOn`/`turnOff` โยน error เมื่อไม่สำเร็จ (ไม่ให้สิทธิ์, ดึง key ไม่ได้, server ล้มเหลว) แอปแสดงข้อความเอง */ export function usePushSubscription({ getPublicKey, onSubscribe, onUnsubscribe, swPath = "/sw.js", }: UsePushSubscriptionOptions) { const [supported, setSupported] = useState(true); const [publicKey, setPublicKey] = useState(null); const [enabled, setEnabled] = useState(false); const [needsRenewal, setNeedsRenewal] = useState(false); const [loading, setLoading] = useState(true); // ฟังก์ชันจากแอปมักสร้างใหม่ทุก render — อ่านล่าสุดจาก ref ไม่ให้ effect วิ่งซ้ำ const getKey = useRef(getPublicKey); getKey.current = getPublicKey; // ผู้ใช้กดเปิด/ปิดแล้ว = ผลตรวจตอนเปิดหน้าที่มาทีหลังห้ามทับสถานะใหม่ const acted = useRef(false); useEffect(() => { const ok = "serviceWorker" in navigator && "PushManager" in window && "Notification" in window; if (!ok) { setSupported(false); setLoading(false); return; } let cancelled = false; void (async () => { try { const key = await getKey.current(); if (cancelled || acted.current || !key) return; setPublicKey(key); const registration = await navigator.serviceWorker.getRegistration(); const subscription = await registration?.pushManager.getSubscription(); if (cancelled || acted.current || !subscription) return; if (!subscriptionUsesKey(subscription, key)) setNeedsRenewal(true); else setEnabled(Notification.permission === "granted"); } catch { // ดึง key/อ่านสถานะไม่ได้ตอนเปิดหน้า = `available` เป็น false — `turnOn` ลองดึง key ใหม่ให้ } finally { if (!cancelled && !acted.current) setLoading(false); } })(); return () => { cancelled = true; }; }, []); const turnOn = useCallback(async () => { acted.current = true; setLoading(true); // ถอนของเดิมแล้วแต่สร้าง/บันทึกของใหม่ไม่สำเร็จ = ตอนนี้ไม่มี subscription เลย สถานะต้องเป็นปิด let removedPrevious = false; try { const key = publicKey ?? (await getKey.current()); if (!key) throw new Error("Web Push public key unavailable"); setPublicKey(key); const permission = await Notification.requestPermission(); if (permission !== "granted") throw new Error("Notification permission denied"); await navigator.serviceWorker.register(swPath); const registration = await navigator.serviceWorker.ready; // ถอนของเดิมเสมอ: key เก่าใช้ซ้ำไม่ได้ และของบัญชีอื่นบนเบราว์เซอร์นี้ต้องหยุดรับ const previous = await registration.pushManager.getSubscription(); if (previous) { // แจ้ง server ด้วย ไม่งั้น endpoint เก่าค้างในฐานข้อมูล · ล้มก็ไปต่อ เป้าหมายหลักคือเปิดของใหม่ให้ได้ await onUnsubscribe?.(previous.endpoint).catch(() => {}); await previous.unsubscribe(); removedPrevious = true; } const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToBytes(key), }); try { await onSubscribe(subscription.toJSON()); } catch (error) { await subscription.unsubscribe(); throw error; } setEnabled(true); setNeedsRenewal(false); } catch (error) { if (removedPrevious) { setEnabled(false); setNeedsRenewal(false); } throw error; } finally { setLoading(false); } }, [onSubscribe, onUnsubscribe, publicKey, swPath]); const turnOff = useCallback(async () => { acted.current = true; setLoading(true); try { const registration = await navigator.serviceWorker.getRegistration(); const subscription = await registration?.pushManager.getSubscription(); if (subscription) { await onUnsubscribe?.(subscription.endpoint); await subscription.unsubscribe(); } setEnabled(false); } finally { setLoading(false); } }, [onUnsubscribe]); return { supported, available: publicKey !== null, enabled, needsRenewal, loading, turnOn, turnOff, }; }