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:
@@ -60,6 +60,55 @@ describe("GET /api/cameras/:id/latest-snapshot", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/cameras/:id/snapshots/:snapshotId/neighbors", () => {
|
||||
const url = (cam: string, id: string) => `/api/cameras/${cam}/snapshots/${id}/neighbors`;
|
||||
|
||||
it("steps through one camera's snapshots by time, ties broken by id", async () => {
|
||||
await seedUser(db, { username: "admin", password: "pw" });
|
||||
const { cookie } = await login(app, "admin", "pw");
|
||||
shot("a", "cam-dahua", "2026-11-17T10:00:00.000Z");
|
||||
shot("b", "cam-dahua", "2026-11-17T11:00:00.000Z");
|
||||
shot("c", "cam-dahua", "2026-11-17T11:00:00.000Z"); // same instant as b
|
||||
shot("d", "cam-dahua", "2026-11-17T12:00:00.000Z");
|
||||
shot("x", "other", "2026-11-17T11:30:00.000Z"); // another camera: never a neighbour
|
||||
const get = async (id: string) => (await app.inject({ url: url("cam-dahua", id), headers: { cookie } })).json();
|
||||
const ids = (r: { older: { id: string } | null; newer: { id: string } | null }) => [r.older?.id ?? null, r.newer?.id ?? null];
|
||||
expect(ids(await get("a"))).toEqual([null, "b"]);
|
||||
expect(ids(await get("b"))).toEqual(["a", "c"]);
|
||||
expect(ids(await get("c"))).toEqual(["b", "d"]);
|
||||
expect(ids(await get("d"))).toEqual(["c", null]);
|
||||
expect(await get("b")).toMatchObject({ older: { id: "a", direction: "entry", capturedAt: "2026-11-17T10:00:00.000Z" } });
|
||||
// latest-snapshot uses the same tie-break, so "newer" is never offered from the latest
|
||||
const latest = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie } });
|
||||
expect(latest.json().id).toBe("d");
|
||||
});
|
||||
|
||||
it("a tie at the newest end: latest-snapshot is the one with no newer", async () => {
|
||||
await seedUser(db, { username: "admin", password: "pw" });
|
||||
const { cookie } = await login(app, "admin", "pw");
|
||||
shot("p", "cam-dahua", "2026-11-17T10:00:00.000Z");
|
||||
shot("q", "cam-dahua", "2026-11-17T12:00:00.000Z");
|
||||
shot("r", "cam-dahua", "2026-11-17T12:00:00.000Z");
|
||||
const latest = (await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie } })).json();
|
||||
const n = (await app.inject({ url: url("cam-dahua", latest.id), headers: { cookie } })).json();
|
||||
expect(latest.id).toBe("r");
|
||||
expect(n).toMatchObject({ older: { id: "q" }, newer: null });
|
||||
});
|
||||
|
||||
it("404s another camera's snapshot, 403s without session:read", async () => {
|
||||
await seedUser(db, { username: "admin", password: "pw" });
|
||||
const admin = await login(app, "admin", "pw");
|
||||
shot("x", "other", "2026-11-17T11:30:00.000Z");
|
||||
const foreign = await app.inject({ url: url("cam-dahua", "x"), headers: { cookie: admin.cookie } });
|
||||
expect(foreign.statusCode).toBe(404);
|
||||
|
||||
await seedUser(db, { username: "dev", password: "pw", roleId: "devonly", permissions: ["device:read"] });
|
||||
const dev = await login(app, "dev", "pw");
|
||||
const res = await app.inject({ url: url("other", "x"), headers: { cookie: dev.cookie } });
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WS /api/cameras/:id/live", () => {
|
||||
const origin = "http://booth.local:8080";
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { desc, devices, eq, snapshots, type Db } from "@parking/db";
|
||||
import { and, asc, desc, devices, eq, gt, gte, lt, lte, or, snapshots, type Db } from "@parking/db";
|
||||
import { isLiveStreamDevice } from "@parking/devices";
|
||||
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||
import { buildCamera } from "../snapshot.js";
|
||||
@@ -10,6 +10,9 @@ import { authenticateWsHandshake } from "./ws.js";
|
||||
// - GET /api/cameras/:deviceId/latest-snapshot — the tile's default picture: the newest
|
||||
// entry/exit evidence still this camera captured (metadata; bytes stay at
|
||||
// /api/snapshots/:id). Evidence → `session:read`, like every snapshot read.
|
||||
// - GET /api/cameras/:deviceId/snapshots/:snapshotId/neighbors — the large view's ‹ ›:
|
||||
// this camera's next older and next newer snapshot ({ older, newer }, each meta or
|
||||
// null). Same permission. Order is (capturedAt, id) everywhere so ties are stable.
|
||||
// - WS /api/cameras/:deviceId/live — live video while the camera sees a vehicle.
|
||||
// Same handshake auth as /api/ws (Origin allowlist, then desktop ticket or cookie),
|
||||
// then `device:read` (the footer's permission). Server → client: text JSON
|
||||
@@ -42,7 +45,7 @@ export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLive
|
||||
.select({ id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt })
|
||||
.from(snapshots)
|
||||
.where(eq(snapshots.deviceId, req.params.deviceId))
|
||||
.orderBy(desc(snapshots.capturedAt))
|
||||
.orderBy(desc(snapshots.capturedAt), desc(snapshots.id))
|
||||
.limit(1)
|
||||
.get();
|
||||
if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" });
|
||||
@@ -50,6 +53,51 @@ export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLive
|
||||
},
|
||||
);
|
||||
|
||||
app.get<{ Params: { deviceId: string; snapshotId: string } }>(
|
||||
"/api/cameras/:deviceId/snapshots/:snapshotId/neighbors",
|
||||
{ preHandler: requirePermission("session:read") },
|
||||
async (req, reply) => {
|
||||
const { deviceId, snapshotId } = req.params;
|
||||
const at = db
|
||||
.select({ capturedAt: snapshots.capturedAt })
|
||||
.from(snapshots)
|
||||
.where(and(eq(snapshots.id, snapshotId), eq(snapshots.deviceId, deviceId)))
|
||||
.get();
|
||||
if (!at) return reply.code(404).send({ error: "no such snapshot for this camera" });
|
||||
const meta = { id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt };
|
||||
// capturedAt is always toISOString() (UTC, fixed width), so string order = time order.
|
||||
// The plain lte/gte bound next to the OR lets SQLite seek snapshots_device_time_idx
|
||||
// from this snapshot instead of walking the camera's index from one end.
|
||||
const older = db
|
||||
.select(meta)
|
||||
.from(snapshots)
|
||||
.where(
|
||||
and(
|
||||
eq(snapshots.deviceId, deviceId),
|
||||
lte(snapshots.capturedAt, at.capturedAt),
|
||||
or(lt(snapshots.capturedAt, at.capturedAt), and(eq(snapshots.capturedAt, at.capturedAt), lt(snapshots.id, snapshotId))),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(snapshots.capturedAt), desc(snapshots.id))
|
||||
.limit(1)
|
||||
.get();
|
||||
const newer = db
|
||||
.select(meta)
|
||||
.from(snapshots)
|
||||
.where(
|
||||
and(
|
||||
eq(snapshots.deviceId, deviceId),
|
||||
gte(snapshots.capturedAt, at.capturedAt),
|
||||
or(gt(snapshots.capturedAt, at.capturedAt), and(eq(snapshots.capturedAt, at.capturedAt), gt(snapshots.id, snapshotId))),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(snapshots.capturedAt), asc(snapshots.id))
|
||||
.limit(1)
|
||||
.get();
|
||||
return { older: older ?? null, newer: newer ?? null };
|
||||
},
|
||||
);
|
||||
|
||||
app.get<{ Params: { deviceId: string } }>(
|
||||
"/api/cameras/:deviceId/live",
|
||||
{
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user