cb43ad78ca
On the Snapshot side the large view steps through that camera's snapshots (‹ older, › newer, also ← →), muted at either end; the caption carries the date and always names the picture on screen (the previous one stays while the next loads; a pruned still says "unavailable"). The tile stays on the newest; closing resets. New read-only route GET /api/cameras/:deviceId/snapshots/:snapshotId/neighbors (session:read), ordered by (capturedAt, id) like latest-snapshot, bounded to seek the device/time index. Also carries the user's own label edits in en.ts / sq.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RZgP5oMncSaVmKRKk1UvN4
490 lines
18 KiB
TypeScript
490 lines
18 KiB
TypeScript
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||
import { createPortal } from "react-dom";
|
||
import { useTranslation } from "react-i18next";
|
||
import { useQuery } from "@tanstack/react-query";
|
||
import {
|
||
fetchCameraSnapshotNeighbors,
|
||
fetchLatestCameraSnapshot,
|
||
fetchSnapshotObjectUrl,
|
||
type CameraSnapshotMeta,
|
||
type DeviceStatus,
|
||
} from "../api.js";
|
||
import { formatClock, formatRelativeDateTime } from "../lib/format.js";
|
||
import { useLiveStore } from "../lib/live-store.js";
|
||
import { wsUrl } from "../lib/origin.js";
|
||
import { createPlatformSocket } from "../lib/platform-ws.js";
|
||
|
||
// Booth camera tiles (wiki/decisions/camera-live-view.md). Opened from the camera
|
||
// chips in the device footer; docked bottom-right, the first opened rightmost and each
|
||
// next one to its left. A tile rests on the camera's newest entry/exit snapshot and
|
||
// switches to live video while that camera is seeing a vehicle (the server's per-camera
|
||
// activity, pushed over /api/ws). Clicking the picture opens a large view in the
|
||
// tile's state (live if the tile is live, else the snapshot), with a Live / Snapshot
|
||
// switch that streams LIVE ON DEMAND, car or no car; closing it returns the tile to
|
||
// automatic — a stream the user started stops, one the camera started carries on. On
|
||
// the Snapshot side, ‹ › step through this camera's older / newer snapshots (the tile
|
||
// itself always rests on the newest; the large view reopens on it). Live frames come over their own socket as JPEG binaries; only the newest frame is
|
||
// shown, and the tile and the large view share that one socket. Advisory viewing —
|
||
// nothing here gates anything.
|
||
|
||
type LiveState =
|
||
| { state: "connecting" }
|
||
| { state: "live" }
|
||
| { state: "retrying"; reason: string }
|
||
| { state: "unavailable"; reason: string };
|
||
|
||
/** Delay before re-opening a live socket that dropped while the camera is still active. */
|
||
const RECONNECT_MS = 2000;
|
||
|
||
export function CameraDock({
|
||
openIds,
|
||
cameras,
|
||
label,
|
||
canSeeSnapshots,
|
||
onClose,
|
||
}: {
|
||
openIds: string[];
|
||
/** Configured cameras (for labels, and to skip a tile whose camera was removed). */
|
||
cameras: DeviceStatus[];
|
||
label: (d: DeviceStatus) => string;
|
||
canSeeSnapshots: boolean;
|
||
onClose: (deviceId: string) => void;
|
||
}) {
|
||
const byId = new Map(cameras.map((c) => [c.deviceId, c]));
|
||
const shown = openIds.filter((id) => byId.has(id));
|
||
if (shown.length === 0) return null;
|
||
return (
|
||
// Above the footer; first opened rightmost (row-reverse), the next to its left.
|
||
<div className="pointer-events-none fixed bottom-9 right-2 z-40 flex flex-row-reverse items-end gap-2">
|
||
{shown.map((id) => (
|
||
<CameraTile
|
||
key={id}
|
||
deviceId={id}
|
||
title={label(byId.get(id)!)}
|
||
canSeeSnapshots={canSeeSnapshots}
|
||
onClose={() => onClose(id)}
|
||
/>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function CameraTile({
|
||
deviceId,
|
||
title,
|
||
canSeeSnapshots,
|
||
onClose,
|
||
}: {
|
||
deviceId: string;
|
||
title: string;
|
||
canSeeSnapshots: boolean;
|
||
onClose: () => void;
|
||
}) {
|
||
const { t } = useTranslation();
|
||
/** The camera is reporting a vehicle (server-side activity, 30 s after its last push). */
|
||
const active = useLiveStore((s) => s.activeCameras[deviceId] === true);
|
||
/** Large view open, and what it shows (opens in the tile's state, then the user's pick). */
|
||
const [expanded, setExpanded] = useState(false);
|
||
const [modalMode, setModalMode] = useState<"live" | "snapshot">("live");
|
||
// Modal open → the user's choice rules; closed → automatic (live while a vehicle is in view).
|
||
const wantLive = expanded ? modalMode === "live" : active;
|
||
const live = useLiveFrames(deviceId, wantLive);
|
||
const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots);
|
||
const showLive = wantLive && live.hasFrame;
|
||
/** The snapshot the large view shows when the user has stepped away from the newest. */
|
||
const [browsed, setBrowsed] = useState<CameraSnapshotMeta | null>(null);
|
||
const browsedPic = useSnapshotPicture(browsed);
|
||
/** What the ‹ › step from: the snapshot asked for (its picture may still be loading). */
|
||
const modalShot = browsed ?? snapshot.meta;
|
||
const browsing = expanded && modalMode === "snapshot" && canSeeSnapshots && modalShot !== null;
|
||
const neighbors = useQuery({
|
||
// Under "camera-latest" so a new snapshot's invalidation refreshes "newer" too.
|
||
queryKey: ["camera-latest", deviceId, "neighbors", modalShot?.id],
|
||
queryFn: () => fetchCameraSnapshotNeighbors(deviceId, modalShot!.id),
|
||
enabled: browsing,
|
||
});
|
||
const nav = browsing
|
||
? { older: neighbors.data?.older ?? null, newer: neighbors.data?.newer ?? null, go: setBrowsed }
|
||
: null;
|
||
|
||
const caption = wantLive
|
||
? showLive
|
||
? active
|
||
? t("camera.vehicleInView")
|
||
: t("camera.liveOnDemand")
|
||
: live.status.state === "unavailable" || live.status.state === "retrying"
|
||
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
|
||
: t("camera.connecting")
|
||
: snapshot.pic.meta
|
||
? `${snapshot.pic.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.pic.meta.capturedAt)}`
|
||
: "";
|
||
// The large view's picture: a stepped-to snapshot once its bytes are in, the previous
|
||
// picture until then. The caption always names the picture SHOWN (these are evidence
|
||
// stills — a date must never sit under another snapshot's picture).
|
||
const modalPic = browsed ? (browsedPic.meta ? browsedPic : snapshot.pic) : snapshot.pic;
|
||
const modalCaption = wantLive
|
||
? caption
|
||
: browsed && browsedPic.failed
|
||
? t("camera.snapshotUnavailable")
|
||
: modalPic.meta
|
||
? `${modalPic.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatRelativeDateTime(modalPic.meta.capturedAt, t, { seconds: true })}`
|
||
: caption;
|
||
const view = (slot: "tile" | "modal") => (
|
||
<CameraView
|
||
imgRef={live.imgRefs[slot]}
|
||
showLive={showLive}
|
||
snapshotUrl={slot === "modal" ? (browsed && browsedPic.failed ? null : modalPic.url) : snapshot.pic.url}
|
||
placeholder={
|
||
slot === "modal" && browsed && browsedPic.failed
|
||
? t("camera.snapshotUnavailable")
|
||
: canSeeSnapshots
|
||
? t("camera.noSnapshot")
|
||
: t("camera.idle")
|
||
}
|
||
caption={slot === "modal" ? modalCaption : caption}
|
||
large={slot === "modal"}
|
||
/>
|
||
);
|
||
|
||
return (
|
||
<div className="pointer-events-auto flex w-[15vw] min-w-[200px] flex-col overflow-hidden rounded-term border border-term-border bg-term-panel shadow-2xl">
|
||
<div className="flex items-center gap-2 border-b border-term-border bg-term-panel-2 px-2 py-1 text-[0.6875rem]">
|
||
<span className="min-w-0 flex-1 truncate font-semibold text-term-text">{title}</span>
|
||
<button
|
||
type="button"
|
||
onClick={onClose}
|
||
className="shrink-0 text-term-muted hover:text-term-text"
|
||
aria-label={t("common.close")}
|
||
title={t("common.close")}
|
||
>
|
||
✕
|
||
</button>
|
||
</div>
|
||
{/* The picture is the expand control: the large view opens showing what the tile
|
||
shows. Seeded from `active`, not from "a frame has arrived", so a camera-started
|
||
stream that is still connecting is not torn down by the click. */}
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setModalMode(active ? "live" : "snapshot");
|
||
setExpanded(true);
|
||
}}
|
||
className="block w-full cursor-zoom-in"
|
||
title={t("camera.expand")}
|
||
aria-label={t("camera.expand")}
|
||
>
|
||
{view("tile")}
|
||
</button>
|
||
{expanded && (
|
||
<CameraModal
|
||
title={title}
|
||
mode={modalMode}
|
||
onMode={setModalMode}
|
||
nav={nav}
|
||
onClose={() => {
|
||
setExpanded(false);
|
||
setBrowsed(null);
|
||
}}
|
||
>
|
||
{view("modal")}
|
||
</CameraModal>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** The picture area shared by the tile and the large view: live frames (painted
|
||
* straight into the <img>, no re-render per frame) or the resting snapshot. */
|
||
function CameraView({
|
||
imgRef,
|
||
showLive,
|
||
snapshotUrl,
|
||
placeholder,
|
||
caption,
|
||
large,
|
||
}: {
|
||
imgRef: (el: HTMLImageElement | null) => void;
|
||
showLive: boolean;
|
||
snapshotUrl: string | null;
|
||
placeholder: string;
|
||
caption: string;
|
||
large: boolean;
|
||
}) {
|
||
return (
|
||
<div className="relative aspect-video w-full bg-black">
|
||
<img ref={imgRef} alt="" className={`absolute inset-0 h-full w-full object-contain ${showLive ? "" : "hidden"}`} />
|
||
{!showLive && snapshotUrl && (
|
||
<img src={snapshotUrl} alt="" className="absolute inset-0 h-full w-full object-contain" />
|
||
)}
|
||
{!showLive && !snapshotUrl && (
|
||
<div className="absolute inset-0 flex items-center justify-center px-2 text-center text-[0.6875rem] text-term-muted">
|
||
{placeholder}
|
||
</div>
|
||
)}
|
||
{showLive && <LiveBadge large={large} />}
|
||
{caption && (
|
||
<div
|
||
className={`absolute bottom-0 left-0 right-0 truncate bg-black/60 text-left text-term-muted ${
|
||
large ? "px-3 py-1 text-[0.8125rem]" : "px-1.5 py-0.5 text-[0.625rem]"
|
||
}`}
|
||
>
|
||
{caption}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** "● LIVE" with a pulsing green dot, over the video's top-left corner. */
|
||
function LiveBadge({ large }: { large: boolean }) {
|
||
const { t } = useTranslation();
|
||
return (
|
||
<span
|
||
className={`absolute left-1.5 top-1.5 flex items-center gap-1.5 rounded-full bg-black/70 font-semibold uppercase tracking-wider text-term-green ${
|
||
large ? "px-2.5 py-1 text-[0.8125rem]" : "px-1.5 py-0.5 text-[0.625rem]"
|
||
}`}
|
||
>
|
||
<span className="relative flex h-2 w-2">
|
||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-term-green opacity-75" />
|
||
<span className="relative inline-flex h-2 w-2 rounded-full bg-term-green" />
|
||
</span>
|
||
{t("camera.live")}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
type SnapshotNav = {
|
||
older: CameraSnapshotMeta | null;
|
||
newer: CameraSnapshotMeta | null;
|
||
go: (shot: CameraSnapshotMeta) => void;
|
||
};
|
||
|
||
/** Large view of one camera with a Live / Snapshot switch and, on the Snapshot side,
|
||
* ‹ › (also ← →) to step through older / newer snapshots — muted at either end.
|
||
* Closes on ✕, Escape or a backdrop click. */
|
||
function CameraModal({
|
||
title,
|
||
mode,
|
||
onMode,
|
||
nav,
|
||
onClose,
|
||
children,
|
||
}: {
|
||
title: string;
|
||
mode: "live" | "snapshot";
|
||
onMode: (m: "live" | "snapshot") => void;
|
||
nav: SnapshotNav | null;
|
||
onClose: () => void;
|
||
children: ReactNode;
|
||
}) {
|
||
const { t } = useTranslation();
|
||
useEffect(() => {
|
||
const onKey = (e: KeyboardEvent) => {
|
||
if (e.key === "Escape") onClose();
|
||
else if (e.key === "ArrowLeft" && nav?.older) nav.go(nav.older);
|
||
else if (e.key === "ArrowRight" && nav?.newer) nav.go(nav.newer);
|
||
};
|
||
document.addEventListener("keydown", onKey);
|
||
return () => document.removeEventListener("keydown", onKey);
|
||
}, [onClose, nav]);
|
||
const chevron = (side: "left" | "right") => {
|
||
const target = side === "left" ? nav?.older : nav?.newer;
|
||
const label = t(side === "left" ? "camera.older" : "camera.newer");
|
||
return (
|
||
<button
|
||
type="button"
|
||
disabled={!target}
|
||
onClick={() => target && nav?.go(target)}
|
||
aria-label={label}
|
||
title={label}
|
||
className={`absolute top-1/2 ${side === "left" ? "left-2" : "right-2"} flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-black/60 text-3xl leading-none text-term-text transition-opacity hover:bg-black/80 disabled:cursor-default disabled:opacity-25 disabled:hover:bg-black/60`}
|
||
>
|
||
{side === "left" ? "‹" : "›"}
|
||
</button>
|
||
);
|
||
};
|
||
const seg = (m: "live" | "snapshot", label: string) => (
|
||
<button
|
||
type="button"
|
||
onClick={() => onMode(m)}
|
||
aria-pressed={mode === m}
|
||
className={`px-3 py-0.5 text-[0.75rem] font-semibold uppercase tracking-wider ${
|
||
mode === m ? "bg-term-amber text-term-bg" : "text-term-muted hover:text-term-text"
|
||
}`}
|
||
>
|
||
{label}
|
||
</button>
|
||
);
|
||
// Portalled to <body>: the dock is a fixed, z-indexed, pointer-events-none layer that
|
||
// would otherwise trap the modal inside its stacking context.
|
||
return createPortal(
|
||
<div
|
||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-6"
|
||
onClick={onClose}
|
||
role="dialog"
|
||
aria-modal="true"
|
||
aria-label={title}
|
||
>
|
||
<div
|
||
className="flex w-[min(90vw,calc((100vh-7rem)*16/9))] flex-col overflow-hidden rounded-term border border-term-border bg-term-panel shadow-2xl"
|
||
onClick={(e) => e.stopPropagation()}
|
||
>
|
||
<div className="flex items-center gap-3 border-b border-term-border bg-term-panel-2 px-3 py-1.5 text-[0.8125rem]">
|
||
<span className="min-w-0 flex-1 truncate font-semibold text-term-text">{title}</span>
|
||
<div className="flex shrink-0 overflow-hidden rounded-term border border-term-border" role="group">
|
||
{seg("live", t("camera.live"))}
|
||
{seg("snapshot", t("camera.snapshot"))}
|
||
</div>
|
||
<button
|
||
type="button"
|
||
onClick={onClose}
|
||
className="shrink-0 text-term-muted hover:text-term-text"
|
||
aria-label={t("common.close")}
|
||
title={t("common.close")}
|
||
>
|
||
✕
|
||
</button>
|
||
</div>
|
||
<div className="relative">
|
||
{children}
|
||
{nav && chevron("left")}
|
||
{nav && chevron("right")}
|
||
</div>
|
||
</div>
|
||
</div>,
|
||
document.body,
|
||
);
|
||
}
|
||
|
||
/** Newest snapshot for the tile's resting picture: `meta` is the newest known, `pic` what
|
||
* is on screen (the previous picture until the newest has loaded). */
|
||
function useLatestSnapshot(deviceId: string, enabled: boolean) {
|
||
const meta = useQuery({
|
||
queryKey: ["camera-latest", deviceId],
|
||
queryFn: () => fetchLatestCameraSnapshot(deviceId),
|
||
enabled,
|
||
staleTime: 60_000,
|
||
});
|
||
const pic = useSnapshotPicture(meta.data ?? null);
|
||
return { meta: meta.data ?? null, pic };
|
||
}
|
||
|
||
type SnapshotPicture = { meta: CameraSnapshotMeta | null; url: string | null; failed: boolean };
|
||
|
||
/** A snapshot's bytes as an object URL, paired with the meta it belongs to. On a change
|
||
* the previous picture (and its meta) stays until the next has loaded — no blank flash
|
||
* while stepping — then is revoked; `failed` when the last request failed (e.g. pruned
|
||
* by retention). Everything is revoked on unmount. */
|
||
function useSnapshotPicture(want: CameraSnapshotMeta | null): SnapshotPicture {
|
||
const [pic, setPic] = useState<SnapshotPicture>({ meta: null, url: null, failed: false });
|
||
const current = useRef<string | null>(null);
|
||
const replace = (next: SnapshotPicture) => {
|
||
if (current.current && current.current !== next.url) URL.revokeObjectURL(current.current);
|
||
current.current = next.url;
|
||
setPic(next);
|
||
};
|
||
const id = want?.id ?? null;
|
||
useEffect(() => {
|
||
if (!want) {
|
||
replace({ meta: null, url: null, failed: false });
|
||
return;
|
||
}
|
||
let cancelled = false;
|
||
setPic((p) => ({ ...p, failed: false }));
|
||
fetchSnapshotObjectUrl(want.id)
|
||
.then((u) => (cancelled ? URL.revokeObjectURL(u) : replace({ meta: want, url: u, failed: false })))
|
||
.catch(() => !cancelled && setPic((p) => ({ ...p, failed: true })));
|
||
return () => {
|
||
cancelled = true;
|
||
};
|
||
// Keyed by id only: a new `want` object for the same snapshot must not refetch.
|
||
}, [id]);
|
||
useEffect(() => () => replace({ meta: null, url: null, failed: false }), []);
|
||
return pic;
|
||
}
|
||
|
||
/**
|
||
* While `active` (wanted: camera activity, or the user's choice in the large view), hold a live socket to the camera and paint each JPEG into `imgRef`.
|
||
* Closed (and the last frame dropped) as soon as the camera goes idle or the tile
|
||
* unmounts; reconnects after a drop while still active. The server shares one camera
|
||
* session between every viewer and skips frames for a slow one.
|
||
*/
|
||
function useLiveFrames(deviceId: string, active: boolean) {
|
||
// Every <img> showing this camera (the tile, and the large view while open) gets each
|
||
// frame; a view that mounts between frames is given the newest one at once.
|
||
const imgs = useRef(new Map<string, HTMLImageElement>());
|
||
const latest = useRef<string | null>(null);
|
||
const imgRefs = useMemo(() => {
|
||
const slot = (name: string) => (el: HTMLImageElement | null) => {
|
||
if (el) {
|
||
imgs.current.set(name, el);
|
||
if (latest.current) el.src = latest.current;
|
||
} else {
|
||
imgs.current.delete(name);
|
||
}
|
||
};
|
||
return { tile: slot("tile"), modal: slot("modal") };
|
||
}, []);
|
||
const [status, setStatus] = useState<LiveState>({ state: "connecting" });
|
||
const [hasFrame, setHasFrame] = useState(false);
|
||
|
||
useEffect(() => {
|
||
if (!active) {
|
||
setHasFrame(false);
|
||
setStatus({ state: "connecting" });
|
||
return;
|
||
}
|
||
let closed = false;
|
||
let currentUrl: string | null = null;
|
||
let retry: number | undefined;
|
||
let sock: ReturnType<typeof createPlatformSocket> | null = null;
|
||
|
||
const paint = (buf: ArrayBuffer) => {
|
||
if (closed) return; // a frame landing after cleanup must not resurrect the view
|
||
const next = URL.createObjectURL(new Blob([buf], { type: "image/jpeg" }));
|
||
const prev = currentUrl;
|
||
currentUrl = next;
|
||
latest.current = next;
|
||
for (const img of imgs.current.values()) img.src = next;
|
||
if (prev) URL.revokeObjectURL(prev);
|
||
setHasFrame(true);
|
||
};
|
||
|
||
const connect = () => {
|
||
if (closed) return;
|
||
setStatus({ state: "connecting" });
|
||
sock = createPlatformSocket(wsUrl(`/api/cameras/${encodeURIComponent(deviceId)}/live`));
|
||
sock.onmessage = (ev) => {
|
||
if (closed) return;
|
||
if (typeof ev.data === "string") {
|
||
try {
|
||
const msg = JSON.parse(ev.data) as { kind: string } & LiveState;
|
||
if (msg.kind === "status") setStatus(msg);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
} else {
|
||
paint(ev.data);
|
||
}
|
||
};
|
||
sock.onclose = () => {
|
||
if (closed) return;
|
||
retry = window.setTimeout(connect, RECONNECT_MS);
|
||
};
|
||
sock.onerror = () => sock?.close();
|
||
};
|
||
connect();
|
||
|
||
return () => {
|
||
closed = true;
|
||
if (retry) window.clearTimeout(retry);
|
||
sock?.close();
|
||
if (currentUrl) URL.revokeObjectURL(currentUrl);
|
||
latest.current = null;
|
||
for (const img of imgs.current.values()) img.removeAttribute("src");
|
||
};
|
||
}, [deviceId, active]);
|
||
|
||
return { imgRefs, status, hasFrame };
|
||
}
|