v3: fix the frontend's findings, and the backend pieces they needed — each by a rule the code now keeps everywhere. Votes and likes go through one useOptimisticToggles in WSProvider: clicks on one item before any ack share one baseline, which a failure or the timeout restores (a second click used to cancel the first one's rollback), only the last ack's count is applied, a votes_update or comment_likes_update waits while this tab has toggles in flight, and a welcome reconciles them against the server's sets (a vote cast offline left its count one too high). lastLikeEvent, which nothing read, is gone. Follows are refetched when the new follows_changed message, sent to the follower's sockets on every follow write, says another tab changed them; a failed load keeps the Follow buttons disabled and is retried 10 s later instead of leaving them disabled for good (success: false) or enabled over empty sets (network error); follow and unfollow resolve to whether they worked, and the button says when they didn't. CategoriesProvider follows the same rule, so a network error no longer turns every category URL into a 404. Every list is kept by one rule: useDumpListSync and usePlaylistListSync never add an item, and usePositionAwareSync remembers the place of any item that leaves a list, whatever took it out, and puts it back when its next event shows it again; with dump_created now setting lastDumpEvent, a dump going private and back returns to its place on another user's profile, which never happened before, and an updated playlist missing from a list is no longer prepended. useFeedCache keys every cache by viewer (the profile pages restored the owner's private dumps to whoever went back) and reads it again when its key changes (another profile in the same page showed the previous one's list). Every response of a list's first page or next pages goes through expectOk (Index, UserPlaylists, useUserDumpFeed and Notifications read body.data unchecked).
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>
This commit is contained in:
@@ -65,7 +65,22 @@ export function Dump(): React.JSX.Element {
|
||||
const { selectedDump } = useParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const preloaded = (location.state as { dump?: Dump } | null)?.dump ?? null;
|
||||
// Taken once: it stays in the history entry, where a reload or Back would
|
||||
// show that snapshot forever, so it is cleared from there below.
|
||||
const [handedOver] = useState(
|
||||
() => (location.state as { dump?: Dump } | null)?.dump ?? null,
|
||||
);
|
||||
const preloaded = handedOver &&
|
||||
(handedOver.id === selectedDump || handedOver.slug === selectedDump)
|
||||
? handedOver
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (!(location.state as { dump?: Dump } | null)?.dump) return;
|
||||
navigate(`${location.pathname}${location.search}${location.hash}`, {
|
||||
replace: true,
|
||||
state: null,
|
||||
});
|
||||
}, [location, navigate]);
|
||||
|
||||
const [dumpState, setDumpState] = useState<DumpState>(
|
||||
preloaded ? { status: "loaded", dump: preloaded } : { status: "loading" },
|
||||
@@ -91,7 +106,7 @@ export function Dump(): React.JSX.Element {
|
||||
const [titleSaving, setTitleSaving] = useState(false);
|
||||
const [titleError, setTitleError] = useState<string | null>(null);
|
||||
|
||||
const { user, token, mediaToken, authFetch } = useAuth();
|
||||
const { user, mediaToken, authFetch } = useAuth();
|
||||
const { byId } = useCategories();
|
||||
const {
|
||||
voteCounts,
|
||||
@@ -578,7 +593,6 @@ export function Dump(): React.JSX.Element {
|
||||
dumpId={dump.id}
|
||||
comments={comments}
|
||||
currentUser={user}
|
||||
token={token}
|
||||
onCommentCreated={(c) =>
|
||||
setComments((prev) =>
|
||||
prev.some((x) => x.id === c.id) ? prev : [...prev, c]
|
||||
|
||||
@@ -10,7 +10,10 @@ import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import { VALIDATION } from "../../shared/validation.ts";
|
||||
import {
|
||||
DUMP_MAX_FILE_SIZE_BYTES,
|
||||
VALIDATION,
|
||||
} from "../../shared/validation.ts";
|
||||
import type { Dump, UpdateDumpRequest } from "../../shared/dump.ts";
|
||||
import type { Wire } from "../../shared/api.ts";
|
||||
import { deserializeDump } from "../utils/shared/deserialize.ts";
|
||||
@@ -20,6 +23,7 @@ import {
|
||||
parseAPIResponse,
|
||||
} from "../utils/shared/api.ts";
|
||||
import { useAuth, useRequiredAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { can } from "../utils/auth/permissions.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { formatBytes } from "../utils/shared/format.ts";
|
||||
import {
|
||||
@@ -50,17 +54,16 @@ type DumpEditState =
|
||||
| { status: "loaded"; dump: Dump };
|
||||
|
||||
/**
|
||||
* Renders `/dumps/:selectedDump/edit`, for a signed-in user. The page itself
|
||||
* doesn't check that the user may edit the dump: `Dump` links here only for
|
||||
* its poster and moderators, and the API refuses anyone else's changes. The
|
||||
* dump comes from `GET /api/dumps/:dumpId`. The thumbnail, the preview refresh
|
||||
* Renders `/dumps/:selectedDump/edit`, for the dump's poster and moderators;
|
||||
* anyone else signed in gets an error rather than a form the API would refuse
|
||||
* to save. The dump comes from `GET /api/dumps/:dumpId`. The thumbnail, the preview refresh
|
||||
* and the deletion apply at once, and the form's other fields on "Save", which
|
||||
* goes back to the dump's page. A deletion goes to the index.
|
||||
*/
|
||||
export function DumpEdit(): React.JSX.Element {
|
||||
const { selectedDump } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { authFetch, token, mediaToken } = useRequiredAuth();
|
||||
const { authFetch, token, mediaToken, user } = useRequiredAuth();
|
||||
|
||||
const [state, setState] = useState<DumpEditState>({ status: "loading" });
|
||||
|
||||
@@ -92,10 +95,16 @@ export function DumpEdit(): React.JSX.Element {
|
||||
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
|
||||
|
||||
if (apiResponse.success) {
|
||||
setState({
|
||||
status: "loaded",
|
||||
dump: deserializeDump(apiResponse.data),
|
||||
});
|
||||
const dump = deserializeDump(apiResponse.data);
|
||||
// The same rule as the API's.
|
||||
if (dump.userId !== user.id && !can(user, "dump:moderate")) {
|
||||
setState({
|
||||
status: "error",
|
||||
error: t`Only its poster or a moderator can edit this dump.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setState({ status: "loaded", dump });
|
||||
} else {
|
||||
setState({ status: "error", error: apiResponse.error.message });
|
||||
}
|
||||
@@ -103,7 +112,7 @@ export function DumpEdit(): React.JSX.Element {
|
||||
setState({ status: "error", error: friendlyFetchError(err) });
|
||||
}
|
||||
})();
|
||||
}, [selectedDump, token]);
|
||||
}, [selectedDump, token, user]);
|
||||
|
||||
const handleRefreshMetadata = async () => {
|
||||
if (state.status !== "loaded" || state.dump.kind !== "url") return;
|
||||
@@ -173,8 +182,7 @@ export function DumpEdit(): React.JSX.Element {
|
||||
setDeleteError(friendlyFetchError(err));
|
||||
return;
|
||||
}
|
||||
// Meant for Index, to hide the dump before `dump_deleted` arrives, but the
|
||||
// redirect from `/` doesn't pass the state on.
|
||||
// For Index, to hide the dump before `dump_deleted` arrives.
|
||||
navigate("/", { state: { deletedDumpId: state.dump.id } });
|
||||
};
|
||||
|
||||
@@ -471,6 +479,7 @@ function DumpEditForm({
|
||||
<FileField<EditValues>
|
||||
name="newFile"
|
||||
hint={t`Drop a replacement here`}
|
||||
maxBytes={DUMP_MAX_FILE_SIZE_BYTES}
|
||||
showLimit={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -31,7 +31,7 @@ import { deserializeDump, hydrateDump } from "../utils/shared/deserialize.ts";
|
||||
import type { Dump } from "../../shared/dump.ts";
|
||||
import type { PaginatedData, Wire } from "../../shared/api.ts";
|
||||
|
||||
import { friendlyFetchError } from "../utils/shared/api.ts";
|
||||
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
|
||||
import { useFeedCache } from "../hooks/feed/useFeedCache.ts";
|
||||
import { useScrollSave } from "../hooks/feed/useScrollSave.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
@@ -127,7 +127,7 @@ export function Index(
|
||||
);
|
||||
|
||||
const { cached, saveState } = useFeedCache<Dump>(
|
||||
`feed:index:${categorySlug ?? "all"}:${user?.id ?? "guest"}`,
|
||||
`feed:index:${categorySlug ?? "all"}`,
|
||||
hydrateDump,
|
||||
);
|
||||
const [dumpsState, setDumpsState] = useState<DumpsState>(() =>
|
||||
@@ -141,7 +141,6 @@ export function Index(
|
||||
}
|
||||
: { status: "loading" }
|
||||
);
|
||||
const mainFetchDone = useRef(false);
|
||||
|
||||
// The Web Share Target: Android's share sheet opens `/?share_url=…`, which
|
||||
// the redirect from `/` keeps. The query is dropped from the URL at once, so
|
||||
@@ -156,8 +155,7 @@ export function Index(
|
||||
}, [shareUrl, location.pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mainFetchDone.current || cached) return;
|
||||
mainFetchDone.current = true;
|
||||
if (cached) return;
|
||||
const controller = new AbortController();
|
||||
(async () => {
|
||||
try {
|
||||
@@ -165,9 +163,9 @@ export function Index(
|
||||
signal: controller.signal,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const body = await res.json();
|
||||
const { items, hasMore } = body.data as PaginatedData<Wire<Dump>>;
|
||||
const { items, hasMore } = await expectOk<
|
||||
PaginatedData<Wire<Dump>>
|
||||
>(res);
|
||||
setDumpsState({
|
||||
status: "loaded",
|
||||
dumps: items.map(deserializeDump),
|
||||
@@ -180,10 +178,7 @@ export function Index(
|
||||
setDumpsState({ status: "error", error: friendlyFetchError(err) });
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
mainFetchDone.current = false;
|
||||
controller.abort();
|
||||
};
|
||||
return () => controller.abort();
|
||||
}, [cached, token, feedUrl]);
|
||||
|
||||
const setDumpsItems = useCallback(
|
||||
@@ -207,9 +202,8 @@ export function Index(
|
||||
signal: controller.signal,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
const { items } = body.data as PaginatedData<Wire<Dump>>;
|
||||
.then((res) => expectOk<PaginatedData<Wire<Dump>>>(res))
|
||||
.then(({ items }) => {
|
||||
const fresh = items.map(deserializeDump);
|
||||
setDumpsState((s) => {
|
||||
if (s.status !== "loaded") return s;
|
||||
@@ -235,9 +229,8 @@ export function Index(
|
||||
fetch(feedUrl(nextPage), {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
const { items, hasMore } = body.data as PaginatedData<Wire<Dump>>;
|
||||
.then((res) => expectOk<PaginatedData<Wire<Dump>>>(res))
|
||||
.then(({ items, hasMore }) => {
|
||||
setDumpsState((s) =>
|
||||
s.status === "loaded"
|
||||
? {
|
||||
@@ -300,8 +293,8 @@ export function Index(
|
||||
);
|
||||
|
||||
const restIds = useMemo(() => new Set(dumps.map((d) => d.id)), [dumps]);
|
||||
// Dumps deleted since loading are dropped. `justDeletedId` never matches,
|
||||
// though: DumpEdit navigates to `/`, whose redirect drops the state.
|
||||
// Dumps deleted since loading are dropped, and the one the edit page just
|
||||
// deleted before its `dump_deleted` arrives.
|
||||
const combined = useMemo(
|
||||
() =>
|
||||
[...recentDumps.filter((d) => inScope(d) && !restIds.has(d.id)), ...dumps]
|
||||
@@ -358,7 +351,6 @@ export function Index(
|
||||
user={user}
|
||||
castVote={castVote}
|
||||
removeVote={removeVote}
|
||||
deletedDumpIds={deletedDumpIds}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
@@ -299,6 +299,15 @@ export function Notifications(): React.JSX.Element {
|
||||
arrived: [],
|
||||
});
|
||||
|
||||
// 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 () => {
|
||||
@@ -330,6 +339,7 @@ export function Notifications(): React.JSX.Element {
|
||||
}
|
||||
// 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",
|
||||
@@ -369,6 +379,8 @@ export function Notifications(): React.JSX.Element {
|
||||
const loaded = state.status === "loaded";
|
||||
useEffect(() => {
|
||||
if (!lastNotification || !loaded) return;
|
||||
if (markedReadRef.current === lastNotification) return;
|
||||
markedReadRef.current = lastNotification;
|
||||
authFetch(`${API_URL}/api/notifications/read-all`, { method: "POST" })
|
||||
.then((res) => {
|
||||
if (res.ok) clearUnreadNotifications();
|
||||
@@ -385,9 +397,8 @@ export function Notifications(): React.JSX.Element {
|
||||
authFetch(
|
||||
`${API_URL}/api/notifications?page=${nextPage}&limit=${NOTIFICATIONS_PAGE_SIZE}`,
|
||||
)
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
const data = body.data as PaginatedData<Wire<Notification>>;
|
||||
.then((res) => expectOk<PaginatedData<Wire<Notification>>>(res))
|
||||
.then((data) => {
|
||||
setState((s) =>
|
||||
s.status === "loaded"
|
||||
? {
|
||||
|
||||
@@ -125,9 +125,12 @@ export function PlaylistDetail(): React.JSX.Element {
|
||||
|
||||
// For the socket effects, which must not re-run when it changes.
|
||||
const activeDumpIdsRef = useRef(activeDumpIds);
|
||||
// Every dump seen in the playlist, so that one hidden when it turned private
|
||||
// comes back when it turns public.
|
||||
// Every dump of the playlist seen so far, so that one hidden when it turned
|
||||
// private comes back when it turns public. A dump removed from the playlist
|
||||
// leaves it.
|
||||
const knownDumpIdsRef = useRef<Set<string>>(new Set());
|
||||
// The removals still in flight, by dump, which an undo must wait for.
|
||||
const removalsRef = useRef<Map<string, Promise<unknown>>>(new Map());
|
||||
// The server's last order, where such a dump comes back.
|
||||
const dumpOrderRef = useRef<string[]>([]);
|
||||
|
||||
@@ -272,6 +275,9 @@ export function PlaylistDetail(): React.JSX.Element {
|
||||
|
||||
for (const id of prev) {
|
||||
if (!newIds.has(id)) {
|
||||
// Shown until now and gone from the list: removed from the
|
||||
// playlist, not hidden (that comes as `dump_deleted`).
|
||||
knownDumpIdsRef.current.delete(id);
|
||||
setActiveDumpIds((s) => {
|
||||
const n = new Set(s);
|
||||
n.delete(id);
|
||||
@@ -480,17 +486,31 @@ export function PlaylistDetail(): React.JSX.Element {
|
||||
};
|
||||
|
||||
const handleRemoveDump = (dumpId: string) => {
|
||||
if (!playlistId) return;
|
||||
if (!playlistId || state.status !== "loaded") return;
|
||||
const index = state.playlist.dumps.findIndex((d) => d.id === dumpId);
|
||||
const dump = state.playlist.dumps[index];
|
||||
knownDumpIdsRef.current.delete(dumpId);
|
||||
// Removed on the server at once; the undo adds it back.
|
||||
authFetch(`${API_URL}/api/playlists/${playlistId}/dumps/${dumpId}`, {
|
||||
method: "DELETE",
|
||||
}).then((res) => {
|
||||
const removal = authFetch(
|
||||
`${API_URL}/api/playlists/${playlistId}/dumps/${dumpId}`,
|
||||
{ method: "DELETE" },
|
||||
).then((res) => {
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
}).catch(() => {
|
||||
cancels.current.get(dumpId)?.();
|
||||
knownDumpIdsRef.current.add(dumpId);
|
||||
setActiveDumpIds((prev) => new Set([...prev, dumpId]));
|
||||
// The fade may have taken it out of the list already.
|
||||
setState((s) => {
|
||||
if (s.status !== "loaded" || !dump) return s;
|
||||
if (s.playlist.dumps.some((d) => d.id === dumpId)) return s;
|
||||
const dumps = [...s.playlist.dumps];
|
||||
dumps.splice(Math.min(index, dumps.length), 0, dump);
|
||||
return { ...s, playlist: { ...s.playlist, dumps } };
|
||||
});
|
||||
setActionError(t`The dump couldn't be removed. Try again.`);
|
||||
});
|
||||
}).finally(() => removalsRef.current.delete(dumpId));
|
||||
removalsRef.current.set(dumpId, removal);
|
||||
setActiveDumpIds((prev) => {
|
||||
const n = new Set(prev);
|
||||
n.delete(dumpId);
|
||||
@@ -510,23 +530,41 @@ export function PlaylistDetail(): React.JSX.Element {
|
||||
.filter((d) => restoredIds.has(d.id))
|
||||
.map((d) => d.id);
|
||||
pendingUndoOrderRef.current = desiredOrder;
|
||||
knownDumpIdsRef.current.add(dumpId);
|
||||
// Added back only once the removal has landed, or the two could cross.
|
||||
// The server adds the dump first, so the order is restored after.
|
||||
authFetch(`${API_URL}/api/playlists/${playlistId}/dumps/${dumpId}`, {
|
||||
method: "POST",
|
||||
})
|
||||
(removalsRef.current.get(dumpId) ?? Promise.resolve())
|
||||
.then(() =>
|
||||
authFetch(`${API_URL}/api/playlists/${playlistId}/order`, {
|
||||
authFetch(`${API_URL}/api/playlists/${playlistId}/dumps/${dumpId}`, {
|
||||
method: "POST",
|
||||
})
|
||||
)
|
||||
.then((res) => {
|
||||
// 409: the removal failed, so it never left.
|
||||
if (!res.ok && res.status !== 409) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
return authFetch(`${API_URL}/api/playlists/${playlistId}/order`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(
|
||||
{ dumpIds: desiredOrder } satisfies ReorderPlaylistRequest,
|
||||
),
|
||||
})
|
||||
)
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
knownDumpIdsRef.current.delete(dumpId);
|
||||
setActiveDumpIds((prev) => {
|
||||
const n = new Set(prev);
|
||||
n.delete(dumpId);
|
||||
return n;
|
||||
});
|
||||
startFade(dumpId);
|
||||
setActionError(t`The dump couldn't be put back. Try again.`);
|
||||
})
|
||||
.finally(() => {
|
||||
pendingUndoOrderRef.current = null;
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
};
|
||||
|
||||
const openEdit = () => setEditOpen(true);
|
||||
@@ -817,6 +855,12 @@ function PlaylistEditForm(
|
||||
) {
|
||||
const { authFetch, mediaToken } = useAuth();
|
||||
const [imagePreview, setImagePreview] = useState<string | null>(null);
|
||||
// Each preview holds the file in memory until its URL is revoked: when the
|
||||
// next one replaces it, or when the form closes.
|
||||
useEffect(() => {
|
||||
if (!imagePreview) return;
|
||||
return () => URL.revokeObjectURL(imagePreview);
|
||||
}, [imagePreview]);
|
||||
const form = useApiForm<EditValues>({
|
||||
defaultValues: {
|
||||
title: playlist.title,
|
||||
|
||||
@@ -51,13 +51,10 @@ export function UserDumps(): React.JSX.Element {
|
||||
dumpItems,
|
||||
setItems,
|
||||
lastDumpEvent,
|
||||
(d) => d.isPrivate,
|
||||
(d) => !d.isPrivate && d.userId === profileUserId,
|
||||
);
|
||||
useDumpListSync(setItems, {
|
||||
ownerId: profileUserId ?? undefined,
|
||||
isOwner: isOwnProfile,
|
||||
skipReinsert: true,
|
||||
});
|
||||
|
||||
if (state.status === "loading") {
|
||||
|
||||
@@ -120,13 +120,11 @@ export function UserPlaylists(): React.JSX.Element {
|
||||
createdItems,
|
||||
setCreated,
|
||||
lastPlaylistItem,
|
||||
(p) => !p.isPublic,
|
||||
(p) => p.isPublic && p.userId === profileUserId,
|
||||
);
|
||||
usePlaylistListSync(setCreated, {
|
||||
isOwner: isOwnProfile,
|
||||
ownerId: profileUserId ?? undefined,
|
||||
skipReinsert: true,
|
||||
});
|
||||
|
||||
const setFollowed = useCallback((fn: (prev: Playlist[]) => Playlist[]) => {
|
||||
@@ -234,9 +232,8 @@ export function UserPlaylists(): React.JSX.Element {
|
||||
`${API_URL}/api/users/${username}/playlists?page=${nextPage}&limit=${DEFAULT_PAGE_SIZE}`,
|
||||
{ headers: token ? { Authorization: `Bearer ${token}` } : {} },
|
||||
)
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
const { items, hasMore } = body.data as PaginatedData<Wire<Playlist>>;
|
||||
.then((res) => expectOk<PaginatedData<Wire<Playlist>>>(res))
|
||||
.then(({ items, hasMore }) => {
|
||||
setState((s) =>
|
||||
s.status === "loaded"
|
||||
? {
|
||||
@@ -274,9 +271,8 @@ export function UserPlaylists(): React.JSX.Element {
|
||||
fetch(
|
||||
`${API_URL}/api/users/${username}/followed-playlists?page=${nextPage}&limit=${DEFAULT_PAGE_SIZE}`,
|
||||
)
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
const { items, hasMore } = body.data as PaginatedData<Wire<Playlist>>;
|
||||
.then((res) => expectOk<PaginatedData<Wire<Playlist>>>(res))
|
||||
.then(({ items, hasMore }) => {
|
||||
setState((s) =>
|
||||
s.status === "loaded"
|
||||
? {
|
||||
|
||||
@@ -337,13 +337,10 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
dumpItems,
|
||||
setDumps,
|
||||
lastDumpEvent,
|
||||
(d) => d.isPrivate,
|
||||
(d) => !d.isPrivate && d.userId === profileUserId,
|
||||
);
|
||||
useDumpListSync(setDumps, {
|
||||
ownerId: profileUserId ?? undefined,
|
||||
isOwner: isOwnProfile,
|
||||
skipReinsert: true,
|
||||
});
|
||||
|
||||
// A withdrawn vote leaves its dump in the list, for UpvotedDumpList to fade
|
||||
@@ -362,10 +359,9 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
voteItems,
|
||||
setVotes,
|
||||
lastDumpEvent,
|
||||
(d) => d.isPrivate,
|
||||
(d) => !d.isPrivate && !withdrawnVoteIdsRef.current.has(d.id),
|
||||
);
|
||||
useDumpListSync(setVotes, { skipReinsert: true });
|
||||
useDumpListSync(setVotes);
|
||||
|
||||
const setPlaylists = useCallback((fn: (prev: Playlist[]) => Playlist[]) => {
|
||||
setState((s) =>
|
||||
@@ -382,13 +378,11 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
playlistItems,
|
||||
setPlaylists,
|
||||
lastPlaylistItem,
|
||||
(p) => !p.isPublic,
|
||||
(p) => p.isPublic && p.userId === profileUserId,
|
||||
);
|
||||
usePlaylistListSync(setPlaylists, {
|
||||
isOwner: isOwnProfile,
|
||||
ownerId: profileUserId ?? undefined,
|
||||
skipReinsert: true,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -591,7 +585,10 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
withdrawnVoteIdsRef.current.add(dumpId);
|
||||
} else {
|
||||
withdrawnVoteIdsRef.current.delete(dumpId);
|
||||
fetch(`${API_URL}/api/dumps/${dumpId}`)
|
||||
// Signed in, or a private dump the viewer owns can't be fetched.
|
||||
fetch(`${API_URL}/api/dumps/${dumpId}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
if (!body.success) return;
|
||||
@@ -613,7 +610,7 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}, [lastVoteEvent, profileUserId]);
|
||||
}, [lastVoteEvent, profileUserId, token]);
|
||||
|
||||
// Saves the lists and the scroll position, so that Back restores both.
|
||||
useEffect(() => {
|
||||
@@ -654,6 +651,16 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
);
|
||||
}, [playlistFeed, savePlaylists]);
|
||||
|
||||
// The two lazy tabs' fetches aren't aborted when the user switches tabs:
|
||||
// they finish in the background. Only another profile or leaving the page
|
||||
// aborts them, since their state is reset then anyway.
|
||||
const followedFetchRef = useRef<AbortController | null>(null);
|
||||
const inviteesFetchRef = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => {
|
||||
followedFetchRef.current?.abort();
|
||||
inviteesFetchRef.current?.abort();
|
||||
}, [username]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
tab !== "followed" || followedState !== null || state.status !== "loaded"
|
||||
@@ -663,6 +670,7 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
// Deferred, since the lint forbids a setState in an effect's body.
|
||||
queueMicrotask(() => setFollowedState({ status: "loading" }));
|
||||
const controller = new AbortController();
|
||||
followedFetchRef.current = controller;
|
||||
Promise.all([
|
||||
fetch(
|
||||
`${API_URL}/api/users/${username}/followed-users?page=1&limit=${DEFAULT_PAGE_SIZE}`,
|
||||
@@ -697,9 +705,8 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
if (err.name === "AbortError") return;
|
||||
setFollowedState({ status: "error", error: friendlyFetchError(err) });
|
||||
});
|
||||
return () => controller.abort();
|
||||
// followedState only guards the first fetch. As a dependency, its change
|
||||
// to "loading" would abort that fetch.
|
||||
// followedState only guards the first fetch; as a dependency, its change
|
||||
// to "loading" would run this again.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tab, state.status, username]);
|
||||
|
||||
@@ -712,6 +719,7 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
}
|
||||
queueMicrotask(() => setInviteTreeState({ status: "loading" }));
|
||||
const controller = new AbortController();
|
||||
inviteesFetchRef.current = controller;
|
||||
fetch(
|
||||
`${API_URL}/api/users/${username}/invitees`,
|
||||
{ signal: controller.signal },
|
||||
@@ -727,7 +735,6 @@ export function UserPublicProfile(): React.JSX.Element {
|
||||
if (err.name === "AbortError") return;
|
||||
setInviteTreeState({ status: "error", error: friendlyFetchError(err) });
|
||||
});
|
||||
return () => controller.abort();
|
||||
// inviteTreeState only guards the first fetch, as followedState above.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tab, state.status, username]);
|
||||
|
||||
@@ -66,11 +66,18 @@ export function UserRegister(): React.JSX.Element {
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
fetch(`${API_URL}/api/invites/${encodeURIComponent(token)}`)
|
||||
// Aborted for a newer token, whose answer alone may land.
|
||||
const controller = new AbortController();
|
||||
fetch(`${API_URL}/api/invites/${encodeURIComponent(token)}`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((r) => {
|
||||
setTokenState(r.ok ? { status: "valid" } : { status: "invalid" });
|
||||
})
|
||||
.catch(() => setTokenState({ status: "invalid" }));
|
||||
.catch((err) => {
|
||||
if (err.name !== "AbortError") setTokenState({ status: "invalid" });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [token]);
|
||||
|
||||
const onSubmit = form.submit(async ({ username, email, password }) => {
|
||||
|
||||
@@ -32,7 +32,7 @@ import { PageError } from "../components/layout/PageError.tsx";
|
||||
*/
|
||||
export function UserUpvoted(): React.JSX.Element {
|
||||
const { username } = useParams();
|
||||
const { user: me } = useAuth();
|
||||
const { user: me, token } = useAuth();
|
||||
const { voteCounts, myVotes, lastVoteEvent, castVote, removeVote } = useWS();
|
||||
|
||||
useDocumentTitle(username ?? null);
|
||||
@@ -124,7 +124,10 @@ export function UserUpvoted(): React.JSX.Element {
|
||||
} else {
|
||||
setVotedIds((prev) => new Set([...prev, dumpId]));
|
||||
cancelFading(dumpId);
|
||||
fetch(`${API_URL}/api/dumps/${dumpId}`)
|
||||
// Signed in, or a private dump the viewer owns can't be fetched.
|
||||
fetch(`${API_URL}/api/dumps/${dumpId}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then((body) => {
|
||||
if (!body.success) return;
|
||||
@@ -138,7 +141,14 @@ export function UserUpvoted(): React.JSX.Element {
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}, [lastVoteEvent, profileUserId, startFading, cancelFading, setState]);
|
||||
}, [
|
||||
lastVoteEvent,
|
||||
profileUserId,
|
||||
startFading,
|
||||
cancelFading,
|
||||
setState,
|
||||
token,
|
||||
]);
|
||||
|
||||
if (state.status === "loading") {
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user