v3: fix the frontend's findings, and the backend pieces they needed — each by a rule the code now keeps everywhere. Votes and likes go through one useOptimisticToggles in WSProvider: clicks on one item before any ack share one baseline, which a failure or the timeout restores (a second click used to cancel the first one's rollback), only the last ack's count is applied, a votes_update or comment_likes_update waits while this tab has toggles in flight, and a welcome reconciles them against the server's sets (a vote cast offline left its count one too high). lastLikeEvent, which nothing read, is gone. Follows are refetched when the new follows_changed message, sent to the follower's sockets on every follow write, says another tab changed them; a failed load keeps the Follow buttons disabled and is retried 10 s later instead of leaving them disabled for good (success: false) or enabled over empty sets (network error); follow and unfollow resolve to whether they worked, and the button says when they didn't. CategoriesProvider follows the same rule, so a network error no longer turns every category URL into a 404. Every list is kept by one rule: useDumpListSync and usePlaylistListSync never add an item, and usePositionAwareSync remembers the place of any item that leaves a list, whatever took it out, and puts it back when its next event shows it again; with dump_created now setting lastDumpEvent, a dump going private and back returns to its place on another user's profile, which never happened before, and an updated playlist missing from a list is no longer prepended. useFeedCache keys every cache by viewer (the profile pages restored the owner's private dumps to whoever went back) and reads it again when its key changes (another profile in the same page showed the previous one's list). Every response of a list's first page or next pages goes through expectOk (Index, UserPlaylists, useUserDumpFeed and Notifications read body.data unchecked).
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 55s
Build and Deploy Static Documentation Site / build-and-push (push) Successful in 22s

Smaller fixes: the redirects from / and /<slug> keep the navigation state, so the index hides the dump DumpEdit just deleted; Index's mainFetchDone ref, which blocked nothing, is gone; DumpEdit refuses someone else's dump up front, as the API does; the Dump page takes a handed-over dump once and clears it from the history entry, so a reload fetches; a newly upvoted dump is fetched with the viewer's token; the notifications page sends read-all once per notification; the profile's followed and invitees tabs finish loading when left mid-fetch; UserListPopover no longer closes when its own list scrolls; the vote and like counts open their lists for visitors too (a disabled button swallowed the click; they are aria-disabled now); the removal of a playlist's dump forgets it (an edit brought it back), a failed removal puts it back where it was, an undo waits for the removal in flight, and a refused undo says so; PlaylistCreateForm tells whether the dump made it into the new playlist; the cover preview's object URL is revoked; the muted icon has its cross; the bell no longer stays rung after two notifications within 700 ms; a stale invite check can't overwrite a newer one; a stored theme or color scheme is checked; the default feed tab is one store every reader follows, across tabs; the file fields enforce the size they state, derived from DUMP_MAX_FILE_SIZE_BYTES; formatBytes, friendlyFetchError and ImagePicker are translated (Intl names the units), and ImagePicker ignores keys while uploading; visited dumps and playlists keep a week of visits and are parsed once; a chime is claimed under a Web Lock, so two tabs can't both play it; a date in the future reads as "now". Dead code goes: PageShell's centerSlot, overLimit, the exports of isSafeHex and hueFromString, the comment tree's token prop and ChatContext's isChatOpen and closeChat. The French catalogue has the 11 new messages. 214 backend and 632 frontend tests pass; tsc, deno lint, ESLint and doc:lint are clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-29 20:08:00 +00:00
parent a36a4cac6b
commit 80f3292c8f
84 changed files with 2451 additions and 1964 deletions

View File

@@ -5,6 +5,7 @@
* @module
*/
import { t } from "@lingui/core/macro";
import type { APIResponse } from "../../../shared/api.ts";
/**
@@ -17,19 +18,20 @@ export function parseAPIResponse<T>(raw: unknown): APIResponse<T> {
if (raw !== null && typeof raw === "object" && "success" in raw) {
return raw as APIResponse<T>;
}
throw new Error("Unexpected response format");
throw new Error(t`Unexpected response format`);
}
/**
* Returns the message to show for `err`, an error caught around a request. A
* `TypeError` means the request never reached the server (no network, CORS),
* and gets a message saying so. The messages are not translated.
* and gets a message saying so. The server's own messages come through as
* they are.
*/
export function friendlyFetchError(err: unknown): string {
if (err instanceof TypeError) {
return "Could not connect to the server. Check your connection and try again.";
return t`Could not connect to the server. Check your connection and try again.`;
}
return err instanceof Error ? err.message : "An unexpected error occurred.";
return err instanceof Error ? err.message : t`An unexpected error occurred.`;
}
/**

View File

@@ -15,11 +15,3 @@ export function charCountClass(len: number, max: number): string {
if (len >= max * 0.85) return " text-editor-count--warn";
return "";
}
/**
* Checks whether `value` is longer than `max`, which the server would refuse.
* Only the tests call it.
*/
export function overLimit(value: string, max: number): boolean {
return value.length > max;
}

View File

@@ -5,14 +5,26 @@
* @module
*/
import { i18n } from "@lingui/core";
/**
* Returns `bytes` as a size in B, KB or MB, where a KB is 1024 bytes. The units
* are not translated.
* Returns `bytes` as a size in bytes, kilobytes or megabytes, where a
* kilobyte is 1024 bytes, in the app's language ("1.5 kB", "1,5 ko").
* `Intl` names the units, so they follow the language without a catalog.
*/
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
const [value, unit] = bytes < 1024
? [bytes, "byte"]
: bytes < 1024 * 1024
? [bytes / 1024, "kilobyte"]
: [bytes / (1024 * 1024), "megabyte"];
return new Intl.NumberFormat(i18n.locale, {
style: "unit",
unit,
// English's short form of a byte is "byte", even for 512.
unitDisplay: unit === "byte" ? "narrow" : "short",
maximumFractionDigits: 1,
}).format(value);
}
/**

View File

@@ -10,12 +10,13 @@ import { i18n } from "@lingui/core";
/**
* Returns how long ago `date` was, as "3 minutes ago", in the current locale.
* It is computed at render, so the text only moves on when the caller
* re-renders. A month counts 30 days and a year 365.
* re-renders. A month counts 30 days and a year 365. Every date shown is of
* something that happened, so one in the future, which only a clock ahead of
* this one can give, reads as "now".
*/
export function relativeTime(date: Date): string {
const rtf = new Intl.RelativeTimeFormat(i18n.locale, { numeric: "auto" });
const diff = date.getTime() - Date.now();
const abs = Math.abs(diff) / 1000;
const abs = Math.max(0, Date.now() - date.getTime()) / 1000;
if (abs < 60) return rtf.format(-Math.round(abs), "second");
if (abs < 3600) return rtf.format(-Math.round(abs / 60), "minute");

View File

@@ -75,11 +75,8 @@ function unlock() {
globalThis.addEventListener("pointerdown", unlock);
globalThis.addEventListener("keydown", unlock);
/**
* Claims `eventId` for this tab, and returns whether no other tab had. Two tabs
* checking at the same instant can both win.
*/
function claim(eventId: string): boolean {
/** Checks `CLAIM_KEY` and sets it to `eventId`, in one step or not at all. */
function checkAndSet(eventId: string): boolean {
try {
if (localStorage.getItem(CLAIM_KEY) === eventId) return false;
localStorage.setItem(CLAIM_KEY, eventId);
@@ -89,6 +86,17 @@ function claim(eventId: string): boolean {
return true;
}
/**
* Claims `eventId` for this tab, and resolves to whether no other tab had. The
* check and the write run under a lock shared by the site's tabs, so two tabs
* can't both win; a browser without Web Locks goes without it.
*/
function claim(eventId: string): Promise<boolean> {
const locks = globalThis.navigator?.locks;
if (!locks) return Promise.resolve(checkAndSet(eventId));
return locks.request(CLAIM_KEY, () => checkAndSet(eventId));
}
/**
* Plays one note of `freq` Hz on `ac`, from `start` for `duration` seconds,
* peaking at gain `peak`.
@@ -141,8 +149,9 @@ export function playChime(kind: ChimeKind, eventId: string): void {
if (now - lastChatAt < CHAT_THROTTLE) return;
lastChatAt = now;
}
if (!claim(`${kind}:${eventId}`)) return;
render(kind);
void claim(`${kind}:${eventId}`).then((won) => {
if (won) render(kind);
});
}
/**

View File

@@ -12,7 +12,7 @@
* property is substituted verbatim wherever it is used, unparsed. So the form
* is checked here before it reaches a style.
*/
export function isSafeHex(value: string | undefined): value is string {
function isSafeHex(value: string | undefined): value is string {
return !!value && /^#[0-9a-f]{6}$/.test(value);
}
@@ -33,7 +33,7 @@ function hashString(seed: string): number {
* Returns a colour of a hue drawn from `seed`, so that the same site always
* gets the same tint.
*/
export function hueFromString(seed: string): string {
function hueFromString(seed: string): string {
return `hsl(${hashString(seed) % 360} 55% 55%)`;
}

View File

@@ -10,32 +10,65 @@ const PLAYLIST_KEY = "visited_playlists";
/** The age past which an item shows no unread dot, visited or not. */
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
function loadSet(key: string): Set<string> {
try {
const raw = localStorage.getItem(key);
return raw ? new Set(JSON.parse(raw) as string[]) : new Set();
} catch {
return new Set();
}
}
// Each key's visits, id to epoch ms, with the stored string they were parsed
// from: reading the string is cheap, and it is parsed again only when it
// changed (another tab, or cleared storage).
const cache = new Map<
string,
{ raw: string | null; visits: Map<string, number> }
>();
function saveSet(key: string, set: Set<string>): void {
function load(key: string): Map<string, number> {
let raw: string | null;
try {
localStorage.setItem(key, JSON.stringify([...set]));
} catch { /* With storage full or blocked, the visit is forgotten. */ }
raw = localStorage.getItem(key);
} catch {
// Blocked storage: whatever this page recorded.
return cache.get(key)?.visits ?? new Map();
}
const cached = cache.get(key);
if (cached && cached.raw === raw) return cached.visits;
let visits = new Map<string, number>();
try {
const parsed = JSON.parse(raw ?? "{}") as Record<string, number> | string[];
// A list from before visits had times counts as visited now.
visits = Array.isArray(parsed)
? new Map(parsed.map((id) => [id, Date.now()]))
: new Map(Object.entries(parsed));
} catch {
// Unreadable: nothing visited.
}
cache.set(key, { raw, visits });
return visits;
}
/**
* Checks whether dump `id` was opened in this browser. It parses the whole
* stored list on every call.
* Records `id` as visited under `key`, and drops the visits older than 7 days:
* an item was at most that old when visited, so past then it shows no dot
* anyway, and the list stays small.
*/
function record(key: string, id: string): void {
const visits = load(key);
const now = Date.now();
visits.set(id, now);
for (const [visitedId, at] of visits) {
if (now - at > MAX_AGE_MS) visits.delete(visitedId);
}
const raw = JSON.stringify(Object.fromEntries(visits));
cache.set(key, { raw, visits });
try {
localStorage.setItem(key, raw);
} catch { /* With storage full or blocked, the visit lasts until reload. */ }
}
/** Checks whether dump `id` was opened in this browser. */
export function isDumpVisited(id: string): boolean {
return loadSet(DUMP_KEY).has(id);
return load(DUMP_KEY).has(id);
}
/** Checks whether playlist `id` was opened in this browser. */
export function isPlaylistVisited(id: string): boolean {
return loadSet(PLAYLIST_KEY).has(id);
return load(PLAYLIST_KEY).has(id);
}
/**
@@ -43,16 +76,12 @@ export function isPlaylistVisited(id: string): boolean {
* keeps its dot until it renders again.
*/
export function markDumpVisited(id: string): void {
const set = loadSet(DUMP_KEY);
set.add(id);
saveSet(DUMP_KEY, set);
record(DUMP_KEY, id);
}
/** Records playlist `id` as opened, as {@link markDumpVisited} does a dump. */
export function markPlaylistVisited(id: string): void {
const set = loadSet(PLAYLIST_KEY);
set.add(id);
saveSet(PLAYLIST_KEY, set);
record(PLAYLIST_KEY, id);
}
/**