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.

Settings page​

Not released yet (comes after 1.7.0) The user's settings (components/settings/Settings.tsx) are five areas, each a SettingsArea. An area shows what an ordinary person changes. Everything else goes into its advanced part, which is closed at first and not rendered until it opens.

  • A new option goes into the advanced part unless most people would look for it. Its label says in plain words what it does, and one sentence says what changes for the photos.
  • Deep links: give the card a SettingsSection with an id from sectionIds.ts and list the id in the area's sections. useAdvancedPart opens the part when the address points at one of them. Ids are never renamed, people have saved links to them.
  • Search: add the card to components/spotlight/settingsActions.ts, with the same section.
  • "Different from the standard": add the field to UserSettingDefaultsSerializer (GET /api/user-setting-defaults/), to UserSettingDefaults in the API client and to changedSettings.ts. The server's model defaults are the only list of standards, so the line cannot disagree with them.

🧪 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.

The suite runs as an admin who already answered the one-time dialogs, so none of them covers the page under test: the e2e stack's entrypoint marks the thank-you dialog seen and the error reporting question answered before it scans, and the setup step does the same through the API on any other backend (on a server without the ML models, answering the question there starts their download). Every click and fill gives up after 15 seconds, so a selector that no longer matches fails at once with its locator instead of after the setup's 15-minute budget.

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.
  • Not released yet (comes after 1.7.0) Every shot gets the same Storage card: openShot in screens.spec.ts answers /api/storagestats/ with STORAGE (120 GB of 500 GB used), so no shot shows the disk of the machine that took it. Shots taken before 1.8.0 can still show the real disk; take them again to change that.
  • Not released yet (comes after 1.7.0) search-results and account-menu need the Windows or Mac program, not the e2e stack: account-menu waits for Quit LibrePhotos, which only the programs show, and search-results needs search by what is in a photo, which needs the models. Run the program, or python librephotos_standalone.py run in apps/backend, with a library of free sample photos and a user with a password, and point E2E_BASE_URL, E2E_USERNAME and E2E_PASSWORD at it.

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. New in 1.7.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. New in 1.7.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.
  • New in 1.7.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.
  • New in 1.7.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.
  • New in 1.7.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.

Token refresh and the end of a session​

