v3: every paged list loads its pages one way, PlaylistDetail is split like the profile, and the comments keep the README's rules — Index, FollowedFeed, useUserDumpFeed, UserPlaylists, UserListPopover, Notifications, Search and the profile's followed users each hand-wrote "fetch the next page, append it, clear loadingMore on failure". A list the API pages is now a PagedList whose next page useLoadMore appends, and a list that loads on its own goes through usePagedList, which is useFetchState (now taking an initial value, as a restored cache, that starts loaded) plus useLoadMore. Pages are read by pageUrl with readPage (a refusal throws) or readFirstPage (a refusal is empty, as fetchFirstPage was), signed-in reads go through authFetch, and useFeedCache's saveState takes the list. Notifications keeps the socket's arrivals as their own list merged at render, as Index does with recentDumps, and marks them read in one effect. PlaylistDetail (963 lines) only puts the pieces together (146): usePlaylist holds the playlist, its live sync and its edits, PlaylistHeader, PlaylistEditForm and PlaylistDumpList are one file each, and LiveDumpCard is the vote wiring DumpCardList and the playlist both use. What it re-invented is shared: the load is useFetchState, a dump going private and back is usePositionAwareSync, deletes and edits are useDumpListSync (which also keeps comment counts, which the page didn't). A removal is sent when its fade ends, or as the page is left, so an undo sends nothing: the removal/re-add/reorder dance, the pending-undo order and the 80 ms debounce of its echoes are gone. A refused reorder goes back to the server's last order and says so, instead of reloading the page. The comments written since the documentation pass broke its rules in places: module docs as a label and a colon ("The "dumps" tab of a profile: …"), noun-phrase fragments on types, fields and constants, stale lists of callers, over-long lines; they are sentences now, and the ones the refactor made wrong (PlaylistDetail as useFading's and FollowPlaylistButton's caller, "the profiles" as usePositionAwareSync's only users) say what is true. 650 frontend and 214 backend tests pass (new: usePagedList, useFetchState's initial, pageUrl/readPage, the deferred removal, a dump returning at its place in a playlist), and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 49s
Build and Deploy Static Documentation Site / build-and-push (push) Successful in 22s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-29 21:19:33 +00:00
parent 69d9bf899b
commit 07ac4bc629
81 changed files with 2016 additions and 2210 deletions

View File

@@ -5,7 +5,7 @@
* @module
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback } from "react";
import { Link, useSearchParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
@@ -28,30 +28,32 @@ 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 { DEFAULT_PAGE_SIZE, SEARCH_URL } from "../config/api.ts";
import { friendlyFetchError } from "../utils/shared/api.ts";
import type { SearchResults } from "../../shared/search.ts";
import { SEARCH_URL } from "../config/api.ts";
import { expectOk } from "../utils/shared/api.ts";
import {
canLoadMore,
firstPage,
type PagedList,
pageUrl,
} from "../utils/feed/pagedList.ts";
import { useFetchState } from "../hooks/shared/useFetchState.ts";
import { useLoadMore } from "../hooks/feed/usePagedList.ts";
const SEARCH_TABS = ["dumps", "users", "playlists"] as const;
type Tab = (typeof SEARCH_TABS)[number];
// Only the dumps are paged: the API answers at most 20 users and playlists.
type SearchState =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; error: string }
| {
status: "loaded";
q: string;
dumps: {
items: Dump[];
total: number;
hasMore: boolean;
page: number;
loadingMore: boolean;
};
users: PublicUser[];
playlists: Playlist[];
};
/**
* Held by `Search` for a query, from the first page of `SearchResults`. The
* dumps take the next pages.
*/
interface Results {
dumps: PagedList<Dump>;
/** It counts every match, which the pages loaded so far may not reach. */
dumpTotal: number;
users: PublicUser[];
playlists: Playlist[];
}
/**
* Renders `/search?q=` and `/search/~/:searchTab`, for anyone. The results come
@@ -65,131 +67,49 @@ export function Search(): React.JSX.Element {
const q = searchParams.get("q") ?? "";
const [tab, setTab] = useTabParam<Tab>(SEARCH_TABS, "dumps");
const { token } = useAuth();
const { user, authFetch } = useAuth();
const search = useCallback(async (page: number, signal?: AbortSignal) => {
const url = new URL(SEARCH_URL, location.origin);
url.searchParams.set("q", q);
return expectOk<Wire<SearchResults>>(
await authFetch(pageUrl(url.toString(), page), { signal }),
);
}, [authFetch, q]);
const [state, setState] = useState<SearchState>({ status: "idle" });
const abortRef = useRef<AbortController | null>(null);
const fetchSearch = useCallback(async (query: string, page: number) => {
// Deferred: the set-state-in-effect lint rule forbids setting state
// synchronously in the effect that calls this.
if (!query.trim()) {
queueMicrotask(() => setState({ status: "idle" }));
return;
}
if (page === 1) {
queueMicrotask(() => setState({ status: "loading" }));
}
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
try {
const url = new URL(SEARCH_URL, location.origin);
url.searchParams.set("q", query);
url.searchParams.set("page", String(page));
url.searchParams.set("limit", String(DEFAULT_PAGE_SIZE));
const res = await fetch(url.toString(), {
signal: controller.signal,
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(body?.error?.message ?? `HTTP ${res.status}`);
}
const body = await res.json() as {
success: true;
data: {
dumps: { items: Wire<Dump>[]; total: number; hasMore: boolean };
users: Wire<PublicUser>[];
playlists: Wire<Playlist>[];
};
};
const { data } = body;
if (page === 1) {
setState({
status: "loaded",
q: query,
dumps: {
items: data.dumps.items.map(deserializeDump),
total: data.dumps.total,
hasMore: data.dumps.hasMore,
page: 1,
loadingMore: false,
},
users: data.users.map(deserializePublicUser),
playlists: data.playlists.map(deserializePlaylist),
});
} else {
setState((prev) => {
if (prev.status !== "loaded") return prev;
return {
...prev,
dumps: {
...prev.dumps,
items: [
...prev.dumps.items,
...data.dumps.items.map(deserializeDump),
],
hasMore: data.dumps.hasMore,
page,
loadingMore: false,
},
};
});
}
} catch (err) {
if ((err as Error).name === "AbortError") return;
// A later page that fails leaves the results already shown; scrolling
// back to the end tries it again.
if (page > 1) {
setState((prev) =>
prev.status === "loaded"
? { ...prev, dumps: { ...prev.dumps, loadingMore: false } }
: prev
);
return;
}
setState({ status: "error", error: friendlyFetchError(err) });
}
}, [token]);
useEffect(() => {
// The lint rule flags the call itself, whatever fetchSearch defers inside.
queueMicrotask(() => fetchSearch(q, 1));
return () => abortRef.current?.abort();
}, [q, fetchSearch]);
const loadMore = useCallback(() => {
if (
state.status !== "loaded" || !state.dumps.hasMore ||
state.dumps.loadingMore
) return;
setState((prev) => {
if (prev.status !== "loaded") return prev;
return { ...prev, dumps: { ...prev.dumps, loadingMore: true } };
});
fetchSearch(q, state.dumps.page + 1);
}, [state, q, fetchSearch]);
const sentinelRef = useInfiniteScroll(
loadMore,
state.status === "loaded" && tab === "dumps" && state.dumps.hasMore &&
!state.dumps.loadingMore,
const { state, setData } = useFetchState<Results>(
q.trim() ? `${q}:${user?.id ?? "guest"}` : undefined,
(signal) =>
search(1, signal).then(({ dumps, users, playlists }) => ({
dumps: firstPage(dumps.items.map(deserializeDump), dumps.hasMore),
dumpTotal: dumps.total ?? 0,
users: users.map(deserializePublicUser),
playlists: playlists.map(deserializePlaylist),
})),
);
const dumpCount = state.status === "loaded" ? state.dumps.total : null;
const userCount = state.status === "loaded" ? state.users.length : null;
const playlistCount = state.status === "loaded"
? state.playlists.length
: null;
const dumps = state.status === "loaded" ? state.data.dumps : null;
const loadMore = useLoadMore(
dumps,
useCallback(
(fn: (dumps: PagedList<Dump>) => PagedList<Dump>) =>
setData((d) => ({ ...d, dumps: fn(d.dumps) })),
[setData],
),
(page) =>
search(page).then(({ dumps }) => ({
items: dumps.items.map(deserializeDump),
hasMore: dumps.hasMore,
})),
);
const sentinelRef = useInfiniteScroll(
loadMore,
tab === "dumps" && canLoadMore(dumps),
);
const results = state.status === "loaded" ? state.data : null;
const dumpCount = results ? results.dumpTotal : null;
const userCount = results ? results.users.length : null;
const playlistCount = results ? results.playlists.length : null;
function tabLabel(tab: Tab, count: number | null) {
const label = tab === "dumps"
@@ -224,13 +144,13 @@ export function Search(): React.JSX.Element {
/>
)}
{state.status === "idle" && (
{!q.trim() && (
<p className="search-page-empty">
<Trans>Enter a query to search.</Trans>
</p>
)}
{state.status === "loading" && (
{q.trim() && state.status === "loading" && (
<p className="search-page-empty">
<Trans>Searching…</Trans>
</p>
@@ -240,29 +160,27 @@ export function Search(): React.JSX.Element {
<ErrorCard title={t`Search failed`} message={state.error} />
)}
{state.status === "loaded" && tab === "dumps" && (
<>
{state.dumps.items.length === 0
? <p className="search-page-empty">{t`No dumps match "${q}".`}</p>
: (
<>
<DumpCardList dumps={state.dumps.items} />
<FeedFooter
hasMore={state.dumps.hasMore}
loadingMore={state.dumps.loadingMore}
sentinelRef={sentinelRef}
/>
</>
)}
</>
{results && tab === "dumps" && (
results.dumps.items.length === 0
? <p className="search-page-empty">{t`No dumps match "${q}".`}</p>
: (
<>
<DumpCardList dumps={results.dumps.items} />
<FeedFooter
hasMore={results.dumps.hasMore}
loadingMore={results.dumps.loadingMore}
sentinelRef={sentinelRef}
/>
</>
)
)}
{state.status === "loaded" && tab === "users" && (
state.users.length === 0
{results && tab === "users" && (
results.users.length === 0
? <p className="search-page-empty">{t`No users match "${q}".`}</p>
: (
<ul className="user-results">
{state.users.map((u) => (
{results.users.map((u) => (
<li key={u.id}>
<Link
to={`/users/${u.username}`}
@@ -281,14 +199,14 @@ export function Search(): React.JSX.Element {
)
)}
{state.status === "loaded" && tab === "playlists" && (
state.playlists.length === 0
{results && tab === "playlists" && (
results.playlists.length === 0
? (
<p className="search-page-empty">
{t`No playlists match "${q}".`}
</p>
)
: <PlaylistCardList playlists={state.playlists} />
: <PlaylistCardList playlists={results.playlists} />
)}
</main>
</div>