peppa/apps/web/components/VersionWatch.tsx
Асель 8ff54d6363 Merge main into task/pep-98: PEP-111/114 texts through the dictionary
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:32:40 +05:00

50 lines
2.1 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { RefreshCw } from "lucide-react";
import { useT } from "@/components/I18n";
/**
* 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 t = useT();
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 timer = setInterval(check, 60_000);
const onVisible = () => document.visibilityState === "visible" && void check();
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
return () => {
alive = false;
clearInterval(timer);
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>{t("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" /> {t("Обновить страницу")}
</button>
</div>
);
}