Not released yet (comes after 1.7.0) The shared transport (packages/api-client/src/transport/client.ts) refreshes a token for the session that sent the request, and only for it. The web, the mobile app and the desktop app all use it, each with its own token supplier (cookies, expo-secure-store, the desktop's session with its Rust mirror and keychain).

  • A request remembers the refresh token stored when it was sent, and its 401 is refreshed only while that token is still the stored one. When nothing is stored any more (a logout), the session has ended: no refresh starts, and the 401 stands. When another session's refresh token is stored (a sign-out followed by a sign-in), the request is neither refreshed nor retried, and it signs nobody out: it rejects with an ApiError 401.
  • Refreshes are single-flight per refresh token: requests of one session share one refresh, and a request of another session never waits on it or gets its answer.
  • A refresh stores its new access token, and retries the requests waiting for it, only if the stored refresh token is still the one it sent. A supplier whose storage is asynchronous provides setAccessTokenFor(refresh, token), which checks and writes as one step (the mobile tokenStorage runs every read and write of the tokens one at a time, so a sign-in or logout cannot land between the check and the write). After a logout (nothing stored) the requests fail as signed out; after a sign-in as someone else they fail without touching that session.
  • A 400 or 401 from the refresh endpoint ends the session (clearTokens and onAuthError, or the platform's onUnauthorized). Anything else keeps the tokens: a network error, a 5xx, the 429 throttle, an answer without a token, and a 403, which the backend never sends and so comes from a proxy or a firewall in front of it. The request rejects with a retryable error: the network error itself, or an ApiError with the refresh's status (a 5xx or 429; any other status is reported as 503). Once the refresh has failed without a break, measured on a monotonic clock, for longer than the refresh token had left at its first failure, the session ends too; one failure never ends it. This rule is in practice web-only: on mobile performance.now() starts again at every launch and stands still while the phone sleeps, so a server that is never reachable leaves the app signed in, with its offline mirror, until a refresh is answered with a 400 or 401.
  • A request refreshes at most once: a 401 after a proactive refresh (the access token was about to expire) reuses that refresh's answer.
  • Not released yet (comes after 1.7.0) A 401 for an access token that is no longer the stored one is retried with the stored token instead of starting a refresh (storedSince in client.ts). Two requests sent with one expired token used to refresh it twice when the second 401 came after the first refresh had finished, which spends the refresh throttle (60 a minute). After reading the stored access token it checks that the stored refresh token is still the request's session; when another session's tokens were stored in between, the request is not retried and ends as superseded (sessionEnded). Up to 1.7.0 every such 401 refreshed again.
  • Not released yet (comes after 1.7.0) onUnauthorized(endpoint, response, session) gets the refresh token the refused request was sent with (null when there was none). The web ends a session once (expireSession in api_client/session.ts): it remembers the refresh token of the session it ended, and later 401s of requests sent with that token, or with none, change nothing. A request of a session signed in later, in this tab or another, ends that session as usual. Up to 1.7.0 the tab kept one "ending" flag until the page load; when "Leave site?" kept the page (files uploading, an unsaved edit), a later session that ran out never went to the login page.
  • On the web, logging out clears the cookies, waits up to 10 seconds for this tab's refreshes to settle (endpoints.logout waits for refreshSettled(), which covers the error forwarder's client too), and only then tells the server, whose answer clears the HttpOnly jwt cookie. A refresh that has not settled after those 10 seconds is cancelled first (cancelRefreshes() aborts its fetch, and the refresh settles at once even when a fetch ignores the abort): a cancelled refresh stores nothing and ends no session, and the requests waiting on it reject with a retryable error. So no refresh answer of this tab can set the jwt cookie after the logout answer cleared it. A refresh answer that lands later in another tab is not stored, so that tab ends its own session and its logout clears the jwt cookie again.
  • On the web, "signed in" means a refresh cookie is there (hasLiveSession in api_client/authCookies.ts), so an access cookie alone never sends the login page back into the app. Whether the refresh token is still valid is left to the server, not to the computer's clock, so a stale refresh cookie shows the app once before the first request ends the session and loads /login?session=expired.

A tab open across an upgrade, and saved UI state​

Not released yet (comes after 1.7.0)
  • A code file of the running build that the server no longer has (vite:preloadError, or a failed import() that reportBrowserError sees) reloads the page once a minute at most (service/newBuildReload.ts). While that reload is under way, errors are not reported. The hold now lasts the same minute: when "Leave site?" keeps the page (files uploading, an unsaved edit), errors are reported again after it, and the next missing file reloads again. Up to 1.7.0 the hold lasted until the page went, so such a tab never reported an error again.
  • The error reporter loads its Sentry client with the first error (loadClient in service/errorReporting/reportBrowserError.ts). A failed load is not kept: the next error loads it again. Up to 1.7.0 one failed load (offline for a moment) dropped every later report of the page.
  • readStored in util/storage.ts falls back to a value under its legacy key without moving it; the first writeStored of the key moves it, since it writes the new key and removes the legacy one. Up to 1.7.0 the read moved it, and two tabs of a new build could write the old value over an edit the other tab had saved a moment before, because a tab reads its own copy of localStorage, which another tab's writes reach later.

The API client outside the browser​

New in 1.7.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'. Not released yet (comes after 1.7.0) endpoints uses the timer helper of src/polling.ts (the logout's bounded wait), so that module imports nothing from React Query: invalidateAfter takes any object with an invalidateQueries method. The desktop workflow's npm run typecheck fails when something under core reaches @tanstack/react-query.

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.