feat(cameras): ‹ › through older/newer snapshots in the large view

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
This commit is contained in:
2026-11-17 17:31:58 +01:00
parent bccef3875b
commit cb43ad78ca
8 changed files with 267 additions and 43 deletions
+8
View File
@@ -180,6 +180,14 @@ export async function fetchLatestCameraSnapshot(deviceId: string): Promise<Camer
}
}
/** The next older / newer snapshot of the same camera (the large view's ‹ ›). */
export function fetchCameraSnapshotNeighbors(
deviceId: string,
snapshotId: string,
): Promise<{ older: CameraSnapshotMeta | null; newer: CameraSnapshotMeta | null }> {
return apiFetch(`/api/cameras/${encodeURIComponent(deviceId)}/snapshots/${encodeURIComponent(snapshotId)}/neighbors`);
}
/** Snapshot bytes as an object URL. Fetched (not an <img src>) so it works in the
* desktop shell too, whose webview does not carry the session cookie. The caller
* revokes the URL. */
+4 -1
View File
@@ -272,7 +272,7 @@ export const en: Catalog = {
camera: {
expand: "Show larger",
snapshot: "Snapshot",
liveOnDemand: "Live on request",
liveOnDemand: "Live on-demand",
live: "Live",
showTile: "Show this camera",
hideTile: "Hide this camera",
@@ -281,6 +281,9 @@ export const en: Catalog = {
connecting: "Connecting to live video…",
liveUnavailable: "Live video unavailable",
vehicleInView: "Vehicle in view",
older: "Older snapshot",
newer: "Newer snapshot",
snapshotUnavailable: "Snapshot unavailable",
},
booth: {
processTicket: "Process ticket",
+12 -9
View File
@@ -273,16 +273,19 @@ export const sq = {
},
camera: {
expand: "Shfaq më të madhe",
snapshot: "Foto",
liveOnDemand: "Live me kërkesë",
snapshot: "Snapshot",
liveOnDemand: "Live on-demand",
live: "Live",
showTile: "Shfaq këtë kamerë",
hideTile: "Fshih këtë kamerë",
noSnapshot: "Ende pa foto",
noSnapshot: "Ende pa snapshot",
idle: "Videoja live nis kur vjen një automjet",
connecting: "Po lidhet videoja live…",
liveUnavailable: "Videoja live nuk është e disponueshme",
vehicleInView: "Automjet në pamje",
older: "Foto më e vjetër",
newer: "Foto më e re",
snapshotUnavailable: "Fotoja nuk është e disponueshme",
},
booth: {
processTicket: "Proceso biletën",
@@ -337,7 +340,7 @@ export const sq = {
forgiveExitOk: "Dalja u hap manualisht, pa pagesë.",
forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}",
forgiveDialogTitle: "Hapje manuale",
forgiveDialogBody: "Hap barrierën e DALJES manualisht. Nuk merret asnjë pagesë dhe nuk printohet asgjë; hapja nënshkruhet me emrin tënd bashkë me foton e kamerës së daljes dhe shfaqet në raportin e turnit tënd.",
forgiveDialogBody: "Hap barrierën e DALJES manualisht. Nuk merret asnjë pagesë dhe nuk printohet asgjë; hapja nënshkruhet me emrin tënd bashkë me snapshot-in e kamerës së daljes dhe shfaqet në raportin e turnit tënd.",
forgiveDialogReason: "Arsyeja (opsionale)",
forgiveDialogReasonPlaceholder: "p.sh. hyri kur barrierat ishin të hapura…",
forgiveDialogConfirm: "Hap daljen — pa pagesë",
@@ -397,7 +400,7 @@ export const sq = {
edSource: "Burimi",
edIdentity: "Identiteti",
edReason: "Arsyeja",
edSnapshots: "Fotot",
edSnapshots: "Snapshot-et",
edPayload: "Të dhënat e nënshkruara",
edChain: "Zinxhiri",
edSignature: "Nënshkrimi",
@@ -533,7 +536,7 @@ export const sq = {
// Category titles + the singular noun used in buttons/modal titles.
catControllers: "Kontrollerat (barrierat + butoni i hyrjes)",
catReaders: "Lexuesit (QR / RFID)",
catCameras: "Kamerat (foto + targë)",
catCameras: "Kamerat (snapshot + targë)",
catPrinters: "Printerat (bileta / vouchera)",
nounController: "kontroller",
nounReader: "lexues",
@@ -874,7 +877,7 @@ export const sq = {
reserveSubs: "Rezervo vendet e abonentëve",
reserveSubsHint: "Mban një vend për makinat e çdo abonenti aktiv edhe kur nuk janë të parkuar — kalimtarët e shohin 'plot' më shpejt. Joaktiv: numërohen vetëm makinat brenda (mbingarkesa menaxhohet me parkim manual).",
anprEntry: "Hapje automatike për targat e abonentëve (ANPR)",
anprEntryHint: "Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Fotot e targave regjistrohen gjithsesi.",
anprEntryHint: "Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Snapshot-et e targave regjistrohen gjithsesi.",
parkDetails: "Të dhënat e parkimit (opsionale — shfaqen në bileta/fatura)",
save: "Ruaj",
saved: "U ruajt.",
@@ -1298,8 +1301,8 @@ export const sq = {
exitForgiven: "Dalje manuale — {{amount}}, barriera u hap.",
exitForgivenNotOpened: "Dalje manuale — {{amount}}, barriera nuk u hap: {{reason}}",
// snapshots
noSnapshots: "asnjë foto",
loadingSnapshots: "duke ngarkuar fotot…",
noSnapshots: "asnjë snapshot",
loadingSnapshots: "duke ngarkuar snapshot-et…",
snapEntry: "hyrje",
snapExit: "dalje",
snapFailed: "kamera e paarritshme",
+126 -31
View File
@@ -2,8 +2,14 @@ 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 { fetchLatestCameraSnapshot, fetchSnapshotObjectUrl, type DeviceStatus } from "../api.js";
import { formatClock } from "../lib/format.js";
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";
@@ -15,7 +21,9 @@ import { createPlatformSocket } from "../lib/platform-ws.js";
// 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. Live frames come over their own socket as JPEG binaries; only the newest frame is
// 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.
@@ -83,6 +91,21 @@ function CameraTile({
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
@@ -92,16 +115,33 @@ function CameraTile({
: live.status.state === "unavailable" || live.status.state === "retrying"
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
: t("camera.connecting")
: snapshot.meta
? `${snapshot.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.meta.capturedAt)}`
: 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={snapshot.url}
placeholder={canSeeSnapshots ? t("camera.noSnapshot") : t("camera.idle")}
caption={caption}
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"}
/>
);
@@ -136,7 +176,16 @@ function CameraTile({
{view("tile")}
</button>
{expanded && (
<CameraModal title={title} mode={modalMode} onMode={setModalMode} onClose={() => setExpanded(false)}>
<CameraModal
title={title}
mode={modalMode}
onMode={setModalMode}
nav={nav}
onClose={() => {
setExpanded(false);
setBrowsed(null);
}}
>
{view("modal")}
</CameraModal>
)}
@@ -204,27 +253,56 @@ function LiveBadge({ large }: { large: boolean }) {
);
}
/** Large view of one camera with a Live / Snapshot switch. Closes on ✕, Escape or a
* backdrop click. */
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) => e.key === "Escape" && onClose();
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]);
}, [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"
@@ -267,14 +345,19 @@ function CameraModal({
✕
</button>
</div>
{children}
<div className="relative">
{children}
{nav && chevron("left")}
{nav && chevron("right")}
</div>
</div>
</div>,
document.body,
);
}
/** Newest snapshot for the tile's resting picture, as an object URL (revoked on change). */
/** 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],
@@ -282,30 +365,42 @@ function useLatestSnapshot(deviceId: string, enabled: boolean) {
enabled,
staleTime: 60_000,
});
const id = meta.data?.id ?? null;
const [url, setUrl] = useState<string | null>(null);
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 (!id) {
setUrl(null);
if (!want) {
replace({ meta: null, url: null, failed: false });
return;
}
let cancelled = false;
let made: string | null = null;
fetchSnapshotObjectUrl(id)
.then((u) => {
if (cancelled) URL.revokeObjectURL(u);
else {
made = u;
setUrl(u);
}
})
.catch(() => !cancelled && setUrl(null));
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;
if (made) URL.revokeObjectURL(made);
};
// Keyed by id only: a new `want` object for the same snapshot must not refetch.
}, [id]);
return { meta: meta.data ?? null, url };
useEffect(() => () => replace({ meta: null, url: null, failed: false }), []);
return pic;
}
/**