peppa/apps/web/components/LiveRefresh.tsx
Асель 05dfb08b67 Merge main into task/pep-98: PEP-119 texts through the dictionary
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:56:56 +05:00

129 lines
4.5 KiB
TypeScript
Raw 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 { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { useT } from "@/components/I18n";
import { m } from "@peppa/shared/i18n";
type Mode = "connecting" | "live" | "reconnecting" | "polling";
const LABEL: Record<Mode, string> = {
connecting: m("подключение…"),
live: m("в реальном времени"),
reconnecting: m("переподключение…"),
polling: m("опрос раз в 5 с"),
};
const DOT: Record<Mode, string> = {
connecting: "bg-muted-foreground",
live: "bg-ok",
reconnecting: "bg-warn animate-pulse",
polling: "bg-warn",
};
/** True while the user is typing or left an unsent draft: a refresh must wait. */
function busy(): boolean {
const el = document.activeElement;
const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && ["text", "search", ""].includes(el.type));
const draft = [...document.querySelectorAll<HTMLTextAreaElement | HTMLInputElement>("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue);
return typing || draft;
}
/**
* Live page (PEP-37): listens to /api/live for its scope and re-renders server data when
* something there changed (router.refresh keeps client state and typed text). Falls back to
* polling every 5 s when the stream can't be opened; shows the connection state.
*/
export function LiveRefresh({ scope, pollMs = 5000 }: { scope: string; pollMs?: number }) {
const router = useRouter();
const [mode, setMode] = useState<Mode>("connecting");
const pending = useRef(false);
const t = useT();
useEffect(() => {
let closed = false;
let es: EventSource | null = null;
let fails = 0;
let opened = false;
let poll: ReturnType<typeof setInterval> | null = null;
let retry: ReturnType<typeof setTimeout> | null = null;
let flushTimer: ReturnType<typeof setTimeout> | null = null;
// Debounced refresh that waits for the user to finish typing.
const flush = () => {
flushTimer = null;
if (closed || !pending.current) return;
if (busy() || document.visibilityState !== "visible") {
flushTimer = setTimeout(flush, 2000);
return;
}
pending.current = false;
router.refresh();
};
const request = () => {
pending.current = true;
if (!flushTimer) flushTimer = setTimeout(flush, 300);
};
const onVisible = () => document.visibilityState === "visible" && pending.current && request();
const startPolling = () => {
if (poll) return;
setMode("polling");
poll = setInterval(request, pollMs);
// Try the stream again now and then.
retry = setTimeout(() => {
if (poll) clearInterval(poll);
poll = null;
fails = 0;
connect();
}, 30_000);
};
const connect = () => {
if (closed) return;
if (typeof EventSource === "undefined") return startPolling();
es = new EventSource(`/api/live?scope=${encodeURIComponent(scope)}`);
es.addEventListener("ready", () => {
// Back after a drop: changes may have been missed.
if (opened) request();
opened = true;
fails = 0;
setMode("live");
});
es.addEventListener("change", request);
es.onerror = () => {
if (closed) return;
fails++;
if (fails >= 3 || es?.readyState === EventSource.CLOSED) {
es?.close();
es = null;
startPolling();
} else setMode("reconnecting");
};
};
connect();
document.addEventListener("visibilitychange", onVisible);
return () => {
closed = true;
es?.close();
if (poll) clearInterval(poll);
if (retry) clearTimeout(retry);
if (flushTimer) clearTimeout(flushTimer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [router, scope, pollMs]);
return (
<div
role="status"
aria-live="polite"
title={mode === "polling" ? t("Канал событий недоступен — страница обновляется по таймеру") : t("Страница обновляется сама, когда что-то меняется")}
className="pointer-events-none fixed right-3 bottom-[calc(4.25rem+env(safe-area-inset-bottom))] z-40 md:bottom-3 flex items-center gap-1.5 rounded-full border bg-background/90 px-2.5 py-1 font-mono text-[11px] text-muted-foreground shadow-sm backdrop-blur"
>
<span className={cn("size-1.5 rounded-full", DOT[mode])} />
{t(LABEL[mode])}
</div>
);
}