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.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
107
src/hooks/feed/usePagedList.ts
Normal file
107
src/hooks/feed/usePagedList.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Loads a list a page at a time. Every list the API pages goes through
|
||||
* {@link useLoadMore} for its next pages, and a list that loads on its own
|
||||
* through {@link usePagedList}, from its first page on.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback, useLayoutEffect, useRef } from "react";
|
||||
import type { PaginatedData } from "../../../shared/api.ts";
|
||||
import {
|
||||
canLoadMore,
|
||||
firstPage,
|
||||
mapItems,
|
||||
type PagedList,
|
||||
restoredList,
|
||||
} from "../../utils/feed/pagedList.ts";
|
||||
import type { FeedCacheEntry } from "./useFeedCache.ts";
|
||||
import { type FetchState, useFetchState } from "../shared/useFetchState.ts";
|
||||
|
||||
/**
|
||||
* Passed to {@link useLoadMore} and {@link usePagedList} by a list's page or
|
||||
* hook. It resolves to page `page` of the list, its items deserialized, as
|
||||
* `fetch` with `pageUrl` and `readPage` gives it, and rejects when the page
|
||||
* can't be had.
|
||||
*/
|
||||
export type FetchPage<T> = (
|
||||
page: number,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<PaginatedData<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.
|
||||
*/
|
||||
export function useLoadMore<T>(
|
||||
list: PagedList<T> | null,
|
||||
setList: (fn: (list: PagedList<T>) => PagedList<T>) => void,
|
||||
fetchPage: FetchPage<T>,
|
||||
): () => void {
|
||||
// A ref, so that a new `fetchPage` on every render keeps the call stable.
|
||||
const fetchPageRef = useRef(fetchPage);
|
||||
useLayoutEffect(() => {
|
||||
fetchPageRef.current = fetchPage;
|
||||
});
|
||||
|
||||
return useCallback(() => {
|
||||
if (!list || !canLoadMore(list)) return;
|
||||
const page = list.page + 1;
|
||||
setList((l) => ({ ...l, loadingMore: true }));
|
||||
fetchPageRef.current(page)
|
||||
.then(({ items, hasMore }) =>
|
||||
setList((l) => ({
|
||||
items: [...l.items, ...items],
|
||||
hasMore,
|
||||
page,
|
||||
loadingMore: false,
|
||||
}))
|
||||
)
|
||||
.catch(() => setList((l) => ({ ...l, loadingMore: false })));
|
||||
}, [list, setList]);
|
||||
}
|
||||
|
||||
/** Returned by {@link usePagedList}. */
|
||||
export interface UsePagedListResult<T> {
|
||||
state: FetchState<PagedList<T>>;
|
||||
/** Does nothing until loaded. Passed to the sync hooks. */
|
||||
setItems: (fn: (items: T[]) => T[]) => void;
|
||||
/** It goes to `useInfiniteScroll` or to a `LoadMoreButton`. */
|
||||
loadMore: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function usePagedList<T>(
|
||||
key: string | undefined,
|
||||
fetchPage: FetchPage<T>,
|
||||
cached?: Omit<FeedCacheEntry<T>, "savedAt"> | null,
|
||||
): UsePagedListResult<T> {
|
||||
const { state, setData } = useFetchState(
|
||||
key,
|
||||
(signal) =>
|
||||
fetchPage(1, signal).then(({ items, hasMore }) =>
|
||||
firstPage(items, hasMore)
|
||||
),
|
||||
{ initial: cached ? restoredList(cached) : undefined },
|
||||
);
|
||||
const setItems = useCallback(
|
||||
(fn: (items: T[]) => T[]) => setData(mapItems(fn)),
|
||||
[setData],
|
||||
);
|
||||
const loadMore = useLoadMore(
|
||||
state.status === "loaded" ? state.data : null,
|
||||
setData,
|
||||
fetchPage,
|
||||
);
|
||||
return { state, setItems, loadMore };
|
||||
}
|
||||
Reference in New Issue
Block a user