Files
Hello/web/src/lib/api.ts
T
Thomas KarnerandClaude Opus 5 29c8cf6bfe Build the gallery: virtualised grid, filters and a full-size viewer
The client half. The gallery now reads real captures, pages by cursor and
loads thumbnails through the auth-checked route, so an image is only ever
served to a request that carried a valid session.

Virtualised because the gallery is the one screen that grows without bound.
5000 captures a day is past a million DOM nodes inside a year, and the browser
gives up long before the database does. react-virtual virtualises a list
rather than a grid, so the grid is a list of rows whose column count is
computed from the measured container width - which also makes it responsive
without a media-query ladder, and is why the width is observed rather than
assumed. A ResizeObserver rather than a window resize listener, because the
filter panel changes that element's width without the window changing at all.

Filters cover what the server can answer: date range, device, kept, reviewed,
pre-trigger. Taxon and tag are deliberately absent until taxa is seeded and
the observation editor exists, for the same reason they are absent from the
endpoint. The triage filters are tri-state selects rather than checkboxes,
because "kept" has three meanings - everything, only kept, only rejected - and
a checkbox expresses two of them.

Filters are part of the query key, so changing one starts fresh pagination
instead of appending. A cursor from the previous filter set describes a
position in a list that no longer exists.

The viewer is keyboard-driven on purpose. Labelling a day of captures is
look-decide-next a few hundred times, and that loop is only bearable from the
keyboard. It steps only through what is already loaded, and the button is
disabled at the edge rather than showing a blank frame while a page arrives.

Two contract details the UI has to get right, both now carried in code with
the reason attached: captured_at_device is null when the camera's clock was
unsynced and is rendered as "not synced" rather than as 1970 (API.md,
X-Captured-At: 0), and a model-sourced observation is badged as a prediction,
because that table is also the training data for any future model and a
prediction shown as a human label would poison it.

has_thumb is why the summary carries it: the grid shows a placeholder for a
capture whose thumbnail job has not run, instead of a broken image.

Conventions held: no user-facing string literal in a component - 60-odd new
keys in en.ts and de.ts, and the typed catalogue makes a missing German string
a build error rather than English in front of a German user. No colour literal
outside tokens.css either; the one place that wanted rgba() uses color-mix
against a token instead. 36 contrast pairs across three themes still pass.

Verified against the real stack with 506 real captures through the Vite proxy,
which is the path the browser takes: 9 pages of 60 following the cursor, all
506 seen, zero duplicates across pages that include real burst timestamp ties,
0.28s for the lot, and 12 of 12 sampled thumbnails arriving as valid WebP.

Not verified: how it looks. I have no browser here, so the layout, the scroll
behaviour and the virtualisation actually recycling rows are unconfirmed by
eye. Typecheck, build and the data path are green; the visual pass is yours.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 19:36:47 +02:00

254 lines
7.8 KiB
TypeScript

/* The one place that talks to the server.
*
* Same-origin by design: in development Vite proxies /api to port 8090, in
* production Caddy serves this bundle and the API from the same hostname.
* That means session cookies behave identically in both, and there is no CORS
* configuration anywhere.
*/
export class ApiError extends Error {
readonly status: number;
readonly body: unknown;
constructor(status: number, message: string, body: unknown) {
super(message);
this.name = "ApiError";
this.status = status;
this.body = body;
}
/** True when the endpoint is simply not built yet (Phase 2 / Phase 3). */
get isMissingEndpoint(): boolean {
return this.status === 404;
}
}
/* CSRF, the browser half.
*
* The server sets `poorbird_csrf` as a readable cookie alongside the HttpOnly
* session cookie, and requires this header to match the token on the session
* row for every mutating request. Reading a cookie is exactly what an attacker
* on another origin cannot do, which is what makes echoing it meaningful.
*
* Deliberately read fresh on each call rather than cached: signing out and back
* in issues a new token, and a stale one in a module variable would produce a
* 403 that looks like a server bug. */
const CSRF_COOKIE = "poorbird_csrf";
/** Methods the server requires a CSRF token for. Must match UNSAFE_METHODS. */
const UNSAFE = new Set(["POST", "PUT", "PATCH", "DELETE"]);
function csrfToken(): string | null {
// document.cookie is a flat "a=1; b=2" string; there is no read API for one
// cookie. Split rather than regex so a token containing no special
// characters cannot be mangled by an over-clever pattern.
for (const part of document.cookie.split("; ")) {
const eq = part.indexOf("=");
if (eq > 0 && part.slice(0, eq) === CSRF_COOKIE) {
return decodeURIComponent(part.slice(eq + 1));
}
}
return null;
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const method = (init?.method ?? "GET").toUpperCase();
const csrf = UNSAFE.has(method) ? csrfToken() : null;
let response: Response;
try {
response = await fetch(`/api/v1${path}`, {
// `...init` FIRST, then the values that must win. It used to come last,
// which meant a caller passing any headers at all replaced this whole
// object rather than merging into it -- so apiPost, which always sets
// Content-Type, was silently dropping Accept. Harmless then. Not
// harmless now: it would have dropped the CSRF header on exactly the
// mutating requests that require one, and every POST would answer 403.
...init,
credentials: "same-origin",
headers: {
Accept: "application/json",
// Omitted when there is no cookie, which is the case for the very
// first request of all: logging in. The server exempts it for the
// same reason -- there is no session to protect yet.
...(csrf === null ? {} : { "X-CSRF-Token": csrf }),
...init?.headers,
},
});
} catch (cause) {
// fetch only rejects on a network-level failure: server down, DNS, CORS.
throw new ApiError(0, `Cannot reach the server: ${String(cause)}`, null);
}
const text = await response.text();
let body: unknown = null;
if (text.length > 0) {
try {
body = JSON.parse(text);
} catch {
body = text;
}
}
if (!response.ok) {
throw new ApiError(response.status, `${response.status} ${response.statusText}`, body);
}
return body as T;
}
export function apiGet<T>(path: string): Promise<T> {
return request<T>(path);
}
export function apiPost<T>(path: string, payload?: unknown): Promise<T> {
return request<T>(path, {
method: "POST",
headers: payload === undefined ? {} : { "Content-Type": "application/json" },
body: payload === undefined ? undefined : JSON.stringify(payload),
});
}
/* --- response types ---------------------------------------------------
* These mirror the server. Keep them in step with the FastAPI handlers;
* generating them from /openapi.json is a worthwhile upgrade once there are
* more than a handful. */
export interface HealthResponse {
status: "ok" | "degraded";
version: string;
uptime_s: number;
database: {
ok: boolean;
error: string | null;
devices?: number;
captures?: number;
last_backup_at?: string | null;
};
disk: {
available: boolean;
path: string;
total_bytes?: number;
free_bytes?: number;
used_pct?: number | null;
};
enroll_secret_configured: boolean;
}
export function getHealth(): Promise<HealthResponse> {
return apiGet<HealthResponse>("/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<CapturePage> {
// 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<CapturePage>(`/captures?${params.toString()}`);
}
export function getCapture(id: string): Promise<CaptureDetail> {
return apiGet<CaptureDetail>(`/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 <img src>, 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`;
}