Files
siftlode/frontend/src/components/PlexPlaylistView.tsx
T
peter 63bf1bca78 fix(plex): an accepted reorder refetches the detail it just wrote
`commit`'s success handler writes the dragged list into the detail cache — round 6's fix, so a
re-entry inside the 30s staleTime renders the accepted order without a request — but then invalidated
only the LIST key, while the YouTube sibling it cites invalidates both. `next` is the membership of
the render that started the drag, and `reorder_playlist` only touches the rating_keys it is handed,
so it never ratifies that list: anything that landed meanwhile was clobbered by the write with
nothing scheduled to correct it. `commit` sets no busy flag either, so a removal really can complete
while a reorder is in flight, and with staleTime 30s and refetchOnWindowFocus off the phantom row
stayed on screen for as long as the view was mounted — and the next drag persisted an order built
from it.

Round 6's test had to be re-pointed, because it was written in a world with no refetch: its mock
answered the pre-reorder order forever, which a server that just accepted the write cannot do. It now
holds the refetch open instead, so it still pins what round 6 actually fixed — the cache is right
WITHOUT waiting for a request — and would fail if the write were deleted. Both halves are
mutation-checked against each other.
2026-09-12 16:22:27 +02:00

665 lines
24 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { qk } from "../lib/queryKeys";
import { useTranslation } from "react-i18next";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
ArrowLeft,
ChevronDown,
ChevronRight,
GripVertical,
ListTree,
Pencil,
Play,
Rows3,
Trash2,
X,
} from "lucide-react";
import { api, HttpError, type PlexCard } from "../lib/api";
import { notifyActionError } from "../lib/actionErrors";
import { formatRuntime } from "../lib/format";
import { getAccountRaw, LS, setAccountRaw } from "../lib/storage";
import { useConfirm } from "./ConfirmProvider";
import { Button } from "./ui/Button";
import { LoadingState, StateMessage } from "./ui/QueryState";
import ViewSwitcher, { type ViewOption } from "./ViewSwitcher";
// A playlist's items, grouped for readability: movies stay standalone, while a run of episodes from the
// same show collapses into a season/show group so a whole series doesn't sprawl into an endless flat
// list. Reorder is drag & drop (a whole show-group moves as one block; episodes reorder within their
// show). Two layouts — Accordion (A) and Tree (C) — are a per-account preference. Rendered as a
// PlexBrowse subview; "Play all" opens the player with the whole ordered list as its queue.
type Layout = "accordion" | "tree";
type Season = { key: string; number: number | null; items: PlexCard[] };
type Block =
| { kind: "movie"; id: string; item: PlexCard }
| {
kind: "show";
id: string;
showKey: string;
title: string;
items: PlexCard[];
seasons: Season[];
};
function buildSeasons(items: PlexCard[]): Season[] {
const map = new Map<string, Season>();
for (const it of items) {
const num = it.season_number ?? null;
const key = String(num ?? "?");
let s = map.get(key);
if (!s) {
s = { key, number: num, items: [] };
map.set(key, s);
}
s.items.push(it);
}
return [...map.values()];
}
// Turn the flat ordered list into blocks: contiguous episodes of one show group together (then split
// into seasons for display); everything else (movies) is its own block.
function buildBlocks(items: PlexCard[]): Block[] {
const blocks: Block[] = [];
for (const it of items) {
if (it.type === "episode") {
const showKey = it.show_id || it.show_title || "?";
const last = blocks[blocks.length - 1];
if (last && last.kind === "show" && last.showKey === showKey) {
last.items.push(it);
} else {
blocks.push({
kind: "show",
id: `show:${showKey}`,
showKey,
title: it.show_title || it.title,
items: [it],
seasons: [],
});
}
} else {
blocks.push({ kind: "movie", id: it.id, item: it });
}
}
for (const b of blocks) if (b.kind === "show") b.seasons = buildSeasons(b.items);
return blocks;
}
const flatten = (blocks: Block[]): PlexCard[] =>
blocks.flatMap((b) => (b.kind === "movie" ? [b.item] : b.items));
// Callbacks + shared state passed down to the module-scope block/row components.
type Ctx = {
layout: Layout;
busy: boolean;
expandedShows: Set<string>;
collapsedSeasons: Set<string>;
toggleShow: (k: string) => void;
toggleSeason: (k: string) => void;
onPlay: (rk: string) => void;
onRemove: (keys: string[]) => void;
};
function Poster({ src, className }: { src: string; className: string }) {
return (
<div
className={`relative shrink-0 overflow-hidden rounded-sm border border-border bg-surface ${className}`}
>
<img src={src} alt="" loading="lazy" className="h-full w-full object-cover" />
</div>
);
}
function DragHandle(props: Record<string, unknown>) {
return (
<button
{...props}
className="shrink-0 cursor-grab text-muted hover:text-fg active:cursor-grabbing"
aria-label="reorder"
>
<GripVertical className="h-4 w-4" />
</button>
);
}
function EpisodeRow({ ep, ctx, dense }: { ep: PlexCard; ctx: Ctx; dense: boolean }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: ep.id,
disabled: ctx.busy,
});
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.6 : 1,
};
const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched";
return (
<div
ref={setNodeRef}
style={style}
className={`flex items-center gap-2.5 rounded-lg ${dense ? "px-1.5 py-1" : "glass-card p-1.5"}`}
>
<DragHandle {...attributes} {...listeners} />
<span className="w-5 shrink-0 text-center text-2xs text-muted tabular-nums">
{ep.episode_number}
</span>
<button
onClick={() => ctx.onPlay(ep.id)}
className="group flex min-w-0 flex-1 items-center gap-2.5 text-left"
>
<div
className={`relative shrink-0 overflow-hidden rounded-sm border border-border bg-surface ${dense ? "aspect-video w-14" : "aspect-video w-20"}`}
>
<img src={ep.thumb} alt="" loading="lazy" className="h-full w-full object-cover" />
{ep.status === "watched" && (
<span className="absolute right-0.5 top-0.5 rounded-sm bg-black/70 px-1 text-[0.5625rem] text-white">
✓
</span>
)}
{inProgress && <div className="absolute inset-x-0 bottom-0 h-0.5 bg-accent" />}
<div className="absolute inset-0 grid place-items-center bg-black/40 opacity-0 transition group-hover:opacity-100">
<Play className="h-4 w-4 text-white" fill="currentColor" />
</div>
</div>
<div className="min-w-0 truncate text-[0.8125rem]">{ep.title}</div>
</button>
<button
onClick={() => ctx.onRemove([ep.id])}
disabled={ctx.busy}
className="shrink-0 rounded-sm p-1 text-muted hover:text-danger disabled:opacity-30"
aria-label="remove"
>
<X className="h-4 w-4" />
</button>
</div>
);
}
function MovieRow({ item, ctx }: { item: PlexCard; ctx: Ctx }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: item.id,
disabled: ctx.busy,
});
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.6 : 1,
};
const dense = ctx.layout === "tree";
return (
<div
ref={setNodeRef}
style={style}
className="glass-card flex items-center gap-3 rounded-xl p-2"
>
<DragHandle {...attributes} {...listeners} />
<button
onClick={() => ctx.onPlay(item.id)}
className="group flex min-w-0 flex-1 items-center gap-3 text-left"
>
<Poster src={item.thumb} className={dense ? "aspect-2/3 w-10" : "aspect-2/3 w-14"} />
<div className="min-w-0">
<div className="truncate text-sm font-medium">{item.title}</div>
<div className="text-xs text-muted">{item.year}</div>
</div>
<div className="pointer-events-none ml-auto grid h-8 w-8 shrink-0 place-items-center rounded-full bg-accent/0 text-transparent transition group-hover:bg-accent/15 group-hover:text-accent">
<Play className="h-4 w-4" fill="currentColor" />
</div>
</button>
<button
onClick={() => ctx.onRemove([item.id])}
disabled={ctx.busy}
className="shrink-0 rounded-sm p-1 text-muted hover:text-danger disabled:opacity-30"
aria-label="remove"
>
<X className="h-4 w-4" />
</button>
</div>
);
}
function ShowGroup({ block, ctx }: { block: Extract<Block, { kind: "show" }>; ctx: Ctx }) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: block.id,
disabled: ctx.busy,
});
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.6 : 1,
};
const open = ctx.expandedShows.has(block.showKey);
const dense = ctx.layout === "tree";
const seasonLabel = (s: Season) =>
s.number != null
? t("plex.playlist.season", { n: s.number })
: t("plex.playlist.seasonUnknown");
return (
<div ref={setNodeRef} style={style} className="glass-card overflow-hidden rounded-xl">
{/* Group header — drag moves the whole show; chevron collapses; X removes the whole show. */}
<div className="flex items-center gap-2.5 p-2">
<DragHandle {...attributes} {...listeners} />
<button
onClick={() => ctx.toggleShow(block.showKey)}
className="grid h-6 w-6 shrink-0 place-items-center rounded-sm text-muted hover:text-fg"
aria-expanded={open}
>
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
{!dense && (
<button onClick={() => ctx.toggleShow(block.showKey)} className="flex shrink-0">
{block.items.slice(0, 3).map((ep, i) => (
<img
key={ep.id}
src={ep.thumb}
alt=""
loading="lazy"
className="aspect-2/3 w-8 rounded-sm border-2 border-surface object-cover"
style={{ marginLeft: i ? -14 : 0 }}
/>
))}
</button>
)}
<button onClick={() => ctx.toggleShow(block.showKey)} className="min-w-0 flex-1 text-left">
<div className="truncate text-sm font-semibold">{block.title}</div>
<div className="text-2xs text-muted">
{t("plex.playlist.episodes", { count: block.items.length })}
</div>
</button>
<button
onClick={() => ctx.onRemove(block.items.map((i) => i.id))}
disabled={ctx.busy}
title={t("plex.playlist.removeShow")}
className="shrink-0 rounded-sm p-1 text-muted hover:text-danger disabled:opacity-30"
>
<X className="h-4 w-4" />
</button>
</div>
{open && (
<div className={`border-t border-border/50 ${dense ? "px-2 pb-1.5 pt-1" : "px-2 pb-2"}`}>
<SortableContext
items={block.items.map((i) => i.id)}
strategy={verticalListSortingStrategy}
>
{block.seasons.map((s) => {
const sKey = `${block.showKey}:${s.key}`;
const sOpen = !dense || !ctx.collapsedSeasons.has(sKey);
return (
<div key={s.key} className={dense ? "" : "mt-1.5 first:mt-0.5"}>
<div className="flex items-center gap-1.5 py-1 pl-1">
{dense && (
<button
onClick={() => ctx.toggleSeason(sKey)}
className="grid h-5 w-5 shrink-0 place-items-center rounded-sm text-muted hover:text-fg"
aria-expanded={sOpen}
>
{sOpen ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
</button>
)}
<span className="text-2xs font-medium uppercase tracking-wide text-muted">
{seasonLabel(s)} · {s.items.length}
</span>
<button
onClick={() => ctx.onRemove(s.items.map((i) => i.id))}
disabled={ctx.busy}
title={t("plex.playlist.removeSeason")}
className="ml-1 rounded-sm p-0.5 text-muted hover:text-danger disabled:opacity-30"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
{sOpen && (
<div
className={
dense ? "ml-2 space-y-0.5 border-l border-border/50 pl-1.5" : "space-y-1"
}
>
{s.items.map((ep) => (
<EpisodeRow key={ep.id} ep={ep} ctx={ctx} dense={dense} />
))}
</div>
)}
</div>
);
})}
</SortableContext>
</div>
)}
</div>
);
}
export default function PlexPlaylistView({
playlistId,
onBack,
onPlay,
}: {
playlistId: number;
onBack: () => void;
onPlay: (itemRk: string, queue: string[]) => void;
}) {
const { t } = useTranslation();
const qc = useQueryClient();
const confirm = useConfirm();
const [renaming, setRenaming] = useState(false);
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [layout, setLayout] = useState<Layout>(() =>
getAccountRaw(LS.plexPlaylistLayout) === "tree" ? "tree" : "accordion",
);
useEffect(() => {
setAccountRaw(LS.plexPlaylistLayout, layout);
}, [layout]);
// Show groups start collapsed (compact headers) so a long series doesn't force endless scrolling;
// seasons start expanded once their show is opened. Both are just local view state.
const [expandedShows, setExpandedShows] = useState<Set<string>>(new Set());
const [collapsedSeasons, setCollapsedSeasons] = useState<Set<string>>(new Set());
const q = useQuery({
queryKey: qk.plexPlaylist(playlistId),
queryFn: () => api.plexPlaylist(playlistId),
});
// Local optimistic copy so drag/remove are instant; re-synced whenever the query returns.
const [items, setItems] = useState<PlexCard[]>([]);
useEffect(() => {
if (q.data) setItems(q.data.items);
}, [q.data]);
const blocks = useMemo(() => buildBlocks(items), [items]);
const order = useMemo(() => items.map((i) => i.id), [items]);
// Total playtime of the whole playlist, mirroring the YouTube playlist header (E9 12D): items with
// an unknown duration count as 0, and the runtime is dropped from the meta line when nothing sums.
const totalSeconds = useMemo(
() => items.reduce((acc, it) => acc + (it.duration_seconds ?? 0), 0),
[items],
);
const invalidate = () => {
qc.invalidateQueries({ queryKey: qk.plexPlaylist(playlistId) });
qc.invalidateQueries({ queryKey: qk.plexPlaylists() });
};
// Every edit here is optimistic on the local copy, and none of them used to handle a failure: a
// removal that failed stayed removed on screen (the resync never ran), and a 404 — the playlist
// deleted on another device, now a structured `not_found` — was an unhandled rejection that said
// nothing at all (deep-review round 4; the YouTube side was fixed in round 3). A failure is said,
// and the rows are put back from what the server last sent — explicitly, because a resync that
// returns the same list keeps the same `q.data` and the re-sync effect above never runs.
// Read the cache AT ROLLBACK TIME, not the `q.data` of the render that bound the failing handler:
// a removal completing while a reorder was in flight refreshed the list, and the reorder's stale
// closure then put the removed row back on screen — where the deep-equal refetch could not clear
// it, and the next drag persisted an order containing it (deep-review round 5). `Playlists.tsx`'s
// sibling `restoreFromCache` reads it live for the same reason.
const putBack = () => {
const cur = qc.getQueryData<{ items: PlexCard[] }>(qk.plexPlaylist(playlistId));
if (cur) setItems(cur.items);
invalidate();
};
function commit(next: PlexCard[]) {
if (busy) return; // a reorder racing a removal is what makes a rollback ambiguous
setItems(next);
api
.plexReorderPlaylist(
playlistId,
next.map((i) => i.id),
)
.then(() => {
// Write the accepted order into the DETAIL cache, not just the list. That cache is what
// `putBack` rolls back to and what a re-entry inside the 30 s staleTime renders without
// refetching — so after an accepted reorder it showed the pre-reorder order again, and the
// next drag from there persisted it, silently undoing the one the server took. The
// YouTube sibling (`Playlists.tsx`) got this in round 5; this half was left behind (round
// 6). One accepted write, one cache entry that matches it.
qc.setQueryData<{ items: PlexCard[] }>(qk.plexPlaylist(playlistId), (old) =>
old ? { ...old, items: next } : old,
);
qc.invalidateQueries({ queryKey: qk.plexPlaylist(playlistId) });
// …and then REFETCH it, exactly as the sibling does. `next` is this render's membership, and
// the server only reorders the keys it was given — so anything that landed meanwhile (a row
// removed from another surface, an item added elsewhere) is clobbered by that write. With
// only the list key invalidated nothing corrected it: staleTime is 30 s and
// refetchOnWindowFocus is off, so the wrong membership stayed on screen for as long as the
// view was mounted and the next drag persisted an order built from it (round 7).
qc.invalidateQueries({ queryKey: qk.plexPlaylists() });
})
.catch((e: unknown) => {
notifyActionError(e, t("plex.playlist.reorderFailed"));
putBack();
});
}
async function onRemove(keys: string[]) {
if (busy || !keys.length) return;
setBusy(true);
const set = new Set(keys);
setItems((prev) => prev.filter((i) => !set.has(i.id)));
try {
if (keys.length === 1) await api.plexPlaylistRemoveItem(playlistId, keys[0]!);
else await api.plexPlaylistRemoveBulk(playlistId, keys);
invalidate();
} catch (e) {
notifyActionError(e, t("plex.playlist.removeFailed"));
putBack();
} finally {
setBusy(false);
}
}
async function rename() {
const title = name.trim();
if (!title) return;
try {
await api.plexRenamePlaylist(playlistId, title);
} catch (e) {
notifyActionError(e, t("plex.playlist.renameFailed")); // the field stays open to try again
return;
}
setRenaming(false);
invalidate();
}
async function del() {
if (
!(await confirm({
message: t("plex.playlist.deleteConfirm", { title: q.data?.title }),
danger: true,
}))
)
return;
try {
await api.plexDeletePlaylist(playlistId);
} catch (e) {
// Gone already (deleted on another device): what was asked for is true — leave the dead page.
// Anything else is a real failure, and the page stays.
if (!(e instanceof HttpError && e.status === 404)) {
notifyActionError(e, t("plex.playlist.deleteFailed"));
return;
}
}
qc.invalidateQueries({ queryKey: qk.plexPlaylists() });
onBack();
}
const toggleShow = (k: string) =>
setExpandedShows((s) => {
const n = new Set(s);
n.has(k) ? n.delete(k) : n.add(k);
return n;
});
const toggleSeason = (k: string) =>
setCollapsedSeasons((s) => {
const n = new Set(s);
n.has(k) ? n.delete(k) : n.add(k);
return n;
});
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
function onDragEnd(e: DragEndEvent) {
const { active, over } = e;
if (!over || active.id === over.id) return;
const aId = String(active.id);
const oId = String(over.id);
const blockIds = new Set(blocks.map((b) => b.id));
if (blockIds.has(aId)) {
// Moving a whole block (movie or show). Resolve the drop target to a block.
let oBlockId = oId;
if (!blockIds.has(oId)) {
const b = blocks.find((bl) => bl.kind === "show" && bl.items.some((it) => it.id === oId));
if (!b) return;
oBlockId = b.id;
}
const from = blocks.findIndex((b) => b.id === aId);
const to = blocks.findIndex((b) => b.id === oBlockId);
if (from < 0 || to < 0) return;
commit(flatten(arrayMove(blocks, from, to)));
} else {
// Moving an episode — only within its own show block.
const b = blocks.find((bl) => bl.kind === "show" && bl.items.some((it) => it.id === aId));
if (!b || b.kind !== "show" || !b.items.some((it) => it.id === oId)) return;
const from = b.items.findIndex((it) => it.id === aId);
const to = b.items.findIndex((it) => it.id === oId);
commit(
flatten(
blocks.map((bl) =>
bl.id === b.id ? { ...bl, items: arrayMove(b.items, from, to) } : bl,
),
),
);
}
}
const ctx: Ctx = {
layout,
busy,
expandedShows,
collapsedSeasons,
toggleShow,
toggleSeason,
onPlay: (rk) => onPlay(rk, order),
onRemove,
};
const layoutOptions: ViewOption<Layout>[] = [
{ id: "accordion", label: t("plex.playlist.layoutAccordion"), icon: Rows3 },
{ id: "tree", label: t("plex.playlist.layoutTree"), icon: ListTree },
];
return (
<div className="mx-auto w-[90%] max-w-[1100px] p-4">
<Button variant="glass" size="xs" className="mb-4" onClick={onBack}>
<ArrowLeft className="h-4 w-4" />
{t("plex.backToLibrary")}
</Button>
<div className="glass rounded-2xl p-4 sm:p-6">
<div className="mb-4 flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
{renaming ? (
<input
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && rename()}
onBlur={rename}
className="glass-card w-full rounded-lg px-3 py-1.5 text-lg font-bold focus:outline-hidden focus:ring-2 focus:ring-accent/40"
/>
) : (
<h1 className="truncate text-2xl font-bold">{q.data?.title ?? " "}</h1>
)}
{items.length > 0 && (
<div className="mt-0.5 text-sm text-muted">
{t("plex.browse.items", { count: items.length })}
{totalSeconds > 0 && ` · ${formatRuntime(totalSeconds)}`}
</div>
)}
</div>
{/* Layout preference: Accordion or Tree — the shared list-view switcher. */}
<ViewSwitcher
value={layout}
options={layoutOptions}
onChange={setLayout}
label={t("plex.playlist.layoutLabel")}
/>
<button
onClick={() => {
setName(q.data?.title ?? "");
setRenaming(true);
}}
title={t("plex.playlist.rename")}
className="glass-card glass-hover rounded-lg p-2 text-sm hover:text-accent"
>
<Pencil className="h-4 w-4" />
</button>
{items.length > 0 && (
<button
onClick={() => onPlay(order[0]!, order)}
className="inline-flex items-center gap-2 rounded-xl bg-accent px-4 py-2 font-medium text-white hover:opacity-90"
>
<Play className="h-5 w-5 fill-current" />
{t("plex.playlist.playAll")}
</button>
)}
<button
onClick={del}
title={t("plex.playlist.delete")}
className="glass-card glass-hover rounded-lg p-2 text-sm hover:text-danger"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
{q.isError && !q.data ? (
<StateMessage tone="error" onRetry={() => q.refetch()}>
{t("common.loadError")}
</StateMessage>
) : q.isLoading ? (
<LoadingState label={t("plex.loading")} />
) : items.length === 0 ? (
<p className="py-6 text-center text-sm text-muted">{t("plex.playlist.empty")}</p>
) : (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
<SortableContext items={blocks.map((b) => b.id)} strategy={verticalListSortingStrategy}>
<div className="space-y-1.5">
{blocks.map((b) =>
b.kind === "movie" ? (
<MovieRow key={b.id} item={b.item} ctx={ctx} />
) : (
<ShowGroup key={b.id} block={b} ctx={ctx} />
),
)}
</div>
</SortableContext>
</DndContext>
)}
</div>
</div>
);
}