Skip to main content

Frontend

The frontend is a React 18 single-page app, written in TypeScript and built with Vite. Mantine provides the UI components, TanStack Router handles routing, and TanStack Query handles server state.

The full tech stack, the development commands (yarn start, yarn test, yarn build) and the code style conventions are documented in apps/frontend/README.md, which lives next to the code. Please read that first — this page only covers what it does not: debugging, and how the source tree is laid out.

✨ Code Standards​

We use ESLint and Prettier to keep our code tidy. Before you commit, run yarn lint:error to check your changes and yarn lint:error:fix to apply the automatic fixes — the ESLint config enforces Prettier through the prettier/prettier rule, so linting also flags unformatted code. The lint-frontend CI workflow runs the lint, test and build steps on every pull request that touches apps/frontend and fails on anything unclean, so nothing un-linted gets merged.

yarn build does not type-check, so run yarn typecheck as well. It runs tsc --noEmit over the app and vite.config.ts. The frontend has zero type errors and no baseline: any error fails it, and so does the typecheck-frontend CI workflow. Fix the type rather than working around it.

The repository ships a husky pre-commit hook (apps/frontend/.husky/pre-commit, which runs lint-staged), but it is currently inactive in the monorepo: yarn install runs the prepare script — husky — with the working directory set to apps/frontend, which has no .git of its own, so husky exits without registering the hook. Don't rely on it; lint before you commit.

🎨 Colours and surfaces​

The web app has one accent colour and a small set of surfaces, and two lint rules keep it that way.

Colours name a role, not a hue. A colour prop (c, color, bg, iconColor, ...) takes no colour or brand for the primary accent, gray, dark or dimmed for neutral, red for danger, orange for a warning and green for success. CSS uses var(--mantine-primary-color-*) for the primary. The theme (src/theme/cssVariables.ts) keeps the roles readable in both schemes: outline buttons in the dark scheme use shade 3 of their colour, and warning and gray text in the light scheme use darker inks that pass WCAG AA on white and on their tints. Mantine's other palette names (blue, cyan, grape, indigo, lime, pink, teal, violet, yellow) are decoration with no meaning, and stock blue is not the app's accent. ban/palette-color fails on them in props, colour maps, returned colour names, union types and --mantine-color-<hue>-* strings, and src/architecture/styles.test.ts counts them in CSS modules. A colour that really is not a role, such as the histogram's red, green and blue channels or the favourite star, is a named --app-* variable in src/theme/colors.css, the one place allowed to use the palette directly.

Surfaces come from components/common/surfaces. Only that folder imports Mantine's Card and Paper (ban/raw-surface), so border, radius and shadow are decided once:

SurfaceUse it forLook
ContentCarda block of a page (SettingsCard builds on it)border, large radius, no shadow
Panela box inside a card or dialogborder, medium radius, no shadow
FloatingCarda card over the page: the upload and What's new cards, map popups, the sign-in cardborder, large radius, extra-large shadow, a raised background in the dark scheme so it sits above the page cards
MediaCarda card with a photo that runs to its edges (MediaCard.Section)border, medium radius, no shadow

Their props leave out radius, shadow and withBorder, so a page cannot restyle one. A new kind of surface is a new component in that folder.

🧪 End-to-end tests​

apps/frontend/e2e holds a Playwright smoke suite: log in, the timeline shows photos, the lightbox opens, a favorite toggles and persists, log out. It has its own package.json, separate from the app's. The e2e workflow runs it nightly, on demand, and on pull requests labelled e2e, and uploads the Playwright report, traces and container logs when it fails.

Against the Docker e2e stack (what CI does). deploy/compose/docker-compose.e2e.yml builds the proxy, frontend and backend from your checkout, creates admin/admin and scans the eight sample photos in deploy/e2e/photos:

docker compose -f deploy/compose/docker-compose.e2e.yml up -d --build --wait
cd apps/frontend/e2e
yarn install
yarn playwright install chromium
yarn test # or `yarn test:ui` for the interactive runner
docker compose -f ../../../deploy/compose/docker-compose.e2e.yml down -v

