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:
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Gives components the signed-in user's settings, which are stored on the
|
||||
* server and kept with the session. `ThemeProvider` reads the style and
|
||||
* scheme from it, and the profile's settings tab the digest switches.
|
||||
* scheme from it, and the settings page the digest switches.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -25,7 +25,7 @@ export interface UseSettingsResult {
|
||||
settings: UserSettings | null;
|
||||
/**
|
||||
* Applies `patch` at once, then saves it with `PATCH
|
||||
* /api/users/me/settings`. A refusal puts the previous settings back and
|
||||
* /api/me/settings`. A refusal puts the previous settings back and
|
||||
* throws.
|
||||
*/
|
||||
updateSettings: (patch: UpdateSettingsRequest) => Promise<void>;
|
||||
@@ -42,7 +42,7 @@ export function useSettings(): UseSettingsResult {
|
||||
if (previous) updateSession({ settings: { ...previous, ...patch } });
|
||||
try {
|
||||
const saved = await expectOk<UserSettings>(
|
||||
await authFetch(`${API_URL}/api/users/me/settings`, {
|
||||
await authFetch(`${API_URL}/api/me/settings`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch satisfies UpdateSettingsRequest),
|
||||
}),
|
||||
|
||||
@@ -47,7 +47,7 @@ export interface UseDumpCardLinkResult {
|
||||
* inside the card, such as the title or a category, keep their own target.
|
||||
*/
|
||||
export function useDumpCardLink(
|
||||
dump: Pick<Dump, "id" | "slug">,
|
||||
dump: Pick<Dump, "id" | "slug" | "ownerUsername">,
|
||||
): UseDumpCardLinkResult {
|
||||
const navigate = useNavigate();
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { useAuth } from "../auth/useAuth.ts";
|
||||
import { useWS } from "../ws/useWS.ts";
|
||||
import { fadeClassName, useFading } from "../feed/useFading.ts";
|
||||
|
||||
/** Passed to {@link useUpvotedList} by `UserUpvoted` and the profile. */
|
||||
/** Passed to {@link useUpvotedList} by `useUserDumpFeed`, for an upvoted list. */
|
||||
export interface UseUpvotedListOptions {
|
||||
/**
|
||||
* The list holds this user's upvotes. It is null while their profile loads.
|
||||
|
||||
@@ -1,135 +1,100 @@
|
||||
/**
|
||||
* Feeds the profile subpages that list all of a user's dumps, or all they
|
||||
* upvoted, loading them a page at a time.
|
||||
* Feeds a profile's lists of dumps, the user's own and those they upvoted, to
|
||||
* its overview and to its "dumps" and "upvoted" tabs, and keeps them live.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { type RefCallback, useCallback, useEffect, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { API_URL } from "../../config/api.ts";
|
||||
import { friendlyFetchError } from "../../utils/shared/api.ts";
|
||||
import { fetchPublicUser } from "../../utils/shared/fetchPublicUser.ts";
|
||||
import {
|
||||
canLoadMore,
|
||||
mapItems,
|
||||
type PagedList,
|
||||
pageUrl,
|
||||
readFirstPage,
|
||||
readPage,
|
||||
restoredList,
|
||||
} from "../../utils/feed/pagedList.ts";
|
||||
import type { LoadState } from "../../utils/shared/loadState.ts";
|
||||
import { pageUrl, readPage } from "../../utils/feed/pagedList.ts";
|
||||
import type { Dump } from "../../../shared/dump.ts";
|
||||
import type { PublicUser } from "../../../shared/user.ts";
|
||||
import {
|
||||
deserializeDump,
|
||||
hydrateDump,
|
||||
} from "../../utils/shared/deserialize.ts";
|
||||
import { useAuth } from "../auth/useAuth.ts";
|
||||
import { useWS } from "../ws/useWS.ts";
|
||||
import { useFeedCache } from "../feed/useFeedCache.ts";
|
||||
import { useInfiniteScroll } from "../feed/useInfiniteScroll.ts";
|
||||
import { useLoadMore } from "../feed/usePagedList.ts";
|
||||
import { usePagedList, type UsePagedListResult } from "../feed/usePagedList.ts";
|
||||
import { useScrollRestore, useScrollSave } from "../feed/useScrollSave.ts";
|
||||
import { usePositionAwareSync } from "../feed/usePositionAwareSync.ts";
|
||||
import { useDumpListSync } from "./useDumpListSync.ts";
|
||||
import { useUpvotedList } from "./useUpvotedList.ts";
|
||||
|
||||
/**
|
||||
* Held by {@link useUserDumpFeed} for `UserDumps` and `UserUpvoted`. It fails
|
||||
* when the user doesn't exist, and holds an empty list when only the dumps
|
||||
* failed to load.
|
||||
*/
|
||||
export type UserDumpFeedState = LoadState<{
|
||||
profileUser: PublicUser;
|
||||
dumps: PagedList<Dump>;
|
||||
}>;
|
||||
/** One of a profile's lists of dumps, a path segment of its API and page. */
|
||||
export type UserDumpList = "dumps" | "upvoted";
|
||||
|
||||
/** Returned by {@link useUserDumpFeed} to `UserDumps` and `UserUpvoted`. */
|
||||
export interface UseUserDumpFeedResult {
|
||||
state: UserDumpFeedState;
|
||||
/** Returned by {@link useUserDumpFeed}. */
|
||||
export interface UseUserDumpFeedResult extends UsePagedListResult<Dump> {
|
||||
/**
|
||||
* It does nothing until loaded. It goes to `useDumpListSync` and
|
||||
* `useUpvotedList`.
|
||||
* It goes to the list's `DumpCardList`: on the upvoted list, it fades out a
|
||||
* withdrawn upvote.
|
||||
*/
|
||||
setItems: (fn: (prev: Dump[]) => Dump[]) => void;
|
||||
/** It comes from `useInfiniteScroll`, for an element after the last card. */
|
||||
sentinelRef: RefCallback<HTMLDivElement>;
|
||||
cardClassName?: (dump: Dump) => string | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the profile of `username`, from `GET /api/users/:username`, with its
|
||||
* dumps from `GET /api/users/:username/<endpoint>`, `endpoint` being "dumps"
|
||||
* or "votes". The dumps are fetched signed in, so the user sees their own
|
||||
* private ones. The next page loads as the sentinel scrolls into view. The
|
||||
* list and its scroll position are saved under `cacheKey` as the page is
|
||||
* left, and going back restores them, refetching only the profile.
|
||||
* Returns `list` of user `userId`, from `GET /api/users/:userId/<list>`, fetched
|
||||
* signed in so users see their own private dumps, with the call that loads its
|
||||
* next page. The socket keeps it live: a dump that goes private and public
|
||||
* again comes back at its place, and the upvoted list follows the user's
|
||||
* votes, `source` holding dumps at hand that a vote of theirs puts first at
|
||||
* once. The list and the scroll position are saved as the page is left, under
|
||||
* a key the overview and the tab share, and going back restores them.
|
||||
*/
|
||||
export function useUserDumpFeed(
|
||||
username: string | undefined,
|
||||
endpoint: string,
|
||||
cacheKey: string,
|
||||
userId: string,
|
||||
list: UserDumpList,
|
||||
{ isOwner, source }: { isOwner: boolean; source?: Dump[] },
|
||||
): UseUserDumpFeedResult {
|
||||
const { authFetch } = useAuth();
|
||||
const { cached, saveState } = useFeedCache<Dump>(cacheKey, hydrateDump);
|
||||
|
||||
const [state, setState] = useState<UserDumpFeedState>({ status: "loading" });
|
||||
const [prevUsername, setPrevUsername] = useState(username);
|
||||
if (prevUsername !== username) {
|
||||
setPrevUsername(username);
|
||||
setState({ status: "loading" });
|
||||
}
|
||||
|
||||
const setDumps = useCallback(
|
||||
(fn: (list: PagedList<Dump>) => PagedList<Dump>) =>
|
||||
setState((s) => s.status !== "loaded" ? s : { ...s, dumps: fn(s.dumps) }),
|
||||
[],
|
||||
);
|
||||
const setItems = useCallback(
|
||||
(fn: (prev: Dump[]) => Dump[]) => setDumps(mapItems(fn)),
|
||||
[setDumps],
|
||||
const { user, authFetch } = useAuth();
|
||||
const { lastDumpEvent } = useWS();
|
||||
const { cached, saveState } = useFeedCache<Dump>(
|
||||
`feed:profile-${list}:${userId}`,
|
||||
hydrateDump,
|
||||
);
|
||||
|
||||
const url = `${API_URL}/api/users/${username}/${endpoint}`;
|
||||
const fetchPage = useCallback(
|
||||
(page: number, signal?: AbortSignal) =>
|
||||
authFetch(pageUrl(url, page), { signal })
|
||||
.then((res) => readPage(res, deserializeDump)),
|
||||
[authFetch, url],
|
||||
const url = `${API_URL}/api/users/${userId}/${list}`;
|
||||
const paged = usePagedList<Dump>(
|
||||
`${url}:${user?.id ?? "guest"}`,
|
||||
useCallback(
|
||||
(page: number, signal?: AbortSignal) =>
|
||||
authFetch(pageUrl(url, page), { signal })
|
||||
.then((res) => readPage(res, deserializeDump)),
|
||||
[authFetch, url],
|
||||
),
|
||||
cached,
|
||||
);
|
||||
const { state, setItems } = paged;
|
||||
const items = state.status === "loaded" ? state.data.items : [];
|
||||
|
||||
useEffect(() => {
|
||||
if (!username) return;
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
// Back on the page, the list comes from the cache and only the user is
|
||||
// fetched again.
|
||||
const list = cached
|
||||
? restoredList(cached)
|
||||
: authFetch(pageUrl(url, 1), { signal })
|
||||
.then((res) => readFirstPage(res, deserializeDump));
|
||||
Promise.all([fetchPublicUser(username, signal), list])
|
||||
.then(([profileUser, dumps]) =>
|
||||
setState({ status: "loaded", profileUser, dumps })
|
||||
)
|
||||
.catch((err) => {
|
||||
if (signal.aborted) return;
|
||||
setState({ status: "error", error: friendlyFetchError(err) });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [username, cached, authFetch, url]);
|
||||
|
||||
const list = state.status === "loaded" ? state.dumps : null;
|
||||
const sentinelRef = useInfiniteScroll(
|
||||
useLoadMore(list, setDumps, fetchPage),
|
||||
canLoadMore(list),
|
||||
const upvoted = useUpvotedList({
|
||||
profileUserId: list === "upvoted" ? userId : null,
|
||||
setItems,
|
||||
source,
|
||||
});
|
||||
usePositionAwareSync(
|
||||
items,
|
||||
setItems,
|
||||
lastDumpEvent,
|
||||
list === "dumps"
|
||||
? (d) => !d.isPrivate && d.userId === userId
|
||||
: (d) => !d.isPrivate && !upvoted.isWithdrawn(d.id),
|
||||
);
|
||||
useDumpListSync(setItems, { isOwner: list === "dumps" && isOwner });
|
||||
|
||||
useScrollSave(
|
||||
state.status === "loaded",
|
||||
useCallback((y) => {
|
||||
if (state.status === "loaded") saveState(state.dumps, y);
|
||||
if (state.status === "loaded") saveState(state.data, y);
|
||||
}, [state, saveState]),
|
||||
);
|
||||
|
||||
useScrollRestore(cached?.scrollY, state.status === "loaded");
|
||||
|
||||
return { state, setItems, sentinelRef };
|
||||
return {
|
||||
...paged,
|
||||
cardClassName: list === "upvoted" ? upvoted.cardClassName : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Suggests users to @mention as the user types in `TextEditor`. It keeps the
|
||||
* state of the suggestions, fetched from `GET /api/users/search`, and
|
||||
* state of the suggestions, fetched from `GET /api/users?q=`, and
|
||||
* `TextEditor` renders them in a `MentionDropdown`.
|
||||
*
|
||||
* @module
|
||||
@@ -158,9 +158,7 @@ export function useMentionAutocomplete(
|
||||
abortRef.current = controller;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${API_URL}/api/users/search?q=${
|
||||
encodeURIComponent(mention.query)
|
||||
}`,
|
||||
`${API_URL}/api/users?q=${encodeURIComponent(mention.query)}`,
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const body = await res.json();
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import {
|
||||
DEFAULT_FEED_TAB,
|
||||
FEED_TABS,
|
||||
type FeedTab,
|
||||
} from "../../config/feedTabs.ts";
|
||||
import { FEED_TABS, type FeedTab } from "../../../shared/paths.ts";
|
||||
import { DEFAULT_FEED_TAB } from "../../config/feedTabs.ts";
|
||||
import { useAuth } from "../auth/useAuth.ts";
|
||||
|
||||
const STORAGE_KEY = "default-feed-tab";
|
||||
/** The v3 name of the "follow" tab, which a browser may still hold. */
|
||||
const V3_FOLLOW = "followed";
|
||||
|
||||
// The components reading the tab, told when this tab changes it.
|
||||
const listeners = new Set<() => void>();
|
||||
@@ -20,11 +20,19 @@ const listeners = new Set<() => void>();
|
||||
// Holds the choice made while storage is blocked, until a reload.
|
||||
let unstored: FeedTab | null = null;
|
||||
|
||||
/** Returns {@link DEFAULT_FEED_TAB} when the stored value isn't a tab. */
|
||||
/**
|
||||
* Returns the stored tab, or {@link DEFAULT_FEED_TAB} when the stored value
|
||||
* isn't a tab. A v3 "followed" is stored again as "follow", once, so nobody
|
||||
* loses their choice.
|
||||
*/
|
||||
function readStored(): FeedTab {
|
||||
let stored: string | null;
|
||||
try {
|
||||
stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === V3_FOLLOW) {
|
||||
stored = "follow";
|
||||
localStorage.setItem(STORAGE_KEY, stored);
|
||||
}
|
||||
} catch {
|
||||
stored = unstored;
|
||||
}
|
||||
@@ -55,12 +63,22 @@ function setDefaultFeedTab(tab: FeedTab): void {
|
||||
|
||||
/**
|
||||
* Returns the feed tab the index opens on, and a setter that stores a new
|
||||
* choice. The profile's settings set it. The index's redirect, its tab bar and
|
||||
* `Index` read it, and each falls back to {@link DEFAULT_FEED_TAB} when it is
|
||||
* "followed" and nobody is signed in. A new choice reaches every reader at
|
||||
* once, in this browser tab and the others.
|
||||
* choice. The settings page sets it; the feed reads it through
|
||||
* {@link useViewerDefaultFeedTab}. A new choice reaches every reader at once,
|
||||
* in this browser tab and the others.
|
||||
*/
|
||||
export function useDefaultFeedTab(): [FeedTab, (tab: FeedTab) => void] {
|
||||
const tab = useSyncExternalStore(subscribe, readStored);
|
||||
return [tab, setDefaultFeedTab];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the tab the bare `/` and `/<category>` show this viewer: their
|
||||
* choice, or {@link DEFAULT_FEED_TAB} for "follow" when nobody is signed in,
|
||||
* since it needs a session. `Index` and its tab bar read it.
|
||||
*/
|
||||
export function useViewerDefaultFeedTab(): FeedTab {
|
||||
const { user } = useAuth();
|
||||
const [preferred] = useDefaultFeedTab();
|
||||
return preferred === "follow" && !user ? DEFAULT_FEED_TAB : preferred;
|
||||
}
|
||||
|
||||
@@ -32,10 +32,9 @@ export type FetchPage<T> = (
|
||||
/**
|
||||
* Returns the call that loads the page after `list`'s last one and appends it
|
||||
* through `setList`. It does nothing unless `canLoadMore(list)`; a page that
|
||||
* fails leaves the list as it was, for the next call to try again. The pages
|
||||
* that load their lists with their user (`UserPlaylists`, `useUserDumpFeed`,
|
||||
* the profile's followed users) use it directly, and `usePagedList` for the
|
||||
* others.
|
||||
* fails leaves the list as it was, for the next call to try again. A page
|
||||
* that loads its list along with more, as the search page does, uses it
|
||||
* directly, and `usePagedList` for the others.
|
||||
*/
|
||||
export function useLoadMore<T>(
|
||||
list: PagedList<T> | null,
|
||||
@@ -78,8 +77,8 @@ export interface UsePagedListResult<T> {
|
||||
* Returns the list `fetchPage` serves for `key`, from its first page, and the
|
||||
* call that loads the next. `key` changes as `useFetchState`'s does, and
|
||||
* `cached`, `useFeedCache`'s restored list for it, if any, is shown without
|
||||
* loading. The index's feeds, the notifications and the popover of voters and
|
||||
* likers use it.
|
||||
* loading. The index's feeds, the profile's lists, the notifications and the
|
||||
* popover of voters and likers use it.
|
||||
*/
|
||||
export function usePagedList<T>(
|
||||
key: string | undefined,
|
||||
|
||||
@@ -28,7 +28,8 @@ import {
|
||||
deserializePlaylistWithDumps,
|
||||
} from "../../utils/shared/deserialize.ts";
|
||||
import { expectOk, friendlyFetchError } from "../../utils/shared/api.ts";
|
||||
import { playlistUrl } from "../../utils/shared/urls.ts";
|
||||
import { isAt, playlistUrl } from "../../utils/shared/urls.ts";
|
||||
import { useCanonicalPath } from "../shared/useCanonicalPath.ts";
|
||||
import { useAuth } from "../auth/useAuth.ts";
|
||||
import { useWS } from "../ws/useWS.ts";
|
||||
import { type FetchState, useFetchState } from "../shared/useFetchState.ts";
|
||||
@@ -87,35 +88,45 @@ function withDetails(
|
||||
return {
|
||||
...playlist,
|
||||
...updated,
|
||||
// Set only where the dumps were counted, which an edit's answer isn't.
|
||||
ownerUsername: updated.ownerUsername ?? playlist.ownerUsername,
|
||||
// Set only where the dumps were counted.
|
||||
dumpCount: updated.dumpCount ?? playlist.dumpCount,
|
||||
dumps: playlist.dumps,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the playlist `playlistId` (its id or its slug) from
|
||||
* `GET /api/playlists/:playlistId`, with the dumps the viewer may see in it.
|
||||
* The socket's events keep its details and dumps live: a dump another client
|
||||
* removes fades out, one it adds is fetched, a new order is applied, one that
|
||||
* goes private leaves and comes back at its place, and a deleted playlist
|
||||
* sends the page home. A new slug replaces the URL.
|
||||
* Returns the playlist at `/@username/playlists/slug` from
|
||||
* `GET /api/users/@:username/playlists/:slug`, with the dumps the viewer may
|
||||
* see in it. The socket's events keep its details and dumps live: a dump
|
||||
* another client removes fades out, one it adds is fetched, a new order is
|
||||
* applied, one that goes private leaves and comes back at its place, and a
|
||||
* deleted playlist sends the page home. A new slug replaces the URL, and a
|
||||
* path that names the playlist on screen, as that one does, fetches nothing.
|
||||
*/
|
||||
export function usePlaylist(
|
||||
playlistId: string | undefined,
|
||||
username: string | undefined,
|
||||
slug: string | undefined,
|
||||
): UsePlaylistResult {
|
||||
const navigate = useNavigate();
|
||||
const { user, authFetch } = useAuth();
|
||||
const { lastDumpEvent, lastPlaylistEvent } = useWS();
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
|
||||
// The path last fetched. The URL may move on to the same playlist's current
|
||||
// path, which mustn't fetch it again.
|
||||
const [target, setTarget] = useState({ username, slug });
|
||||
|
||||
// The server's last order of the dumps this viewer may see, which a refused
|
||||
// reorder goes back to.
|
||||
const serverOrderRef = useRef<string[]>([]);
|
||||
const { state, setData } = useFetchState(
|
||||
playlistId && `${playlistId}:${user?.id ?? "guest"}`,
|
||||
target.username && target.slug &&
|
||||
`${target.username}/${target.slug}:${user?.id ?? "guest"}`,
|
||||
(signal) =>
|
||||
authFetch(`${API_URL}/api/playlists/${playlistId}`, { signal })
|
||||
authFetch(
|
||||
`${API_URL}/api/users/@${target.username}/playlists/${target.slug}`,
|
||||
{ signal },
|
||||
)
|
||||
.then(expectOk<Wire<PlaylistWithDumps>>)
|
||||
.then((wire) => {
|
||||
const playlist = deserializePlaylistWithDumps(wire);
|
||||
@@ -124,7 +135,14 @@ export function usePlaylist(
|
||||
}),
|
||||
);
|
||||
const playlist = state.status === "loaded" ? state.data : null;
|
||||
// The socket names playlists by id, while the URL may hold the slug.
|
||||
if (
|
||||
(target.username !== username || target.slug !== slug) &&
|
||||
!isAt(playlist, username, slug)
|
||||
) {
|
||||
setTarget({ username, slug });
|
||||
}
|
||||
useCanonicalPath(playlist && playlistUrl(playlist));
|
||||
// The socket and the API's writes name playlists by id.
|
||||
const id = playlist?.id;
|
||||
const url = `${API_URL}/api/playlists/${id}`;
|
||||
|
||||
@@ -198,13 +216,10 @@ export function usePlaylist(
|
||||
};
|
||||
}, []);
|
||||
|
||||
// A new slug, or owner's name, reaches the URL through useCanonicalPath.
|
||||
const applyDetails = useCallback((updated: Playlist) => {
|
||||
const slug = latestRef.current.playlist?.slug;
|
||||
setData((p) => withDetails(p, updated));
|
||||
if (updated.slug && updated.slug !== slug) {
|
||||
navigate(playlistUrl(updated), { replace: true });
|
||||
}
|
||||
}, [setData, navigate]);
|
||||
}, [setData]);
|
||||
|
||||
useEffect(() => {
|
||||
const ev = lastPlaylistEvent;
|
||||
|
||||
@@ -35,7 +35,7 @@ export interface UsePlaylistMembershipsResult {
|
||||
|
||||
/**
|
||||
* Returns the user's playlists with whether each holds `dumpId`, from
|
||||
* `GET /api/playlists/by-dump/:dumpId/memberships`. A null `dumpId`, as before
|
||||
* `GET /api/me/playlists?contains=:dumpId`. A null `dumpId`, as before
|
||||
* `DumpCreateModal` has posted its dump, loads nothing.
|
||||
*/
|
||||
export function usePlaylistMemberships(
|
||||
@@ -45,7 +45,7 @@ export function usePlaylistMemberships(
|
||||
const { state, setData } = useFetchState(
|
||||
dumpId ?? undefined,
|
||||
(signal) =>
|
||||
authFetch(`${API_URL}/api/playlists/by-dump/${dumpId}/memberships`, {
|
||||
authFetch(`${API_URL}/api/me/playlists?contains=${dumpId}`, {
|
||||
signal,
|
||||
})
|
||||
.then(expectOk<Wire<PlaylistMembership>[]>)
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
27
src/hooks/shared/useCanonicalPath.ts
Normal file
27
src/hooks/shared/useCanonicalPath.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Puts a page's current path in the URL once the page knows it. A user, dump
|
||||
* or playlist reached by a former name or slug, or by a name in another case,
|
||||
* comes back from the API under its current one, from which the page builds
|
||||
* its path; the server's OG middleware answers the same with a 301.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
/**
|
||||
* Replaces the current path with `canonical` when they differ, keeping the
|
||||
* query string, the hash and the history entry's state. It replaces the
|
||||
* entry, so going back skips the old path. Nothing happens while `canonical`
|
||||
* is null, as while the page loads. The profile, dump, dump editor and
|
||||
* playlist pages call it.
|
||||
*/
|
||||
export function useCanonicalPath(canonical: string | null | undefined): void {
|
||||
const { pathname, search, hash, state } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
useEffect(() => {
|
||||
if (!canonical || canonical === pathname) return;
|
||||
navigate(`${canonical}${search}${hash}`, { replace: true, state });
|
||||
}, [canonical, pathname, search, hash, state, navigate]);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* Keeps a page's active tab in its URL, for the profile and search pages.
|
||||
* Keeps a page's active tab in its path, as one more segment, for the profile
|
||||
* and search pages.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -7,44 +8,36 @@
|
||||
import { useCallback } from "react";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
|
||||
/** Separates the page's path from the tab, as App.tsx's routes expect. */
|
||||
const SEP = "/~/";
|
||||
|
||||
/**
|
||||
* Returns the tab named after `/~/` in the current path, or `defaultTab` when
|
||||
* there is none or it isn't in `validTabs`, and a setter that navigates to a
|
||||
* tab in place of the current history entry. The page's route must take both
|
||||
* `<path>` and `<path>/~/:tab`, as `/users/:username/~/:profileTab` does. The
|
||||
* default tab's URL is the bare path, except at the root, where it stays
|
||||
* explicit.
|
||||
* Returns the tab the path segment after `base` names, `defaultTab` on the
|
||||
* bare `base`, or null when the segment names none of `validTabs`, for the
|
||||
* page to answer as not found; and a setter that navigates to a tab in place
|
||||
* of the current history entry, the default tab to the bare `base`. A segment
|
||||
* after the tab's, as the profile's `/follow/playlists`, is the tab's own
|
||||
* business.
|
||||
*/
|
||||
export function useTabParam<T extends string>(
|
||||
base: string,
|
||||
validTabs: Iterable<T>,
|
||||
defaultTab: T,
|
||||
): [T, (tab: T) => void] {
|
||||
): [T | null, (tab: T) => void] {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const valid = new Set<string>(validTabs as Iterable<string>);
|
||||
const path = location.pathname;
|
||||
const sepAt = path.indexOf(SEP);
|
||||
|
||||
let base = sepAt === -1 ? path : path.slice(0, sepAt);
|
||||
// The root "/" becomes "".
|
||||
if (base.endsWith("/")) base = base.slice(0, -1);
|
||||
|
||||
const raw = sepAt === -1
|
||||
? null
|
||||
: path.slice(sepAt + SEP.length).replace(/\/$/, "");
|
||||
const tab = (raw && valid.has(raw) ? raw : defaultTab) as T;
|
||||
const segment = location.pathname.slice(base.length).split("/")[1] ?? "";
|
||||
const tab = segment === ""
|
||||
? defaultTab
|
||||
: valid.has(segment) && segment !== defaultTab
|
||||
? segment as T
|
||||
: null;
|
||||
|
||||
const setTab = useCallback(
|
||||
(t: T) => {
|
||||
const target = t === defaultTab && base ? base : `${base}${SEP}${t}`;
|
||||
// Keeps the query string (the search page's `?q=`) and the entry's
|
||||
// state, since this is the same entry and `AppHeader`'s search reads
|
||||
// where to go back to from it.
|
||||
navigate(`${target}${location.search}`, {
|
||||
navigate(`${base}${t === defaultTab ? "" : `/${t}`}${location.search}`, {
|
||||
replace: true,
|
||||
state: location.state,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user