v4: weekly digests and monthly recaps go out by email, every email is written once as Markdown in the app's one catalog, and a review of the last two commits removes what they stated twice — users get a weekly digest (what happened to them, what the people and playlists they follow posted, the week's top dumps, the community) and a monthly recap (the month's top dumps and the community), both on by default, in their own style and scheme. digest-service sends what is due every quarter of an hour from digest_schedule (migration 0020), which holds each user's rolling 7- or 30-day period; existing users' first periods are spread over the coming week or month, a digest more than a period late covers the last full one, an empty one isn't sent, and an address like admin@localhost is skipped. Each digest carries a one-click unsubscribe (List-Unsubscribe and List-Unsubscribe-Post, POST /api/users/unsubscribe) and a link to the new /unsubscribe page, which asks before turning that cadence off, since mail scanners open every link; the token (lib/jwt) names the user and the cadence and never expires. The welcome email now says the digests are on. The emails' words moved out of a hand-written api/mail/strings.ts into the Lingui catalogs the interface uses: lingui extracts api/mail/ too, the catalogs moved to a top-level locales/ that both halves read, compile emits ES modules the server imports (api/mail/i18n.ts), messages take ICU plurals, and the labels the settings tab, the unsubscribe page and the emails share are one message each (their French had already drifted apart). Each template writes its email once as Markdown, which is the plain-text part, and EmailKit.render draws its blocks in the style (a lone link is a button, a list item starting with an image a thumbnail row, a numbered list a ranking, --- the footer), so no string is declared for an HTML and a text version; user text is escaped for Markdown, which the welcome body didn't do for usernames, whose _ read as emphasis. paint() set colors before a border-top shorthand that reset them, so every divider was black. The review also gave one home to what was written twice: the locale list (shared/locale.ts, read by lingui.config, the client, the server and its catalog loader), the base style and default scheme (shared/theme.ts), an email's look (lookOf, which digest-service, welcome and reset share), whether email is on (EMAIL_ENABLED, read by email-service and index.html), a setting's column and its default in the digests' SQL (SETTINGS_COLUMNS, DEFAULT_SETTINGS), the unsubscribe token (made once, not parsed back from a URL), AuthProvider's compare-and-store, ThemeProvider's twin style and scheme code (useThemeChoice), the test JWT encoder, and duplicate digest messages. The email palettes stay a flattened copy of the themes' tokens, now under a test that caught Times' secondary and link colors drifting. The Dockerfile copies api/mail and locales so the build extracts the emails' messages and the server finds its catalogs, and deno.json maps @lingui/core for the runtime image. 236 backend tests (new: digest building, sending, catch-up, scheduling and unsubscribing; the Markdown renderer; French from the catalog; palettes against themes; the stagger migration; unsubscribe tokens) and 661 frontend tests (new: the unsubscribe page) 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 22:14:46 +00:00
parent 89014639cb
commit 7960d74c55
60 changed files with 3778 additions and 534 deletions

View File

@@ -59,12 +59,30 @@ export function AuthProvider(
useEffect(() => {
if (!token) return;
const read = (path: string) =>
fetch(`${API_URL}${path}`, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
const dataOf = async (res: Response) => {
if (!res.ok) return null;
const json = await res.json();
return json?.success && json.data ? json.data : null;
};
// Only a change replaces the session, so an unchanged one keeps its
// identity and doesn't re-render the app.
const merge = (patch: Partial<Pick<Session, "user" | "settings">>) =>
setAuthResponse((prev) => {
if (!prev || prev.token !== token) return prev;
const next = { ...prev, ...patch };
if (JSON.stringify(next) === JSON.stringify(prev)) return prev;
storeSession(next);
return next;
});
const validate = async () => {
try {
const res = await fetch(`${API_URL}/api/users/me`, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
const res = await read("/api/users/me");
if (res.status === 401) {
// Only this token is dead. The session may have moved on to fresh
// tokens while we asked (a password change, here or in another tab).
@@ -73,45 +91,15 @@ export function AuthProvider(
return;
}
// The stored user dates from sign-in, and the role, avatar or email
// may have changed since, by an admin or in another browser. Only a
// change replaces it, so an unchanged session keeps its identity and
// doesn't re-render the app.
if (res.ok) {
const json = await res.json();
if (json?.success && json.data) {
const freshUser = deserializeSelfUser(json.data);
setAuthResponse((prev) => {
if (
!prev ||
JSON.stringify(prev.user) === JSON.stringify(freshUser)
) return prev;
const updated = { ...prev, user: freshUser };
storeSession(updated);
return updated;
});
}
}
// may have changed since, by an admin or in another browser.
const user = await dataOf(res);
if (user) merge({ user: deserializeSelfUser(user) });
// 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;
});
}
}
const settings: UserSettings | null = await dataOf(
await read("/api/users/me/settings"),
);
if (settings) merge({ settings });
} catch {
// Offline is not signed out: only a 401 ends the session.
}

View File

@@ -6,7 +6,12 @@
*/
import { createContext } from "react";
import type { ColorScheme, StyleName } from "../../../shared/theme.ts";
import {
BASE_STYLE,
type ColorScheme,
DEFAULT_COLOR_SCHEME,
type StyleName,
} from "../../../shared/theme.ts";
/**
* Provided by `ThemeProvider` to `useTheme`. A setter applies the choice and
@@ -23,8 +28,8 @@ export interface ThemeContextValue {
export const ThemeContext: React.Context<ThemeContextValue> = createContext<
ThemeContextValue
>({
style: "smooth",
colorScheme: "auto",
style: BASE_STYLE,
colorScheme: DEFAULT_COLOR_SCHEME,
setStyle: () => {},
setColorScheme: () => {},
});

View File

@@ -8,11 +8,13 @@
* @module
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useRef } from "react";
import { ThemeContext } from "./ThemeContext.ts";
import {
BASE_STYLE,
COLOR_SCHEMES,
type ColorScheme,
DEFAULT_COLOR_SCHEME,
STYLE_NAMES,
type StyleName,
} from "../../../shared/theme.ts";
@@ -20,120 +22,70 @@ 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";
import {
type ThemeChoiceSpec,
useThemeChoice,
} from "../../hooks/theme/useThemeChoice.ts";
/** Passed to {@link ThemeProvider} by `App`. */
export interface ThemeProviderProps {
children: React.ReactNode;
}
/** Returns the stored `key` when it is one of `allowed`, else null. */
function readChoice<T extends string>(
key: string,
allowed: readonly T[],
): T | null {
try {
const stored = localStorage.getItem(key);
return (allowed as readonly string[]).includes(stored ?? "")
? stored as T
: null;
} catch {
return null;
}
}
const STYLE: ThemeChoiceSpec<StyleName> = {
storageKey: "style",
allowed: STYLE_NAMES,
setting: "style",
fallback: DEFAULT_STYLE,
attribute: "data-style",
base: BASE_STYLE,
};
function writeChoice(key: string, value: string): void {
try {
localStorage.setItem(key, value);
} catch {
// Blocked storage only costs the choice at the next visit.
}
}
const SCHEME: ThemeChoiceSpec<ColorScheme> = {
storageKey: "color-scheme",
allowed: COLOR_SCHEMES,
setting: "colorScheme",
fallback: DEFAULT_COLOR_SCHEME,
attribute: "data-color-scheme",
base: DEFAULT_COLOR_SCHEME,
};
/**
* 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 "smooth" and "auto".
*
* 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.
* Provides {@link ThemeContext}. Each half of the theme goes through
* `useThemeChoice`, which sets it on the root element as `data-style` or
* `data-color-scheme` and mirrors it to localStorage, where an inline script
* in index.html applies it 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 {
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 [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 style = useThemeChoice(STYLE);
const scheme = useThemeChoice(SCHEME);
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 (settings.style === null && style.local) patch.style = style.local;
if (settings.colorScheme === null && scheme.local) {
patch.colorScheme = scheme.local;
}
if (Object.keys(patch).length > 0) {
updateSettings(patch).catch(() => {/* tried again next session */});
}
}, [settings, token, localStyle, localScheme, updateSettings]);
}, [settings, token, style.local, scheme.local, updateSettings]);
const style = accountStyle ?? localStyle ?? DEFAULT_STYLE;
const colorScheme = accountScheme ?? localScheme ?? "auto";
useEffect(() => {
const el = document.documentElement;
if (style === "smooth") {
el.removeAttribute("data-style");
} else {
el.setAttribute("data-style", style);
}
}, [style]);
useEffect(() => {
const el = document.documentElement;
if (colorScheme === "auto") {
el.removeAttribute("data-color-scheme");
} else {
el.setAttribute("data-color-scheme", colorScheme);
}
}, [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],
);
const value = useMemo(() => ({
style: style.value,
colorScheme: scheme.value,
setStyle: style.set,
setColorScheme: scheme.set,
}), [style.value, scheme.value, style.set, scheme.set]);
return (
<ThemeContext.Provider value={value}>