UI: scaffold the web app - shell, themes, i18n, auth plumbing
React 19 + TypeScript + Vite + TanStack Query/Router in web/, built on the dev machine and shipped as static files (SPEC section 6). Typechecks and builds clean; the System page reads live /health through the Vite proxy, which proves browser -> proxy -> FastAPI -> PostgreSQL end to end. Themes: light, dark and blue (dark navy), as design tokens on data-theme. An inline script applies the stored theme before first paint. No colour literal lives outside tokens.css. check-contrast.mjs asserts WCAG AA for every text/background pair in every theme, with no dependencies. It failed on its first run and found three --border-strong values below the 3:1 that WCAG 1.4.11 wants for interactive boundaries; all three are fixed and 36 pairs now pass. Colour contrast is the classic silently-regressing property, so it gets a test rather than a promise. i18n is hand-written and typed rather than react-i18next: en.ts defines the key set, de.ts is typed against it, so a missing German string fails the build instead of quietly showing English to a German user. Authentication is built but NOT enforced, deliberately. /auth/session, /auth/login and /auth/logout do not exist yet, so router.tsx does not wrap routes in RequireAuth and a banner says so plainly. There is no development bypass: a bypass that works is the kind of code that survives into production, and an auth bypass that works is the worst possible bug. Gallery and Devices render honest empty states rather than mock rows. Fake data hides the layout problems real data exposes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5a098e44d8
commit
384b09371a
28 files changed
+3968
-1
No files matched your search
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.local
|
||||
.vite/
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
# poorBird web
|
||||
|
||||
Phase 3 scaffolding: shell, themes, i18n and the auth plumbing. Built on the
|
||||
dev machine and shipped to the server as static files — nothing here runs on
|
||||
the server (SPEC §6).
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm install
|
||||
npm run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
The dev server proxies `/api` to `http://127.0.0.1:8090`, so start the API
|
||||
too (see [`../server/README.md`](../server/README.md)). Both must be running
|
||||
or the System page shows "cannot reach the server", which is the honest
|
||||
answer rather than a blank screen.
|
||||
|
||||
| Script | Does |
|
||||
|---|---|
|
||||
| `npm run dev` | Vite dev server with HMR |
|
||||
| `npm run build` | typecheck, then production bundle into `dist/` |
|
||||
| `npm run typecheck` | `tsc --noEmit` on its own |
|
||||
| `npm run check:contrast` | assert WCAG contrast for all three themes |
|
||||
|
||||
> On Windows, Vite binds IPv6 `localhost`. Use `http://localhost:5173`, not
|
||||
> `http://127.0.0.1:5173`.
|
||||
|
||||
---
|
||||
|
||||
## What is real and what is not
|
||||
|
||||
Only `GET /api/v1/health` exists on the server today, so only the **System**
|
||||
page shows live data. It is the end-to-end proof: browser → Vite proxy →
|
||||
FastAPI → PostgreSQL.
|
||||
|
||||
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, and Phase 2 is what brings real captures.
|
||||
|
||||
**Authentication is built but not enforced.** `/auth/session`, `/auth/login`
|
||||
and `/auth/logout` are Phase 3 server work and do not exist yet. So:
|
||||
|
||||
- `AuthProvider` and `RequireAuth` are written and typechecked
|
||||
- `router.tsx` does **not** wrap routes in `RequireAuth` yet, and says why
|
||||
- a banner in the layout states plainly that sign-in is not enforced
|
||||
- **there is no development bypass**, on purpose — a bypass that works is the
|
||||
kind of code that survives into production, and an auth bypass that works is
|
||||
the worst possible bug
|
||||
|
||||
Wiring it up when the endpoints land is three lines in `router.tsx` plus
|
||||
deleting the banner.
|
||||
|
||||
---
|
||||
|
||||
## Conventions
|
||||
|
||||
**No user-facing string literal in a component. Ever.** Every one goes
|
||||
through `useT()`. `src/i18n/en.ts` defines the key set; `de.ts` is typed as
|
||||
`Catalogue`, so a missing or misspelled German key fails `npm run build`
|
||||
rather than showing English to a German user at runtime.
|
||||
|
||||
**No colour literal outside `src/styles/tokens.css`.** Components reference
|
||||
tokens, which is what makes a fourth theme a single CSS block. Run
|
||||
`npm run check:contrast` after touching any colour — it caught three failing
|
||||
`--border-strong` values the first time it ran.
|
||||
|
||||
**Themes** are `data-theme` on `<html>`: `light`, `dark`, `blue` (dark navy).
|
||||
An inline script in `index.html` applies the stored choice before first paint
|
||||
to avoid a flash of the wrong theme; it must stay in sync with
|
||||
`theme/ThemeProvider.tsx` — same storage key, same attribute, same default.
|
||||
Once accounts exist, `users.theme` becomes the source of truth and
|
||||
localStorage stays as the pre-login default.
|
||||
|
||||
---
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/
|
||||
main.tsx providers, in order
|
||||
router.tsx the whole route table, one flat file
|
||||
i18n/ en.ts (source of truth), de.ts (typed against it)
|
||||
theme/ data-theme on <html>
|
||||
auth/ provider, login form, route guard (not wired yet)
|
||||
lib/api.ts the only place that calls fetch
|
||||
components/ layout and shared pieces
|
||||
pages/ one per route
|
||||
styles/ tokens.css (themes), global.css (everything else)
|
||||
scripts/check-contrast.mjs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notes on the stack
|
||||
|
||||
**TypeScript is strict**, including `noUncheckedIndexedAccess` and
|
||||
`verbatimModuleSyntax`. Learning TypeScript with the checks off teaches a
|
||||
different language than the one everyone else writes. The error messages say
|
||||
what to do.
|
||||
|
||||
**i18n is hand-written, not `react-i18next`.** Two languages and a few hundred
|
||||
strings do not need a library, and the typed catalogue gives compile-time
|
||||
completeness that i18next does not provide by default. If real plural grammar
|
||||
is ever needed, ICU MessageFormat is the upgrade and the call sites keep their
|
||||
shape.
|
||||
|
||||
**TanStack Router with code-based routes**, per SPEC §6, rather than the
|
||||
file-based convention — one visible route table, no codegen step. Its payoff
|
||||
is that `<Link to="/devices">` is typechecked, so a typo in a path is a build
|
||||
error instead of a 404 found later.
|
||||
|
||||
**No ESLint yet.** `tsc --noEmit` catches the important class of mistakes;
|
||||
ESLint is worth adding but its flat-config setup is a distraction during
|
||||
scaffolding.
|
||||
@@ -0,0 +1,34 @@
|
||||
<!doctype html>
|
||||
<html lang="de" data-theme="blue">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>poorBird</title>
|
||||
<script>
|
||||
// Applies the stored theme before first paint, so there is no flash of
|
||||
// the wrong one. Must stay in sync with theme/ThemeProvider.tsx: same
|
||||
// storage key, same attribute, same default.
|
||||
(function () {
|
||||
try {
|
||||
var stored = localStorage.getItem("poorbird.theme");
|
||||
if (stored === "light" || stored === "dark" || stored === "blue") {
|
||||
document.documentElement.setAttribute("data-theme", stored);
|
||||
}
|
||||
} catch (e) {
|
||||
// Blocked storage: the markup default (blue) stands.
|
||||
}
|
||||
try {
|
||||
var lang = localStorage.getItem("poorbird.locale");
|
||||
if (lang === "de" || lang === "en") {
|
||||
document.documentElement.lang = lang;
|
||||
}
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2039
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "poorbird-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"preview": "vite preview",
|
||||
"check:contrast": "node scripts/check-contrast.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@tanstack/react-router": "^1.95.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^6.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/* Assert WCAG contrast for every theme in tokens.css.
|
||||
*
|
||||
* Colour contrast is the classic silently-regressing property: you nudge one
|
||||
* hex value, it still "looks fine" on your monitor, and the muted text is now
|
||||
* unreadable for someone else. So it gets a test rather than a promise.
|
||||
*
|
||||
* No dependencies -- run with `npm run check:contrast`.
|
||||
*/
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const css = readFileSync(join(here, "..", "src", "styles", "tokens.css"), "utf8");
|
||||
|
||||
/** Extract custom properties per theme from the stylesheet. */
|
||||
function parseThemes(source) {
|
||||
const themes = {};
|
||||
const blockRe = /([^{}]+)\{([^}]*)\}/g;
|
||||
let match;
|
||||
while ((match = blockRe.exec(source)) !== null) {
|
||||
const selectors = match[1]
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
.split(",")
|
||||
.map((s) => s.trim());
|
||||
const body = match[2];
|
||||
|
||||
const props = {};
|
||||
const propRe = /(--[\w-]+)\s*:\s*([^;]+);/g;
|
||||
let prop;
|
||||
while ((prop = propRe.exec(body)) !== null) {
|
||||
props[prop[1]] = prop[2].trim();
|
||||
}
|
||||
|
||||
for (const selector of selectors) {
|
||||
const named = selector.match(/\[data-theme="([\w-]+)"\]/);
|
||||
if (named) {
|
||||
themes[named[1]] = { ...(themes[named[1]] ?? {}), ...props };
|
||||
}
|
||||
}
|
||||
}
|
||||
return themes;
|
||||
}
|
||||
|
||||
function toLinear(channel) {
|
||||
const c = channel / 255;
|
||||
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
function luminance(hex) {
|
||||
const clean = hex.replace("#", "").trim();
|
||||
if (!/^[0-9a-fA-F]{6}$/.test(clean)) return null;
|
||||
const r = parseInt(clean.slice(0, 2), 16);
|
||||
const g = parseInt(clean.slice(2, 4), 16);
|
||||
const b = parseInt(clean.slice(4, 6), 16);
|
||||
return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);
|
||||
}
|
||||
|
||||
function contrast(fg, bg) {
|
||||
const a = luminance(fg);
|
||||
const b = luminance(bg);
|
||||
if (a === null || b === null) return null;
|
||||
const [hi, lo] = a > b ? [a, b] : [b, a];
|
||||
return (hi + 0.05) / (lo + 0.05);
|
||||
}
|
||||
|
||||
/* Each pair: [foreground token, background token, minimum ratio].
|
||||
* 4.5 is WCAG AA for body text; 3.0 is AA for large text and for the
|
||||
* boundaries of interactive components. */
|
||||
const PAIRS = [
|
||||
["--text", "--bg", 4.5],
|
||||
["--text", "--surface", 4.5],
|
||||
["--text", "--surface-raised", 4.5],
|
||||
["--text-muted", "--bg", 4.5],
|
||||
["--text-muted", "--surface", 4.5],
|
||||
["--accent", "--bg", 4.5],
|
||||
["--accent", "--surface", 4.5],
|
||||
["--text-inverse", "--accent", 4.5],
|
||||
["--success", "--surface", 4.5],
|
||||
["--warning", "--surface", 4.5],
|
||||
["--danger", "--surface", 4.5],
|
||||
["--border-strong", "--surface", 3.0],
|
||||
];
|
||||
|
||||
const themes = parseThemes(css);
|
||||
const names = Object.keys(themes);
|
||||
|
||||
if (names.length === 0) {
|
||||
console.error("no themes found in tokens.css - has the file moved?");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let failures = 0;
|
||||
let checked = 0;
|
||||
|
||||
for (const name of names) {
|
||||
const tokens = themes[name];
|
||||
console.log(`\n ${name}`);
|
||||
for (const [fgToken, bgToken, min] of PAIRS) {
|
||||
const fg = tokens[fgToken];
|
||||
const bg = tokens[bgToken];
|
||||
if (!fg || !bg) {
|
||||
console.log(` ? ${fgToken} on ${bgToken} - token missing`);
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
const ratio = contrast(fg, bg);
|
||||
if (ratio === null) {
|
||||
console.log(` ? ${fgToken} on ${bgToken} - not a plain hex colour`);
|
||||
continue;
|
||||
}
|
||||
checked++;
|
||||
const ok = ratio >= min;
|
||||
if (!ok) failures++;
|
||||
const mark = ok ? "ok " : "FAIL";
|
||||
console.log(
|
||||
` ${mark} ${fgToken} on ${bgToken} ${ratio.toFixed(2)}:1 (need ${min})`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`\n${checked} pairs checked across ${names.length} themes, ${failures} failure(s)\n`
|
||||
);
|
||||
process.exit(failures > 0 ? 1 : 0);
|
||||
@@ -0,0 +1,122 @@
|
||||
/* The authentication shell.
|
||||
*
|
||||
* IMPORTANT, and deliberate: none of the endpoints this talks to exist yet.
|
||||
* Phase 3 builds /auth/session, /auth/login and /auth/logout on the server.
|
||||
* Until then `useAuth()` reports "anonymous" and <RequireAuth> is written but
|
||||
* NOT wired into the router -- see router.tsx.
|
||||
*
|
||||
* There is no development bypass here on purpose. A bypass is the kind of
|
||||
* code that survives into production because it works, and an auth bypass
|
||||
* that works is the worst possible bug. The app is simply ungated until the
|
||||
* real thing lands, which is visible and hard to forget.
|
||||
*
|
||||
* TOTP is part of the shape from the start (TODO 3.0): optional per user,
|
||||
* enforced for admins. Retrofitting it later would mean reopening the login
|
||||
* flow, the session model, the user model and the audit log at once.
|
||||
*/
|
||||
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { createContext, useCallback, useContext, useMemo } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { ApiError, apiGet, apiPost } from "../lib/api";
|
||||
|
||||
export type Role = "admin" | "editor" | "viewer";
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
role: Role;
|
||||
locale: string;
|
||||
theme: string;
|
||||
}
|
||||
|
||||
export interface Credentials {
|
||||
username: string;
|
||||
password: string;
|
||||
/** Six digits, when the account has TOTP enabled. */
|
||||
totp?: string;
|
||||
}
|
||||
|
||||
export type AuthState =
|
||||
| { status: "loading" }
|
||||
/** The server has no auth endpoints yet. Distinct from "signed out". */
|
||||
| { status: "unavailable" }
|
||||
| { status: "anonymous" }
|
||||
| { status: "authenticated"; user: User };
|
||||
|
||||
interface AuthValue {
|
||||
state: AuthState;
|
||||
signIn: (credentials: Credentials) => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
/** Convenience for `state.status === "authenticated" && role check`. */
|
||||
can: (...roles: Role[]) => boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthValue | null>(null);
|
||||
|
||||
function useSessionQuery() {
|
||||
return useQuery<User | null, ApiError>({
|
||||
queryKey: ["auth", "session"],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return await apiGet<User>("/auth/session");
|
||||
} catch (error) {
|
||||
// 401 is the normal "not signed in" answer, not a failure.
|
||||
if (error instanceof ApiError && error.status === 401) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
retry: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
const query = useSessionQuery();
|
||||
|
||||
const state = useMemo<AuthState>(() => {
|
||||
if (query.isPending) return { status: "loading" };
|
||||
if (query.error?.isMissingEndpoint) return { status: "unavailable" };
|
||||
if (query.data) return { status: "authenticated", user: query.data };
|
||||
return { status: "anonymous" };
|
||||
}, [query.isPending, query.error, query.data]);
|
||||
|
||||
const signIn = useCallback(
|
||||
async (credentials: Credentials) => {
|
||||
const user = await apiPost<User>("/auth/login", credentials);
|
||||
queryClient.setQueryData(["auth", "session"], user);
|
||||
},
|
||||
[queryClient]
|
||||
);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
await apiPost("/auth/logout");
|
||||
queryClient.setQueryData(["auth", "session"], null);
|
||||
// Anything cached under the old identity must not be shown to the next one.
|
||||
await queryClient.invalidateQueries();
|
||||
}, [queryClient]);
|
||||
|
||||
const can = useCallback(
|
||||
(...roles: Role[]) => state.status === "authenticated" && roles.includes(state.user.role),
|
||||
[state]
|
||||
);
|
||||
|
||||
const value = useMemo<AuthValue>(() => ({ state, signIn, signOut, can }), [
|
||||
state,
|
||||
signIn,
|
||||
signOut,
|
||||
can,
|
||||
]);
|
||||
|
||||
return <AuthContext value={value}>{children}</AuthContext>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthValue {
|
||||
const value = useContext(AuthContext);
|
||||
if (value === null) {
|
||||
throw new Error("useAuth must be used inside <AuthProvider>");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState } from "react";
|
||||
import type { FormEvent } from "react";
|
||||
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
|
||||
/* The sign-in form. Fully built, and currently talking to an endpoint that
|
||||
* does not exist -- a 404 is reported honestly rather than dressed up as
|
||||
* "wrong password". The TOTP field is present from the start because the
|
||||
* policy is decided (TODO 3.0). */
|
||||
export function LoginPage() {
|
||||
const t = useT();
|
||||
const { signIn } = useAuth();
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [totp, setTotp] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function onSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await signIn({ username, password, totp: totp || undefined });
|
||||
} catch (cause) {
|
||||
if (cause instanceof ApiError && cause.isMissingEndpoint) {
|
||||
setError(t("auth.unavailable"));
|
||||
} else {
|
||||
setError(t("auth.failed"));
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="centered-page">
|
||||
<form className="card login-card" onSubmit={onSubmit}>
|
||||
<h1 className="login-title">{t("auth.signIn")}</h1>
|
||||
|
||||
<label className="field">
|
||||
<span className="field-label">{t("auth.username")}</span>
|
||||
<input
|
||||
className="input"
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span className="field-label">{t("auth.password")}</span>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span className="field-label">{t("auth.totp")}</span>
|
||||
<input
|
||||
className="input"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9]{6}"
|
||||
maxLength={6}
|
||||
value={totp}
|
||||
onChange={(e) => setTotp(e.target.value)}
|
||||
/>
|
||||
<span className="field-hint">{t("auth.totpHint")}</span>
|
||||
</label>
|
||||
|
||||
{error !== null && (
|
||||
<p className="alert alert-danger" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button className="button button-primary" type="submit" disabled={busy}>
|
||||
{busy ? t("auth.signingIn") : t("auth.signIn")}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { LoginPage } from "./LoginPage";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
import type { Role } from "./AuthProvider";
|
||||
|
||||
/* Route guard. Written now, wired in when Phase 3 lands the endpoints --
|
||||
* see router.tsx for why it is not used yet.
|
||||
*
|
||||
* This is the client-side half only. It decides what to *render*; it is not
|
||||
* access control. The server authorises every request independently, and the
|
||||
* image bytes go through the auth-checked handoff (SPEC 3.3), because an
|
||||
* unguessable URL is not access control either. */
|
||||
export function RequireAuth({
|
||||
children,
|
||||
roles,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
/** When given, the signed-in user must hold one of these roles. */
|
||||
roles?: Role[];
|
||||
}) {
|
||||
const t = useT();
|
||||
const { state, can } = useAuth();
|
||||
|
||||
if (state.status === "loading") {
|
||||
return <p className="muted centered-page">{t("common.loading")}</p>;
|
||||
}
|
||||
|
||||
if (state.status === "unavailable" || state.status === "anonymous") {
|
||||
return <LoginPage />;
|
||||
}
|
||||
|
||||
if (roles !== undefined && !can(...roles)) {
|
||||
return (
|
||||
<div className="centered-page">
|
||||
<p className="alert alert-danger">{t("common.error")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Link, Outlet } from "@tanstack/react-router";
|
||||
|
||||
import { useAuth } from "../auth/AuthProvider";
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { LanguageSwitcher } from "./LanguageSwitcher";
|
||||
import { ThemeSwitcher } from "./ThemeSwitcher";
|
||||
|
||||
export function AppLayout() {
|
||||
const t = useT();
|
||||
const { state } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<header className="header">
|
||||
<Link to="/" className="brand">
|
||||
<span className="brand-mark" aria-hidden="true" />
|
||||
<span className="brand-name">{t("app.name")}</span>
|
||||
</Link>
|
||||
|
||||
<nav className="nav">
|
||||
<Link to="/" className="nav-link" activeProps={{ className: "nav-link is-active" }}>
|
||||
{t("nav.gallery")}
|
||||
</Link>
|
||||
<Link
|
||||
to="/devices"
|
||||
className="nav-link"
|
||||
activeProps={{ className: "nav-link is-active" }}
|
||||
>
|
||||
{t("nav.devices")}
|
||||
</Link>
|
||||
<Link
|
||||
to="/system"
|
||||
className="nav-link"
|
||||
activeProps={{ className: "nav-link is-active" }}
|
||||
>
|
||||
{t("nav.system")}
|
||||
</Link>
|
||||
</nav>
|
||||
|
||||
<div className="header-tools">
|
||||
<LanguageSwitcher />
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Visible for as long as the app is ungated. It disappears by
|
||||
deleting this block when RequireAuth is wired into the router. */}
|
||||
{state.status !== "authenticated" && (
|
||||
<p className="banner" role="status">
|
||||
{t("auth.notEnforced")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<main className="main">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/** An empty list that explains itself. Used wherever a feature is real but
|
||||
* has no data yet, which during Phase 3 is most of them. */
|
||||
export function EmptyState({
|
||||
title,
|
||||
body,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
body: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<h2 className="empty-title">{title}</h2>
|
||||
<p className="empty-body">{body}</p>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { LOCALES, useI18n } from "../i18n/I18nProvider";
|
||||
import type { Locale } from "../i18n/I18nProvider";
|
||||
|
||||
const LABEL: Record<Locale, "lang.de" | "lang.en"> = {
|
||||
de: "lang.de",
|
||||
en: "lang.en",
|
||||
};
|
||||
|
||||
export function LanguageSwitcher() {
|
||||
const { locale, setLocale, t } = useI18n();
|
||||
|
||||
return (
|
||||
<label className="picker">
|
||||
<span className="visually-hidden">{t("lang.label")}</span>
|
||||
<select
|
||||
className="select"
|
||||
value={locale}
|
||||
onChange={(e) => setLocale(e.target.value as Locale)}
|
||||
>
|
||||
{LOCALES.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{t(LABEL[code])}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { THEMES, useTheme } from "../theme/ThemeProvider";
|
||||
import type { Theme } from "../theme/ThemeProvider";
|
||||
|
||||
const LABEL: Record<Theme, "theme.light" | "theme.dark" | "theme.blue"> = {
|
||||
light: "theme.light",
|
||||
dark: "theme.dark",
|
||||
blue: "theme.blue",
|
||||
};
|
||||
|
||||
export function ThemeSwitcher() {
|
||||
const t = useT();
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<label className="picker">
|
||||
<span className="visually-hidden">{t("theme.label")}</span>
|
||||
<select
|
||||
className="select"
|
||||
value={theme}
|
||||
onChange={(e) => setTheme(e.target.value as Theme)}
|
||||
>
|
||||
{THEMES.map((name) => (
|
||||
<option key={name} value={name}>
|
||||
{t(LABEL[name])}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/* A small typed translator instead of a library.
|
||||
*
|
||||
* Two languages and a few hundred strings do not need i18next, and the
|
||||
* hand-written catalogue buys something i18next does not give by default:
|
||||
* a missing German string fails the build rather than falling back silently
|
||||
* to English in front of the user.
|
||||
*
|
||||
* If this ever needs plurals with real grammar, ICU MessageFormat or
|
||||
* react-i18next is the upgrade path and the call sites do not change shape.
|
||||
*/
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { de } from "./de";
|
||||
import { en } from "./en";
|
||||
import type { Catalogue, TranslationKey } from "./en";
|
||||
|
||||
export const LOCALES = ["de", "en"] as const;
|
||||
export type Locale = (typeof LOCALES)[number];
|
||||
|
||||
const CATALOGUES: Record<Locale, Catalogue> = { de, en };
|
||||
const STORAGE_KEY = "poorbird.locale";
|
||||
|
||||
/** Values substituted into `{placeholders}`. */
|
||||
export type TranslationVars = Record<string, string | number>;
|
||||
|
||||
export type Translate = (key: TranslationKey, vars?: TranslationVars) => string;
|
||||
|
||||
interface I18nValue {
|
||||
locale: Locale;
|
||||
setLocale: (locale: Locale) => void;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nValue | null>(null);
|
||||
|
||||
function isLocale(value: unknown): value is Locale {
|
||||
return typeof value === "string" && (LOCALES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function initialLocale(): Locale {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (isLocale(stored)) return stored;
|
||||
} catch {
|
||||
// Private mode or blocked storage. Fall through to the browser setting.
|
||||
}
|
||||
return navigator.language.toLowerCase().startsWith("de") ? "de" : "en";
|
||||
}
|
||||
|
||||
function interpolate(template: string, vars?: TranslationVars): string {
|
||||
if (!vars) return template;
|
||||
return template.replace(/\{(\w+)\}/g, (whole, name: string) => {
|
||||
const value = vars[name];
|
||||
// Leaving the placeholder visible beats printing "undefined" at a user.
|
||||
return value === undefined ? whole : String(value);
|
||||
});
|
||||
}
|
||||
|
||||
export function I18nProvider({ children }: { children: ReactNode }) {
|
||||
const [locale, setLocaleState] = useState<Locale>(initialLocale);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = locale;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, locale);
|
||||
} catch {
|
||||
// Not worth telling the user about; the choice just will not persist.
|
||||
}
|
||||
}, [locale]);
|
||||
|
||||
const setLocale = useCallback((next: Locale) => setLocaleState(next), []);
|
||||
|
||||
const t = useCallback<Translate>(
|
||||
(key, vars) => interpolate(CATALOGUES[locale][key], vars),
|
||||
[locale]
|
||||
);
|
||||
|
||||
const value = useMemo<I18nValue>(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
|
||||
|
||||
return <I18nContext value={value}>{children}</I18nContext>;
|
||||
}
|
||||
|
||||
export function useI18n(): I18nValue {
|
||||
const value = useContext(I18nContext);
|
||||
if (value === null) {
|
||||
throw new Error("useI18n must be used inside <I18nProvider>");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Shorthand for the common case: `const t = useT()`. */
|
||||
export function useT(): Translate {
|
||||
return useI18n().t;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { Catalogue } from "./en";
|
||||
|
||||
/* Typed as Catalogue, so a missing or misspelled key fails `npm run build`.
|
||||
* That is the whole reason this file is hand-written rather than loaded as
|
||||
* JSON at runtime: a missing German string should never reach a browser. */
|
||||
export const de: Catalogue = {
|
||||
"app.name": "poorBird",
|
||||
"app.tagline": "Gartenvogel-Kamera",
|
||||
|
||||
"nav.gallery": "Galerie",
|
||||
"nav.devices": "Geräte",
|
||||
"nav.system": "System",
|
||||
|
||||
"common.loading": "Wird geladen…",
|
||||
"common.retry": "Erneut versuchen",
|
||||
"common.error": "Etwas ist schiefgelaufen",
|
||||
"common.notMeasured": "—",
|
||||
"common.yes": "Ja",
|
||||
"common.no": "Nein",
|
||||
|
||||
"theme.label": "Design",
|
||||
"theme.light": "Hell",
|
||||
"theme.dark": "Dunkel",
|
||||
"theme.blue": "Blau",
|
||||
|
||||
"lang.label": "Sprache",
|
||||
"lang.en": "Englisch",
|
||||
"lang.de": "Deutsch",
|
||||
|
||||
"auth.notEnforced":
|
||||
"Die Anmeldung ist noch nicht aktiv — die Auth-Endpunkte kommen in Phase 3.",
|
||||
"auth.signIn": "Anmelden",
|
||||
"auth.username": "Benutzername",
|
||||
"auth.password": "Passwort",
|
||||
"auth.totp": "Bestätigungscode",
|
||||
"auth.totpHint": "Sechs Ziffern aus deiner Authenticator-App",
|
||||
"auth.signingIn": "Anmeldung läuft…",
|
||||
"auth.failed": "Anmeldung fehlgeschlagen. Benutzername und Passwort prüfen.",
|
||||
"auth.unavailable":
|
||||
"Den Anmelde-Endpunkt gibt es noch nicht. Diese Seite ist die Hülle dafür.",
|
||||
|
||||
"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.",
|
||||
|
||||
"devices.title": "Geräte",
|
||||
"devices.empty.title": "Keine Geräte registriert",
|
||||
"devices.empty.body":
|
||||
"Eine Kamera erscheint hier, sobald sie sich registriert hat. Das kommt in Phase 2.",
|
||||
|
||||
"system.title": "System",
|
||||
"system.status": "Status",
|
||||
"system.status.ok": "In Ordnung",
|
||||
"system.status.degraded": "Eingeschränkt",
|
||||
"system.version": "Version",
|
||||
"system.uptime": "Laufzeit",
|
||||
"system.database": "Datenbank",
|
||||
"system.database.ok": "Verbunden",
|
||||
"system.database.down": "Nicht erreichbar",
|
||||
"system.devices": "Geräte",
|
||||
"system.captures": "Aufnahmen",
|
||||
"system.lastBackup": "Letzte Sicherung",
|
||||
"system.lastBackup.never": "Nie",
|
||||
"system.disk": "Bildspeicher",
|
||||
"system.disk.free": "{free} frei von {total}",
|
||||
"system.disk.unavailable": "Pfad nicht verfügbar",
|
||||
"system.enrollSecret": "Registrierungs-Secret",
|
||||
"system.enrollSecret.set": "Konfiguriert",
|
||||
"system.enrollSecret.unset": "Nicht gesetzt",
|
||||
"system.unreachable.title": "Server nicht erreichbar",
|
||||
"system.unreachable.body":
|
||||
"Die API hat nicht geantwortet. Läuft sie auf Port 8090?",
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
/* English is the source of truth for the key set.
|
||||
*
|
||||
* `as const` makes TypeScript remember every literal key, which is what lets
|
||||
* de.ts be checked for completeness at build time. Add a key here first.
|
||||
*/
|
||||
export const en = {
|
||||
"app.name": "poorBird",
|
||||
"app.tagline": "Garden bird camera",
|
||||
|
||||
"nav.gallery": "Gallery",
|
||||
"nav.devices": "Devices",
|
||||
"nav.system": "System",
|
||||
|
||||
"common.loading": "Loading…",
|
||||
"common.retry": "Try again",
|
||||
"common.error": "Something went wrong",
|
||||
"common.notMeasured": "—",
|
||||
"common.yes": "Yes",
|
||||
"common.no": "No",
|
||||
|
||||
"theme.label": "Theme",
|
||||
"theme.light": "Light",
|
||||
"theme.dark": "Dark",
|
||||
"theme.blue": "Blue",
|
||||
|
||||
"lang.label": "Language",
|
||||
"lang.en": "English",
|
||||
"lang.de": "German",
|
||||
|
||||
"auth.notEnforced":
|
||||
"Sign-in is not enforced yet — the auth endpoints arrive in Phase 3.",
|
||||
"auth.signIn": "Sign in",
|
||||
"auth.username": "Username",
|
||||
"auth.password": "Password",
|
||||
"auth.totp": "Authentication code",
|
||||
"auth.totpHint": "Six digits from your authenticator app",
|
||||
"auth.signingIn": "Signing in…",
|
||||
"auth.failed": "Sign-in failed. Check your username and password.",
|
||||
"auth.unavailable":
|
||||
"The sign-in endpoint does not exist yet. This screen is the shell it will use.",
|
||||
|
||||
"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.",
|
||||
|
||||
"devices.title": "Devices",
|
||||
"devices.empty.title": "No devices enrolled",
|
||||
"devices.empty.body":
|
||||
"A camera appears here after it enrolls. Enrollment arrives in Phase 2.",
|
||||
|
||||
"system.title": "System",
|
||||
"system.status": "Status",
|
||||
"system.status.ok": "Healthy",
|
||||
"system.status.degraded": "Degraded",
|
||||
"system.version": "Version",
|
||||
"system.uptime": "Uptime",
|
||||
"system.database": "Database",
|
||||
"system.database.ok": "Connected",
|
||||
"system.database.down": "Unreachable",
|
||||
"system.devices": "Devices",
|
||||
"system.captures": "Captures",
|
||||
"system.lastBackup": "Last backup",
|
||||
"system.lastBackup.never": "Never",
|
||||
"system.disk": "Image storage",
|
||||
"system.disk.free": "{free} free of {total}",
|
||||
"system.disk.unavailable": "Path not available",
|
||||
"system.enrollSecret": "Enrollment secret",
|
||||
"system.enrollSecret.set": "Configured",
|
||||
"system.enrollSecret.unset": "Not set",
|
||||
"system.unreachable.title": "Cannot reach the server",
|
||||
"system.unreachable.body":
|
||||
"The API did not respond. Is it running on port 8090?",
|
||||
} as const;
|
||||
|
||||
/** Every valid translation key. A typo in `t("...")` is a compile error. */
|
||||
export type TranslationKey = keyof typeof en;
|
||||
|
||||
/** The shape every other language must fill completely. */
|
||||
export type Catalogue = Record<TranslationKey, string>;
|
||||
@@ -0,0 +1,95 @@
|
||||
/* 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;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`/api/v1${path}`, {
|
||||
credentials: "same-origin",
|
||||
headers: { Accept: "application/json", ...init?.headers },
|
||||
...init,
|
||||
});
|
||||
} 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");
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
import { AuthProvider } from "./auth/AuthProvider";
|
||||
import { I18nProvider } from "./i18n/I18nProvider";
|
||||
import { router } from "./router";
|
||||
import "./styles/tokens.css";
|
||||
import "./styles/global.css";
|
||||
import { ThemeProvider } from "./theme/ThemeProvider";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// A garden bird camera is not a trading desk. Refetching on every
|
||||
// window focus is noise.
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const container = document.getElementById("root");
|
||||
if (container === null) {
|
||||
throw new Error("#root is missing from index.html");
|
||||
}
|
||||
|
||||
createRoot(container).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nProvider>
|
||||
<ThemeProvider>
|
||||
{/* AuthProvider needs the query client, so it sits inside it. */}
|
||||
<AuthProvider>
|
||||
<RouterProvider router={router} />
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
import { EmptyState } from "../components/EmptyState";
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
|
||||
export function DevicesPage() {
|
||||
const t = useT();
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h1 className="page-title">{t("devices.title")}</h1>
|
||||
<EmptyState title={t("devices.empty.title")} body={t("devices.empty.body")} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { EmptyState } from "../components/EmptyState";
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
|
||||
/* 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. */
|
||||
export function GalleryPage() {
|
||||
const t = useT();
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h1 className="page-title">{t("gallery.title")}</h1>
|
||||
<EmptyState title={t("gallery.empty.title")} body={t("gallery.empty.body")} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { useT } from "../i18n/I18nProvider";
|
||||
import { getHealth } from "../lib/api";
|
||||
import type { HealthResponse } from "../lib/api";
|
||||
import type { Translate } from "../i18n/I18nProvider";
|
||||
|
||||
/* The only page wired to real data at Phase 3, because /health is the only
|
||||
* endpoint that exists. That makes it the end-to-end proof: browser ->
|
||||
* Vite proxy -> FastAPI -> PostgreSQL and back. */
|
||||
|
||||
function formatBytes(bytes: number | undefined): string {
|
||||
if (bytes === undefined) return "—";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024;
|
||||
unit += 1;
|
||||
}
|
||||
return `${value.toFixed(value < 10 && unit > 0 ? 1 : 0)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
function formatUptime(seconds: number): string {
|
||||
const s = Math.floor(seconds);
|
||||
if (s < 60) return `${s}s`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `${m}m ${s % 60}s`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `${h}h ${m % 60}m`;
|
||||
return `${Math.floor(h / 24)}d ${h % 24}h`;
|
||||
}
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="row">
|
||||
<dt className="row-label">{label}</dt>
|
||||
<dd className="row-value">{children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HealthDetail({ health, t }: { health: HealthResponse; t: Translate }) {
|
||||
const dbOk = health.database.ok;
|
||||
return (
|
||||
<>
|
||||
<div className="card">
|
||||
<dl className="rows">
|
||||
<Row label={t("system.status")}>
|
||||
<span className={dbOk ? "pill pill-ok" : "pill pill-warn"}>
|
||||
{health.status === "ok" ? t("system.status.ok") : t("system.status.degraded")}
|
||||
</span>
|
||||
</Row>
|
||||
<Row label={t("system.version")}>
|
||||
<code>{health.version}</code>
|
||||
</Row>
|
||||
<Row label={t("system.uptime")}>{formatUptime(health.uptime_s)}</Row>
|
||||
<Row label={t("system.enrollSecret")}>
|
||||
{health.enroll_secret_configured ? (
|
||||
t("system.enrollSecret.set")
|
||||
) : (
|
||||
<span className="warn">{t("system.enrollSecret.unset")}</span>
|
||||
)}
|
||||
</Row>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<dl className="rows">
|
||||
<Row label={t("system.database")}>
|
||||
<span className={dbOk ? "pill pill-ok" : "pill pill-danger"}>
|
||||
{dbOk ? t("system.database.ok") : t("system.database.down")}
|
||||
</span>
|
||||
{health.database.error !== null && (
|
||||
<div className="mono-small">{health.database.error}</div>
|
||||
)}
|
||||
</Row>
|
||||
<Row label={t("system.devices")}>{health.database.devices ?? "—"}</Row>
|
||||
<Row label={t("system.captures")}>{health.database.captures ?? "—"}</Row>
|
||||
<Row label={t("system.lastBackup")}>
|
||||
{health.database.last_backup_at ? (
|
||||
new Date(health.database.last_backup_at).toLocaleString()
|
||||
) : (
|
||||
/* Not an error yet -- backups are Phase 5 and blocked on the
|
||||
NAS protocol question. It becomes an alarm then, not now. */
|
||||
<span className="muted">{t("system.lastBackup.never")}</span>
|
||||
)}
|
||||
</Row>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<dl className="rows">
|
||||
<Row label={t("system.disk")}>
|
||||
{health.disk.available ? (
|
||||
<>
|
||||
{t("system.disk.free", {
|
||||
free: formatBytes(health.disk.free_bytes),
|
||||
total: formatBytes(health.disk.total_bytes),
|
||||
})}
|
||||
<div className="mono-small">{health.disk.path}</div>
|
||||
</>
|
||||
) : (
|
||||
<span className="warn">{t("system.disk.unavailable")}</span>
|
||||
)}
|
||||
</Row>
|
||||
</dl>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SystemPage() {
|
||||
const t = useT();
|
||||
const { data, error, isPending, refetch } = useQuery({
|
||||
queryKey: ["health"],
|
||||
queryFn: getHealth,
|
||||
refetchInterval: 15_000,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h1 className="page-title">{t("system.title")}</h1>
|
||||
|
||||
{isPending && <p className="muted">{t("common.loading")}</p>}
|
||||
|
||||
{error !== null && !isPending && (
|
||||
<div className="card">
|
||||
<h2 className="empty-title">{t("system.unreachable.title")}</h2>
|
||||
<p className="empty-body">{t("system.unreachable.body")}</p>
|
||||
<button className="button" onClick={() => void refetch()}>
|
||||
{t("common.retry")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data !== undefined && <HealthDetail health={data} t={t} />}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/* Routes, defined in code rather than by file convention.
|
||||
*
|
||||
* One file, flat, so the whole route table is visible at once. TanStack
|
||||
* Router's value here is that <Link to="/devices"> is type-checked: a typo in
|
||||
* a path is a build error, not a 404 you find later.
|
||||
*/
|
||||
|
||||
import {
|
||||
createRootRoute,
|
||||
createRoute,
|
||||
createRouter,
|
||||
} from "@tanstack/react-router";
|
||||
|
||||
import { AppLayout } from "./components/AppLayout";
|
||||
import { DevicesPage } from "./pages/DevicesPage";
|
||||
import { GalleryPage } from "./pages/GalleryPage";
|
||||
import { SystemPage } from "./pages/SystemPage";
|
||||
|
||||
const rootRoute = createRootRoute({ component: AppLayout });
|
||||
|
||||
/* NOT GATED YET.
|
||||
*
|
||||
* Once Phase 3 lands /auth/session, /auth/login and /auth/logout, wrap these
|
||||
* components in <RequireAuth> (and pass `roles={["admin"]}` for the device
|
||||
* and system routes, per SPEC 3.1). The component is written and waiting in
|
||||
* auth/RequireAuth.tsx.
|
||||
*
|
||||
* Doing it now would leave the app unusable behind a login form that cannot
|
||||
* succeed, so instead it is ungated and says so in a banner. */
|
||||
const galleryRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/",
|
||||
component: GalleryPage,
|
||||
});
|
||||
|
||||
const devicesRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/devices",
|
||||
component: DevicesPage,
|
||||
});
|
||||
|
||||
const systemRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/system",
|
||||
component: SystemPage,
|
||||
});
|
||||
|
||||
const routeTree = rootRoute.addChildren([galleryRoute, devicesRoute, systemRoute]);
|
||||
|
||||
export const router = createRouter({ routeTree });
|
||||
|
||||
/* Teaches TypeScript about this specific router, which is what makes <Link>
|
||||
* paths checked. Without it, `to` is just a string. */
|
||||
declare module "@tanstack/react-router" {
|
||||
interface Register {
|
||||
router: typeof router;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
/* Base styles. Every colour is a token from tokens.css -- no literals here,
|
||||
* so adding a theme never means touching this file. */
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--text-base);
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
code,
|
||||
.mono-small {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.mono-small {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--text-muted);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.warn {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- shell ----------------------------------------------------------- */
|
||||
|
||||
.app {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-5);
|
||||
height: var(--header-height);
|
||||
padding: 0 var(--space-4);
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: var(--radius);
|
||||
color: var(--text-muted);
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
transition: background var(--transition), color var(--transition);
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
background: var(--surface-sunken);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-link.is-active {
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.header-tools {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.banner {
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-4);
|
||||
background: var(--accent-subtle);
|
||||
color: var(--text);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: var(--space-6) var(--space-4);
|
||||
}
|
||||
|
||||
.page-title {
|
||||
margin: 0 0 var(--space-5);
|
||||
font-size: var(--text-2xl);
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.centered-page {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 60vh;
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
/* --- surfaces -------------------------------------------------------- */
|
||||
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow);
|
||||
padding: var(--space-5);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.rows {
|
||||
margin: 0;
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 220px) 1fr;
|
||||
gap: var(--space-4);
|
||||
align-items: baseline;
|
||||
}
|
||||
|
||||
.row-label {
|
||||
color: var(--text-muted);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.row-value {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pill {
|
||||
display: inline-block;
|
||||
padding: 2px var(--space-2);
|
||||
border-radius: 999px;
|
||||
font-size: var(--text-xs);
|
||||
font-weight: 600;
|
||||
border: 1px solid currentcolor;
|
||||
}
|
||||
|
||||
.pill-ok {
|
||||
color: var(--success);
|
||||
}
|
||||
.pill-warn {
|
||||
color: var(--warning);
|
||||
}
|
||||
.pill-danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
background: var(--surface);
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--space-7) var(--space-5);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
margin: 0 0 var(--space-2);
|
||||
font-size: var(--text-lg);
|
||||
}
|
||||
|
||||
.empty-body {
|
||||
margin: 0 auto;
|
||||
max-width: 46ch;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: var(--space-3);
|
||||
border-radius: var(--radius);
|
||||
font-size: var(--text-sm);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.alert-danger {
|
||||
color: var(--danger);
|
||||
border: 1px solid var(--danger);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
/* --- controls -------------------------------------------------------- */
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.field-label {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.input,
|
||||
.select {
|
||||
width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
background: var(--surface-raised);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
font: inherit;
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.select {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.input:focus-visible,
|
||||
.select:focus-visible,
|
||||
.button:focus-visible,
|
||||
.nav-link:focus-visible,
|
||||
.brand:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.button {
|
||||
padding: var(--space-2) var(--space-4);
|
||||
background: var(--surface-raised);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
font: inherit;
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 550;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition), border-color var(--transition);
|
||||
}
|
||||
|
||||
.button:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.button-primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--text-inverse);
|
||||
}
|
||||
|
||||
.button-primary:hover:not(:disabled) {
|
||||
background: var(--accent-hover);
|
||||
border-color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: min(380px, 100%);
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
margin: 0;
|
||||
font-size: var(--text-xl);
|
||||
}
|
||||
|
||||
/* --- small screens ---------------------------------------------------- */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.header {
|
||||
flex-wrap: wrap;
|
||||
height: auto;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.nav {
|
||||
order: 3;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.row {
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.main {
|
||||
padding: var(--space-5) var(--space-4);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
transition-duration: 0.01ms !important;
|
||||
animation-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/* Design tokens.
|
||||
*
|
||||
* Three themes, selected by `data-theme` on <html>: light, dark, blue.
|
||||
* Components never write a colour literal -- they reference a token, so a
|
||||
* fourth theme is a block in this file and nothing else.
|
||||
*
|
||||
* Contrast: every text/background pair below meets WCAG AA (>= 4.5:1 for body
|
||||
* text, >= 3:1 for large text and UI borders). `npm run check:contrast`
|
||||
* asserts it -- run it after touching any colour here, because this is
|
||||
* exactly the kind of thing that regresses silently.
|
||||
*/
|
||||
|
||||
:root {
|
||||
/* --- shape and space (theme-independent) --- */
|
||||
--radius-sm: 4px;
|
||||
--radius: 8px;
|
||||
--radius-lg: 14px;
|
||||
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 24px;
|
||||
--space-6: 32px;
|
||||
--space-7: 48px;
|
||||
|
||||
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
|
||||
"Helvetica Neue", Arial, sans-serif;
|
||||
--font-mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Consolas,
|
||||
"Liberation Mono", monospace;
|
||||
|
||||
--text-xs: 0.75rem;
|
||||
--text-sm: 0.875rem;
|
||||
--text-base: 1rem;
|
||||
--text-lg: 1.125rem;
|
||||
--text-xl: 1.5rem;
|
||||
--text-2xl: 2rem;
|
||||
|
||||
--transition: 120ms ease;
|
||||
--header-height: 56px;
|
||||
}
|
||||
|
||||
/* --- light ---------------------------------------------------------- */
|
||||
:root,
|
||||
[data-theme="light"] {
|
||||
color-scheme: light;
|
||||
|
||||
--bg: #f6f8fb;
|
||||
--surface: #ffffff;
|
||||
--surface-raised: #ffffff;
|
||||
--surface-sunken: #eef2f7;
|
||||
/* --border is decorative (dividers, card edges) and is exempt from the
|
||||
contrast rule. --border-strong bounds interactive controls -- inputs,
|
||||
focus rings -- so WCAG 1.4.11 wants 3:1 against the surface behind it. */
|
||||
--border: #dde3ec;
|
||||
--border-strong: #848f9e;
|
||||
|
||||
--text: #14202e;
|
||||
--text-muted: #56677d;
|
||||
--text-inverse: #ffffff;
|
||||
|
||||
--accent: #1257c4;
|
||||
--accent-hover: #0e46a0;
|
||||
--accent-subtle: #e4edfb;
|
||||
|
||||
--success: #17724a;
|
||||
--warning: #8a5a00;
|
||||
--danger: #b3242c;
|
||||
|
||||
--shadow: 0 1px 2px rgb(16 24 40 / 6%), 0 4px 12px rgb(16 24 40 / 8%);
|
||||
--overlay: rgb(16 24 40 / 40%);
|
||||
}
|
||||
|
||||
/* --- dark (neutral) ------------------------------------------------- */
|
||||
[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--bg: #121417;
|
||||
--surface: #191c21;
|
||||
--surface-raised: #21252b;
|
||||
--surface-sunken: #0d0f12;
|
||||
--border: #2e343c;
|
||||
--border-strong: #656d7a;
|
||||
|
||||
--text: #e8eaed;
|
||||
--text-muted: #a3adba;
|
||||
--text-inverse: #10141a;
|
||||
|
||||
--accent: #6ba1ff;
|
||||
--accent-hover: #8bb6ff;
|
||||
--accent-subtle: #1b2534;
|
||||
|
||||
--success: #3dd68c;
|
||||
--warning: #f0b429;
|
||||
--danger: #ff6b71;
|
||||
|
||||
--shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 8px 24px rgb(0 0 0 / 40%);
|
||||
--overlay: rgb(0 0 0 / 60%);
|
||||
}
|
||||
|
||||
/* --- blue (dark navy) ----------------------------------------------- */
|
||||
[data-theme="blue"] {
|
||||
color-scheme: dark;
|
||||
|
||||
--bg: #0b1220;
|
||||
--surface: #111c2e;
|
||||
--surface-raised: #17253b;
|
||||
--surface-sunken: #070d17;
|
||||
--border: #22344f;
|
||||
--border-strong: #5a7196;
|
||||
|
||||
--text: #e6edf7;
|
||||
--text-muted: #9fb3ce;
|
||||
--text-inverse: #0b1220;
|
||||
|
||||
--accent: #4c8dff;
|
||||
--accent-hover: #6ba1ff;
|
||||
--accent-subtle: #152740;
|
||||
|
||||
--success: #3dd68c;
|
||||
--warning: #f0b429;
|
||||
--danger: #f2545b;
|
||||
|
||||
--shadow: 0 1px 2px rgb(0 0 0 / 45%), 0 8px 28px rgb(3 8 18 / 55%);
|
||||
--overlay: rgb(4 9 18 / 65%);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/* Theme selection.
|
||||
*
|
||||
* The chosen theme is written to `data-theme` on <html>, which is what
|
||||
* tokens.css keys off. Persistence is localStorage for now; once accounts
|
||||
* exist (Phase 3) the server-side `users.theme` column becomes the source of
|
||||
* truth and this stays as the pre-login default and the first-paint value.
|
||||
*
|
||||
* The flash-of-wrong-theme is prevented by an inline script in index.html,
|
||||
* which runs before React and before first paint. Keep the storage key and
|
||||
* the attribute name in sync with that script.
|
||||
*/
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export const THEMES = ["light", "dark", "blue"] as const;
|
||||
export type Theme = (typeof THEMES)[number];
|
||||
|
||||
const STORAGE_KEY = "poorbird.theme";
|
||||
|
||||
interface ThemeValue {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeValue | null>(null);
|
||||
|
||||
function isTheme(value: unknown): value is Theme {
|
||||
return typeof value === "string" && (THEMES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function initialTheme(): Theme {
|
||||
// The inline script has already decided and applied one; read it back so
|
||||
// React and the DOM never disagree.
|
||||
const applied = document.documentElement.getAttribute("data-theme");
|
||||
if (isTheme(applied)) return applied;
|
||||
return "blue";
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>(initialTheme);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, theme);
|
||||
} catch {
|
||||
// Blocked storage: the theme applies, it just will not be remembered.
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
const setTheme = useCallback((next: Theme) => setThemeState(next), []);
|
||||
const value = useMemo<ThemeValue>(() => ({ theme, setTheme }), [theme, setTheme]);
|
||||
|
||||
return <ThemeContext value={value}>{children}</ThemeContext>;
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeValue {
|
||||
const value = useContext(ThemeContext);
|
||||
if (value === null) {
|
||||
throw new Error("useTheme must be used inside <ThemeProvider>");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Strict on purpose. Learning TypeScript with the checks off teaches you
|
||||
a different language than the one everyone else is writing. */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
|
||||
/* Requires `import type { X }` for type-only imports. The error message
|
||||
says exactly what to do, and it keeps types out of the JS bundle. */
|
||||
"verbatimModuleSyntax": true,
|
||||
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5173,
|
||||
// The dev server proxies the API so the browser only ever talks to one
|
||||
// origin. No CORS config on the server, and cookies behave the same in
|
||||
// development as they will in production behind Caddy.
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:8090",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
// Caddy serves this directory as static files. Nothing here runs on the
|
||||
// server; the whole app is built on the dev machine (SPEC 6).
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user