diff --git a/TODO.md b/TODO.md index db70982..292fb1c 100644 --- a/TODO.md +++ b/TODO.md @@ -167,7 +167,16 @@ and the System page reads live data through the Vite proxy. - [x] Wire `RequireAuth` into `router.tsx` and delete the "not enforced" banner — gallery needs any signed-in user, Devices and System need `admin`. Sign-out is in the header. - [ ] ESLint (skipped during scaffolding; `tsc --noEmit` covers the important cases for now) -- [ ] Virtualised gallery grid; filters for date range, taxon, device, tag, reviewed, kept +- [x] Virtualised gallery grid, cursor-paged, thumbnails through the auth-checked route. + Filters for date range, device, kept, reviewed and pre-trigger — the columns that have + data. **Taxon and tag filters are deliberately still missing:** both need a join, and + neither has anything to join to until `taxa` is seeded and the observation editor exists. + A filter that can only return nothing is worse than an absent one, because the UI offers it. +- [x] `poorbird seed --captures 500` — synthetic captures with real JPEGs on disk, realistic + burst structure and pre-trigger flags. `--clear` is scoped to its own device so it can + never remove a real camera's frames. +- [ ] Full-size viewer: keyboard navigation is in, but it only steps through what is already + loaded. Stepping past the last loaded page needs the viewer to be able to trigger a fetch. - [ ] Observation editor — `captures` 1—n `observations`, so a photo can hold two species or none - [ ] Taxon autocomplete; seed `taxa` with 60–80 Central European garden species incl. GBIF keys, `name_de` + `name_en`, `is_local_common` ranking first - [ ] Tags, favourite/reject (`kept`), review flag diff --git a/web/README.md b/web/README.md index b95162a..d5e8f67 100644 --- a/web/README.md +++ b/web/README.md @@ -60,13 +60,30 @@ The guard here decides what to *render*. It is not access control: the server authorises every request on its own, and deleting `RequireAuth.tsx` would expose no data, it would only render pages whose requests then 401. -**Only `GET /health` and `/auth/*` return real data.** So the **System** page -shows live values and the others do not yet: +**The gallery is real.** It reads `GET /api/v1/captures`, pages by cursor, +and loads thumbnails through the auth-checked route — so an image is only +served to a request that carried a valid session. -Gallery and Devices render an honest empty state. They are deliberately not -filled with mock rows — fake data hides exactly the layout problems that real -data exposes. The capture and device listing endpoints are the next server -work; the six captures already in the dev database have nothing to serve them. +To have something to look at: + +```bash +cd ../server +.venv/Scripts/poorbird seed --captures 500 +.venv/Scripts/poorbird seed --clear # when you are done +``` + +`--clear` only ever removes seeded data. It is scoped to its own device, so a +real camera's captures are never in scope. + +**Devices still renders an honest empty state.** It needs a device listing +endpoint, which is Phase 4. It is deliberately not filled with mock rows — +fake data hides exactly the layout problems real data exposes. + +The grid is virtualised, which matters at the scale this reaches rather than +the scale it starts at: 5000 captures a day is past a million DOM nodes within +a year, and the browser gives up long before the database does. Only visible +rows exist, and the column count is computed from the measured container width +rather than from media queries. --- @@ -105,9 +122,11 @@ src/ router.tsx the whole route table, one flat file i18n/ en.ts (source of truth), de.ts (typed against it) theme/ data-theme on - auth/ provider, login form, route guard (not wired yet) - lib/api.ts the only place that calls fetch - components/ layout and shared pieces + auth/ provider, login form, route guard + lib/api.ts the only place that calls fetch, and the only one + that knows about CSRF or builds image URLs + components/ layout, shared pieces, CaptureGrid, CaptureViewer, + GalleryFilters pages/ one per route styles/ tokens.css (themes), global.css (everything else) scripts/check-contrast.mjs diff --git a/web/package-lock.json b/web/package-lock.json index 1f3871e..1cb4cdd 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@tanstack/react-query": "^5.62.0", "@tanstack/react-router": "^1.95.0", + "@tanstack/react-virtual": "^3.14.13", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -1291,6 +1292,23 @@ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/@tanstack/react-virtual": { + "version": "3.14.13", + "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.13.tgz", + "integrity": "sha512-JbDTAwtzZ99aOeCrAfW5EsE5KSq5RWh6Af2dtFwyLIIk48Ja7vm6n4axu/43T3vfjFnEGJalxJ1wyYjSQD6bSg==", + "license": "MIT", + "dependencies": { + "@tanstack/virtual-core": "3.17.11" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/@tanstack/router-core": { "version": "1.171.32", "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.171.32.tgz", @@ -1320,6 +1338,16 @@ "url": "https://github.com/sponsors/tannerlinsley" } }, + "node_modules/@tanstack/virtual-core": { + "version": "3.17.11", + "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.11.tgz", + "integrity": "sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", diff --git a/web/package.json b/web/package.json index 02b39f9..a9d6bf6 100644 --- a/web/package.json +++ b/web/package.json @@ -13,6 +13,7 @@ "dependencies": { "@tanstack/react-query": "^5.62.0", "@tanstack/react-router": "^1.95.0", + "@tanstack/react-virtual": "^3.14.13", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/web/src/components/CaptureGrid.tsx b/web/src/components/CaptureGrid.tsx new file mode 100644 index 0000000..9cd7b3d --- /dev/null +++ b/web/src/components/CaptureGrid.tsx @@ -0,0 +1,182 @@ +/* The virtualised capture grid. + * + * Virtualised because the gallery is the one screen that grows without bound: + * 5000 captures a day means a year is well past a million DOM nodes, and the + * browser gives up long before the data does. Only the visible rows exist. + * + * react-virtual virtualises a list, not a grid, so the grid is a list of rows + * and the column count is computed from the measured width. That keeps the + * layout responsive without a media-query ladder, and it is why the container + * width is observed rather than assumed. + */ + +import { useVirtualizer } from "@tanstack/react-virtual"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; + +import { useT } from "../i18n/I18nProvider"; +import type { CaptureSummary } from "../lib/api"; +import { thumbUrl } from "../lib/api"; + +/** Smallest tile that still shows a recognisable bird. */ +const MIN_TILE_PX = 200; +const GAP_PX = 12; + +/* Thumbnails are 400px on the long edge (SPEC 3.3) and the camera shoots 4:3, + * so a 4:3 tile shows the whole frame without cropping. Guessing wrong here + * only costs a reflow, because the row height is derived from it rather than + * measured per image. */ +const TILE_ASPECT = 3 / 4; + +/** Start the next page this many rows before the end. */ +const PREFETCH_ROWS = 3; + +function useColumnCount(ref: React.RefObject): number { + const [columns, setColumns] = useState(1); + + useLayoutEffect(() => { + const element = ref.current; + if (element === null) return; + + const measure = () => { + const width = element.clientWidth; + if (width === 0) return; + setColumns(Math.max(1, Math.floor((width + GAP_PX) / (MIN_TILE_PX + GAP_PX)))); + }; + + measure(); + // ResizeObserver rather than a window resize listener: the sidebar and + // the filter panel change this element's width without the window + // changing size at all. + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, [ref]); + + return columns; +} + +function Tile({ + capture, + onOpen, +}: { + capture: CaptureSummary; + onOpen: (capture: CaptureSummary) => void; +}) { + const t = useT(); + + return ( + + ); +} + +export function CaptureGrid({ + captures, + hasMore, + isLoadingMore, + onLoadMore, + onOpen, +}: { + captures: CaptureSummary[]; + hasMore: boolean; + isLoadingMore: boolean; + onLoadMore: () => void; + onOpen: (capture: CaptureSummary) => void; +}) { + const t = useT(); + const scrollRef = useRef(null); + const columns = useColumnCount(scrollRef); + const rowCount = Math.ceil(captures.length / columns); + + const virtualizer = useVirtualizer({ + count: rowCount, + getScrollElement: () => scrollRef.current, + // Width per tile is (container - gaps) / columns; height follows the + // aspect ratio. Close enough that rows do not need measuring. + estimateSize: useCallback(() => { + const width = scrollRef.current?.clientWidth ?? MIN_TILE_PX * columns; + const tileWidth = (width - GAP_PX * (columns - 1)) / columns; + return tileWidth / TILE_ASPECT + GAP_PX; + }, [columns]), + overscan: 2, + }); + + // Re-measure when the column count changes, or every row keeps the height + // it had at the old width and the grid overlaps itself. + useEffect(() => { + virtualizer.measure(); + }, [columns, virtualizer]); + + const virtualRows = virtualizer.getVirtualItems(); + const lastVisibleRow = virtualRows.at(-1)?.index ?? 0; + + useEffect(() => { + if (hasMore && !isLoadingMore && lastVisibleRow >= rowCount - PREFETCH_ROWS) { + onLoadMore(); + } + }, [hasMore, isLoadingMore, lastVisibleRow, rowCount, onLoadMore]); + + return ( +
+
+ {virtualRows.map((row) => { + const start = row.index * columns; + return ( +
+ {captures.slice(start, start + columns).map((capture) => ( + + ))} +
+ ); + })} +
+ +

+ {isLoadingMore ? t("gallery.loadingMore") : hasMore ? "" : t("gallery.allLoaded")} +

+
+ ); +} diff --git a/web/src/components/CaptureViewer.tsx b/web/src/components/CaptureViewer.tsx new file mode 100644 index 0000000..ef8c366 --- /dev/null +++ b/web/src/components/CaptureViewer.tsx @@ -0,0 +1,208 @@ +/* Full-screen view of one capture. + * + * Keyboard-driven on purpose. Labelling a day of captures is a loop of + * look-decide-next, hundreds of times, and that loop is only bearable from + * the keyboard -- arrows to move, Escape to leave. The mouse is the fallback, + * not the design. + */ + +import { useQuery } from "@tanstack/react-query"; +import { useEffect } from "react"; + +import { useT } from "../i18n/I18nProvider"; +import type { Translate } from "../i18n/I18nProvider"; +import type { CaptureSummary } from "../lib/api"; +import { getCapture, imageUrl } from "../lib/api"; + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +function triggerLabel(t: Translate, trigger: CaptureSummary["trigger"]): string { + switch (trigger) { + case "radar": + return t("capture.trigger.radar"); + case "manual": + return t("capture.trigger.manual"); + case "timer": + return t("capture.trigger.timer"); + case "stream_grab": + return t("capture.trigger.stream_grab"); + } +} + +function Row({ label, value }: { label: string; value: string }) { + return ( +
+ {label} + {value} +
+ ); +} + +export function CaptureViewer({ + capture, + onClose, + onPrevious, + onNext, +}: { + capture: CaptureSummary; + onClose: () => void; + onPrevious: (() => void) | null; + onNext: (() => void) | null; +}) { + const t = useT(); + + // The summary is already in hand from the grid, so the detail query only + // adds the extra fields. Showing the image immediately and filling the + // metadata a moment later beats a spinner over the whole overlay. + const detail = useQuery({ + queryKey: ["capture", capture.id], + queryFn: () => getCapture(capture.id), + staleTime: 60_000, + }); + + useEffect(() => { + function onKey(event: KeyboardEvent) { + if (event.key === "Escape") onClose(); + if (event.key === "ArrowLeft" && onPrevious !== null) onPrevious(); + if (event.key === "ArrowRight" && onNext !== null) onNext(); + } + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onClose, onPrevious, onNext]); + + const full = detail.data; + + return ( + // eslint-disable-next-line -- the overlay is a dialog; the backdrop click + // is a convenience and every action it offers is also a real button. +
+
+
+ {new Date(capture.received_at).toLocaleString()} +
+ + + +
+
+ +
+
+ +
+ + +
+
+
+ ); +} diff --git a/web/src/components/GalleryFilters.tsx b/web/src/components/GalleryFilters.tsx new file mode 100644 index 0000000..7644dca --- /dev/null +++ b/web/src/components/GalleryFilters.tsx @@ -0,0 +1,168 @@ +/* Gallery filters. + * + * Only the filters the server can actually answer. Taxon and tag filters are + * in TODO Phase 3 and deliberately absent until there is a seeded taxa table + * and an observation editor to fill them -- offering a control that can only + * ever return nothing is worse than not offering it. + * + * The triage filters are tri-state (any / yes / no) rather than checkboxes, + * because "kept" has three meanings here: show everything, show only kept, + * show only rejected. A checkbox can express two of those. + */ + +import { useT } from "../i18n/I18nProvider"; +import type { CaptureFilters } from "../lib/api"; + +export type { CaptureFilters }; + +/** A { + const raw = event.target.value; + onChange(raw === "" ? undefined : raw === "true"); + }} + > + + + + + + ); +} + +/** A date input carries a local calendar day; the API wants an instant. */ +function dayStart(value: string): string | undefined { + if (value === "") return undefined; + return new Date(`${value}T00:00:00`).toISOString(); +} + +function dayEnd(value: string): string | undefined { + if (value === "") return undefined; + // Inclusive: picking the same day for both ends should return that day, + // which an exclusive midnight boundary would make an empty range. + return new Date(`${value}T23:59:59.999`).toISOString(); +} + +/** Back to what a date input can display, in local time. */ +function toDateInput(iso: string | undefined): string { + if (iso === undefined) return ""; + const date = new Date(iso); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + return `${date.getFullYear()}-${month}-${day}`; +} + +export function GalleryFilters({ + filters, + onChange, + devices, +}: { + filters: CaptureFilters; + onChange: (next: CaptureFilters) => void; + devices: { id: number; name: string }[]; +}) { + const t = useT(); + const active = Object.values(filters).some((value) => value !== undefined); + + return ( +
+ + + + + + + onChange({ ...filters, kept })} + yesLabel={t("filters.onlyKept")} + noLabel={t("filters.onlyRejected")} + /> + + onChange({ ...filters, reviewed })} + yesLabel={t("filters.onlyReviewed")} + noLabel={t("filters.onlyUnreviewed")} + /> + + + + +
+ ); +} diff --git a/web/src/i18n/de.ts b/web/src/i18n/de.ts index df99b18..5dc7c9c 100644 --- a/web/src/i18n/de.ts +++ b/web/src/i18n/de.ts @@ -43,7 +43,60 @@ export const de: Catalogue = { "gallery.title": "Galerie", "gallery.empty.title": "Noch keine Aufnahmen", "gallery.empty.body": - "Die Kamera hat noch nichts hochgeladen. Der Upload kommt in Phase 2; bis dahin bleibt diese Liste leer.", + "Die Kamera hat noch nichts hochgeladen. Zum Ausprobieren welche erzeugen: poorbird seed --captures 500", + "gallery.empty.filtered.title": "Keine Treffer für diese Filter", + "gallery.empty.filtered.body": "Zeitraum erweitern oder Filter zurücksetzen.", + "gallery.count": "{shown} von {total} geladen", + "gallery.loadingMore": "Lädt weitere…", + "gallery.allLoaded": "Das sind alle.", + "gallery.noThumb": "Keine Vorschau", + "gallery.thumbPending": "Vorschau noch nicht fertig", + + "filters.title": "Filter", + "filters.clear": "Filter zurücksetzen", + "filters.device": "Kamera", + "filters.device.all": "Alle Kameras", + "filters.from": "Von", + "filters.to": "Bis", + "filters.kept": "Behalten", + "filters.reviewed": "Durchgesehen", + "filters.preTrigger": "Nur Pre-Trigger", + "filters.any": "Alle", + "filters.onlyKept": "Nur behaltene", + "filters.onlyRejected": "Nur verworfene", + "filters.onlyReviewed": "Nur durchgesehene", + "filters.onlyUnreviewed": "Nur nicht durchgesehene", + + "capture.title": "Aufnahme", + "capture.close": "Schließen", + "capture.previous": "Zurück", + "capture.next": "Weiter", + "capture.openFull": "In Originalgröße öffnen", + "capture.receivedAt": "Empfangen", + "capture.capturedAt": "Kamerauhr", + "capture.capturedAt.unsynced": "Nicht synchronisiert", + "capture.device": "Kamera", + "capture.dimensions": "Größe", + "capture.fileSize": "Datei", + "capture.trigger": "Auslöser", + "capture.trigger.radar": "Radar", + "capture.trigger.manual": "Manuell", + "capture.trigger.timer": "Timer", + "capture.trigger.stream_grab": "Stream-Bild", + "capture.preTrigger": "Pre-Trigger-Bild", + "capture.preTrigger.hint": + "Vor dem Auslösen aufgenommen, aus dem Ringpuffer der Kamera", + "capture.burst": "Bild {index} von {count}", + "capture.radarDistance": "Radar-Entfernung", + "capture.radarEnergy": "Radar-Energie", + "capture.rssi": "WLAN-Signal", + "capture.temperature": "Temperatur", + "capture.reviewed": "Durchgesehen", + "capture.kept": "Behalten", + "capture.observations": "Beobachtungen", + "capture.observations.none": "Noch nicht bestimmt", + "capture.observations.model": "Modell-Vorhersage", + "capture.tags": "Schlagwörter", "devices.title": "Geräte", "devices.empty.title": "Keine Geräte registriert", diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index fbf19db..7f56fa3 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -49,7 +49,61 @@ export const en = { "gallery.title": "Gallery", "gallery.empty.title": "No captures yet", "gallery.empty.body": - "The camera has not uploaded anything. Ingest arrives in Phase 2; until then this list stays empty.", + "The camera has not uploaded anything yet. Generate some to work with: poorbird seed --captures 500", + "gallery.empty.filtered.title": "Nothing matches these filters", + "gallery.empty.filtered.body": "Widen the date range, or clear the filters.", + "gallery.count": "{shown} of {total} loaded", + "gallery.loadingMore": "Loading more…", + "gallery.allLoaded": "That is all of them.", + "gallery.noThumb": "No preview", + // The thumbnail job has not run yet. Distinct from "cannot be decoded", + // which looks identical to a user and means something very different. + "gallery.thumbPending": "Preview not ready", + + "filters.title": "Filters", + "filters.clear": "Clear filters", + "filters.device": "Camera", + "filters.device.all": "All cameras", + "filters.from": "From", + "filters.to": "To", + "filters.kept": "Kept", + "filters.reviewed": "Reviewed", + "filters.preTrigger": "Pre-trigger only", + "filters.any": "Any", + "filters.onlyKept": "Kept only", + "filters.onlyRejected": "Rejected only", + "filters.onlyReviewed": "Reviewed only", + "filters.onlyUnreviewed": "Not reviewed only", + + "capture.title": "Capture", + "capture.close": "Close", + "capture.previous": "Previous", + "capture.next": "Next", + "capture.openFull": "Open full size", + "capture.receivedAt": "Received", + "capture.capturedAt": "Camera clock", + "capture.capturedAt.unsynced": "Not synced", + "capture.device": "Camera", + "capture.dimensions": "Size", + "capture.fileSize": "File", + "capture.trigger": "Trigger", + "capture.trigger.radar": "Radar", + "capture.trigger.manual": "Manual", + "capture.trigger.timer": "Timer", + "capture.trigger.stream_grab": "Stream grab", + "capture.preTrigger": "Pre-trigger frame", + "capture.preTrigger.hint": "Captured before the trigger fired, from the camera's ring buffer", + "capture.burst": "Frame {index} of {count}", + "capture.radarDistance": "Radar distance", + "capture.radarEnergy": "Radar energy", + "capture.rssi": "WiFi signal", + "capture.temperature": "Temperature", + "capture.reviewed": "Reviewed", + "capture.kept": "Kept", + "capture.observations": "Observations", + "capture.observations.none": "Not labelled yet", + "capture.observations.model": "Model prediction", + "capture.tags": "Tags", "devices.title": "Devices", "devices.empty.title": "No devices enrolled", diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 4ff3fa1..adadac3 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -137,3 +137,117 @@ export interface HealthResponse { export function getHealth(): Promise { return apiGet("/health"); } + +/* --- gallery ---------------------------------------------------------- */ + +export interface CaptureSummary { + id: string; + device_id: number; + /** Server time, and authoritative (SPEC C7). Always present. */ + received_at: string; + /** Null when the camera's clock was unsynced. Never render it as 1970. */ + captured_at_device: string | null; + width: number | null; + height: number | null; + bytes: number; + trigger: "radar" | "manual" | "timer" | "stream_grab"; + pre_trigger: boolean; + burst_id: string | null; + burst_index: number | null; + burst_count: number | null; + reviewed: boolean; + kept: boolean; + /** False while the thumbnail job is queued, or forever if it cannot decode. */ + has_thumb: boolean; +} + +export interface CapturePage { + items: CaptureSummary[]; + /** Null at the end. Opaque -- pass it back, do not parse it. */ + next_cursor: string | null; +} + +export interface TagOut { + id: number; + label: string; + colour: string | null; +} + +export interface TaxonOut { + id: number; + scientific_name: string; + name_de: string | null; + name_en: string | null; +} + +export interface ObservationOut { + id: number; + taxon: TaxonOut | null; + individuals: number; + age: string; + sex: string; + behaviour: string | null; + certainty: string; + notes: string | null; + /** "model" is a prediction. Never present one as a human label. */ + source: "human" | "model"; + confidence: number | null; +} + +export interface CaptureDetail extends CaptureSummary { + device_name: string; + sha256: string; + radar_state: number | null; + radar_distance_cm: number | null; + radar_energy: number | null; + battery_mv: number | null; + rssi: number | null; + temp_c: number | null; + frame_seq: number | null; + observations: ObservationOut[]; + tags: TagOut[]; +} + +export interface CaptureFilters { + device_id?: number; + received_from?: string; + received_to?: string; + kept?: boolean; + reviewed?: boolean; + pre_trigger?: boolean; + trigger?: string; +} + +export function listCaptures( + filters: CaptureFilters, + cursor: string | null, + limit = 60 +): Promise { + // URLSearchParams, not string concatenation: an ISO timestamp ends in + // "+00:00" and a raw "+" in a query string means a space, so the server + // would answer 422 for a date it could otherwise have parsed. + const params = new URLSearchParams({ limit: String(limit) }); + if (cursor !== null) params.set("cursor", cursor); + for (const [key, value] of Object.entries(filters)) { + // A tri-state filter is absent when undefined, and `false` is a real + // value -- so this cannot be a truthiness check. + if (value !== undefined) params.set(key, String(value)); + } + return apiGet(`/captures?${params.toString()}`); +} + +export function getCapture(id: string): Promise { + return apiGet(`/captures/${id}`); +} + +/* Image URLs are built here rather than sent by the server, because this + * module is already the one place that knows the API prefix. They go straight + * into , so they are paths from the site root, and the session cookie + * rides along because it is same-origin. */ +export function thumbUrl(id: string): string { + return `/api/v1/captures/${id}/thumb`; +} + +export function imageUrl(id: string): string { + return `/api/v1/captures/${id}/image`; +} diff --git a/web/src/pages/GalleryPage.tsx b/web/src/pages/GalleryPage.tsx index bb49355..8658e6e 100644 --- a/web/src/pages/GalleryPage.tsx +++ b/web/src/pages/GalleryPage.tsx @@ -1,16 +1,121 @@ +import { useInfiniteQuery } from "@tanstack/react-query"; +import { useMemo, useState } from "react"; + +import { CaptureGrid } from "../components/CaptureGrid"; +import { CaptureViewer } from "../components/CaptureViewer"; +import { GalleryFilters } from "../components/GalleryFilters"; +import type { CaptureFilters } from "../components/GalleryFilters"; import { EmptyState } from "../components/EmptyState"; import { useT } from "../i18n/I18nProvider"; +import { ApiError, listCaptures } from "../lib/api"; -/* The gallery. Phase 2 gives it something to show; until /captures exists - * there is nothing to fetch, so this is honestly empty rather than filled - * with fake rows that would hide layout problems. */ +/* The gallery. + * + * Paged by cursor rather than page number, matching the server: at 5000 + * captures a day OFFSET gets slower the further back you scroll, which is the + * direction a gallery scrolls. + * + * The filters are part of the query key, so changing one starts a fresh + * pagination rather than appending to the previous result -- a cursor from the + * old filter set describes a position in a list that no longer exists. + */ export function GalleryPage() { const t = useT(); + const [filters, setFilters] = useState({}); + const [openIndex, setOpenIndex] = useState(null); + + const query = useInfiniteQuery({ + queryKey: ["captures", filters], + queryFn: ({ pageParam }) => listCaptures(filters, pageParam), + initialPageParam: null as string | null, + getNextPageParam: (lastPage) => lastPage.next_cursor, + staleTime: 30_000, + }); + + const captures = useMemo( + () => query.data?.pages.flatMap((page) => page.items) ?? [], + [query.data] + ); + + if (query.isPending) { + return ( +
+

{t("gallery.title")}

+

{t("common.loading")}

+
+ ); + } + + if (query.isError) { + const error = query.error; + const message = + error instanceof ApiError && error.status === 0 + ? t("system.unreachable.body") + : t("common.error"); + return ( +
+

{t("gallery.title")}

+

+ {message} +

+ +
+ ); + } + + // Devices to offer in the filter come from what has actually been loaded. + // A device list endpoint is Phase 4; until then this is honest about only + // knowing the cameras it has seen captures from. + const devices = [...new Set(captures.map((capture) => capture.device_id))] + .sort((a, b) => a - b) + .map((id) => ({ id, name: `#${id}` })); + + const filtersActive = Object.values(filters).some((value) => value !== undefined); + const open = openIndex === null ? null : (captures[openIndex] ?? null); return ( -
-

