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:
@@ -46,8 +46,8 @@ describe("useUserDumpFeed", () => {
|
||||
{ status: "loaded" }
|
||||
>;
|
||||
expect(s.profileUser.username).toBe("ann");
|
||||
expect(s.items[0].createdAt).toBeInstanceOf(Date);
|
||||
expect(s.hasMore).toBe(true);
|
||||
expect(s.dumps.items[0].createdAt).toBeInstanceOf(Date);
|
||||
expect(s.dumps.hasMore).toBe(true);
|
||||
const [req] = calls("GET /api/users/:u/dumps");
|
||||
expect(req.url.searchParams.get("page")).toBe("1");
|
||||
expect(req.headers.get("Authorization")).toBe(`Bearer ${session.token}`);
|
||||
@@ -91,7 +91,7 @@ describe("useUserDumpFeed", () => {
|
||||
act(() => obs.report(true));
|
||||
await waitFor(() => {
|
||||
const s = result.current.state;
|
||||
expect(s.status === "loaded" && s.items.map((d) => d.id)).toEqual([
|
||||
expect(s.status === "loaded" && s.dumps.items.map((d) => d.id)).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
]);
|
||||
@@ -100,8 +100,8 @@ describe("useUserDumpFeed", () => {
|
||||
typeof result.current.state,
|
||||
{ status: "loaded" }
|
||||
>;
|
||||
expect(s.hasMore).toBe(false);
|
||||
expect(s.page).toBe(2);
|
||||
expect(s.dumps.hasMore).toBe(false);
|
||||
expect(s.dumps.page).toBe(2);
|
||||
});
|
||||
|
||||
test("changing user resets to loading", async () => {
|
||||
@@ -130,6 +130,6 @@ describe("useUserDumpFeed", () => {
|
||||
typeof result.current.state,
|
||||
{ status: "loaded" }
|
||||
>;
|
||||
expect(s.items.map((d) => d.id)).toEqual(["b"]);
|
||||
expect(s.dumps.items.map((d) => d.id)).toEqual(["b"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,7 +22,13 @@ describe("useFeedCache", () => {
|
||||
const first = renderHook(() => useFeedCache<{ n: number }>("k", (x) => x), {
|
||||
wrapper: wrapper(),
|
||||
});
|
||||
act(() => first.result.current.saveState([{ n: 1 }], 2, true, 300));
|
||||
act(() =>
|
||||
first.result.current.saveState({
|
||||
items: [{ n: 1 }],
|
||||
page: 2,
|
||||
hasMore: true,
|
||||
}, 300)
|
||||
);
|
||||
const second = renderHook(
|
||||
() => useFeedCache<{ n: number }>("k", (x) => ({ n: x.n * 10 })),
|
||||
{ wrapper: wrapper() },
|
||||
@@ -40,7 +46,9 @@ describe("useFeedCache", () => {
|
||||
const first = renderHook(() => useFeedCache("k", (x) => x), {
|
||||
wrapper: wrapper(),
|
||||
});
|
||||
act(() => first.result.current.saveState([], 1, false, 0));
|
||||
act(() =>
|
||||
first.result.current.saveState({ items: [], page: 1, hasMore: false }, 0)
|
||||
);
|
||||
vi.advanceTimersByTime(11 * 60 * 1000);
|
||||
const second = renderHook(() => useFeedCache("k", (x) => x), {
|
||||
wrapper: wrapper(),
|
||||
@@ -92,6 +100,8 @@ describe("useFeedCache", () => {
|
||||
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
|
||||
throw new Error("QuotaExceededError");
|
||||
});
|
||||
expect(() => result.current.saveState([], 1, false, 0)).not.toThrow();
|
||||
expect(() =>
|
||||
result.current.saveState({ items: [], page: 1, hasMore: false }, 0)
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
64
src/test/hooks/feed/usePagedList.test.tsx
Normal file
64
src/test/hooks/feed/usePagedList.test.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { usePagedList } from "../../../hooks/feed/usePagedList.ts";
|
||||
import { deferred } from "../../fetch.ts";
|
||||
|
||||
describe("usePagedList", () => {
|
||||
test("loads the first page, then appends the next ones", async () => {
|
||||
const fetchPage = vi.fn((page: number) =>
|
||||
Promise.resolve({ items: [page], hasMore: page < 2 })
|
||||
);
|
||||
const { result } = renderHook(() => usePagedList("k", fetchPage));
|
||||
await waitFor(() => expect(result.current.state.status).toBe("loaded"));
|
||||
act(() => result.current.loadMore());
|
||||
await waitFor(() =>
|
||||
expect(result.current.state).toEqual({
|
||||
status: "loaded",
|
||||
data: { items: [1, 2], hasMore: false, page: 2, loadingMore: false },
|
||||
})
|
||||
);
|
||||
act(() => result.current.loadMore());
|
||||
expect(fetchPage).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("loads one next page at a time, and a failed one can be tried again", async () => {
|
||||
const next = deferred<{ items: number[]; hasMore: boolean }>();
|
||||
const fetchPage = vi.fn((page: number) =>
|
||||
page === 1 ? Promise.resolve({ items: [1], hasMore: true }) : next.promise
|
||||
);
|
||||
const { result } = renderHook(() => usePagedList("k", fetchPage));
|
||||
await waitFor(() => expect(result.current.state.status).toBe("loaded"));
|
||||
act(() => result.current.loadMore());
|
||||
act(() => result.current.loadMore());
|
||||
expect(fetchPage).toHaveBeenCalledTimes(2);
|
||||
await act(async () => {
|
||||
next.reject(new Error("offline"));
|
||||
await next.promise.catch(() => {});
|
||||
});
|
||||
expect(result.current.state).toMatchObject({
|
||||
data: { items: [1], page: 1, loadingMore: false },
|
||||
});
|
||||
});
|
||||
|
||||
test("a cached list shows as it was, and carries on from its page", async () => {
|
||||
const fetchPage = vi.fn((page: number) =>
|
||||
Promise.resolve({ items: [page], hasMore: false })
|
||||
);
|
||||
const { result } = renderHook(() =>
|
||||
usePagedList("k", fetchPage, {
|
||||
items: [1, 2],
|
||||
page: 2,
|
||||
hasMore: true,
|
||||
scrollY: 0,
|
||||
})
|
||||
);
|
||||
expect(result.current.state).toMatchObject({ data: { items: [1, 2] } });
|
||||
act(() => result.current.loadMore());
|
||||
await waitFor(() =>
|
||||
expect(result.current.state).toMatchObject({
|
||||
data: { items: [1, 2, 3] },
|
||||
})
|
||||
);
|
||||
expect(fetchPage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ describe("useFetchState", () => {
|
||||
test("loads once enabled, and only once per key", async () => {
|
||||
const load = vi.fn(() => Promise.resolve(1));
|
||||
const { result, rerender } = renderHook(
|
||||
({ enabled }) => useFetchState("a", load, enabled),
|
||||
({ enabled }) => useFetchState("a", load, { enabled }),
|
||||
{ initialProps: { enabled: false } },
|
||||
);
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
@@ -25,7 +25,7 @@ describe("useFetchState", () => {
|
||||
test("turning it off doesn't stop a load under way", async () => {
|
||||
const d = deferred<number>();
|
||||
const { result, rerender } = renderHook(
|
||||
({ enabled }) => useFetchState("a", () => d.promise, enabled),
|
||||
({ enabled }) => useFetchState("a", () => d.promise, { enabled }),
|
||||
{ initialProps: { enabled: true } },
|
||||
);
|
||||
rerender({ enabled: false });
|
||||
@@ -79,4 +79,18 @@ describe("useFetchState", () => {
|
||||
act(() => result.current.setData((xs) => [...xs, 2]));
|
||||
expect(result.current.state).toEqual({ status: "loaded", data: [1, 2] });
|
||||
});
|
||||
|
||||
test("an initial value starts loaded and loads nothing, for its key only", async () => {
|
||||
const load = vi.fn(() => Promise.resolve(2));
|
||||
const { result, rerender } = renderHook(
|
||||
({ key, initial }) => useFetchState(key, load, { initial }),
|
||||
{ initialProps: { key: "a", initial: 1 as number | undefined } },
|
||||
);
|
||||
expect(result.current.state).toEqual({ status: "loaded", data: 1 });
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
rerender({ key: "b", initial: undefined });
|
||||
await waitFor(() =>
|
||||
expect(result.current.state).toEqual({ status: "loaded", data: 2 })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user