v4: settings are stored on the server, starting with the style, the color scheme and the digest switches — every setting lived in the browser's localStorage, so it didn't follow an account to another browser and the server couldn't read it, which the digests need (whether to send each, and in which style). user_settings (migration 0019) holds one row per user who changed anything, the defaults otherwise, and GET/PATCH /api/users/me/settings read and change it (settings-service, model/settings, validators/settings, shared/settings). AuthProvider reads the settings into the session alongside the user, on mount and on focus, so a change made elsewhere arrives; useSettings changes them at once and puts them back if the server refuses. ThemeProvider now sits inside AuthProvider: a signed-in user's choice comes from their settings and is mirrored to localStorage for index.html's first-paint script, a visitor's stays in the browser, and an account with no choice yet takes the one this browser had, once. Until anyone picks a style, the instance's GERBEUR_DEFAULT_STYLE applies, written into index.html's default-style tag along with email-enabled (src/config/instance.ts), and a browser no longer stores the default as if it had been chosen, so changing the instance's style reaches everyone who never picked one. The settings tab gets an Email section with the weekly digest and monthly recap switches, disabled with a note when the server has no SMTP. The style and scheme names moved to shared/theme.ts in the previous commit; the default feed tab and sounds stay in the browser for now. 223 backend tests (new: settings defaults, patches, isolation, refusals and cascade; index.html's new tags) and 658 frontend tests (new: useSettings, the account's theme winning and a browser's carried over, settings read into the session, the digest switches) pass, and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-04 21:20:57 +00:00
parent f20ca83f0c
commit 89014639cb
38 changed files with 923 additions and 128 deletions

View File

@@ -10,6 +10,7 @@ import { type ReactNode, useEffect, useState } from "react";
import { AuthContext, type AuthContextValue } from "./AuthContext.ts";
import { deserializeSelfUser } from "../../utils/shared/deserialize.ts";
import type { UserSettings } from "../../../shared/settings.ts";
import { API_URL } from "../../config/api.ts";
import {
AUTH_STORAGE_KEY,
@@ -27,8 +28,9 @@ export interface AuthProviderProps {
/**
* Provides {@link AuthContext}. The session starts as the stored one and
* follows it when another tab changes it. The server checks it on mount and
* whenever the tab regains focus: a 401 ends it, and a user changed on the
* server replaces the stored one. A session from before media tokens gets one.
* whenever the tab regains focus: a 401 ends it, and a user or settings
* changed on the server replace the stored ones. A session from before media
* tokens gets one.
*/
export function AuthProvider(
{ children }: AuthProviderProps,
@@ -89,6 +91,27 @@ export function AuthProvider(
});
}
}
// The settings follow the account, so another browser may have
// changed them. A failure leaves the ones the session has.
const settingsRes = await fetch(`${API_URL}/api/users/me/settings`, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
if (settingsRes.ok) {
const json = await settingsRes.json();
if (json?.success && json.data) {
const settings = json.data as UserSettings;
setAuthResponse((prev) => {
if (
!prev || prev.token !== token ||
JSON.stringify(prev.settings) === JSON.stringify(settings)
) return prev;
const updated = { ...prev, settings };
storeSession(updated);
return updated;
});
}
}
} catch {
// Offline is not signed out: only a 401 ends the session.
}

View File