{t("gallery.title")}

- +
+
+

{t("gallery.title")}

+ + {t("gallery.count", { shown: captures.length, total: captures.length })} + +
+ + + + {captures.length === 0 ? ( + + ) : ( + void query.fetchNextPage()} + onOpen={(capture) => + setOpenIndex(captures.findIndex((candidate) => candidate.id === capture.id)) + } + /> + )} + + {open !== null && openIndex !== null && ( + setOpenIndex(null)} + onPrevious={openIndex > 0 ? () => setOpenIndex(openIndex - 1) : null} + // Only as far as what is loaded. Stepping past the last loaded + // capture would show a blank frame while a page arrives, so the + // button is simply disabled there. + onNext={openIndex < captures.length - 1 ? () => setOpenIndex(openIndex + 1) : null} + /> + )}
); } diff --git a/web/src/styles/global.css b/web/src/styles/global.css index 10125f5..84cc38b 100644 --- a/web/src/styles/global.css +++ b/web/src/styles/global.css @@ -357,3 +357,241 @@ code, animation-duration: 0.01ms !important; } } + +/* --- gallery --------------------------------------------------------------- + Every colour here is a token. A literal would have to be repeated for each + of the three themes, which is the thing tokens.css exists to prevent. */ + +.gallery-header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-4); + flex-wrap: wrap; +} + +.filters { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: var(--space-3); + padding: var(--space-3) 0 var(--space-4); + border-bottom: 1px solid var(--border); + margin-bottom: var(--space-4); +} + +.field-inline { + gap: var(--space-1); +} + +.field-inline .input { + min-width: 9rem; +} + +/* The virtualiser needs a scrolling element with a bounded height, or every + row is "visible" and nothing is virtualised. */ +.grid-scroll { + overflow-y: auto; + max-height: calc(100vh - 20rem); + min-height: 24rem; + /* Keeps the scrollbar from shifting the layout as rows load. */ + scrollbar-gutter: stable; +} + +.grid-sizer { + position: relative; + width: 100%; +} + +.grid-row { + position: absolute; + top: 0; + left: 0; + width: 100%; + display: grid; +} + +.grid-footer { + min-height: 1.5rem; + padding: var(--space-3) 0; + text-align: center; + font-size: var(--text-sm); +} + +.tile { + position: relative; + display: block; + width: 100%; + height: 100%; + padding: 0; + overflow: hidden; + background: var(--surface-sunken); + border: 1px solid var(--border); + border-radius: var(--radius); + cursor: pointer; + transition: border-color var(--transition); +} + +.tile:hover { + border-color: var(--accent); +} + +.tile:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.tile-image { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} + +.tile-placeholder { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + padding: var(--space-2); + font-size: var(--text-xs); + text-align: center; +} + +.tile-badges { + position: absolute; + bottom: var(--space-1); + left: var(--space-1); + display: flex; + flex-wrap: wrap; + gap: var(--space-1); +} + +.badge { + padding: 2px var(--space-2); + background: var(--accent-subtle); + color: var(--accent); + border-radius: var(--radius-sm); + font-size: var(--text-xs); + font-weight: 550; +} + +.badge-danger { + background: var(--surface-raised); + color: var(--danger); +} + +/* --- capture viewer --- */ + +.viewer-backdrop { + position: fixed; + inset: 0; + z-index: 50; + display: flex; + align-items: center; + justify-content: center; + padding: var(--space-4); + /* color-mix keeps this a token too, rather than a hardcoded rgba(). */ + background: color-mix(in srgb, var(--bg) 82%, transparent); + backdrop-filter: blur(2px); +} + +.viewer { + display: flex; + flex-direction: column; + width: min(1200px, 100%); + max-height: 100%; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + overflow: hidden; +} + +.viewer-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-3) var(--space-4); + border-bottom: 1px solid var(--border); + flex-wrap: wrap; +} + +.viewer-actions { + display: flex; + gap: var(--space-2); +} + +.viewer-body { + display: grid; + grid-template-columns: minmax(0, 1fr) 20rem; + min-height: 0; + overflow: hidden; +} + +.viewer-image-wrap { + display: flex; + align-items: center; + justify-content: center; + min-height: 0; + padding: var(--space-3); + background: var(--surface-sunken); +} + +.viewer-image { + max-width: 100%; + max-height: 70vh; + object-fit: contain; +} + +.viewer-meta { + padding: var(--space-4); + overflow-y: auto; + border-left: 1px solid var(--border); + font-size: var(--text-sm); +} + +.detail-row { + display: flex; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-1) 0; + border-bottom: 1px solid var(--border); +} + +.detail-label { + flex: 0 0 auto; +} + +.detail-value { + text-align: right; + word-break: break-word; +} + +.detail-heading { + margin: var(--space-4) 0 var(--space-2); + font-size: var(--text-sm); + font-weight: 600; +} + +.detail-list { + margin: 0; + padding-left: var(--space-4); +} + +@media (max-width: 720px) { + .viewer-body { + grid-template-columns: minmax(0, 1fr); + overflow-y: auto; + } + + .viewer-meta { + border-left: none; + border-top: 1px solid var(--border); + } + + .grid-scroll { + max-height: calc(100vh - 26rem); + } +}