Smaller fixes: the redirects from / and /<slug> keep the navigation state, so the index hides the dump DumpEdit just deleted; Index's mainFetchDone ref, which blocked nothing, is gone; DumpEdit refuses someone else's dump up front, as the API does; the Dump page takes a handed-over dump once and clears it from the history entry, so a reload fetches; a newly upvoted dump is fetched with the viewer's token; the notifications page sends read-all once per notification; the profile's followed and invitees tabs finish loading when left mid-fetch; UserListPopover no longer closes when its own list scrolls; the vote and like counts open their lists for visitors too (a disabled button swallowed the click; they are aria-disabled now); the removal of a playlist's dump forgets it (an edit brought it back), a failed removal puts it back where it was, an undo waits for the removal in flight, and a refused undo says so; PlaylistCreateForm tells whether the dump made it into the new playlist; the cover preview's object URL is revoked; the muted icon has its cross; the bell no longer stays rung after two notifications within 700 ms; a stale invite check can't overwrite a newer one; a stored theme or color scheme is checked; the default feed tab is one store every reader follows, across tabs; the file fields enforce the size they state, derived from DUMP_MAX_FILE_SIZE_BYTES; formatBytes, friendlyFetchError and ImagePicker are translated (Intl names the units), and ImagePicker ignores keys while uploading; visited dumps and playlists keep a week of visits and are parsed once; a chime is claimed under a Web Lock, so two tabs can't both play it; a date in the future reads as "now". Dead code goes: PageShell's centerSlot, overLimit, the exports of isSafeHex and hueFromString, the comment tree's token prop and ChatContext's isChatOpen and closeChat. The French catalogue has the 11 new messages. 214 backend and 632 frontend tests pass; tsc, deno lint, ESLint and doc:lint are clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
213 lines
6.9 KiB
TypeScript
213 lines
6.9 KiB
TypeScript
/**
|
|
* Loads a user's dumps or upvoted dumps, a page at a time, for the profile
|
|
* subpages that list them in full.
|
|
*
|
|
* @module
|
|
*/
|
|
|
|
import {
|
|
type RefCallback,
|
|
useCallback,
|
|
useEffect,
|
|
useLayoutEffect,
|
|
useRef,
|
|
useState,
|
|
} from "react";
|
|
|
|
import { API_URL, DEFAULT_PAGE_SIZE } from "../../config/api.ts";
|
|
import { expectOk, friendlyFetchError } from "../../utils/shared/api.ts";
|
|
import type { Dump } from "../../../shared/dump.ts";
|
|
import type { PaginatedData, Wire } from "../../../shared/api.ts";
|
|
import type { PublicUser } from "../../../shared/user.ts";
|
|
import {
|
|
deserializeDump,
|
|
deserializePublicUser,
|
|
hydrateDump,
|
|
} from "../../utils/shared/deserialize.ts";
|
|
import { useAuth } from "../auth/useAuth.ts";
|
|
import { useFeedCache } from "../feed/useFeedCache.ts";
|
|
import { useInfiniteScroll } from "../feed/useInfiniteScroll.ts";
|
|
import { useScrollSave } from "../feed/useScrollSave.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 =
|
|
| { status: "loading" }
|
|
| { status: "error"; error: string }
|
|
| {
|
|
status: "loaded";
|
|
profileUser: PublicUser;
|
|
items: Dump[];
|
|
hasMore: boolean;
|
|
page: number;
|
|
loadingMore: boolean;
|
|
};
|
|
|
|
/** Passed to {@link useUserDumpFeed} by `UserUpvoted`. */
|
|
export interface UseUserDumpFeedOptions {
|
|
/** Called with the dumps of each page after the first, once appended. */
|
|
onItemsAppended?: (items: Dump[]) => void;
|
|
}
|
|
|
|
/** Returned by {@link useUserDumpFeed} to `UserDumps` and `UserUpvoted`. */
|
|
export interface UseUserDumpFeedResult {
|
|
state: UserDumpFeedState;
|
|
/** Lets `UserUpvoted` prepend a dump the user just upvoted. */
|
|
setState: React.Dispatch<React.SetStateAction<UserDumpFeedState>>;
|
|
/** Does nothing until loaded. Passed to `useDumpListSync`. */
|
|
setItems: (fn: (prev: Dump[]) => Dump[]) => void;
|
|
/** From `useInfiniteScroll`, for an element after the last card. */
|
|
sentinelRef: RefCallback<HTMLDivElement>;
|
|
}
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
export function useUserDumpFeed(
|
|
username: string | undefined,
|
|
endpoint: string,
|
|
cacheKey: string,
|
|
options?: UseUserDumpFeedOptions,
|
|
): UseUserDumpFeedResult {
|
|
const { token } = 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 setItems = useCallback((fn: (prev: Dump[]) => Dump[]) => {
|
|
setState((s) => s.status !== "loaded" ? s : { ...s, items: fn(s.items) });
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!username) return;
|
|
const controller = new AbortController();
|
|
|
|
if (cached) {
|
|
fetch(`${API_URL}/api/users/${username}`, { signal: controller.signal })
|
|
.then((r) => r.json())
|
|
.then((body) => {
|
|
if (!body.success) throw new Error("User not found");
|
|
setState({
|
|
status: "loaded",
|
|
profileUser: deserializePublicUser(body.data),
|
|
items: cached.items,
|
|
hasMore: cached.hasMore,
|
|
page: cached.page,
|
|
loadingMore: false,
|
|
});
|
|
})
|
|
.catch((err) => {
|
|
if (err.name === "AbortError") return;
|
|
setState({ status: "error", error: friendlyFetchError(err) });
|
|
});
|
|
return () => controller.abort();
|
|
}
|
|
|
|
const authHeaders: HeadersInit = token
|
|
? { Authorization: `Bearer ${token}` }
|
|
: {};
|
|
Promise.all([
|
|
fetch(`${API_URL}/api/users/${username}`, { signal: controller.signal }),
|
|
fetch(
|
|
`${API_URL}/api/users/${username}/${endpoint}?page=1&limit=${DEFAULT_PAGE_SIZE}`,
|
|
{ headers: authHeaders, signal: controller.signal },
|
|
),
|
|
])
|
|
.then(([userRes, itemsRes]) =>
|
|
Promise.all([userRes.json(), itemsRes.json()])
|
|
)
|
|
.then(([userBody, itemsBody]) => {
|
|
if (!userBody.success) throw new Error("User not found");
|
|
const { items, hasMore } = itemsBody.success
|
|
? itemsBody.data as PaginatedData<Wire<Dump>>
|
|
: { items: [], hasMore: false };
|
|
setState({
|
|
status: "loaded",
|
|
profileUser: deserializePublicUser(userBody.data),
|
|
items: items.map(deserializeDump),
|
|
hasMore,
|
|
page: 1,
|
|
loadingMore: false,
|
|
});
|
|
})
|
|
.catch((err) => {
|
|
if (err.name === "AbortError") return;
|
|
setState({ status: "error", error: friendlyFetchError(err) });
|
|
});
|
|
return () => controller.abort();
|
|
}, [username, endpoint, cached, token]);
|
|
|
|
const { onItemsAppended } = options ?? {};
|
|
|
|
const loadMore = useCallback(() => {
|
|
if (
|
|
state.status !== "loaded" || !state.hasMore || state.loadingMore ||
|
|
!username
|
|
) return;
|
|
const nextPage = state.page + 1;
|
|
setState((s) => s.status === "loaded" ? { ...s, loadingMore: true } : s);
|
|
fetch(
|
|
`${API_URL}/api/users/${username}/${endpoint}?page=${nextPage}&limit=${DEFAULT_PAGE_SIZE}`,
|
|
{ headers: token ? { Authorization: `Bearer ${token}` } : {} },
|
|
)
|
|
.then((res) => expectOk<PaginatedData<Wire<Dump>>>(res))
|
|
.then(({ items, hasMore }) => {
|
|
const newItems = items.map(deserializeDump);
|
|
setState((s) =>
|
|
s.status === "loaded"
|
|
? {
|
|
...s,
|
|
items: [...s.items, ...newItems],
|
|
hasMore,
|
|
page: nextPage,
|
|
loadingMore: false,
|
|
}
|
|
: s
|
|
);
|
|
onItemsAppended?.(newItems);
|
|
})
|
|
.catch(() =>
|
|
setState((s) =>
|
|
s.status === "loaded" ? { ...s, loadingMore: false } : s
|
|
)
|
|
);
|
|
}, [state, username, token, endpoint, onItemsAppended]);
|
|
|
|
const sentinelRef = useInfiniteScroll(
|
|
loadMore,
|
|
state.status === "loaded" && state.hasMore && !state.loadingMore,
|
|
);
|
|
|
|
useScrollSave(
|
|
state.status === "loaded",
|
|
useCallback((y) => {
|
|
if (state.status !== "loaded") return;
|
|
saveState(state.items, state.page, state.hasMore, y);
|
|
}, [state, saveState]),
|
|
);
|
|
|
|
const scrollRestored = useRef(false);
|
|
useLayoutEffect(() => {
|
|
if (cached?.scrollY == null || scrollRestored.current) return;
|
|
if (state.status === "loaded") {
|
|
globalThis.scrollTo(0, cached.scrollY);
|
|
scrollRestored.current = true;
|
|
}
|
|
}, [state.status, cached]);
|
|
|
|
return { state, setState, setItems, sentinelRef };
|
|
}
|