Files
tessera/web/src/App.tsx

277 lines
12 KiB
TypeScript

import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
runOrbit, startReconstitute, type Orbit,
} from "./api";
import { DecayView } from "./components/decay/DecayView";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView";
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
import { VaultScene } from "./components/scene/VaultScene";
import { EmptyState } from "./components/ui/EmptyState";
import { QueryGate } from "./components/ui/QueryGate";
import { SpringPane } from "./components/ui/SpringPane";
import { SnapshotSheet } from "./components/vault/SnapshotSheet";
import { useReducedMotion } from "./hooks/useReducedMotion";
import { orbitStatus } from "./lib/format";
import { groupSnapshots } from "./lib/galaxyLayout";
const panelTitles: Record<HUDMode, string> = {
scene: "Vault",
orbits: "Orbit management",
wormhole: "Wormhole uplink",
decay: "Snapshot retention",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
function priority(orbit: Orbit) {
if (orbit.last_status === "failed") return 0;
return orbitStatus(orbit.last_status).busy ? 1 : 2;
}
export default function App() {
const app = useRef<HTMLDivElement>(null);
const workspaceScroll = useRef<number>(undefined);
const [bigScreen, setBigScreen] = useState(false);
const [mode, setMode] = useState<HUDMode>("scene");
const panelOpen = mode !== "scene";
const [orbitId, setOrbitId] = useState<string>();
const [snapshotId, setSnapshotId] = useState<string | null>(null);
const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null);
const [play, setPlay] = useState(true);
const [restoreBusy, setRestoreBusy] = useState(false);
const [restoreTarget, setRestoreTarget] = useState<{ id: string | null }>();
const reducedMotion = useReducedMotion();
const qc = useQueryClient();
useEffect(() => {
const root = app.current;
if (!root) return;
const syncFullscreen = () => setBigScreen(document.fullscreenElement === root);
root.addEventListener("fullscreenchange", syncFullscreen);
return () => root.removeEventListener("fullscreenchange", syncFullscreen);
}, []);
useEffect(() => {
if (!bigScreen || mode !== "scene") return;
const exitOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape" && !event.defaultPrevented && !document.fullscreenElement) {
setBigScreen(false);
}
};
window.addEventListener("keydown", exitOnEscape);
return () => window.removeEventListener("keydown", exitOnEscape);
}, [bigScreen, mode]);
useLayoutEffect(() => {
if (bigScreen || workspaceScroll.current === undefined) return;
window.scrollTo(0, workspaceScroll.current);
workspaceScroll.current = undefined;
}, [bigScreen]);
function toggleBigScreen() {
const root = app.current;
if (bigScreen) {
if (document.fullscreenElement === root) {
void document.exitFullscreen().catch(() => {});
} else {
setBigScreen(false);
}
return;
}
workspaceScroll.current = window.scrollY;
setBigScreen(true);
// The viewport layout also works when the browser declines native fullscreen.
if (document.fullscreenEnabled) void root?.requestFullscreen?.().catch(() => {});
}
const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 });
const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 });
const orbits = useQuery({ queryKey: ["orbits"], queryFn: fetchOrbits, refetchInterval: 8_000, retry: 1 });
const capture = useMutation({
mutationFn: (target: Orbit) => runOrbit(target.id),
onSettled: () => {
void qc.invalidateQueries({ queryKey: ["orbits"] });
void qc.invalidateQueries({ queryKey: ["snapshots"] });
},
});
const online = health.isSuccess;
const activeId = capture.isPending ? capture.variables.id : undefined;
const sceneOrbits = useMemo(() => (orbits.data ?? []).map((orbit) =>
orbit.id === activeId ? { ...orbit, last_status: orbit.dry_run ? "rehearsing" : "running" } : orbit,
), [orbits.data, activeId]);
const register = useMemo(() => [...sceneOrbits].sort((a, b) => priority(a) - priority(b)), [sceneOrbits]);
const grouped = useMemo(() => groupSnapshots(orbits.data ?? [], snaps.data ?? []), [orbits.data, snaps.data]);
const totalBytes = useMemo(() => (snaps.data ?? []).reduce((sum, snap) => sum + snap.size_bytes, 0), [snaps.data]);
const selected = sceneOrbits.find(({ id }) => id === orbitId);
const history = (selected && grouped.get(selected.id)) ?? [];
const snapshot = snaps.data?.find(({ id }) => id === snapshotId);
const completedOrbitId = capture.isSuccess ? capture.variables.id : undefined;
const arrival = useMemo(() => !reducedMotion && completedOrbitId && capture.data
? { orbitId: completedOrbitId, snapshotId: capture.data }
: undefined, [reducedMotion, completedOrbitId, capture.data]);
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
? orbits.data ? "Live telemetry unavailable. Showing last known orbits." : "Orbit telemetry unavailable."
: register.length ? undefined : "No backup jobs yet. Set up an orbit to begin.";
const snapshotMessage = snaps.isPending ? "Loading snapshot history…" : snaps.isError
? snaps.data ? "Showing last known snapshots." : "Snapshot history unavailable."
: history.length ? undefined : "This orbit has no snapshots yet.";
const captureLabel = capture.isPending ? capture.variables.dry_run ? "Rehearsing" : "Capturing"
: capture.isError ? "Capture failed for"
: capture.variables?.dry_run ? "Rehearsal complete for"
: capture.data ? "Snapshot secured from" : "Capture finished for";
const captureNotice = capture.variables && (
<p className={`capture-notice${capture.isError ? " tone-red" : ""}`} role="status">
{captureLabel} {capture.variables.name}{capture.isPending ? "…" : "."}
</p>
);
const noticeInInspector = !!selected && selected.id === capture.variables?.id;
function selectOrbit(id: string) {
setOrbitId(id);
setPlay(false);
}
function openSnapshot(id: string) {
document.getElementById(`snapshot-${id}`)?.focus({ preventScroll: true });
setSnapshotId(id);
setMode("snapshot");
}
function runCapture(target: Orbit) {
selectOrbit(target.id);
capture.mutate(target);
}
function openConsole(next: HUDMode, target: string | null = null) {
if (next === "reconstitute" && !restoreBusy &&
(!restoreTarget || (target !== null && target !== restoreTarget.id))) {
setRestoreTarget({ id: target });
}
setMode(next);
}
return (
<div ref={app} className={`vault-app${bigScreen ? " big-screen" : ""}`}>
<header className="vault-topbar">
<div className="vault-brand">
<svg viewBox="0 0 38 38" width="34" height="34" aria-hidden="true">
<circle cx="19" cy="19" r="10.5" fill="none" stroke="currentColor" opacity=".5" />
<ellipse cx="19" cy="19" rx="17" ry="5.8" transform="rotate(-32 19 19)" fill="none" stroke="currentColor" />
<circle cx="19" cy="19" r="3" fill="currentColor" />
</svg>
<div><strong>Tessera</strong><span>Backup control</span></div>
</div>
<HUDRail active={mode === "snapshot" ? "scene" : mode} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
</p>
</header>
<main className="vault-main" inert={panelOpen}>
<div className="vault-overview">
<div>
<p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p>
<h1>Orbital vault</h1>
<p className="overview-copy">Backup jobs and recovery points</p>
</div>
<TelemetryStrip orbitCount={orbits.data?.length} failedCount={failedCount} snapCount={snaps.data?.length} totalBytes={totalBytes} />
</div>
<div className="vault-workspace">
<VaultScene
orbits={sceneOrbits} selectedOrbitId={selected?.id} recentSnapshots={history.slice(0, 3)}
flowing={play && !reducedMotion} reducedMotion={reducedMotion} arrival={arrival}
bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen}
onToggleFlow={() => setPlay((value) => !value)}
onSelectOrbit={(id) => {
selectOrbit(id);
document.getElementById(`register-${id}`)?.focus({ preventScroll: true });
}}
onSelectSnapshot={openSnapshot}
/>
<OrbitRegister
orbits={register} selected={selected?.id} message={orbitMessage}
onSelect={selectOrbit} onManage={() => setMode("orbits")}
/>
<OrbitInspector
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
onSelectSnapshot={openSnapshot}
capture={selected && (
<>
<button
type="button" className="console-control capture-button"
onClick={() => runCapture(selected)}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy}
>
<span aria-hidden="true">↘</span>
<span>{selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
</button>
{noticeInInspector && mode !== "orbits" && captureNotice}
</>
)}
/>
</div>
<footer className="vault-footer">
{(!noticeInInspector && mode !== "orbits" && captureNotice) || <p>Vault telemetry</p>}
<p role="status">{restoreBusy ? "Restore active · open Restore to monitor" : "Local backup station"}</p>
</footer>
</main>
<HUDPanel
open={panelOpen}
title={panelTitles[mode]}
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")}
>
<AnimatePresence initial={false}>
{mode === "orbits" && (
<SpringPane key="orbits">
<QueryGate query={orbits}>
{() => <OrbitsView orbits={sceneOrbits} onRun={runCapture} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
</QueryGate>
</SpringPane>
)}
{mode === "wormhole" && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "decay" && (
<SpringPane key="decay"><DecayView orbits={sceneOrbits} /></SpringPane>
)}
{mode === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <SnapshotSheet snap={snapshot} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane>
)}
</AnimatePresence>
<SpringPane active={mode === "reconstitute"}>
{restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard
key={restoreTarget.id ?? "manual"}
snapshots={snaps.data ?? []} selected={restoreTarget.id}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy}
/>
) : (
<QueryGate query={snaps} empty={<EmptyState title="No snapshots to restore" body="Capture an orbit to create a recovery point." />}>
{() => null}
</QueryGate>
))}
</SpringPane>
</HUDPanel>
</div>
);
}