peppa/apps/web/components/VersionWatch.tsx
Асель c739e877f5 PEP-114: a page opened before the site was updated asks to be reloaded
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 15:58:52 +05:00

48 lines
2.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
/**
* PEP-114: a page opened before the site was updated may press buttons the new server doesn't
* know — nothing happens and nothing is said. This watches the server's boot id (once a minute
* and when the tab comes back) and asks to reload when it changed. Never reloads by itself: the
* person may be in the middle of typing.
*/
export function VersionWatch({ boot }: { boot: string }) {
const [stale, setStale] = useState(false);
useEffect(() => {
let alive = true;
const check = async () => {
try {
const r = await fetch("/api/health", { cache: "no-store" });
const now = ((await r.json()) as { boot?: string }).boot;
if (alive && now && now !== boot) setStale(true);
} catch {
/* offline or restarting: the next check will tell */
}
};
const t = setInterval(check, 60_000);
const onVisible = () => document.visibilityState === "visible" && void check();
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
return () => {
alive = false;
clearInterval(t);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("focus", onVisible);
};
}, [boot]);
if (!stale) return null;
return (
<div role="alert" className="sticky top-0 z-40 flex flex-wrap items-center justify-center gap-3 border-b border-primary/50 bg-primary/15 px-4 py-2 text-sm">
<span>Peppa FACTORY обновилась. Обновите страницу — иначе кнопки на ней могут не сработать.</span>
<button type="button" onClick={() => window.location.reload()} className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1 font-medium text-primary-foreground">
<RefreshCw className="size-3.5" /> Обновить страницу
</button>
</div>
);
}