v3: added content slugs, fixed real-time updates in client, added @mentions across the app, added new file selector and drop zone
This commit is contained in:
@@ -1,8 +1,18 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { Link, useNavigate, useParams } from "react-router";
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import type { PlaylistWithDumps, RawPlaylistWithDumps } from "../model.ts";
|
||||
import { deserializePlaylistWithDumps } from "../model.ts";
|
||||
import type {
|
||||
PlaylistWithDumps,
|
||||
RawDump,
|
||||
RawPlaylist,
|
||||
RawPlaylistWithDumps,
|
||||
} from "../model.ts";
|
||||
import {
|
||||
deserializeDump,
|
||||
deserializePlaylist,
|
||||
deserializePlaylistWithDumps,
|
||||
} from "../model.ts";
|
||||
import { playlistUrl } from "../utils/urls.ts";
|
||||
import { useAuth } from "../hooks/useAuth.ts";
|
||||
import { useWS } from "../hooks/useWS.ts";
|
||||
import { relativeTime } from "../utils/relativeTime.ts";
|
||||
@@ -12,8 +22,10 @@ import { PageError } from "../components/PageError.tsx";
|
||||
import { ConfirmModal } from "../components/ConfirmModal.tsx";
|
||||
import { ImagePicker } from "../components/ImagePicker.tsx";
|
||||
import { Markdown } from "../components/Markdown.tsx";
|
||||
import { TextEditor } from "../components/TextEditor.tsx";
|
||||
import { FollowPlaylistButton } from "../components/FollowButton.tsx";
|
||||
import { ErrorCard } from "../components/ErrorCard.tsx";
|
||||
import { Tooltip } from "../components/Tooltip.tsx";
|
||||
import { friendlyFetchError } from "../utils/apiError.ts";
|
||||
|
||||
type LoadState =
|
||||
@@ -31,10 +43,13 @@ export function PlaylistDetail() {
|
||||
castVote,
|
||||
removeVote,
|
||||
deletedDumpIds,
|
||||
lastDumpEvent,
|
||||
lastPlaylistEvent,
|
||||
} = useWS();
|
||||
|
||||
const [state, setState] = useState<LoadState>({ status: "loading" });
|
||||
// Stable UUID for WS comparisons — avoids re-running effects on every state change
|
||||
const playlistUUID = state.status === "loaded" ? state.playlist.id : null;
|
||||
|
||||
// activeDumpIds: which dumps are currently in the playlist (the canonical set)
|
||||
const [activeDumpIds, setActiveDumpIds] = useState<Set<string>>(new Set());
|
||||
@@ -45,7 +60,9 @@ export function PlaylistDetail() {
|
||||
>({});
|
||||
const cancels = useRef<Map<string, () => void>>(new Map());
|
||||
|
||||
const [dragSrcIndex, setDragSrcIndex] = useState<number | null>(null);
|
||||
// dragSrcRef: mutable ref so handleDragOver always sees the current source index
|
||||
// without stale closure issues (state would only update on next render).
|
||||
const dragSrcRef = useRef<number | null>(null);
|
||||
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
|
||||
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
@@ -58,9 +75,18 @@ export function PlaylistDetail() {
|
||||
const [imageFile, setImageFile] = useState<File | null>(null);
|
||||
const [imagePreview, setImagePreview] = useState<string | null>(null);
|
||||
|
||||
// prevActiveDumpIds: used by the WS effect to diff incoming dumpIds
|
||||
const prevActiveDumpIdsRef = useRef<Set<string> | null>(null);
|
||||
const descriptionRef = useRef<HTMLTextAreaElement>(null);
|
||||
// Mirrors activeDumpIds for use in effects without adding it as a dep.
|
||||
// Updated on every render via useLayoutEffect so it's always current.
|
||||
const activeDumpIdsRef = useRef(activeDumpIds);
|
||||
// knownDumpIds: all dump IDs that belong to this playlist (for re-adding when dumps become public again)
|
||||
const knownDumpIdsRef = useRef<Set<string>>(new Set());
|
||||
// Authoritative dump order from the server (fetchPlaylist + dumps_updated events).
|
||||
// Used to re-insert dumps at their correct position after private→public transitions.
|
||||
const dumpOrderRef = useRef<string[]>([]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
activeDumpIdsRef.current = activeDumpIds;
|
||||
});
|
||||
|
||||
useEffect(() => () => {
|
||||
cancels.current.forEach((c) => c());
|
||||
@@ -87,8 +113,10 @@ export function PlaylistDetail() {
|
||||
);
|
||||
setState({ status: "loaded", playlist: pl });
|
||||
const ids = new Set(pl.dumps.map((d) => d.id));
|
||||
const order = pl.dumps.map((d) => d.id);
|
||||
setActiveDumpIds(ids);
|
||||
prevActiveDumpIdsRef.current = ids;
|
||||
dumpOrderRef.current = order;
|
||||
for (const id of ids) knownDumpIdsRef.current.add(id);
|
||||
setFading({});
|
||||
cancels.current.forEach((c) => c());
|
||||
cancels.current.clear();
|
||||
@@ -172,13 +200,17 @@ export function PlaylistDetail() {
|
||||
|
||||
// WS: playlist metadata updated or deleted
|
||||
useEffect(() => {
|
||||
if (!lastPlaylistEvent || !playlistId) return;
|
||||
if (!lastPlaylistEvent || !playlistUUID) return;
|
||||
const ev = lastPlaylistEvent;
|
||||
if (ev.playlistId !== playlistId) return;
|
||||
// Compare against the resolved UUID, not the URL param (which may be a slug)
|
||||
if (ev.playlistId !== playlistUUID) return;
|
||||
|
||||
if (ev.type === "dumps_updated" && ev.dumpIds) {
|
||||
const newIds = new Set(ev.dumpIds);
|
||||
const prev = prevActiveDumpIdsRef.current ?? new Set<string>();
|
||||
for (const id of newIds) knownDumpIdsRef.current.add(id);
|
||||
// Use the ref so we always diff against the current activeDumpIds,
|
||||
// including changes from deletedDumpIds / lastDumpEvent effects.
|
||||
const prev = activeDumpIdsRef.current;
|
||||
|
||||
// Removed: were active, not in new set → fade out
|
||||
for (const id of prev) {
|
||||
@@ -192,46 +224,65 @@ export function PlaylistDetail() {
|
||||
}
|
||||
}
|
||||
|
||||
// Re-added while fading → cancel fade, restore to active
|
||||
// Newly added IDs: cancel any fade, mark active, fetch dump data individually.
|
||||
// We never call fetchPlaylist here — that would reset state to "loading", cycle
|
||||
// playlistUUID, and re-trigger this effect in a loop.
|
||||
for (const id of newIds) {
|
||||
if (!prev.has(id)) {
|
||||
if (cancels.current.has(id)) {
|
||||
cancels.current.get(id)!();
|
||||
}
|
||||
// If this is a brand-new dump we haven't seen, re-fetch
|
||||
setState((s) => {
|
||||
if (s.status !== "loaded") return s;
|
||||
const known = s.playlist.dumps.some((d) => d.id === id);
|
||||
if (!known) {
|
||||
// Trigger a re-fetch asynchronously
|
||||
setTimeout(fetchPlaylist, 0);
|
||||
}
|
||||
return s;
|
||||
});
|
||||
cancels.current.get(id)?.();
|
||||
setActiveDumpIds((s) => new Set([...s, id]));
|
||||
// Capture ev.dumpIds so we can insert the new dump at its correct position.
|
||||
const orderedIds = ev.dumpIds!;
|
||||
fetch(`${API_URL}/api/dumps/${id}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
})
|
||||
.then((r) => r.ok ? r.json() : null)
|
||||
.then((body) => {
|
||||
if (!body?.success) return;
|
||||
const dump = deserializeDump(body.data as RawDump);
|
||||
setState((s) => {
|
||||
if (s.status !== "loaded") return s;
|
||||
if (s.playlist.dumps.some((d) => d.id === dump.id)) return s;
|
||||
// Insert at the correct server-ordered position.
|
||||
const dumpMap = new Map(s.playlist.dumps.map((d) => [d.id, d]));
|
||||
dumpMap.set(dump.id, dump);
|
||||
return {
|
||||
...s,
|
||||
playlist: {
|
||||
...s.playlist,
|
||||
dumps: [
|
||||
...orderedIds
|
||||
.filter((oid) => dumpMap.has(oid))
|
||||
.map((oid) => dumpMap.get(oid)!),
|
||||
...s.playlist.dumps.filter((d) => !newIds.has(d.id)),
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// Reorder active dumps to match the new server order,
|
||||
// keeping fading dumps at their current visual positions.
|
||||
setState((prev) => {
|
||||
if (prev.status !== "loaded") return prev;
|
||||
const dumpMap = new Map(prev.playlist.dumps.map((d) => [d.id, d]));
|
||||
const activeQueue = ev.dumpIds!
|
||||
.filter((id) => dumpMap.has(id))
|
||||
.map((id) => dumpMap.get(id)!);
|
||||
let qi = 0;
|
||||
const result = prev.playlist.dumps
|
||||
.filter((d) => dumpMap.has(d.id))
|
||||
.map((d) => newIds.has(d.id) ? activeQueue[qi++] : d);
|
||||
while (qi < activeQueue.length) result.push(activeQueue[qi++]);
|
||||
// Apply the server-authoritative order: active dumps in ev.dumpIds order,
|
||||
// fading dumps (not in newIds) appended at the end.
|
||||
setState((s) => {
|
||||
if (s.status !== "loaded") return s;
|
||||
const dumpMap = new Map(s.playlist.dumps.map((d) => [d.id, d]));
|
||||
return {
|
||||
...prev,
|
||||
playlist: { ...prev.playlist, dumps: result },
|
||||
...s,
|
||||
playlist: {
|
||||
...s.playlist,
|
||||
dumps: [
|
||||
...ev.dumpIds!
|
||||
.filter((id) => dumpMap.has(id))
|
||||
.map((id) => dumpMap.get(id)!),
|
||||
...s.playlist.dumps.filter((d) => !newIds.has(d.id)),
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
prevActiveDumpIdsRef.current = newIds;
|
||||
dumpOrderRef.current = ev.dumpIds!;
|
||||
} else if (ev.type === "updated" && ev.playlist) {
|
||||
setState((prev) => {
|
||||
if (prev.status !== "loaded") return prev;
|
||||
@@ -249,7 +300,7 @@ export function PlaylistDetail() {
|
||||
} else if (ev.type === "deleted") {
|
||||
navigate("/");
|
||||
}
|
||||
}, [lastPlaylistEvent, playlistId]);
|
||||
}, [lastPlaylistEvent, playlistUUID]);
|
||||
|
||||
// Filter out globally deleted dumps (dump was deleted entirely, not just removed from playlist)
|
||||
useEffect(() => {
|
||||
@@ -269,36 +320,85 @@ export function PlaylistDetail() {
|
||||
});
|
||||
}, [deletedDumpIds]);
|
||||
|
||||
const handleDragStart = (index: number) => setDragSrcIndex(index);
|
||||
// Update dump metadata in-place; re-add if it was in this playlist but hidden (private→public)
|
||||
useEffect(() => {
|
||||
if (!lastDumpEvent) return;
|
||||
const dump = lastDumpEvent;
|
||||
setState((prev) => {
|
||||
if (prev.status !== "loaded") return prev;
|
||||
const idx = prev.playlist.dumps.findIndex((d) => d.id === dump.id);
|
||||
if (idx !== -1) {
|
||||
// Update in-place
|
||||
const dumps = [...prev.playlist.dumps];
|
||||
dumps[idx] = dump;
|
||||
return { ...prev, playlist: { ...prev.playlist, dumps } };
|
||||
}
|
||||
// Re-add if this dump belongs to the playlist and is now public,
|
||||
// inserting at its correct server-ordered position.
|
||||
if (!dump.isPrivate && knownDumpIdsRef.current.has(dump.id)) {
|
||||
const order = dumpOrderRef.current;
|
||||
const dumpMap = new Map(prev.playlist.dumps.map((d) => [d.id, d]));
|
||||
dumpMap.set(dump.id, dump);
|
||||
const reinserted = order.length > 0
|
||||
? [
|
||||
...order.filter((id) => dumpMap.has(id)).map((id) => dumpMap.get(id)!),
|
||||
...prev.playlist.dumps.filter((d) => !new Set(order).has(d.id)),
|
||||
]
|
||||
: [...prev.playlist.dumps, dump];
|
||||
return { ...prev, playlist: { ...prev.playlist, dumps: reinserted } };
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
// Restore to activeDumpIds if re-added
|
||||
if (!dump.isPrivate && knownDumpIdsRef.current.has(dump.id)) {
|
||||
setActiveDumpIds((prev) => {
|
||||
if (prev.has(dump.id)) return prev;
|
||||
return new Set([...prev, dump.id]);
|
||||
});
|
||||
}
|
||||
}, [lastDumpEvent]);
|
||||
|
||||
const handleDragStart = (index: number) => {
|
||||
dragSrcRef.current = index;
|
||||
};
|
||||
|
||||
const handleDragOver = (e: React.DragEvent, index: number) => {
|
||||
e.preventDefault();
|
||||
if (dragSrcIndex === null || dragSrcIndex === index) return;
|
||||
const src = dragSrcRef.current;
|
||||
if (src === null || src === index) return;
|
||||
// Only swap once the pointer has crossed the card's midpoint.
|
||||
// Without this, entering a card immediately re-triggers the swap in the
|
||||
// opposite direction (the two items keep bouncing back and forth).
|
||||
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
const mid = rect.top + rect.height / 2;
|
||||
if (src < index && e.clientY < mid) return; // dragging downward, not past mid yet
|
||||
if (src > index && e.clientY > mid) return; // dragging upward, not past mid yet
|
||||
// Update visual order in state. Use activeDumpIdsRef so the updater never
|
||||
// reads a stale closure — activeDumpIds can't change mid-drag but this is
|
||||
// the correct pattern for setState updaters.
|
||||
setState((prev) => {
|
||||
if (prev.status !== "loaded") return prev;
|
||||
// Only reorder among active dumps
|
||||
const activeDumps = prev.playlist.dumps.filter((d) =>
|
||||
activeDumpIds.has(d.id)
|
||||
);
|
||||
const fadingDumps = prev.playlist.dumps.filter((d) =>
|
||||
!activeDumpIds.has(d.id)
|
||||
);
|
||||
const ids = activeDumpIdsRef.current;
|
||||
const activeDumps = prev.playlist.dumps.filter((d) => ids.has(d.id));
|
||||
const fadingDumps = prev.playlist.dumps.filter((d) => !ids.has(d.id));
|
||||
const reordered = [...activeDumps];
|
||||
const [moved] = reordered.splice(dragSrcIndex, 1);
|
||||
const [moved] = reordered.splice(src, 1);
|
||||
reordered.splice(index, 0, moved);
|
||||
setDragSrcIndex(index);
|
||||
setDragOverIndex(index);
|
||||
return {
|
||||
...prev,
|
||||
playlist: { ...prev.playlist, dumps: [...reordered, ...fadingDumps] },
|
||||
};
|
||||
});
|
||||
// Update the ref and highlight index outside the updater (no side effects inside updaters).
|
||||
dragSrcRef.current = index;
|
||||
setDragOverIndex(index);
|
||||
};
|
||||
|
||||
const handleDragEnd = async () => {
|
||||
if (state.status !== "loaded" || !playlistId) return;
|
||||
setDragSrcIndex(null);
|
||||
const src = dragSrcRef.current;
|
||||
dragSrcRef.current = null;
|
||||
setDragOverIndex(null);
|
||||
if (src === null || state.status !== "loaded" || !playlistId) return;
|
||||
const activeDumps = state.playlist.dumps.filter((d) =>
|
||||
activeDumpIds.has(d.id)
|
||||
);
|
||||
@@ -341,13 +441,6 @@ export function PlaylistDetail() {
|
||||
}).catch(() => {});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const el = descriptionRef.current;
|
||||
if (!el) return;
|
||||
el.style.height = "auto";
|
||||
el.style.height = `${el.scrollHeight}px`;
|
||||
}, [editDescription, editOpen]);
|
||||
|
||||
const openEdit = () => {
|
||||
if (state.status !== "loaded") return;
|
||||
setEditTitle(state.playlist.title);
|
||||
@@ -364,15 +457,25 @@ export function PlaylistDetail() {
|
||||
setEditSaving(true);
|
||||
setEditError(null);
|
||||
try {
|
||||
await authFetch(`${API_URL}/api/playlists/${playlistId}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: editTitle,
|
||||
description: editDescription || undefined,
|
||||
isPublic: editIsPublic,
|
||||
}),
|
||||
});
|
||||
const updateRes = await authFetch(
|
||||
`${API_URL}/api/playlists/${playlistId}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: editTitle,
|
||||
description: editDescription || undefined,
|
||||
isPublic: editIsPublic,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const updateJson = await updateRes.json() as {
|
||||
success: boolean;
|
||||
data: RawPlaylist;
|
||||
};
|
||||
const updatedPlaylist = updateJson.success
|
||||
? deserializePlaylist(updateJson.data)
|
||||
: null;
|
||||
|
||||
if (imageFile) {
|
||||
const fd = new FormData();
|
||||
@@ -384,7 +487,11 @@ export function PlaylistDetail() {
|
||||
}
|
||||
|
||||
setEditOpen(false);
|
||||
fetchPlaylist();
|
||||
if (updatedPlaylist) {
|
||||
navigate(playlistUrl(updatedPlaylist), { replace: true });
|
||||
} else {
|
||||
fetchPlaylist();
|
||||
}
|
||||
} catch (err) {
|
||||
setEditError(friendlyFetchError(err));
|
||||
} finally {
|
||||
@@ -519,12 +626,12 @@ export function PlaylistDetail() {
|
||||
|
||||
{editOpen
|
||||
? (
|
||||
<textarea
|
||||
ref={descriptionRef}
|
||||
<TextEditor
|
||||
className="playlist-edit-textarea"
|
||||
value={editDescription}
|
||||
onChange={(e) => setEditDescription(e.target.value)}
|
||||
onChange={setEditDescription}
|
||||
placeholder="Description (optional)"
|
||||
autoResize
|
||||
rows={1}
|
||||
/>
|
||||
)
|
||||
@@ -571,12 +678,18 @@ export function PlaylistDetail() {
|
||||
@{playlist.ownerUsername}
|
||||
</Link>
|
||||
)}
|
||||
<time
|
||||
dateTime={playlist.createdAt.toISOString()}
|
||||
title={playlist.createdAt.toLocaleString()}
|
||||
>
|
||||
{relativeTime(playlist.createdAt)}
|
||||
</time>
|
||||
<Tooltip text={playlist.createdAt.toLocaleString()}>
|
||||
<time dateTime={playlist.createdAt.toISOString()}>
|
||||
{relativeTime(playlist.createdAt)}
|
||||
</time>
|
||||
</Tooltip>
|
||||
{playlist.updatedAt && (
|
||||
<Tooltip text={`Edited ${playlist.updatedAt.toLocaleString()}`}>
|
||||
<span className="playlist-edited-label">
|
||||
edited {relativeTime(playlist.updatedAt)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -590,7 +703,10 @@ export function PlaylistDetail() {
|
||||
{visibleDumps.length === 0
|
||||
? <p className="empty-state">No dumps in this playlist yet.</p>
|
||||
: (
|
||||
<div className="playlist-dump-list">
|
||||
<div
|
||||
className="playlist-dump-list"
|
||||
onDragOver={isOwner ? (e) => e.preventDefault() : undefined}
|
||||
>
|
||||
{visibleDumps.map((dump) => {
|
||||
const isActive = activeDumpIds.has(dump.id);
|
||||
const phase = fading[dump.id];
|
||||
@@ -617,7 +733,7 @@ export function PlaylistDetail() {
|
||||
onDragOver={isOwner && isActive
|
||||
? (e) => handleDragOver(e, activeIndex)
|
||||
: undefined}
|
||||
onDragEnd={isOwner && isActive ? handleDragEnd : undefined}
|
||||
onDragEnd={isOwner ? handleDragEnd : undefined}
|
||||
>
|
||||
{isOwner && isActive && (
|
||||
<span className="drag-handle" aria-hidden>⠿</span>
|
||||
|
||||
Reference in New Issue
Block a user