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,139 +1,103 @@
/**
* Renders a user's profile page, which is also where the signed-in user edits
* their own profile and settings.
* their own profile.
*
* @module
*/
import { useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import { useLocation, useNavigate, useParams } from "react-router";
import { Trans } from "@lingui/react/macro";
import { API_URL } from "../config/api.ts";
import type { Invitee, PublicUser } from "../../shared/user.ts";
import type { Invitee } from "../../shared/user.ts";
import type { Wire } from "../../shared/api.ts";
import {
deserializeInvitee,
deserializePlaylist,
deserializePublicUser,
} from "../utils/shared/deserialize.ts";
FOLLOW_VIEWS,
type FollowView,
PROFILE_TABS,
type ProfileTab,
userPath,
} from "../../shared/paths.ts";
import { deserializeInvitee } from "../utils/shared/deserialize.ts";
import { dataOr } from "../utils/shared/api.ts";
import { can } from "../utils/auth/permissions.ts";
import {
type PagedList,
pageUrl,
readFirstPage,
readPage,
} from "../utils/feed/pagedList.ts";
import { useLoadMore } from "../hooks/feed/usePagedList.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { useFetchState } from "../hooks/shared/useFetchState.ts";
import { useTabParam } from "../hooks/shared/useTabParam.ts";
import { useCanonicalPath } from "../hooks/shared/useCanonicalPath.ts";
import { useProfile } from "../hooks/profile/useProfile.ts";
import { PageShell } from "../components/layout/PageShell.tsx";
import { PageError } from "../components/layout/PageError.tsx";
import { TabBar } from "../components/shared/TabBar.tsx";
import { ProfileHeader } from "../components/profile/ProfileHeader.tsx";
import { ProfileDescription } from "../components/profile/ProfileDescription.tsx";
import { ProfileOverviewTab } from "../components/profile/ProfileOverviewTab.tsx";
import { ProfileDumpsTab } from "../components/profile/ProfileDumpsTab.tsx";
import { ProfilePlaylistsTab } from "../components/profile/ProfilePlaylistsTab.tsx";
import {
type ProfileFollowed,
ProfileFollowedTab,
} from "../components/profile/ProfileFollowedTab.tsx";
import { ProfileFollowTab } from "../components/profile/ProfileFollowTab.tsx";
import { ProfileInviteesTab } from "../components/profile/ProfileInviteesTab.tsx";
import { ProfileSettingsTab } from "../components/profile/ProfileSettingsTab.tsx";
import { ProfileManageTab } from "../components/profile/ProfileManageTab.tsx";
import { NotFound } from "./NotFound.tsx";
/** The overview, the bare `/@name`, which no path segment names. */
const OVERVIEW = "overview";
type Tab = ProfileTab | typeof OVERVIEW;
const TABS: readonly Tab[] = [OVERVIEW, ...PROFILE_TABS];
/**
* The profile's tabs, the `:profileTab` of `/users/:username/~/:profileTab`.
* "dumps" is the default, at `/users/:username`.
*/
const PROFILE_TABS = [
"dumps",
"playlists",
"followed",
"invitees",
"settings",
"manage",
] as const;
type ProfileTab = (typeof PROFILE_TABS)[number];
/**
* Renders `/users/:username` and `/users/:username/~/:profileTab`, for anyone.
* `useProfile` loads the user with their dumps, upvotes and playlists; the
* "followed" and "invitees" tabs load theirs when first opened, and keep it
* while other tabs show. Each tab is a component of `components/profile/`. On
* their own profile, users edit their avatar, description and email, create
* invites, and get a "settings" tab. The "manage" tab shows another user's
* role to those who hold `user:manage`, and one's own categories to those who
* hold `category:manage`.
* Renders `/@:username` and its tabs, `/@:username/:tab`, and the follow
* tab's view `/@:username/follow/playlists`, for anyone. `useProfile` loads
* the user, by a former name or another case too, and the URL then takes the
* current one; each tab loads its own lists, by the user's id, when shown.
* On their own profile, users edit their avatar, description and email, and
* create invites. The "manage" tab, another user's role and name, is for those
* who hold `user:manage`. A tab or view the profile hasn't is `NotFound`.
*/
export function UserPublicProfile(): React.JSX.Element {
const { username } = useParams();
const { handle = "" } = useParams();
const username = handle.slice(1);
const { pathname } = useLocation();
const navigate = useNavigate();
const { user: me, logout } = useAuth();
const { state, isOwnProfile, setUser, setPlaylists, upvotedCardClassName } =
useProfile(username);
const { state, isOwnProfile, setUser } = useProfile(username);
const user = state.status === "loaded" ? state.data : null;
useDocumentTitle(
state.status === "loaded"
? state.user.username
: state.status === "error"
? null
: undefined,
user ? user.username : state.status === "error" ? null : undefined,
);
// The base is the path's own first segment, however it spells the name.
const base = `/${pathname.split("/")[1]}`;
const [tab, setTab] = useTabParam<Tab>(base, TABS, OVERVIEW);
useCanonicalPath(
user && `${userPath(user.username)}${pathname.slice(base.length)}`,
);
// Only the follow tab has a view, one segment further.
const extra = pathname.slice(base.length).split("/").filter(Boolean).slice(1);
const view: FollowView | null = extra.length === 0
? "users"
: tab === "follow" && extra.length === 1 && extra[0] !== FOLLOW_VIEWS[0] &&
(FOLLOW_VIEWS as readonly string[]).includes(extra[0])
? extra[0] as FollowView
: null;
const canManageUsers = can(me, "user:manage");
const canManageCategories = can(me, "category:manage");
// "manage" holds tools for another user on their profile, and site-wide
// tools on one's own.
const showManageTab = isOwnProfile ? canManageCategories : canManageUsers;
const availableTabs: ProfileTab[] = PROFILE_TABS.filter((t) => {
if (t === "settings") return isOwnProfile;
if (t === "manage") return showManageTab;
return true;
});
// A tab not available here, as while the profile loads, shows "dumps".
const [tab, setTab] = useTabParam<ProfileTab>(availableTabs, "dumps");
const showManageTab = !isOwnProfile && canManageUsers;
const loaded = state.status === "loaded";
const followedUsersUrl = `${API_URL}/api/users/${username}/followed-users`;
const followed = useFetchState<ProfileFollowed>(
username,
(signal) =>
Promise.all([
fetch(pageUrl(followedUsersUrl, 1), { signal })
.then((res) => readFirstPage(res, deserializePublicUser)),
fetch(
pageUrl(`${API_URL}/api/users/${username}/followed-playlists`, 1),
{ signal },
).then((res) => readFirstPage(res, deserializePlaylist)),
]).then(([users, playlists]) => ({ users, playlists })),
{ enabled: loaded && tab === "followed" },
);
const invitees = useFetchState<Invitee[]>(
username,
user?.id,
(signal) =>
fetch(`${API_URL}/api/users/${username}/invitees`, { signal })
fetch(`${API_URL}/api/users/${user!.id}/invitees`, { signal })
.then((res) => dataOr<Wire<Invitee>[]>(res, []))
.then((entries) => entries.map(deserializeInvitee)),
{ enabled: loaded && tab === "invitees" },
{ enabled: tab === "invitees" },
);
const setFollowed = followed.setData;
const loadMoreFollowedUsers = useLoadMore(
followed.state.status === "loaded" ? followed.state.data.users : null,
useCallback(
(fn: (users: PagedList<PublicUser>) => PagedList<PublicUser>) =>
setFollowed((d) => ({ ...d, users: fn(d.users) })),
[setFollowed],
),
(page) =>
fetch(pageUrl(followedUsersUrl, page))
.then((res) => readPage(res, deserializePublicUser)),
);
if (!tab || !view || (tab === "manage" && user && !showManageTab)) {
return <NotFound />;
}
if (state.status === "loading") {
return (
@@ -169,32 +133,31 @@ export function UserPublicProfile(): React.JSX.Element {
);
}
const { user, dumps, votes, playlists } = state;
const profileUser = state.data;
return (
<PageShell>
<ProfileHeader
user={user}
user={profileUser}
isOwnProfile={isOwnProfile}
onUserChange={(u) => setUser(() => u)}
/>
<ProfileDescription
description={user.description}
description={profileUser.description}
isOwnProfile={isOwnProfile}
onSaved={(description) => setUser((u) => ({ ...u, description }))}
/>
<TabBar
tabs={[
{ key: "dumps", label: <Trans>Dumps</Trans> },
{ key: "playlists", label: <Trans>Playlists</Trans> },
{ key: "followed", label: <Trans>Followed</Trans> },
{ key: "invitees", label: <Trans>Invitees</Trans> },
...(isOwnProfile
? [{ key: "settings" as const, label: <Trans>Settings</Trans> }]
: []),
{ key: OVERVIEW as Tab, label: <Trans>Overview</Trans> },
{ key: "dumps" as Tab, label: <Trans>Dumps</Trans> },
{ key: "upvoted" as Tab, label: <Trans>Upvoted</Trans> },
{ key: "playlists" as Tab, label: <Trans>Playlists</Trans> },
{ key: "follow" as Tab, label: <Trans>Followed</Trans> },
{ key: "invitees" as Tab, label: <Trans>Invitees</Trans> },
...(showManageTab
? [{ key: "manage" as const, label: <Trans>Manage</Trans> }]
? [{ key: "manage" as Tab, label: <Trans>Manage</Trans> }]
: []),
]}
activeTab={tab}
@@ -203,41 +166,28 @@ export function UserPublicProfile(): React.JSX.Element {
innerClassName="profile-tabs"
/>
{tab === "dumps" && (
{tab === OVERVIEW && (
<ProfileOverviewTab user={profileUser} isOwnProfile={isOwnProfile} />
)}
{(tab === "dumps" || tab === "upvoted") && (
<ProfileDumpsTab
username={user.username}
dumps={dumps}
votes={votes}
key={tab}
user={profileUser}
list={tab}
isOwnProfile={isOwnProfile}
upvotedCardClassName={upvotedCardClassName}
/>
)}
{tab === "playlists" && (
<ProfilePlaylistsTab
username={user.username}
playlists={playlists}
isOwnProfile={isOwnProfile}
setPlaylists={setPlaylists}
/>
)}
{tab === "followed" && (
<ProfileFollowedTab
username={user.username}
state={followed.state}
onLoadMoreUsers={loadMoreFollowedUsers}
/>
<ProfilePlaylistsTab user={profileUser} isOwnProfile={isOwnProfile} />
)}
{tab === "follow" && <ProfileFollowTab user={profileUser} view={view} />}
{tab === "invitees" && (
<ProfileInviteesTab userId={user.id} state={invitees.state} />
<ProfileInviteesTab userId={profileUser.id} state={invitees.state} />
)}
{tab === "settings" && isOwnProfile && <ProfileSettingsTab />}
{tab === "manage" && (
<ProfileManageTab
user={user}
isOwnProfile={isOwnProfile}
canManageUsers={canManageUsers}
canManageCategories={canManageCategories}
onRoleSaved={(role) => setUser((u) => ({ ...u, role }))}
user={profileUser}
onUserSaved={(u) => setUser(() => u)}
/>
)}
</PageShell>