Against a native stack (no Docker, see Native Windows Setup). Use a fresh data directory and an admin/admin account, copy deploy/e2e/photos to <DataDir>\data\e2e (it has to be inside the backend's data root), then point the suite at the Vite dev server and that folder:

$env:E2E_BASE_URL = "http://localhost:3000"
$env:E2E_SCAN_DIR = "C:\librephotos-devdata\data\e2e"
yarn test

The setup step sets the admin's scan directory and starts a scan when the account has no photos yet. A scan started this way first downloads the ML models (about 1.3 GB, once). The specs expect exactly the sample library, so run them against an account with no other photos. E2E_USERNAME and E2E_PASSWORD override the credentials.

Docs screenshots​

New in 1.5.0 The same package takes the screenshots of this site and of the release posts. yarn screens takes every shot listed in e2e/screens/manifest.ts in the light and the dark theme, at 1600 × 1000 and, for the shots marked phone, on a Pixel 7. It writes <id>-<theme>.webp and <id>-phone-<theme>.webp into apps/docs/static/img/shots/ and regenerates manifest.json there, which the <Screenshot id="..." /> component and the release check read. It logs in like the smoke suite, so the same variables apply:

cd apps/frontend/e2e
E2E_BASE_URL=http://localhost:8080 yarn screens
SHOTS=timeline,lightbox yarn screens # only these shot ids
SHOTS_DIR=/tmp/shots yarn screens # somewhere else, to look before you replace the docs files
yarn screens:unit # the helpers, without a running LibrePhotos
  • Each shot waits for its screen, for the pictures and map tiles in view, and for the page to stop changing. A new shot that looks like the file it would replace (at most 0.2 % of the pixels changed) keeps the old file, so a second run changes nothing. The run says per file whether it kept or wrote it, and how much changed.
  • Shots are WebP at quality 80, or at 70 or 60 when that is what it takes to fit the budget: a desktop shot over 200 KB or a phone shot over 120 KB even at 60 fails its test.
  • The browser clock and the Memories strip are fixed to SHOTS_DAY (default 2026-05-12), so the memories are the same in every run.
  • The e2e stack has the eight sample photos and no machine learning, so it has no faces, places or events: take timeline, lightbox, timeline-filter and category-badge there. The committed landing page shots come from a bigger sample library.

Commit only shots made inside the Playwright Linux container (mcr.microsoft.com/playwright, the version of @playwright/test in e2e/package.json): fonts and rendering differ between operating systems, so shots from your machine would change every image. The screenshots workflow does that: started by hand on a branch (default dev) with the shot ids to take, it builds and starts the e2e stack with the sidebar showing the latest release, runs yarn screens in that container, uploads the shots as an artifact, and opens a PR "docs: refresh screenshots" with the files that changed (none changed, no PR). A PR opened by a workflow starts no checks: close and reopen it to run them.

🐛 Debugging​

React Debug Tool​

React provides a debug tool, which you can download here.

WDYR​

WDYR explains to you why a component re-rendered, by logging the changed props and hooks to the browser console. It is wired up in src/wdyr.ts and only runs in development builds.

Set VITE_APP_WDYR to the literal string true — any other value (True, 1, unset) leaves it off. Where you set it depends on how you run the frontend:

  • Local dev server (yarn start) — add VITE_APP_WDYR=true to apps/frontend/.env.development.

  • Docker dev stack — add VITE_APP_WDYR=true to deploy/compose/.env, then recreate the container so it picks up the new environment:

    docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d frontend

Either way the dev server has to be restarted. WDYR needs its own JSX transform, which vite.config.ts only selects when the variable is set at startup, so flipping it mid-session has no effect.

REST API​

Our REST API is documented with Swagger and ReDoc. Once your development stack is up, both are served from the running instance — see Development Installation for the URLs.

🏙️ Structure​

Everything below is relative to apps/frontend/src.

  • routes holds the pages. Routing is file-based: the path of a file determines its URL. Routes under _protected require a logged-in user, routes under public do not, and __root.tsx is the shell they all render into. routeTree.gen.ts is generated from this folder by the TanStack Router plugin — never edit it by hand.
  • Pages should be split up into React components, which you can find in components, grouped by feature.
  • api_client is the web side of the API layer, and every request starts there. The requests themselves live in packages/api-client, which the mobile app uses too: one endpoint function per call in src/endpoints, each parsing the answer with its zod schema from src/schemas and returning the parsed type. api.ts sets up apiClient, the shared client with the web's policy around it: it attaches the access token, refreshes it on a 401, logs out when that fails, rejects a failed request with ApiError, and shows a "please report this" notification when an answer does not match its schema. Around it, one folder per domain (photos, albums, faces, …) holds the TanStack Query hooks the components actually call (useFetch…Query, use…Mutation): each wraps an endpoints.<name>(apiClient, …) call and adds the web's cache invalidation and notifications, with keys from the domain's key factory in packages/api-client/src/hooks/queryKeys.ts, which the mobile app's hooks share. Files under /media/ (thumbnails, originals, videos) get their URLs from mediaUrl and are fetched with fetchMedia, both in api_client/media/mediaUrl.ts. A component never calls apiClient or fetch itself: when it needs a request, add the endpoint and its schema (with a fixture test) to packages/api-client, then a hook to the domain's folder. Lint enforces this: no file in api_client calls apiClient directly or defines its own zod schema (#2347).
  • hooks and service contain cross-cutting hooks and helpers, such as authentication and notifications.
  • locales holds the translations, set up in i18n.ts. Translations are contributed through Weblate rather than edited directly: its librephotos-frontend component translates apps/frontend/src/locales/*/translation.json against the English file, apps/frontend/src/locales/en/translation.json. i18n.ts loads every directory under locales as its own chunk, English included, so a language Weblate adds loads without a code change. Not released yet (comes after 1.6.0) The first render waits for the user's language and English, the fallback (index.tsx awaits i18nReady), so no raw keys flash. A small script that the build adds to index.html (localePreload.ts, a Vite plugin) preloads both chunks before the app's JavaScript runs, from the lng query parameter, the saved i18nextLng or the browser's first language, so neither waits for the main bundle. Under vitest (MODE "test") i18n.ts still passes English as a bundled resource, so component tests read it synchronously; the build drops that branch. To offer it in the Profile language picker, give it an entry in components/settings/languageOptions.ts; src/i18n.test.ts fails until it is there. Not released yet (comes after 1.6.0) The UI language is detected by util/languageDetector.ts, in the order the i18next-browser-languagedetector package used before it: the lng query parameter, the i18next cookie, i18nextLng in localStorage, then in sessionStorage, the browser's languages and <html lang>. The language a user picks is saved under i18nextLng, so a saved choice survives the change.
  • Not released yet (comes after 1.6.0) Date and time fields are the browser's own inputs, NativeDateInput, NativeTimeInput (withSeconds for step=1) and NativeDateTimeInput in components/common/NativeDateInput.tsx, styled as Mantine inputs with an optional clear button. They read and write the input's wall-clock strings (yyyy-MM-dd, HH:mm:ss, yyyy-MM-ddTHH:mm:ss), which util/dateUtils.ts converts with luxon: photoTimestampWallClock and wallClockToPhotoTimestamp for an exif_timestamp, toDateTimeInputValue and fromDateTimeInputValue for an instant. No JS Date sits in between, so a picked day cannot turn into the day before (#630). The pickers follow the browser's language and calendar, not the UI language, and Firefox on desktop has no time picker. There is no Mantine dates package and no dayjs.
  • The names of things (the words the tagger finds, apps/backend/service/tags/tags.txt) are their own namespace, locales/<lang>/tags.json, loaded only by the pages that show things (hooks/useThingLabel.ts). locales/en/tags.json names every word as itself and is the source a Weblate component translates; src/i18n.tags.test.ts fails when it and tags.txt differ, so a word added to tags.txt goes into tags.json in the same change. Only the display is translated: links and search keep the English word.
  • In util you can find miscellaneous functions.
  • Not released yet (comes after 1.6.0) A package stylesheet that only a lazy feature uses is imported by the component that renders it, not by index.tsx: maplibre-gl/dist/maplibre-gl.css in components/map/ThemedMap.tsx (every map renders through it). Vite loads a lazy chunk's CSS before the chunk runs, and after @mantine/core/styles.css, so the order Mantine asks for holds and nothing renders unstyled. index.tsx keeps only the core styles and the app's colour variables.
  • Not released yet (comes after 1.6.0) Touch, pen and mouse gestures go through hooks/useViewerGestures.ts (trackViewerGestures in hooks/viewerGestures.ts). It reads pointer events on one element and reports a drag (locked to the axis it started on, with the velocity of its last 100 ms), a pinch (scale and the fingers' midpoint), the wheel (in pixels; return true to keep the page from scrolling) and a double tap. A pointer that starts inside [data-own-gesture] is left to that element (the live text, the face drawing layer, the editor's crop overlay and split divider). The element needs touch-action: none. The lightbox (lightbox/LightboxStage.tsx, useLightboxGestures.ts, lightboxView.ts) lays the previous, current and next photo side by side and moves them with --lb-swipe-x. It zooms and pans the current one with --lb-x, --lb-y and --lb-scale, written to the element while a gesture runs and kept in React state (useLightboxZoom) only when it ends, so a gesture never re-renders per frame. The photo editor's canvas (editor/canvas/useStageGestures.ts) uses the same hook.

The API client outside the browser​

Not released yet (comes after 1.6.0) packages/api-client has three entry points: @librephotos/api-client (everything, for the web and mobile apps), @librephotos/api-client/core (src/core.ts: the schemas, the transport, endpoints, the media URL helpers and ResponseParseError, without the TanStack Query hooks and the polling helpers, so it needs only zod), and the narrower schemas, transport and hooks. The desktop app imports core, through a Vite alias like the web app, and node scripts/check-shared-deps.mjs checks its zod (and React or React Query, if it ever declares them) against the package's peer ranges along with the web and mobile apps'.

ApiClientConfig.fetch takes any fetch. createNativeFetch(send) (src/transport/native.ts) builds one that sends every request through a host's own HTTP stack instead of the runtime's fetch, so CORS, the webview's cookie jar and its request limits never apply; the desktop sends everything from Rust this way:

import { createApiClient, createNativeFetch } from "@librephotos/api-client/core";

const client = createApiClient({ baseUrl, tokens, fetch: createNativeFetch(sendThroughRust) });
  • The adapter encodes the request the way fetch would (a FormData body becomes multipart with its boundary in content-type; an object body was already JSON-encoded by the client) and hands send plain data: a NativeRequest with the URL, the upper-case method, lower-case header pairs, the body's bytes (or null), the caller's AbortSignal and the body's file parts. send answers a NativeResponse (status, headers, bytes) for any HTTP status, and rejects only when there is no answer, preferably with a TypeError like fetch. The adapter turns the answer into a Response (no body for 204, 205 and 304), so the refresh interceptor, ApiError and the endpoint schemas run exactly as on the web and on mobile. Aborting the caller's signal rejects at once with an AbortError, whatever send does with its copy of the signal.
  • nativeFilePart(ref, name) is a FormData file part whose bytes the native side already has, such as a byte range of a file on disk: append it without a file name (form.append("file", part), so FormData keeps that very object). The adapter sends a random marker in its place and lists it in NativeRequest.fileParts with its ref; the native side replaces the marker with the bytes before sending. It only works with a fetch made by createNativeFetch; any other fetch would send the marker itself. The desktop's backup engine uploads every chunk this way, so no file bytes pass through JavaScript.
  • Request bodies may also be bytes: a Blob, an ArrayBuffer or a typed array goes out unchanged with the Content-Type given in headers, like a FormData body.
  • endpoints.refreshAccessToken(client, refresh) trades the refresh token for a new access token outside any request, for a platform whose media loader (a native image proxy, an image component with headers) needs a fresh token while no API request is due. The transport still refreshes on its own around requests; a refused refresh token answers 401, which signs the client out like any other unrecoverable 401.

src/__tests__/nativeFetch.test.ts drives the client through a fake native stack that only sees plain data, as a Rust command would.