feat(plex): grouped collapsible playlist view + drag-and-drop + bulk add

Playlist view now groups a run of episodes from the same show into a
collapsible season/show block so a whole series doesn't sprawl into an
endless flat list; movies stay standalone (larger poster card in the
accordion). Two per-account layouts — Accordion and Tree — persisted via
LS.plexPlaylistLayout; show groups start collapsed. Reorder is drag &
drop (@dnd-kit): a show block moves as one unit, episodes reorder within
their show, keyboard-draggable via KeyboardSensor. Remove works per item,
per season, or per whole show. The add-to-playlist dialog is generalised
to a single leaf or a whole group (tri-state none/some/all with an in/size
count); the show page gains add buttons for an episode, a season, and the
whole show. i18n en/hu/de.
This commit is contained in:
npeter83 2026-07-06 22:14:56 +02:00
parent e6b22f971a
commit 2ef22982bb
9 changed files with 603 additions and 139 deletions

View file

@ -1,10 +1,11 @@
import { lazy, Suspense, useEffect, useLayoutEffect, useRef, type CSSProperties } from "react";
import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import { useTranslation } from "react-i18next";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, CheckCircle2, Info, Play } from "lucide-react";
import { ArrowLeft, CheckCircle2, Info, ListPlus, Play } from "lucide-react";
import { api, type PlexCard, type PlexFilters, type PlexPerson } from "../lib/api";
import { useDebounced } from "../lib/useDebounced";
import { useHistorySubview } from "../lib/history";
import PlexPlaylistAdd, { type PlexAddTarget } from "./PlexPlaylistAdd";
// Lazy: the rich player (pulls in hls.js) loads only when something is first played.
const PlexPlayer = lazy(() => import("./PlexPlayer"));
@ -461,6 +462,9 @@ function PlexShowView({
const { t } = useTranslation();
const q = useQuery({ queryKey: ["plex-show", showId], queryFn: () => api.plexShow(showId) });
const d = q.data;
// "Add to playlist" dialog target (single episode / whole season / whole show); null = closed.
const [addTarget, setAddTarget] = useState<PlexAddTarget | null>(null);
const allEpisodeKeys = (d?.seasons ?? []).flatMap((se) => se.episodes.map((e) => e.id));
return (
<div className="p-4 max-w-[1200px] mx-auto">
@ -488,41 +492,74 @@ function PlexShowView({
{d.show.summary && (
<p className="text-sm text-muted mt-2 line-clamp-6 leading-relaxed">{d.show.summary}</p>
)}
{allEpisodeKeys.length > 0 && (
<button
onClick={() => setAddTarget({ kind: "group", ratingKeys: allEpisodeKeys, title: d.show.title })}
className="glass-card glass-hover mt-3 inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium"
>
<ListPlus className="w-4 h-4" />
{t("plex.playlist.addShow")}
</button>
)}
</div>
</div>
{d.seasons.map((se) => (
<div key={se.id} className="mb-6">
<h2 className="text-sm font-semibold mb-2">{se.title}</h2>
<div className="mb-2 flex items-center gap-2">
<h2 className="text-sm font-semibold">{se.title}</h2>
{se.episodes.length > 0 && (
<button
onClick={() =>
setAddTarget({
kind: "group",
ratingKeys: se.episodes.map((e) => e.id),
title: `${d.show.title}${se.title}`,
})
}
title={t("plex.playlist.addSeason")}
aria-label={t("plex.playlist.addSeason")}
className="rounded p-1 text-muted hover:text-accent"
>
<ListPlus className="w-4 h-4" />
</button>
)}
</div>
<div className="flex flex-col divide-y divide-border/60">
{se.episodes.map((ep) => {
const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched";
return (
<button
key={ep.id}
onClick={() => onPlay(ep)}
className="flex items-center gap-3 py-2 text-left group"
>
<div className="relative w-28 aspect-video rounded-lg overflow-hidden bg-card border border-border shrink-0">
<img src={ep.thumb} alt="" loading="lazy" className="w-full h-full object-cover" />
{ep.status === "watched" && (
<span className="absolute top-1 right-1 text-[9px] bg-black/70 text-white px-1 rounded">
</span>
)}
{inProgress && <div className="absolute bottom-0 inset-x-0 h-0.5 bg-accent" />}
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium truncate">
<span className="text-muted mr-1.5">{ep.episode_number}.</span>
{ep.title}
<div key={ep.id} className="flex items-center gap-3 py-2 group">
<button onClick={() => onPlay(ep)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<div className="relative w-28 aspect-video rounded-lg overflow-hidden bg-card border border-border shrink-0">
<img src={ep.thumb} alt="" loading="lazy" className="w-full h-full object-cover" />
{ep.status === "watched" && (
<span className="absolute top-1 right-1 text-[9px] bg-black/70 text-white px-1 rounded">
</span>
)}
{inProgress && <div className="absolute bottom-0 inset-x-0 h-0.5 bg-accent" />}
</div>
{ep.summary && (
<div className="text-xs text-muted line-clamp-2 mt-0.5">{ep.summary}</div>
)}
<div className="text-[11px] text-muted mt-0.5">{dur(ep.duration_seconds)}</div>
</div>
</button>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium truncate">
<span className="text-muted mr-1.5">{ep.episode_number}.</span>
{ep.title}
</div>
{ep.summary && (
<div className="text-xs text-muted line-clamp-2 mt-0.5">{ep.summary}</div>
)}
<div className="text-[11px] text-muted mt-0.5">{dur(ep.duration_seconds)}</div>
</div>
</button>
<button
onClick={() => setAddTarget({ kind: "single", ratingKey: ep.id, title: ep.title })}
title={t("plex.playlist.addEpisode")}
aria-label={t("plex.playlist.addEpisode")}
className="shrink-0 rounded p-1.5 text-muted opacity-0 transition hover:text-accent group-hover:opacity-100"
>
<ListPlus className="w-4 h-4" />
</button>
</div>
);
})}
</div>
@ -530,6 +567,8 @@ function PlexShowView({
))}
</>
)}
{addTarget && <PlexPlaylistAdd target={addTarget} onClose={() => setAddTarget(null)} />}
</div>
);
}

View file

@ -526,7 +526,10 @@ export default function PlexInfo({
/>
)}
{playlistOpen && (
<PlexPlaylistAdd item={{ id: detail.id, title: detail.title }} onClose={() => setPlaylistOpen(false)} />
<PlexPlaylistAdd
target={{ kind: "single", ratingKey: detail.id, title: detail.title }}
onClose={() => setPlaylistOpen(false)}
/>
)}
</div>
);

View file

@ -1,42 +1,60 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, Plus } from "lucide-react";
import { Check, Minus, Plus } from "lucide-react";
import { api, type PlexPlaylist } from "../lib/api";
import Modal from "./Modal";
// "Add this title to a playlist" dialog — per-user (every user has their own playlists), opened from
// the movie info page. Lists my playlists with an in/out toggle (seeded from the backend's has_item)
// and a field to create a new one seeded with this title. Playlists are personal (no admin gate).
export default function PlexPlaylistAdd({
item,
onClose,
}: {
item: { id: string; title: string };
onClose: () => void;
}) {
// What we're adding: a single leaf (movie/episode) or a whole group (a season or an entire show, as a
// set of episode rating_keys). Groups get a tri-state (none / some / all) per playlist.
export type PlexAddTarget =
| { kind: "single"; ratingKey: string; title: string }
| { kind: "group"; ratingKeys: string[]; title: string };
// "Add to playlist" dialog — per-user (every user has their own playlists). Opened from the movie info
// page (single) and the show page (single episode / whole season / whole show). Lists my playlists with
// an in/out (or partial) state and a field to create a new one seeded with the target.
export default function PlexPlaylistAdd({ target, onClose }: { target: PlexAddTarget; onClose: () => void }) {
const { t } = useTranslation();
const qc = useQueryClient();
const [newName, setNewName] = useState("");
const [busy, setBusy] = useState(false);
const [override, setOverride] = useState<Map<number, boolean>>(new Map()); // optimistic toggle state
// Optimistic per-playlist in-count override (0..size), so a toggle reflects instantly.
const [override, setOverride] = useState<Map<number, number>>(new Map());
const isGroup = target.kind === "group";
const size = isGroup ? new Set(target.ratingKeys).size : 1;
const listQ = useQuery({
queryKey: ["plex-playlists", "contains", item.id],
queryFn: () => api.plexPlaylists(item.id),
queryKey: isGroup
? ["plex-playlists", "group", target.ratingKeys]
: ["plex-playlists", "contains", target.ratingKey],
queryFn: () =>
isGroup ? api.plexPlaylists(undefined, target.ratingKeys) : api.plexPlaylists(target.ratingKey),
});
const playlists = listQ.data?.playlists ?? [];
const isIn = (p: PlexPlaylist) => (override.has(p.id) ? override.get(p.id)! : !!p.has_item);
const refresh = () => qc.invalidateQueries({ queryKey: ["plex-playlists"] });
// How many of the target a playlist currently holds (0..size).
function inCount(p: PlexPlaylist): number {
const o = override.get(p.id);
if (o !== undefined) return o;
return isGroup ? p.group_in ?? 0 : p.has_item ? 1 : 0;
}
async function toggle(p: PlexPlaylist) {
if (busy) return;
setBusy(true);
const cur = isIn(p);
const allIn = inCount(p) >= size;
try {
if (cur) await api.plexPlaylistRemoveItem(p.id, item.id);
else await api.plexPlaylistAddItem(p.id, item.id);
setOverride((m) => new Map(m).set(p.id, !cur));
if (isGroup) {
if (allIn) await api.plexPlaylistRemoveBulk(p.id, target.ratingKeys);
else await api.plexPlaylistAddBulk(p.id, target.ratingKeys);
} else {
if (allIn) await api.plexPlaylistRemoveItem(p.id, target.ratingKey);
else await api.plexPlaylistAddItem(p.id, target.ratingKey);
}
setOverride((m) => new Map(m).set(p.id, allIn ? 0 : size));
refresh();
} finally {
setBusy(false);
@ -48,9 +66,15 @@ export default function PlexPlaylistAdd({
if (!title || busy) return;
setBusy(true);
try {
const pl = await api.plexCreatePlaylist(title, item.id);
if (isGroup) {
const pl = await api.plexCreatePlaylist(title);
await api.plexPlaylistAddBulk(pl.id, target.ratingKeys);
setOverride((m) => new Map(m).set(pl.id, size));
} else {
const pl = await api.plexCreatePlaylist(title, target.ratingKey);
setOverride((m) => new Map(m).set(pl.id, 1));
}
setNewName("");
setOverride((m) => new Map(m).set(pl.id, true));
refresh();
} finally {
setBusy(false);
@ -58,7 +82,7 @@ export default function PlexPlaylistAdd({
}
return (
<Modal title={t("plex.playlistAdd.title", { title: item.title })} onClose={onClose}>
<Modal title={t("plex.playlistAdd.title", { title: target.title })} onClose={onClose}>
<div className="mb-3 flex gap-2">
<input
value={newName}
@ -84,27 +108,35 @@ export default function PlexPlaylistAdd({
<p className="py-4 text-center text-sm text-muted">{t("plex.playlistAdd.none")}</p>
) : (
playlists.map((p) => {
const inIt = isIn(p);
const n = inCount(p);
const all = n >= size;
const partial = n > 0 && n < size;
return (
<button
key={p.id}
onClick={() => toggle(p)}
disabled={busy}
className={`glass-card flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm disabled:opacity-50 ${
inIt ? "text-accent" : ""
all ? "text-accent" : ""
}`}
>
<span
className={`grid h-5 w-5 shrink-0 place-items-center rounded border ${
inIt ? "border-accent bg-accent/20" : "border-border"
all || partial ? "border-accent bg-accent/20" : "border-border"
}`}
>
{inIt && <Check className="h-3.5 w-3.5" />}
{all ? <Check className="h-3.5 w-3.5" /> : partial ? <Minus className="h-3.5 w-3.5" /> : null}
</span>
<span className="min-w-0 flex-1 truncate">{p.title}</span>
<span className="shrink-0 text-xs text-muted">
{t("plex.playlistAdd.count", { count: p.item_count })}
</span>
{isGroup ? (
<span className="shrink-0 text-xs text-muted tabular-nums">
{t("plex.playlistAdd.groupProgress", { in: n, size })}
</span>
) : (
<span className="shrink-0 text-xs text-muted">
{t("plex.playlistAdd.count", { count: p.item_count })}
</span>
)}
</button>
);
})

View file

@ -1,12 +1,300 @@
import { useState } from "react";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, ChevronDown, ChevronUp, Pencil, Play, Trash2, X } from "lucide-react";
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, type PlexCard } from "../lib/api";
import { getAccountRaw, LS, setAccountRaw } from "../lib/storage";
import { useConfirm } from "./ConfirmProvider";
// A playlist's ordered items — reorder (up/down), remove, rename, delete, and "Play all" (which opens
// the player with the whole ordered list as its queue). Rendered as a PlexBrowse subview.
// 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 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-[11px] 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 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 bg-black/70 px-1 text-[9px] 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-[13px]">{ep.title}</div>
</button>
<button
onClick={() => ctx.onRemove([ep.id])}
disabled={ctx.busy}
className="shrink-0 rounded p-1 text-muted hover:text-red-400 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 p-1 text-muted hover:text-red-400 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 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 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-[11px] 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 p-1 text-muted hover:text-red-400 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 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-[11px] 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 p-0.5 text-muted hover:text-red-400 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,
@ -22,38 +310,52 @@ export default function PlexPlaylistView({
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: ["plex-playlist", playlistId], queryFn: () => api.plexPlaylist(playlistId) });
const items: PlexCard[] = q.data?.items ?? [];
const order = items.map((i) => i.id);
// 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]);
const invalidate = () => {
qc.invalidateQueries({ queryKey: ["plex-playlist", playlistId] });
qc.invalidateQueries({ queryKey: ["plex-playlists"] });
};
async function move(idx: number, dir: -1 | 1) {
const to = idx + dir;
if (busy || to < 0 || to >= order.length) return;
function commit(next: PlexCard[]) {
setItems(next);
api
.plexReorderPlaylist(playlistId, next.map((i) => i.id))
.then(() => qc.invalidateQueries({ queryKey: ["plex-playlists"] }));
}
async function onRemove(keys: string[]) {
if (busy || !keys.length) return;
setBusy(true);
const next = [...order];
[next[idx], next[to]] = [next[to], next[idx]];
const set = new Set(keys);
setItems((prev) => prev.filter((i) => !set.has(i.id)));
try {
await api.plexReorderPlaylist(playlistId, next);
invalidate();
} finally {
setBusy(false);
}
}
async function remove(itemRk: string) {
if (busy) return;
setBusy(true);
try {
await api.plexPlaylistRemoveItem(playlistId, itemRk);
if (keys.length === 1) await api.plexPlaylistRemoveItem(playlistId, keys[0]);
else await api.plexPlaylistRemoveBulk(playlistId, keys);
invalidate();
} finally {
setBusy(false);
}
}
async function rename() {
const title = name.trim();
if (!title) return;
@ -69,8 +371,79 @@ export default function PlexPlaylistView({
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 LayoutBtn = ({ v, icon, label }: { v: Layout; icon: ReactNode; label: string }) => (
<button
onClick={() => setLayout(v)}
title={label}
aria-label={label}
aria-pressed={layout === v}
className={`rounded-lg p-2 text-sm transition ${
layout === v ? "bg-accent/15 text-accent" : "glass-card glass-hover text-muted"
}`}
>
{icon}
</button>
);
return (
<div className="w-[90%] max-w-[1100px] mx-auto p-4">
<div className="mx-auto w-[90%] max-w-[1100px] p-4">
<button
onClick={onBack}
className="glass-card glass-hover mb-4 inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs"
@ -80,7 +453,6 @@ export default function PlexPlaylistView({
</button>
<div className="glass rounded-2xl p-4 sm:p-6">
{/* Header: title (rename) + Play all + delete */}
<div className="mb-4 flex flex-wrap items-center gap-3">
{renaming ? (
<input
@ -94,6 +466,11 @@ export default function PlexPlaylistView({
) : (
<h1 className="min-w-0 flex-1 truncate text-2xl font-bold">{q.data?.title ?? " "}</h1>
)}
{/* Layout preference: Accordion (A) or Tree (C). */}
<div className="flex items-center gap-1">
<LayoutBtn v="accordion" icon={<Rows3 className="h-4 w-4" />} label={t("plex.playlist.layoutAccordion")} />
<LayoutBtn v="tree" icon={<ListTree className="h-4 w-4" />} label={t("plex.playlist.layoutTree")} />
</div>
<button
onClick={() => {
setName(q.data?.title ?? "");
@ -127,56 +504,19 @@ export default function PlexPlaylistView({
) : items.length === 0 ? (
<p className="py-6 text-center text-sm text-muted">{t("plex.playlist.empty")}</p>
) : (
<ol className="space-y-1.5">
{items.map((it, idx) => (
<li key={it.id} className="glass-card flex items-center gap-3 rounded-lg p-2">
<span className="w-5 shrink-0 text-center text-xs text-muted">{idx + 1}</span>
<button
onClick={() => onPlay(it.id, order)}
className="group flex min-w-0 flex-1 items-center gap-3 text-left"
>
<div className="relative h-14 w-10 shrink-0 overflow-hidden rounded border border-border bg-surface">
<img src={it.thumb} alt="" loading="lazy" className="h-full w-full object-cover" />
<div className="absolute inset-0 grid place-items-center bg-black/40 opacity-0 transition group-hover:opacity-100">
<Play className="h-5 w-5 text-white" fill="currentColor" />
</div>
</div>
<div className="min-w-0">
<div className="truncate text-sm font-medium">
{it.type === "episode" && it.show_title ? `${it.show_title}${it.title}` : it.title}
</div>
<div className="text-xs text-muted">{it.year}</div>
</div>
</button>
<div className="flex shrink-0 items-center gap-1">
<button
onClick={() => move(idx, -1)}
disabled={busy || idx === 0}
className="rounded p-1 text-muted hover:text-fg disabled:opacity-30"
title={t("plex.playlist.up")}
>
<ChevronUp className="h-4 w-4" />
</button>
<button
onClick={() => move(idx, 1)}
disabled={busy || idx === items.length - 1}
className="rounded p-1 text-muted hover:text-fg disabled:opacity-30"
title={t("plex.playlist.down")}
>
<ChevronDown className="h-4 w-4" />
</button>
<button
onClick={() => remove(it.id)}
disabled={busy}
className="rounded p-1 text-muted hover:text-red-400 disabled:opacity-30"
title={t("plex.playlist.remove")}
>
<X className="h-4 w-4" />
</button>
</div>
</li>
))}
</ol>
<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>

View file

@ -158,7 +158,8 @@
"newPlaceholder": "Name der neuen Playlist…",
"create": "Erstellen",
"none": "Noch keine Playlists. Erstelle oben eine.",
"count": "{{count}} Titel"
"count": "{{count}} Titel",
"groupProgress": "{{in}} / {{size}}"
},
"playlist": {
"section": "Playlists",
@ -172,6 +173,16 @@
"empty": "Diese Playlist ist leer. Füge Titel über deren Infoseite hinzu.",
"up": "Nach oben",
"down": "Nach unten",
"remove": "Entfernen"
"remove": "Entfernen",
"layoutAccordion": "Akkordeon-Ansicht",
"layoutTree": "Baum-Ansicht",
"removeShow": "Ganze Serie entfernen",
"removeSeason": "Ganze Staffel entfernen",
"episodes": "{{count}} Folgen",
"season": "Staffel {{n}}",
"seasonUnknown": "Folgen",
"addShow": "Ganze Serie zu einer Playlist",
"addSeason": "Staffel zu einer Playlist",
"addEpisode": "Folge zu einer Playlist"
}
}

View file

@ -158,7 +158,8 @@
"newPlaceholder": "New playlist name…",
"create": "Create",
"none": "No playlists yet. Create one above.",
"count": "{{count}} items"
"count": "{{count}} items",
"groupProgress": "{{in}} / {{size}}"
},
"playlist": {
"section": "Playlists",
@ -172,6 +173,16 @@
"empty": "This playlist is empty. Add titles from their info page.",
"up": "Move up",
"down": "Move down",
"remove": "Remove"
"remove": "Remove",
"layoutAccordion": "Accordion view",
"layoutTree": "Tree view",
"removeShow": "Remove whole show",
"removeSeason": "Remove whole season",
"episodes": "{{count}} episodes",
"season": "Season {{n}}",
"seasonUnknown": "Episodes",
"addShow": "Add whole show to a playlist",
"addSeason": "Add season to a playlist",
"addEpisode": "Add episode to a playlist"
}
}

View file

@ -158,7 +158,8 @@
"newPlaceholder": "Új lista neve…",
"create": "Létrehozás",
"none": "Még nincs lista. Hozz létre egyet fent.",
"count": "{{count}} elem"
"count": "{{count}} elem",
"groupProgress": "{{in}} / {{size}}"
},
"playlist": {
"section": "Lejátszási listák",
@ -172,6 +173,16 @@
"empty": "Ez a lista üres. Adj hozzá címeket az info-oldalukról.",
"up": "Fel",
"down": "Le",
"remove": "Eltávolítás"
"remove": "Eltávolítás",
"layoutAccordion": "Harmonika nézet",
"layoutTree": "Fa nézet",
"removeShow": "Egész sorozat eltávolítása",
"removeSeason": "Egész évad eltávolítása",
"episodes": "{{count}} epizód",
"season": "{{n}}. évad",
"seasonUnknown": "Epizódok",
"addShow": "Egész sorozat listához adása",
"addSeason": "Évad listához adása",
"addEpisode": "Epizód listához adása"
}
}

View file

@ -653,6 +653,7 @@ export interface PlexCard {
season_number?: number | null; // episode
episode_number?: number | null; // episode
show_title?: string | null; // episode (in a mixed playlist)
show_id?: string | null; // episode: the show's rating_key (for grouping a playlist by show/season)
summary?: string | null; // episode
}
export interface PlexBrowseResult {
@ -737,6 +738,7 @@ export interface PlexPlaylist {
item_count: number;
thumb?: string | null;
has_item?: boolean; // only when the list was fetched with ?contains=<rating_key>
group_in?: number; // only when fetched with ?contains_group=<rk,rk,…>: how many of the group it holds
}
export interface PlexPlaylistDetail {
id: number;
@ -1178,11 +1180,25 @@ export const api = {
plexSetCollectionEditable: (rk: string, editable: boolean): Promise<PlexCollection> =>
req(`/api/plex/collections/${encodeURIComponent(rk)}/editable`, { method: "POST", body: JSON.stringify({ editable }) }),
// --- Playlists (Siftlode-native, per-user, ordered) ---
plexPlaylists: (contains?: string): Promise<{ playlists: PlexPlaylist[] }> =>
req(`/api/plex/playlists${contains ? `?contains=${encodeURIComponent(contains)}` : ""}`),
// `contains`=single rating_key → per-playlist has_item; `containsGroup`=a set of rating_keys (a whole
// season/show) → per-playlist group_in + a top-level group_size (for the bulk add-to-playlist dialog).
plexPlaylists: (
contains?: string,
containsGroup?: string[],
): Promise<{ playlists: PlexPlaylist[]; group_size?: number }> => {
const p = new URLSearchParams();
if (contains) p.set("contains", contains);
if (containsGroup) p.set("contains_group", containsGroup.join(","));
const qs = p.toString();
return req(`/api/plex/playlists${qs ? `?${qs}` : ""}`);
},
plexPlaylist: (id: number): Promise<PlexPlaylistDetail> => req(`/api/plex/playlists/${id}`),
plexCreatePlaylist: (title: string, item_rating_key?: string): Promise<PlexPlaylist> =>
req(`/api/plex/playlists`, { method: "POST", body: JSON.stringify({ title, item_rating_key }) }),
plexPlaylistAddBulk: (id: number, itemRks: string[]): Promise<{ added: number; item_count: number }> =>
req(`/api/plex/playlists/${id}/items/bulk`, { method: "POST", body: JSON.stringify({ item_rating_keys: itemRks }) }),
plexPlaylistRemoveBulk: (id: number, itemRks: string[]): Promise<{ removed: number; item_count: number }> =>
req(`/api/plex/playlists/${id}/items/remove-bulk`, { method: "POST", body: JSON.stringify({ item_rating_keys: itemRks }) }),
plexRenamePlaylist: (id: number, title: string): Promise<PlexPlaylist> =>
req(`/api/plex/playlists/${id}`, { method: "PATCH", body: JSON.stringify({ title }) }),
plexDeletePlaylist: (id: number): Promise<{ deleted: number }> =>

View file

@ -27,6 +27,7 @@ export const LS = {
plexShow: "siftlode.plexShow",
plexSort: "siftlode.plexSort",
plexFilters: "siftlode.plexFilters",
plexPlaylistLayout: "siftlode.plexPlaylistLayout",
notifHistory: "siftlode.notifications",
notifSettings: "siftlode.notifSettings",
onboardingDismissed: "siftlode.onboarding.dismissed",