v3: code quality pass, various bug fixes
This commit is contained in:
@@ -2,28 +2,39 @@ import { useEffect, useLayoutEffect, useRef } from "react";
|
||||
import type { Dump } from "../model.ts";
|
||||
import { useWS } from "./useWS.ts";
|
||||
|
||||
interface DumpListSyncOptions {
|
||||
/** Keep private dumps visible (caller is the owner). */
|
||||
isOwner?: boolean;
|
||||
/**
|
||||
* Only re-insert dumps created by this user when they become visible again.
|
||||
* Leave undefined to never re-insert (caller handles it, or no re-insertion needed).
|
||||
*/
|
||||
ownerId?: string;
|
||||
/**
|
||||
* When true, don't re-add a dump that isn't in the list (idx === -1).
|
||||
* Use this when the caller handles re-insertion itself (e.g. with a position map).
|
||||
*/
|
||||
skipReinsert?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a dump list in sync with real-time WS events:
|
||||
* - deletedDumpIds: filters out dumps that were deleted or privatised.
|
||||
* - lastDumpEvent: updates existing dumps in-place; optionally prepends
|
||||
* new ones when `addFilter` returns true for them.
|
||||
*
|
||||
* @param setDumps Updater that patches the caller's dump array.
|
||||
* @param addFilter Optional predicate: return true to prepend a dump that
|
||||
* isn't already in the list (e.g. became public).
|
||||
* - deletedDumpIds growing → filter
|
||||
* - lastDumpEvent "updated" → update in-place, or remove if now private
|
||||
* - lastDumpEvent for a not-in-list dump → prepend if ownerId matches and visible
|
||||
*/
|
||||
export function useDumpListSync(
|
||||
setDumps: (fn: (prev: Dump[]) => Dump[]) => void,
|
||||
addFilter?: (dump: Dump) => boolean,
|
||||
options?: DumpListSyncOptions,
|
||||
): void {
|
||||
const { deletedDumpIds, lastDumpEvent } = useWS();
|
||||
|
||||
// Keep refs up-to-date so closures in effects are never stale.
|
||||
const setDumpsRef = useRef(setDumps);
|
||||
const addFilterRef = useRef(addFilter);
|
||||
const optionsRef = useRef(options);
|
||||
useLayoutEffect(() => {
|
||||
setDumpsRef.current = setDumps;
|
||||
addFilterRef.current = addFilter;
|
||||
optionsRef.current = options;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -35,17 +46,27 @@ export function useDumpListSync(
|
||||
|
||||
useEffect(() => {
|
||||
if (!lastDumpEvent) return;
|
||||
const { isOwner, ownerId, skipReinsert } = optionsRef.current ?? {};
|
||||
const dump = lastDumpEvent;
|
||||
|
||||
setDumpsRef.current((prev) => {
|
||||
const idx = prev.findIndex((d) => d.id === lastDumpEvent.id);
|
||||
const idx = prev.findIndex((d) => d.id === dump.id);
|
||||
|
||||
if (idx !== -1) {
|
||||
// Remove if it became private and the viewer can't see private dumps.
|
||||
if (dump.isPrivate && !isOwner) {
|
||||
return prev.filter((d) => d.id !== dump.id);
|
||||
}
|
||||
const next = [...prev];
|
||||
next[idx] = lastDumpEvent;
|
||||
next[idx] = dump;
|
||||
return next;
|
||||
}
|
||||
if (addFilterRef.current?.(lastDumpEvent)) {
|
||||
return [lastDumpEvent, ...prev];
|
||||
}
|
||||
return prev;
|
||||
|
||||
// Dump not in list: only re-insert when ownerId is set and matches.
|
||||
if (skipReinsert || !ownerId) return prev;
|
||||
if (dump.userId !== ownerId) return prev;
|
||||
if (dump.isPrivate && !isOwner) return prev;
|
||||
return [dump, ...prev];
|
||||
});
|
||||
}, [lastDumpEvent]);
|
||||
}
|
||||
|
||||
78
src/hooks/useFading.ts
Normal file
78
src/hooks/useFading.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
/**
|
||||
* Manages a 2-second cooldown + 350ms dismissal animation for a set of items.
|
||||
*
|
||||
* Call `startFading(id)` when an item should begin fading out.
|
||||
* Call `cancelFading(id)` to abort the animation (e.g. the action was reversed).
|
||||
* Use the returned `fading` record to apply CSS classes:
|
||||
* - `"cooldown"` → item is in the 2-second grace period (darkened)
|
||||
* - `"dismissing"` → item is collapsing (opacity 0 + grid-row collapse)
|
||||
*/
|
||||
export function useFading() {
|
||||
const [fading, setFading] = useState<
|
||||
Record<string, "cooldown" | "dismissing">
|
||||
>({});
|
||||
const cancels = useRef<Map<string, () => void>>(new Map());
|
||||
|
||||
useEffect(() => () => {
|
||||
cancels.current.forEach((c) => c());
|
||||
}, []);
|
||||
|
||||
const startFading = useCallback((id: string) => {
|
||||
if (cancels.current.has(id)) return;
|
||||
let dead = false;
|
||||
let kill = () => {};
|
||||
kill = () => {
|
||||
dead = true;
|
||||
setFading((f) => {
|
||||
const n = { ...f };
|
||||
delete n[id];
|
||||
return n;
|
||||
});
|
||||
cancels.current.delete(id);
|
||||
};
|
||||
cancels.current.set(id, () => kill());
|
||||
setFading((f) => ({ ...f, [id]: "cooldown" }));
|
||||
const t1 = setTimeout(() => {
|
||||
if (dead) return;
|
||||
setFading((f) => ({ ...f, [id]: "dismissing" }));
|
||||
const t2 = setTimeout(() => {
|
||||
if (!dead) kill();
|
||||
}, 350);
|
||||
kill = () => {
|
||||
dead = true;
|
||||
clearTimeout(t2);
|
||||
setFading((f) => {
|
||||
const n = { ...f };
|
||||
delete n[id];
|
||||
return n;
|
||||
});
|
||||
cancels.current.delete(id);
|
||||
};
|
||||
cancels.current.set(id, () => kill());
|
||||
}, 2000);
|
||||
kill = () => {
|
||||
dead = true;
|
||||
clearTimeout(t1);
|
||||
setFading((f) => {
|
||||
const n = { ...f };
|
||||
delete n[id];
|
||||
return n;
|
||||
});
|
||||
cancels.current.delete(id);
|
||||
};
|
||||
cancels.current.set(id, () => kill());
|
||||
}, []);
|
||||
|
||||
const cancelFading = useCallback((id: string) => {
|
||||
cancels.current.get(id)?.();
|
||||
}, []);
|
||||
|
||||
/** Cancel all in-progress animations (e.g. on page navigation). */
|
||||
const cancelAll = useCallback(() => {
|
||||
cancels.current.forEach((c) => c());
|
||||
}, []);
|
||||
|
||||
return { fading, startFading, cancelFading, cancelAll };
|
||||
}
|
||||
@@ -15,6 +15,12 @@ interface PlaylistListSyncOptions {
|
||||
* (followed membership is managed separately), but still update/remove.
|
||||
*/
|
||||
noNewEntries?: boolean;
|
||||
/**
|
||||
* When true, don't re-add a playlist that isn't in the list (idx === -1).
|
||||
* Use this when the caller handles re-insertion itself (e.g. with a position
|
||||
* map, like the dumps/votes pattern in UserPublicProfile).
|
||||
*/
|
||||
skipReinsert?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,6 +66,8 @@ export function usePlaylistListSync(
|
||||
if (noNewEntries) return prev;
|
||||
if (ownerId && ev.playlist.userId !== ownerId) return prev;
|
||||
if (!ev.playlist.isPublic && !isOwner) return prev;
|
||||
// skipReinsert: caller handles re-insertion at the correct position.
|
||||
if (optionsRef.current?.skipReinsert) return prev;
|
||||
return [ev.playlist, ...prev];
|
||||
}
|
||||
// Remove if it became private and the viewer can't see private playlists
|
||||
@@ -75,6 +83,14 @@ export function usePlaylistListSync(
|
||||
return prev.filter((p) => p.id !== ev.playlistId);
|
||||
}
|
||||
|
||||
if (ev.type === "dumps_updated" && ev.dumpIds) {
|
||||
const idx = prev.findIndex((p) => p.id === ev.playlistId);
|
||||
if (idx === -1) return prev;
|
||||
const next = [...prev];
|
||||
next[idx] = { ...next[idx], dumpCount: ev.dumpIds.length };
|
||||
return next;
|
||||
}
|
||||
|
||||
return prev;
|
||||
});
|
||||
}, [lastPlaylistEvent]);
|
||||
|
||||
63
src/hooks/usePositionAwareSync.ts
Normal file
63
src/hooks/usePositionAwareSync.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useLayoutEffect, useRef } from "react";
|
||||
|
||||
/**
|
||||
* Keeps track of item positions as items leave a list and re-inserts them
|
||||
* at their original positions when they become visible again.
|
||||
*
|
||||
* MUST be called BEFORE the corresponding sync hook (useDumpListSync /
|
||||
* usePlaylistListSync) so the save-position effect fires before the hook's
|
||||
* removal effect in the same render cycle.
|
||||
*
|
||||
* @param items The current list (pass [] when state is not loaded).
|
||||
* @param setItems The list setter (same one passed to the sync hook).
|
||||
* @param lastEvent The latest changed item (Dump | Playlist | null).
|
||||
* @param isRemoving Return true when the item is about to leave the list
|
||||
* (e.g. it just became private). Used to save its index.
|
||||
* @param shouldReinsert Return true when the item should come back at its
|
||||
* original position (e.g. it just became public again).
|
||||
*/
|
||||
export function usePositionAwareSync<T extends { id: string }>(
|
||||
items: T[],
|
||||
setItems: (fn: (prev: T[]) => T[]) => void,
|
||||
lastEvent: T | null,
|
||||
isRemoving: (item: T) => boolean,
|
||||
shouldReinsert: (item: T) => boolean,
|
||||
): void {
|
||||
const itemsRef = useRef<T[]>(items);
|
||||
const setItemsRef = useRef(setItems);
|
||||
const isRemovingRef = useRef(isRemoving);
|
||||
const shouldReinsertRef = useRef(shouldReinsert);
|
||||
useLayoutEffect(() => {
|
||||
itemsRef.current = items;
|
||||
setItemsRef.current = setItems;
|
||||
isRemovingRef.current = isRemoving;
|
||||
shouldReinsertRef.current = shouldReinsert;
|
||||
});
|
||||
|
||||
const removedPositionsRef = useRef<Map<string, number>>(new Map());
|
||||
|
||||
// Save position BEFORE the sync hook removes the item.
|
||||
useEffect(() => {
|
||||
if (!lastEvent || !isRemovingRef.current(lastEvent)) return;
|
||||
const idx = itemsRef.current.findIndex((item) => item.id === lastEvent.id);
|
||||
if (idx !== -1) {
|
||||
removedPositionsRef.current.set(lastEvent.id, idx);
|
||||
}
|
||||
}, [lastEvent]);
|
||||
|
||||
// Re-insert at the saved position. Fires before the sync hook's effect for
|
||||
// the same event; skipReinsert on the sync hook prevents double-insertion.
|
||||
useEffect(() => {
|
||||
if (!lastEvent || !shouldReinsertRef.current(lastEvent)) return;
|
||||
const savedIdx = removedPositionsRef.current.get(lastEvent.id);
|
||||
if (savedIdx === undefined) return;
|
||||
removedPositionsRef.current.delete(lastEvent.id);
|
||||
const item = lastEvent;
|
||||
setItemsRef.current((prev) => {
|
||||
if (prev.some((i) => i.id === item.id)) return prev;
|
||||
const next = [...prev];
|
||||
next.splice(Math.min(savedIdx, next.length), 0, item);
|
||||
return next;
|
||||
});
|
||||
}, [lastEvent]);
|
||||
}
|
||||
Reference in New Issue
Block a user