Repository Public
1"use client";2/**3 * file: src/components/editor/nodes/live.tsx4 * description: the "living" side shared by `queryView` and by a `chart` fed by a database: one hook that resolves a `POST /api/query`5 * body (contract of docs/next/API-NEXT.md §4.7), refreshes when the window regains focus, becomes visible or comes back online, and6 * falls back to the last answer kept on the device when the server cannot be reached — always flagged as stale; and the small7 * indicator that says which of the two the reader is looking at ("Live · updated 2 min ago" / "Offline · snapshot from 14:05").8 * The pulse of the indicator is decoration only and stops under `prefers-reduced-motion` (blocks-ra.css).9 * author: Simon-Pierre Boucher — contact@spboucher.ai10 */11import * as React from "react";12import { useQuery } from "@tanstack/react-query";13import { normaliseQueryResult, loadQuerySnapshot, saveQuerySnapshot, refreshedLabel, type QueryResult } from "@/lib/editor/query";14import { api, ApiError } from "@/lib/client/api";15import { useOnline } from "@/lib/client/hooks";1617/** A server without the endpoint (older build): the block keeps its configuration and says so. */18const UNAVAILABLE = new Set([404, 405, 501]);19/** Focus / visibility / online events closer than this to the last answer do not refetch. */20const REFRESH_MIN_MS = 5_000;21const storage = (): Storage | null => { try { return typeof window === "undefined" ? null : window.localStorage; } catch { return null; } };2223export interface LiveQuery {24 /** What to show: the live answer, or the last one known (previous answer of this session, else the copy kept on the device). */25 result: QueryResult | null;26 /** `result` is not the server's current answer. */27 stale: boolean; reason: "offline" | "error" | null;28 /** The endpoint does not exist on this server (404 with no body code / 405 / 501). */29 unavailable: boolean;30 loading: boolean; fetching: boolean; error: Error | null; refresh: () => void;31}32export function useLiveQuery(body: Record<string, unknown> | null, source: string): LiveQuery {33 const online = useOnline();34 const q = useQuery({ queryKey: ["query-view", body], enabled: body != null, staleTime: 30_000, retry: false, refetchOnWindowFocus: false,35 queryFn: async () => {36 let raw: unknown;37 try { raw = await api("/api/query", { method: "POST", json: body, idempotencyKey: false }); }38 catch (e) { if (e instanceof ApiError && UNAVAILABLE.has(e.status) && !(e.status === 404 && e.code)) return { ok: false as const }; throw e; }39 const data = normaliseQueryResult(raw, source); saveQuerySnapshot(storage(), body, raw); return { ok: true as const, data };40 } });41 const { refetch, dataUpdatedAt, errorUpdatedAt, isError } = q; const last = Math.max(dataUpdatedAt, errorUpdatedAt);42 const lastRef = React.useRef(last); lastRef.current = last; const errRef = React.useRef(isError); errRef.current = isError;43 const refresh = React.useCallback(() => { void refetch({ cancelRefetch: false }); }, [refetch]);44 React.useEffect(() => {45 if (body == null) return;46 const wake = (e: Event) => { if (document.visibilityState !== "visible") return; if (e.type !== "online" && !errRef.current && Date.now() - lastRef.current < REFRESH_MIN_MS) return; refresh(); };47 window.addEventListener("focus", wake); window.addEventListener("online", wake); document.addEventListener("visibilitychange", wake);48 return () => { window.removeEventListener("focus", wake); window.removeEventListener("online", wake); document.removeEventListener("visibilitychange", wake); };49 }, [body == null, refresh]); // eslint-disable-line react-hooks/exhaustive-deps50 // the copy kept on the device is read only when the server failed and this session has no earlier answer51 const kept = React.useMemo(() => (q.isError && !q.data?.ok && body != null ? loadQuerySnapshot(storage(), body, source) : null), [q.isError, q.data, body, source]);52 const result = q.data?.ok ? q.data.data : kept;53 const offline = !online || (q.error instanceof ApiError && q.error.status === 0);54 return { result, stale: q.isError && result != null, reason: q.isError ? (offline ? "offline" : "error") : null, unavailable: q.data?.ok === false, loading: q.isLoading, fetching: q.isFetching, error: q.isError ? (q.error as Error) : null, refresh };55}5657/** Re-renders its caller every `ms` while mounted and the page is visible (relative times). */58function useTick(ms: number) {59 const [, set] = React.useState(0);60 React.useEffect(() => { const t = setInterval(() => { if (document.visibilityState === "visible") set((n) => n + 1); }, ms); return () => clearInterval(t); }, [ms]);61}62/** "Live · updated 2 min ago" (pulsing dot) or the stale state ("Offline · snapshot from 14:05"). Plain text: not a live region (it would be re-announced every minute). */63export function LiveBadge({ live, className }: { live: Pick<LiveQuery, "result" | "stale" | "reason" | "fetching">; className?: string }) {64 useTick(30_000);65 const at = live.result?.resolvedAt ?? null; if (!at && !live.fetching) return null;66 const state = live.stale ? (live.reason === "offline" ? "offline" : "stale") : live.fetching ? "updating" : "live";67 const when = refreshedLabel(at);68 const text = state === "offline" ? `Offline · snapshot from ${when}` : state === "stale" ? `Not refreshed · snapshot from ${when}` : state === "updating" ? (when ? `Updating… · ${when}` : "Updating…") : `Live · updated ${when}`;69 const title = at ? `${state === "live" || state === "updating" ? "Read from the server" : "Last answer received from the server"}: ${new Date(at).toLocaleString()}` : undefined;70 return <span className={`live-badge${className ? ` ${className}` : ""}`} data-state={state} data-testid="live-indicator" title={title}><span className="live-dot" aria-hidden /><span className="live-text">{text}</span></span>;71}72