peppa/apps/web/components/LiveRefresh.tsx
2026-11-20 21:37:49 +05:00

126 lines
4.6 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 } from "react";
import { cn } from "@/lib/utils";
import { useT } from "@/components/I18n";
import { applyIslands, liveClient, useLive, useLiveMode, type LiveEvent, type LiveMode } from "@/lib/live";
import { m } from "@peppa/shared/i18n";
const LABEL: Record<LiveMode, string> = {
connecting: m("подключение…"),
live: m("в реальном времени"),
reconnecting: m("переподключение…"),
offline: m("нет связи — пробуем снова"),
};
const DOT: Record<LiveMode, string> = {
connecting: "bg-muted-foreground",
live: "bg-ok",
reconnecting: "bg-warn animate-pulse",
offline: "bg-destructive",
};
/** 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 channel reports. */
export const MIN_REFRESH_GAP_MS = 4000;
/** PEP-225: parts of the `chats` scope a chat page cares about besides messages of its own chat. */
const CHAT_PAGE_PARTS = new Set(["q", "tg", "*"]);
/**
* Live page (PEP-37, PEP-225): watches its scope over the tab's channel. A change the page's
* islands apply in place (board cards, the attention counter…) needs nothing more; anything else
* re-renders server data (router.refresh keeps client state and typed text) — at most once per
* 4 s, never while the person types. Shows the connection state.
*/
export function LiveRefresh({
scope,
pauseHidden = false,
indicator = true,
chatId,
}: {
scope: string;
/** PEP-179: a hidden tab drops the scope (battery) and catches up when back in view. */
pauseHidden?: boolean;
/** PEP-207: the chat hides the corner pill — it sits over the message field. */
indicator?: boolean;
/** PEP-225: a chat page re-renders only for new messages of this chat (and answered questions). */
chatId?: number;
}) {
const router = useRouter();
const mode = useLiveMode();
const t = useT();
const state = useRef({ pending: false, timer: null as ReturnType<typeof setTimeout> | null, last: 0 });
useEffect(() => {
const s = state.current;
return () => {
if (s.timer) clearTimeout(s.timer);
s.timer = null;
};
}, []);
const flush = () => {
const s = state.current;
s.timer = null;
if (!s.pending) return;
// Offline a re-render fails into a full navigation to the browser's error page: wait for the channel.
if (busy() || document.visibilityState !== "visible" || !navigator.onLine || liveClient().mode !== "live") {
s.timer = setTimeout(flush, 2000);
return;
}
const wait = s.last + MIN_REFRESH_GAP_MS - Date.now();
if (wait > 0) {
s.timer = setTimeout(flush, wait);
return;
}
s.pending = false;
s.last = Date.now();
router.refresh();
};
const request = () => {
const s = state.current;
s.pending = true;
if (!s.timer) s.timer = setTimeout(flush, 300);
};
useLive(
scope,
(e: LiveEvent) => {
if (e.type !== "change") return;
let parts = e.parts;
if (chatId != null) {
// Messages of other chats and events not yet projected into this chat don't concern it.
const mine = e.chats?.includes(chatId) ?? false;
parts = parts.filter((p) => (p === "m" ? mine : CHAT_PAGE_PARTS.has(p)));
if (!parts.length) return;
}
const applied = applyIslands(e);
if (parts.every((p) => applied.has(p))) return;
request();
},
{ heavy: pauseHidden },
);
if (!indicator) return null;
return (
<div
role="status"
aria-live="polite"
data-live-mode={mode}
title={mode === "offline" ? t("Нет связи с Peppa FACTORY — страница обновится, когда связь вернётся") : 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>
);
}