v4: every page and API URL follows one of two rules, written down in API.md — pages are a hierarchy where @name is a user and any other root word a category or an app page, tabs and views are plain segments and a default view is the bare path; API resources are /api/<plural>/<key>, a user's key being an id or @name, the caller's things under /api/me, media a sub-resource, lookups by another key a query filter. ~ is gone: the feed is /, /hot, /new, /journal, /follow and /music/hot, a profile /@bob with its overview and the tabs dumps, upvoted, playlists (her own only), follow (users, and /follow/playlists), invitees and manage (role and name, for user:manage), which replace the separate UserDumps, UserUpvoted and UserPlaylists pages; /settings holds the account (now with the username) and /manage the category manager, both linked from the user menu and one's profile. Dumps and playlists live under their owner, /@bob/dumps/<slug> and /@bob/playlists/<slug>, named by slug alone: migration 0021 re-slugs them to the bare slugify(title), unique per owner and kind (the oldest keeps it, clashes get -2), renames the categories whose slug v4 reserves (hot, follow, settings…), and rewrites this site's v3 links in dump notes, comments, chat, and playlist and profile descriptions. A slug changes only when edited, through the edit forms' new link field, which proposes slugify(title) as the title changes; a username changes from /settings or, for user:manage, from /@name/manage. Every slug or name left behind stays an alias of its item or user for good (dump_slug_aliases, playlist_slug_aliases, user_aliases), so old links redirect without chaining and nobody else can take one; slugs change 3 times a day per item, names once in 30 days, moderators exempt. An alias, or a name in another case, answers the item with its current path: the pages put it in their URL (useCanonicalPath, without fetching again), and the OG middleware answers a 301. shared/paths.ts builds and parses every page path, for the client's links, the emails' (digest-service lost its own builders and its id fallbacks, and links /follow and /settings) and the server's matchers (OG tags, self previews, backlinks, self-url); shared/slug.ts holds slugify and the format categories share. Dumps and playlists carry ownerUsername and a required slug, and notifications join their users' current names and their items' paths each time they are sent or read, so renames reach them and a deleted item's has no link. The API was renamed per the plan's table: POST /api/users and /api/sessions, /api/password-resets, /api/me (with settings, password, avatar, media-token, playlists?contains=, follow, feed?from=, notifications), /api/users/:key/{dumps,upvoted,playlists,follow/users,follow/playlists,invitees,avatar} and by path /api/users/:key/{dumps,playlists}/:slug, /api/dumps?url= and ?category=, /api/dumps/:id/{file,thumbnail,metadata}, /api/playlists/:id/cover, /api/remote/{preview,image,bandcamp,youtube} (one router), and /api/unsubscribe, the v3 POST /api/users/unsubscribe staying for the digests already sent. A stored default feed tab "followed" reads as "follow" once. dumps.slug and playlists.slug stay nullable, since SQLite can't add NOT NULL without rebuilding tables others reference; every writer sets them and unique (user_id, slug) indexes hold them. 254 backend tests (new: migration 0021 on a v3 fixture, slug aliases, swaps and rate limits, username renames, aliases and limits, reads by path and their privacy, the OG 301s, both unsubscribe paths, v4-shaped digest links with no ids, notification joins, shared paths and slugs) and 668 frontend tests (new: the profile's tabs and follow views, Settings, Manage, the link field, canonical URLs on the dump, playlist and profile pages, bare default feed paths) pass, and tsc, eslint, deno check, deno lint, deno fmt and doc:lint are clean; the migration was also run on a copy of the development database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-06 16:08:59 +00:00
parent fd0d81fe66
commit 4468438ba7
228 changed files with 7320 additions and 5193 deletions

View File

