import { useCallback, useEffect, useRef, useState } from "react"; import { PWA_UPDATE_READY_EVENT } from "../lib/pwaUpdateEvents"; type PwaUpdateReadyDetail = { applyUpdate?: () => void | Promise; }; function resolveApplyUpdate(event: Event) { const detail = (event as CustomEvent).detail; return typeof detail?.applyUpdate === "function" ? detail.applyUpdate : null; } export function usePwaUpdatePrompt() { const applyUpdateRef = useRef<(() => void | Promise) | null>(null); const [updateReady, setUpdateReady] = useState(false); useEffect(() => { const handleUpdateReady = (event: Event) => { applyUpdateRef.current = resolveApplyUpdate(event); setUpdateReady(true); }; window.addEventListener(PWA_UPDATE_READY_EVENT, handleUpdateReady); return () => { window.removeEventListener(PWA_UPDATE_READY_EVENT, handleUpdateReady); }; }, []); const applyUpdate = useCallback(() => { const handler = applyUpdateRef.current; if (handler) { void handler(); return; } window.location.reload(); }, []); const dismissUpdate = useCallback(() => { setUpdateReady(false); }, []); return { updateReady, applyUpdate, dismissUpdate, }; }