"use client"; import { useEffect, useRef } from "react"; import { toast } from "sonner"; import { hasDeploymentChanged, normalizeDeploymentId, } from "@/lib/deployment/version"; import { withBasePath } from "@/lib/base-path"; const UPDATE_TOAST_ID = "deployment-update"; export function DeploymentUpdateNotifier({ deploymentId, }: { deploymentId: string; }) { const currentDeployment = useRef(normalizeDeploymentId(deploymentId)); const updateAvailable = useRef(false); useEffect(() => { const source = new EventSource(withBasePath("/api/active")); const receiveDeployment = (event: Event) => { if ( updateAvailable.current || !(event instanceof MessageEvent) || typeof event.data !== "string" ) { return; } const nextDeployment = normalizeDeploymentId(event.data); if (!hasDeploymentChanged(currentDeployment.current, nextDeployment)) { return; } updateAvailable.current = true; toast("มีอัปเดตใหม่พร้อมใช้งาน", { id: UPDATE_TOAST_ID, description: "รีโหลดเพื่ออัปเดตเป็นเวอร์ชันล่าสุด", action: { label: "รีโหลด", onClick: () => window.location.reload(), }, duration: Infinity, }); }; source.addEventListener("deployment", receiveDeployment); return () => { source.removeEventListener("deployment", receiveDeployment); source.close(); }; }, []); return null; }