49 lines
1.8 KiB
TypeScript
49 lines
1.8 KiB
TypeScript
// R-P11b — client-side consumer of the dashboard SSE snapshot route
|
|
// (app.$tenant/dashboard.stream). The route owns this hook and feeds the
|
|
// resulting snapshot into DashboardPage as a prop. The loader already supplies a
|
|
// fresh snapshot, so the stream opens after a short warm-up instead of
|
|
// duplicating the expensive snapshot query in the page-load critical path.
|
|
//
|
|
// The stream is always on: the dashboard shows the current state of the
|
|
// workspace, and letting a member switch that off only ever produced staler
|
|
// numbers with no way to tell them apart from fresh ones.
|
|
|
|
import { useEffect, useState } from "react";
|
|
import type { DashboardPageData } from "@hivegrid/view-models";
|
|
|
|
const DASHBOARD_STREAM_WARMUP_MS = 15_000;
|
|
|
|
export function useDashboardStream({ streamUrl, initialGeneratedAt }: { streamUrl: string; initialGeneratedAt: string }) {
|
|
const [snapshot, setSnapshot] = useState<DashboardPageData | null>(null);
|
|
|
|
// A fresh loader snapshot supersedes whatever the stream delivered before.
|
|
useEffect(() => {
|
|
setSnapshot(null);
|
|
}, [initialGeneratedAt, streamUrl]);
|
|
|
|
useEffect(() => {
|
|
if (typeof EventSource === "undefined") {
|
|
return;
|
|
}
|
|
let source: EventSource | null = null;
|
|
const timer = window.setTimeout(() => {
|
|
source = new EventSource(streamUrl);
|
|
source.addEventListener("dashboard.snapshot", onSnapshot as EventListener);
|
|
}, DASHBOARD_STREAM_WARMUP_MS);
|
|
function onSnapshot(event: MessageEvent) {
|
|
try {
|
|
setSnapshot(JSON.parse(event.data) as DashboardPageData);
|
|
} catch {
|
|
// Malformed payloads are ignored; the loader data stays visible.
|
|
}
|
|
}
|
|
return () => {
|
|
window.clearTimeout(timer);
|
|
source?.removeEventListener("dashboard.snapshot", onSnapshot as EventListener);
|
|
source?.close();
|
|
};
|
|
}, [streamUrl]);
|
|
|
|
return { snapshot };
|
|
}
|