@@ -9,8 +9,8 @@ import { createContext } from "react";
import type { ColorScheme, StyleName } from "../../../shared/theme.ts";
/**
* Provided by `ThemeProvider` to `useTheme`. A setter applies and stores the
* choice for this browser.
* Provided by `ThemeProvider` to `useTheme`. A setter applies the choice and
* stores it in this browser, and in the account's settings when signed in.
*/
export interface ThemeContextValue {
style: StyleName;

View File

@@ -1,12 +1,14 @@
/**
* Lets each browser pick the site's style and color scheme. It holds the
* choice, stores it in localStorage and applies it to the document. `App`
* mounts it outermost.
* Lets each user pick the site's style and color scheme, and applies the
* choice to the document. A signed-in user's choice is one of their settings,
* so it follows them across browsers; a visitor's stays in this browser. Until
* either picks a style, the instance's default applies. `App` mounts it inside
* `AuthProvider`, whose session holds the settings.
*
* @module
*/
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ThemeContext } from "./ThemeContext.ts";
import {
COLOR_SCHEMES,
@@ -14,49 +16,90 @@ import {
STYLE_NAMES,
type StyleName,
} from "../../../shared/theme.ts";
import type { UpdateSettingsRequest } from "../../../shared/settings.ts";
import { DEFAULT_STYLE } from "../../config/instance.ts";
import { useSettings } from "../../hooks/auth/useSettings.ts";
import { useAuth } from "../../hooks/auth/useAuth.ts";
/** Passed to {@link ThemeProvider} by `App`. */
export interface ThemeProviderProps {
children: React.ReactNode;
}
/** Returns the stored `key` when it is one of `allowed`, else `fallback`. */
/** Returns the stored `key` when it is one of `allowed`, else null. */
function readChoice<T extends string>(
key: string,
allowed: readonly T[],
fallback: T,
): T {
): T | null {
try {
const stored = localStorage.getItem(key);
return (allowed as readonly string[]).includes(stored ?? "")
? stored as T
: fallback;
: null;
} catch {
return fallback;
return null;
}
}
function writeChoice(key: string, value: string): void {
try {
localStorage.setItem(key, value);
} catch {
// Blocked storage only costs the choice at the next visit.
}
}
/**
* Provides {@link ThemeContext}. It sets the choices on the root element as
* Provides {@link ThemeContext}. It sets the theme on the root element as
* `data-style` and `data-color-scheme`, which the stylesheets key on, and
* leaves them out for the defaults, "smooth" and "auto".
* leaves them out for "smooth" and "auto".
*
* An inline script in index.html sets the same attributes from the same
* localStorage keys before the first paint, so the page doesn't flash the
* default theme. The two must agree.
* This browser's localStorage keeps the last choice made or read from the
* account, which an inline script in index.html applies before the first
* paint, so the page doesn't flash another theme. The two must agree. When an
* account has no choice yet and this browser has one, it is saved to the
* account, once per session.
*/
export function ThemeProvider(
{ children }: ThemeProviderProps,
): React.JSX.Element {
// A value from an older version, or edited by hand, falls back to the
// default ("smooth" was once stored as "default").
const [style, setStyleState] = useState<StyleName>(() =>
readChoice("style", STYLE_NAMES, "smooth")
const { settings, updateSettings } = useSettings();
const { token } = useAuth();
// An unknown stored value, such as "default", which "smooth" was once
// stored as, reads as no choice.
const [localStyle, setLocalStyle] = useState<StyleName | null>(() =>
readChoice("style", STYLE_NAMES)
);
const [colorScheme, setColorSchemeState] = useState<ColorScheme>(() =>
readChoice("color-scheme", COLOR_SCHEMES, "auto")
const [localScheme, setLocalScheme] = useState<ColorScheme | null>(() =>
readChoice("color-scheme", COLOR_SCHEMES)
);
const accountStyle = settings?.style ?? null;
const accountScheme = settings?.colorScheme ?? null;
useEffect(() => {
if (accountStyle) writeChoice("style", accountStyle);
}, [accountStyle]);
useEffect(() => {
if (accountScheme) writeChoice("color-scheme", accountScheme);
}, [accountScheme]);
const carriedOver = useRef<string | null>(null);
useEffect(() => {
if (!settings || !token || carriedOver.current === token) return;
carriedOver.current = token;
const patch: UpdateSettingsRequest = {};
if (settings.style === null && localStyle) patch.style = localStyle;
if (settings.colorScheme === null && localScheme) {
patch.colorScheme = localScheme;
}
if (Object.keys(patch).length > 0) {
updateSettings(patch).catch(() => {/* tried again next session */});
}
}, [settings, token, localStyle, localScheme, updateSettings]);
const style = accountStyle ?? localStyle ?? DEFAULT_STYLE;
const colorScheme = accountScheme ?? localScheme ?? "auto";
useEffect(() => {
const el = document.documentElement;
if (style === "smooth") {
@@ -64,7 +107,6 @@ export function ThemeProvider(
} else {
el.setAttribute("data-style", style);
}
localStorage.setItem("style", style);
}, [style]);
useEffect(() => {
@@ -74,15 +116,24 @@ export function ThemeProvider(
} else {
el.setAttribute("data-color-scheme", colorScheme);
}
localStorage.setItem("color-scheme", colorScheme);
}, [colorScheme]);
const value = useMemo(() => ({
style,
colorScheme,
setStyle: setStyleState,
setColorScheme: setColorSchemeState,
}), [style, colorScheme]);
const signedIn = settings !== null;
const setStyle = useCallback((next: StyleName) => {
setLocalStyle(next);
writeChoice("style", next);
if (signedIn) updateSettings({ style: next }).catch(() => {});
}, [signedIn, updateSettings]);
const setColorScheme = useCallback((next: ColorScheme) => {
setLocalScheme(next);
writeChoice("color-scheme", next);
if (signedIn) updateSettings({ colorScheme: next }).catch(() => {});
}, [signedIn, updateSettings]);
const value = useMemo(
() => ({ style, colorScheme, setStyle, setColorScheme }),
[style, colorScheme, setStyle, setColorScheme],
);
return (
<ThemeContext.Provider value={value}>