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

@@ -5,11 +5,11 @@
* @module
*/
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { Link, useLocation, useNavigate, useParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { dumpThumbnailUrl, dumpUrl } from "../utils/shared/urls.ts";
import { dumpThumbnailUrl, dumpUrl, isAt } from "../utils/shared/urls.ts";
import { can } from "../utils/auth/permissions.ts";
import { AddToPlaylistModal } from "../components/playlist/AddToPlaylistModal.tsx";
@@ -46,6 +46,8 @@ import { PageError } from "../components/layout/PageError.tsx";
import { Markdown } from "../components/editor/Markdown.tsx";
import { CommentThread } from "../components/comment/CommentThread.tsx";
import { Tooltip } from "../components/shared/Tooltip.tsx";
import { userPath } from "../../shared/paths.ts";
import { useCanonicalPath } from "../hooks/shared/useCanonicalPath.ts";
type DumpState =
| { status: "loading" }
@@ -53,16 +55,18 @@ type DumpState =
| { status: "loaded"; dump: Dump };
/**
* Renders `/dumps/:selectedDump`, for anyone who may see the dump: a private
* dump answers 404 to anyone but its poster. The dump comes from
* `GET /api/dumps/:dumpId`, or from the navigation's state when `DumpEdit` or
* a title edit here just saved it. Its comments, related dumps and playlists
* come from their own endpoints, and `WSContext`'s events keep them current.
* The poster and moderators can edit the title in place, and get a link to
* `DumpEdit`.
* Renders `/@:username/dumps/:slug`, for anyone who may see the dump: a
* private dump answers 404 to anyone but its poster. The dump comes from
* `GET /api/users/@:username/dumps/:slug`, or from the navigation's state when
* `DumpEdit` or a title edit here just saved it. Reached by a former name or
* slug, the URL takes the current ones. Its comments, related dumps and
* playlists come from their own endpoints once it is loaded, and
* `WSContext`'s events keep them current. The poster and moderators can edit
* the title in place, and get a link to `DumpEdit`.
*/
export function Dump(): React.JSX.Element {
const { selectedDump } = useParams();
const { handle, slug } = useParams();
const username = handle?.slice(1);
const location = useLocation();
const navigate = useNavigate();
// Taken once, since it stays in the history entry, where a reload or Back
@@ -70,10 +74,7 @@ export function Dump(): React.JSX.Element {
const [handedOver] = useState(
() => (location.state as { dump?: Dump } | null)?.dump ?? null,
);
const preloaded = handedOver &&
(handedOver.id === selectedDump || handedOver.slug === selectedDump)
? handedOver
: null;
const preloaded = isAt(handedOver, username, slug) ? handedOver : null;
useEffect(() => {
if (!(location.state as { dump?: Dump } | null)?.dump) return;
navigate(`${location.pathname}${location.search}${location.hash}`, {
@@ -85,6 +86,14 @@ export function Dump(): React.JSX.Element {
const [dumpState, setDumpState] = useState<DumpState>(
preloaded ? { status: "loaded", dump: preloaded } : { status: "loading" },
);
const loadedDump = dumpState.status === "loaded" ? dumpState.dump : null;
useCanonicalPath(loadedDump && dumpUrl(loadedDump));
// The dump on screen, which a path it was just given, by useCanonicalPath or
// a slug edited elsewhere, needn't fetch again.
const shownRef = useRef<Dump | null>(loadedDump);
useEffect(() => {
shownRef.current = loadedDump;
}, [loadedDump]);
const [op, setOp] = useState<PublicUser | null>(null);
const [playlistModalOpen, setPlaylistModalOpen] = useState(false);
@@ -120,11 +129,11 @@ export function Dump(): React.JSX.Element {
} = useWS();
useEffect(() => {
if (!selectedDump) return;
if (!username || !slug) return;
const controller = new AbortController();
if (preloaded) {
fetch(`${API_URL}/api/users/by-id/${preloaded.userId}`, {
fetch(`${API_URL}/api/users/${preloaded.userId}`, {
signal: controller.signal,
})
.then((r) => r.json())
@@ -133,14 +142,16 @@ export function Dump(): React.JSX.Element {
return () => controller.abort();
}
if (isAt(shownRef.current, username, slug)) return;
(async () => {
setDumpState({ status: "loading" });
setOp(null);
try {
const res = await authFetch(`${API_URL}/api/dumps/${selectedDump}`, {
cache: "no-store",
signal: controller.signal,
});
const res = await authFetch(
`${API_URL}/api/users/@${username}/dumps/${slug}`,
{ cache: "no-store", signal: controller.signal },
);
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
if (!apiResponse.success) {
throw new Error(apiResponse.error.message);
@@ -148,7 +159,7 @@ export function Dump(): React.JSX.Element {
const dump: Dump = deserializeDump(apiResponse.data);
setDumpState({ status: "loaded", dump });
fetch(`${API_URL}/api/users/by-id/${dump.userId}`, {
fetch(`${API_URL}/api/users/${dump.userId}`, {
signal: controller.signal,
})
.then((r) => r.json())
@@ -160,7 +171,7 @@ export function Dump(): React.JSX.Element {
}
})();
return () => controller.abort();
}, [selectedDump, preloaded, authFetch]);
}, [username, slug, preloaded, authFetch]);
useEffect(() => {
if (!lastDumpEvent) return;
@@ -174,10 +185,12 @@ export function Dump(): React.JSX.Element {
});
}, [lastDumpEvent]);
const loadedDumpId = loadedDump?.id ?? null;
useEffect(() => {
if (!selectedDump) return;
if (!loadedDumpId) return;
const controller = new AbortController();
authFetch(`${API_URL}/api/dumps/${selectedDump}/comments`, {
authFetch(`${API_URL}/api/dumps/${loadedDumpId}/comments`, {
signal: controller.signal,
})
.then((r) => r.json())
@@ -190,13 +203,13 @@ export function Dump(): React.JSX.Element {
return () => controller.abort();
// connectionEpoch refetches on reconnect, for the comments missed while the
// socket was down.
}, [selectedDump, authFetch, connectionEpoch]);
}, [loadedDumpId, authFetch, connectionEpoch]);
// The dumps that link to this one, or that it links to.
useEffect(() => {
if (!selectedDump) return;
if (!loadedDumpId) return;
const controller = new AbortController();
authFetch(`${API_URL}/api/dumps/${selectedDump}/related`, {
authFetch(`${API_URL}/api/dumps/${loadedDumpId}/related`, {
signal: controller.signal,
})
.then((r) => r.json())
@@ -207,13 +220,13 @@ export function Dump(): React.JSX.Element {
})
.catch(() => {});
return () => controller.abort();
}, [selectedDump, authFetch]);
}, [loadedDumpId, authFetch]);
// The server leaves out the private playlists of others.
useEffect(() => {
if (!selectedDump) return;
if (!loadedDumpId) return;
const controller = new AbortController();
authFetch(`${API_URL}/api/dumps/${selectedDump}/playlists`, {
authFetch(`${API_URL}/api/dumps/${loadedDumpId}/playlists`, {
signal: controller.signal,
})
.then((r) => r.json())
@@ -228,7 +241,7 @@ export function Dump(): React.JSX.Element {
return () => controller.abort();
// Any playlist event may change the list, and they are rare enough to
// refetch on each.
}, [selectedDump, authFetch, lastPlaylistEvent]);
}, [loadedDumpId, authFetch, lastPlaylistEvent]);
// A notification links to `#comment-<id>`. Rerun when the comments arrive,
// since the element doesn't exist before.
@@ -246,7 +259,6 @@ export function Dump(): React.JSX.Element {
return () => clearTimeout(timer);
}, [comments, location.hash]);
const loadedDumpId = dumpState.status === "loaded" ? dumpState.dump.id : null;
useEffect(() => {
if (
!lastCommentEvent || !loadedDumpId ||
@@ -472,7 +484,7 @@ export function Dump(): React.JSX.Element {
/>
{op
? (
<Link to={`/users/${op.username}`} className="dump-op-link">
<Link to={userPath(op.username)} className="dump-op-link">
{op.username}
</Link>
)