@@ -1,237 +1,60 @@
/**
* Everything a profile page shows comes through this hook. It loads the user
* with the first page of their dumps, upvotes and playlists, and keeps them
* live.
* The user a profile page is about comes through this hook, which loads them
* by the name in the URL and keeps them live. Each tab of the profile loads
* its own lists, by the user's id.
*
* @module
*/
import { useCallback, useEffect, useState } from "react";
import { useEffect, useState } from "react";
import { API_URL } from "../../config/api.ts";
import type { Dump } from "../../../shared/dump.ts";
import type { Playlist } from "../../../shared/playlist.ts";
import type { PublicUser } from "../../../shared/user.ts";
import type { Wire } from "../../../shared/api.ts";
import { friendlyFetchError } from "../../utils/shared/api.ts";
import {
deserializeDump,
deserializePlaylist,
hydrateDump,
hydratePlaylist,
} from "../../utils/shared/deserialize.ts";
import { fetchPublicUser } from "../../utils/shared/fetchPublicUser.ts";
import type { LoadState } from "../../utils/shared/loadState.ts";
import {
type PagedList,
pageUrl,
readFirstPage,
restoredList,
} from "../../utils/feed/pagedList.ts";
import { useAuth } from "../auth/useAuth.ts";
import { useWS } from "../ws/useWS.ts";
import { useFeedCache } from "../feed/useFeedCache.ts";
import { useScrollRestore, useScrollSave } from "../feed/useScrollSave.ts";
import { usePositionAwareSync } from "../feed/usePositionAwareSync.ts";
import { useDumpListSync } from "../dump/useDumpListSync.ts";
import { useUpvotedList } from "../dump/useUpvotedList.ts";
import { usePlaylistListSync } from "../playlist/usePlaylistListSync.ts";
/**
* Loaded by {@link useProfile} for `UserPublicProfile`. Each list holds its
* first page only, and has its own page for the rest.
*/
export interface ProfileData {
user: PublicUser;
dumps: PagedList<Dump>;
votes: PagedList<Dump>;
playlists: PagedList<Playlist>;
}
import { type FetchState, useFetchState } from "../shared/useFetchState.ts";
/** Returned by {@link useProfile} to `UserPublicProfile`. */
export interface UseProfileResult {
state: LoadState<ProfileData>;
state: FetchState<PublicUser>;
/** It is false while the profile loads. */
isOwnProfile: boolean;
/** It shows the header's edits, which the server echoes to other browsers. */
setUser: (fn: (user: PublicUser) => PublicUser) => void;
/**
* It shows the playlist `NewPlaylistButton` made, which the socket echoes
* later.
*/
setPlaylists: (fn: (items: Playlist[]) => Playlist[]) => void;
/**
* It comes from `useUpvotedList`, and goes to the upvoted list's
* `DumpCardList`.
*/
upvotedCardClassName: (dump: Dump) => string | undefined;
}
type ListKey = "dumps" | "votes" | "playlists";
/** Returns `s` with `fn` applied to the items of its list `key`. */
function updateList<K extends ListKey>(
s: LoadState<ProfileData>,
key: K,
fn: (items: ProfileData[K]["items"]) => ProfileData[K]["items"],
): LoadState<ProfileData> {
if (s.status !== "loaded") return s;
return { ...s, [key]: { ...s[key], items: fn(s[key].items) } };
}
/**
* Returns the profile of `username`, from `GET /api/users/:username`, with the
* first pages of `…/dumps`, `…/votes` and `…/playlists`, fetched signed in so
* that users see their own private items. A list the server refuses shows
* empty; the page fails only with the user. The socket's events keep the lists
* live, and `useUpvotedList` the upvoted one. The lists and the scroll
* position are saved as the page is left, and going back restores them,
* refetching only the user.
* Returns the user named `username`, from `GET /api/users/@:username`, which
* answers a former name or another case too. The profile then puts the
* current name in its URL, and that path, naming the user on screen, fetches
* nothing; another user's does. The socket's `user_updated` keeps them live.
*/
export function useProfile(username: string | undefined): UseProfileResult {
const { user: me, authFetch } = useAuth();
const { lastDumpEvent, lastPlaylistEvent, lastUserEvent } = useWS();
const { user: me } = useAuth();
const { lastUserEvent } = useWS();
const dumpsCache = useFeedCache<Dump>(
`feed:profile-dumps:${username ?? ""}`,
hydrateDump,
// The name last fetched, which the URL may leave for the current one.
const [target, setTarget] = useState(username);
const { state, setData } = useFetchState(
target,
(signal) => fetchPublicUser(target!, signal),
);
const votesCache = useFeedCache<Dump>(
`feed:profile-votes:${username ?? ""}`,
hydrateDump,
);
const playlistsCache = useFeedCache<Playlist>(
`feed:profile-playlists:${username ?? ""}`,
hydratePlaylist,
);
const [state, setState] = useState<LoadState<ProfileData>>({
status: "loading",
});
const [prevUsername, setPrevUsername] = useState(username);
if (prevUsername !== username) {
setPrevUsername(username);
setState({ status: "loading" });
const user = state.status === "loaded" ? state.data : null;
if (
target !== username &&
user?.username.toLowerCase() !== username?.toLowerCase()
) {
setTarget(username);
}
const profileUserId = state.status === "loaded" ? state.user.id : null;
const isOwnProfile = !!me && me.id === profileUserId;
const setUser = useCallback((fn: (user: PublicUser) => PublicUser) => {
setState((s) => s.status === "loaded" ? { ...s, user: fn(s.user) } : s);
}, []);
const setDumps = useCallback((fn: (items: Dump[]) => Dump[]) => {
setState((s) => updateList(s, "dumps", fn));
}, []);
const setVotes = useCallback((fn: (items: Dump[]) => Dump[]) => {
setState((s) => updateList(s, "votes", fn));
}, []);
const setPlaylists = useCallback((fn: (items: Playlist[]) => Playlist[]) => {
setState((s) => updateList(s, "playlists", fn));
}, []);
const dumpItems = state.status === "loaded" ? state.dumps.items : [];
usePositionAwareSync(
dumpItems,
setDumps,
lastDumpEvent,
(d) => !d.isPrivate && d.userId === profileUserId,
);
useDumpListSync(setDumps, { isOwner: isOwnProfile });
const upvoted = useUpvotedList({
profileUserId,
setItems: setVotes,
source: dumpItems,
});
const voteItems = state.status === "loaded" ? state.votes.items : [];
usePositionAwareSync(
voteItems,
setVotes,
lastDumpEvent,
(d) => !d.isPrivate && !upvoted.isWithdrawn(d.id),
);
useDumpListSync(setVotes);
const playlistItems = state.status === "loaded" ? state.playlists.items : [];
const lastPlaylistItem = lastPlaylistEvent?.type === "updated"
? (lastPlaylistEvent.playlist ?? null)
: null;
usePositionAwareSync(
playlistItems,
setPlaylists,
lastPlaylistItem,
(p) => p.isPublic && p.userId === profileUserId,
);
usePlaylistListSync(setPlaylists, {
isOwner: isOwnProfile,
ownerId: profileUserId ?? undefined,
});
useEffect(() => {
if (!lastUserEvent) return;
// Mirrors a socket event into state, which can only happen in an effect.
// eslint-disable-next-line react-hooks/set-state-in-effect
setUser((u) => u.id === lastUserEvent.user.id ? lastUserEvent.user : u);
}, [lastUserEvent, setUser]);
const cachedDumps = dumpsCache.cached;
const cachedVotes = votesCache.cached;
const cachedPlaylists = playlistsCache.cached;
useEffect(() => {
if (!username) return;
const controller = new AbortController();
const { signal } = controller;
const firstPageOf = <T>(list: string, deserialize: (w: Wire<T>) => T) =>
authFetch(pageUrl(`${API_URL}/api/users/${username}/${list}`, 1), {
signal,
}).then((res) => readFirstPage(res, deserialize));
// Back on the page, the lists come from the cache and only the user is
// fetched again.
const cached = cachedDumps && cachedVotes && cachedPlaylists;
Promise.all([
fetchPublicUser(username, signal),
cached
? restoredList(cachedDumps)
: firstPageOf("dumps", deserializeDump),
cached
? restoredList(cachedVotes)
: firstPageOf("votes", deserializeDump),
cached
? restoredList(cachedPlaylists)
: firstPageOf("playlists", deserializePlaylist),
])
.then(([user, dumps, votes, playlists]) =>
setState({ status: "loaded", user, dumps, votes, playlists })
)
.catch((err) => {
if (signal.aborted) return;
setState({ status: "error", error: friendlyFetchError(err) });
});
return () => controller.abort();
}, [username, cachedDumps, cachedVotes, cachedPlaylists, authFetch]);
const saveDumps = dumpsCache.saveState;
const saveVotes = votesCache.saveState;
const savePlaylists = playlistsCache.saveState;
useScrollSave(
state.status === "loaded",
useCallback((y) => {
if (state.status !== "loaded") return;
const { dumps, votes, playlists } = state;
saveDumps(dumps, y);
saveVotes(votes, y);
savePlaylists(playlists, y);
}, [state, saveDumps, saveVotes, savePlaylists]),
);
useScrollRestore(cachedDumps?.scrollY, state.status === "loaded");
setData((u) => u.id === lastUserEvent.user.id ? lastUserEvent.user : u);
}, [lastUserEvent, setData]);
return {
state,
isOwnProfile,
setUser,
setPlaylists,
upvotedCardClassName: upvoted.cardClassName,
isOwnProfile: !!me && me.id === user?.id,
setUser: setData,
};
}