peppa/apps/web/components/LiveRefresh.tsx

162 lines
5.7 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;
}
/** PEP-215: at most one re-render per tab in this many ms, however many changes the stream reports. */
export const MIN_REFRESH_GAP_MS = 4000;
/**
* 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, pauseHidden = false, indicator = true }: { scope: string; pollMs?: number; pauseHidden?: boolean; /** PEP-207: the chat hides the corner pill — it sits over the message field. */ indicator?: boolean }) {
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;
let lastRefresh = 0;
// 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;
}
const wait = lastRefresh + MIN_REFRESH_GAP_MS - Date.now();
if (wait > 0) {
flushTimer = setTimeout(flush, wait);
return;
}
pending.current = false;
lastRefresh = Date.now();
router.refresh();
};
const request = () => {
pending.current = true;
if (!flushTimer) flushTimer = setTimeout(flush, 300);
};
// PEP-179 `pauseHidden`: a hidden tab or a minimised app keeps no stream open (battery);
// back in view — reconnect and re-read at once.
const pause = () => {
es?.close();
es = null;
if (poll) clearInterval(poll);
poll = null;
if (retry) clearTimeout(retry);
retry = null;
};
const onVisible = () => {
const visible = document.visibilityState === "visible";
if (pauseHidden) {
if (!visible) return pause();
if (!es && !poll) {
fails = 0;
connect();
pending.current = true;
return request();
}
}
if (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");
};
};
if (!pauseHidden || document.visibilityState === "visible") 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, pauseHidden]);
if (!indicator) return null;
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>
);
}