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:
@@ -6,7 +6,7 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
@@ -31,23 +31,10 @@ import type {
|
||||
UserFollowedData,
|
||||
UserMentionedData,
|
||||
} from "../../shared/notification.ts";
|
||||
import type { PaginatedData, Wire } from "../../shared/api.ts";
|
||||
import { deserializeNotification } from "../utils/shared/deserialize.ts";
|
||||
import { pageUrl, readPage } from "../utils/feed/pagedList.ts";
|
||||
import { usePagedList } from "../hooks/feed/usePagedList.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
|
||||
|
||||
type State =
|
||||
// `arrived` holds what the socket sent before the list came back, which the
|
||||
// list may predate.
|
||||
| { status: "loading"; arrived: Notification[] }
|
||||
| { status: "error"; error: string }
|
||||
| {
|
||||
status: "loaded";
|
||||
items: Notification[];
|
||||
hasMore: boolean;
|
||||
page: number;
|
||||
loadingMore: boolean;
|
||||
};
|
||||
|
||||
type NotifIconKind =
|
||||
| "upvote"
|
||||
@@ -293,94 +280,41 @@ function groupByDate(
|
||||
*/
|
||||
export function Notifications(): React.JSX.Element {
|
||||
useDocumentTitle(t`Notifications`);
|
||||
const { authFetch } = useAuth();
|
||||
const { user, authFetch } = useAuth();
|
||||
const { clearUnreadNotifications, lastNotification } = useWS();
|
||||
const [state, setState] = useState<State>({
|
||||
status: "loading",
|
||||
arrived: [],
|
||||
});
|
||||
const { state, loadMore } = usePagedList(
|
||||
user?.id,
|
||||
(page, signal) =>
|
||||
authFetch(
|
||||
pageUrl(`${API_URL}/api/notifications`, page, NOTIFICATIONS_PAGE_SIZE),
|
||||
{ signal },
|
||||
).then((res) => readPage(res, deserializeNotification)),
|
||||
);
|
||||
|
||||
// The latest notification the read-all requests have covered, so that one
|
||||
// arriving while the page is open is marked read once, and the one the bell
|
||||
// already had isn't marked again after the first load.
|
||||
const lastNotificationRef = useRef(lastNotification);
|
||||
const markedReadRef = useRef(lastNotification);
|
||||
useLayoutEffect(() => {
|
||||
lastNotificationRef.current = lastNotification;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const data = await expectOk<PaginatedData<Wire<Notification>>>(
|
||||
await authFetch(
|
||||
`${API_URL}/api/notifications?page=1&limit=${NOTIFICATIONS_PAGE_SIZE}`,
|
||||
),
|
||||
);
|
||||
if (cancelled) return;
|
||||
const items = data.items.map(deserializeNotification);
|
||||
setState((s) => ({
|
||||
status: "loaded",
|
||||
items: [
|
||||
...(s.status === "loading" ? s.arrived : []).filter((a) =>
|
||||
!items.some((n) => n.id === a.id)
|
||||
),
|
||||
...items,
|
||||
],
|
||||
hasMore: data.hasMore,
|
||||
page: 1,
|
||||
loadingMore: false,
|
||||
}));
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setState({ status: "error", error: friendlyFetchError(err) });
|
||||
}
|
||||
return;
|
||||
}
|
||||
// If this fails, the list is still worth showing, and they stay unread
|
||||
// for next time.
|
||||
markedReadRef.current = lastNotificationRef.current;
|
||||
try {
|
||||
const res = await authFetch(`${API_URL}/api/notifications/read-all`, {
|
||||
method: "POST",
|
||||
});
|
||||
if (cancelled || !res.ok) return;
|
||||
// Only the bell clears. Marking the list read too would take its dots
|
||||
// and "new" count away a moment after they appear.
|
||||
clearUnreadNotifications();
|
||||
} catch {
|
||||
// Offline: they stay unread for next time.
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [authFetch, clearUnreadNotifications]);
|
||||
|
||||
// Each new `lastNotification` is added once, during render rather than in an
|
||||
// effect, so it shows in the same frame.
|
||||
// Each new `lastNotification` is kept once, during render rather than in an
|
||||
// effect, so it shows in the same frame. The list may predate it or not.
|
||||
const [arrived, setArrived] = useState<Notification[]>([]);
|
||||
const [prevLastNotification, setPrevLastNotification] = useState(
|
||||
lastNotification,
|
||||
);
|
||||
if (prevLastNotification !== lastNotification && lastNotification !== null) {
|
||||
setPrevLastNotification(lastNotification);
|
||||
setState((s) => {
|
||||
if (s.status === "loading") {
|
||||
return { ...s, arrived: [lastNotification, ...s.arrived] };
|
||||
}
|
||||
if (s.status !== "loaded") return s;
|
||||
if (s.items.some((n) => n.id === lastNotification.id)) return s;
|
||||
return { ...s, items: [lastNotification, ...s.items] };
|
||||
});
|
||||
setArrived((a) => [lastNotification, ...a]);
|
||||
}
|
||||
const items = useMemo(() => {
|
||||
if (state.status !== "loaded") return [];
|
||||
const listed = new Set(state.data.items.map((n) => n.id));
|
||||
return [...arrived.filter((n) => !listed.has(n.id)), ...state.data.items];
|
||||
}, [state, arrived]);
|
||||
|
||||
// One that arrives while the page is open is being seen: it stays
|
||||
// highlighted here, but the bell must not count it.
|
||||
// Every notification is marked read on the server once the list shows, and
|
||||
// again for each that arrives while the page is open. Only the bell clears:
|
||||
// clearing the list too would take its dots and "new" count away a moment
|
||||
// after they appear. A failure leaves them unread for next time.
|
||||
const loaded = state.status === "loaded";
|
||||
const markedReadRef = useRef<Notification | null | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (!lastNotification || !loaded) return;
|
||||
if (markedReadRef.current === lastNotification) return;
|
||||
if (!loaded || markedReadRef.current === lastNotification) return;
|
||||
markedReadRef.current = lastNotification;
|
||||
authFetch(`${API_URL}/api/notifications/read-all`, { method: "POST" })
|
||||
.then((res) => {
|
||||
@@ -389,39 +323,7 @@ export function Notifications(): React.JSX.Element {
|
||||
.catch(() => {});
|
||||
}, [lastNotification, loaded, authFetch, clearUnreadNotifications]);
|
||||
|
||||
const loadMore = () => {
|
||||
if (state.status !== "loaded" || !state.hasMore || state.loadingMore) {
|
||||
return;
|
||||
}
|
||||
const nextPage = state.page + 1;
|
||||
setState((s) => s.status === "loaded" ? { ...s, loadingMore: true } : s);
|
||||
authFetch(
|
||||
`${API_URL}/api/notifications?page=${nextPage}&limit=${NOTIFICATIONS_PAGE_SIZE}`,
|
||||
)
|
||||
.then((res) => expectOk<PaginatedData<Wire<Notification>>>(res))
|
||||
.then((data) => {
|
||||
setState((s) =>
|
||||
s.status === "loaded"
|
||||
? {
|
||||
...s,
|
||||
items: [...s.items, ...data.items.map(deserializeNotification)],
|
||||
hasMore: data.hasMore,
|
||||
page: nextPage,
|
||||
loadingMore: false,
|
||||
}
|
||||
: s
|
||||
);
|
||||
})
|
||||
.catch(() =>
|
||||
setState((s) =>
|
||||
s.status === "loaded" ? { ...s, loadingMore: false } : s
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const totalUnread = state.status === "loaded"
|
||||
? state.items.filter((n) => !n.read).length
|
||||
: 0;
|
||||
const totalUnread = items.filter((n) => !n.read).length;
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
@@ -447,7 +349,7 @@ export function Notifications(): React.JSX.Element {
|
||||
<ErrorCard title={t`Failed to load`} message={state.error} />
|
||||
)}
|
||||
|
||||
{state.status === "loaded" && state.items.length === 0 && (
|
||||
{state.status === "loaded" && items.length === 0 && (
|
||||
<div className="notifications-empty">
|
||||
<span className="notifications-empty-icon">🔕</span>
|
||||
<p>
|
||||
@@ -462,8 +364,8 @@ export function Notifications(): React.JSX.Element {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state.status === "loaded" && state.items.length > 0 &&
|
||||
groupByDate(state.items).map(({ label, items }) => (
|
||||
{state.status === "loaded" && items.length > 0 &&
|
||||
groupByDate(items).map(({ label, items }) => (
|
||||
<section key={label} className="notif-group">
|
||||
<h2 className="notif-group-label">
|
||||
{label === "Today"
|
||||
@@ -508,8 +410,11 @@ export function Notifications(): React.JSX.Element {
|
||||
</section>
|
||||
))}
|
||||
|
||||
{state.status === "loaded" && state.hasMore && (
|
||||
<LoadMoreButton loadingMore={state.loadingMore} onClick={loadMore} />
|
||||
{state.status === "loaded" && state.data.hasMore && (
|
||||
<LoadMoreButton
|
||||
loadingMore={state.data.loadingMore}
|
||||
onClick={loadMore}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</PageShell>
|
||||
|
||||
Reference in New Issue
Block a user