merge: Plex playlist power — grouped collapsible view, drag & drop, bulk add (UAT accepted, dev-only)
This commit is contained in:
commit
04d35375ed
10 changed files with 698 additions and 145 deletions
|
|
@ -186,11 +186,15 @@ def _episode_card(e: PlexItem, st: PlexState | None) -> dict:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _leaf_card(it: PlexItem, st: PlexState | None, show_title: str | None = None) -> dict:
|
def _leaf_card(
|
||||||
"""A playable-leaf card (movie or episode). Used by playlists, which can mix both kinds."""
|
it: PlexItem, st: PlexState | None, show_title: str | None = None, show_rk: str | None = None
|
||||||
|
) -> dict:
|
||||||
|
"""A playable-leaf card (movie or episode). Used by playlists, which can mix both kinds.
|
||||||
|
`show_rk` (the show's rating_key) lets the client group a playlist's episodes by show/season."""
|
||||||
if it.kind == "episode":
|
if it.kind == "episode":
|
||||||
card = _episode_card(it, st)
|
card = _episode_card(it, st)
|
||||||
card["show_title"] = show_title
|
card["show_title"] = show_title
|
||||||
|
card["show_id"] = show_rk
|
||||||
return card
|
return card
|
||||||
return _movie_card(it, st)
|
return _movie_card(it, st)
|
||||||
|
|
||||||
|
|
@ -639,15 +643,23 @@ def _playlist_item_query(db: Session, pid: int):
|
||||||
@router.get("/playlists")
|
@router.get("/playlists")
|
||||||
def playlists(
|
def playlists(
|
||||||
contains: str | None = None,
|
contains: str | None = None,
|
||||||
|
contains_group: str | None = None,
|
||||||
user: User = Depends(current_user),
|
user: User = Depends(current_user),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""The current user's playlists (newest-touched first), each with an item count + a cover thumb.
|
"""The current user's playlists (newest-touched first), each with an item count + a cover thumb.
|
||||||
`contains`=an item rating_key adds `has_item` per playlist (for the 'add to playlist' dialog)."""
|
`contains`=an item rating_key adds `has_item` per playlist (for the single 'add to playlist' dialog).
|
||||||
|
`contains_group`=a comma-separated list of rating_keys adds `group_in` per playlist (how many of the
|
||||||
|
group it already holds) + a top-level `group_size`, for the 'add a whole season/show' dialog."""
|
||||||
contains_id = None
|
contains_id = None
|
||||||
if contains:
|
if contains:
|
||||||
row = db.query(PlexItem.id).filter_by(rating_key=str(contains)).first()
|
row = db.query(PlexItem.id).filter_by(rating_key=str(contains)).first()
|
||||||
contains_id = row[0] if row else None
|
contains_id = row[0] if row else None
|
||||||
|
group_ids: set[int] | None = None
|
||||||
|
if contains_group is not None:
|
||||||
|
rks = [s for s in (contains_group or "").split(",") if s]
|
||||||
|
rows = db.query(PlexItem.id).filter(PlexItem.rating_key.in_(rks or [""])).all()
|
||||||
|
group_ids = {r[0] for r in rows}
|
||||||
out = []
|
out = []
|
||||||
for pl in db.query(PlexPlaylist).filter_by(user_id=user.id).order_by(PlexPlaylist.updated_at.desc()):
|
for pl in db.query(PlexPlaylist).filter_by(user_id=user.id).order_by(PlexPlaylist.updated_at.desc()):
|
||||||
count = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pl.id).scalar() or 0
|
count = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pl.id).scalar() or 0
|
||||||
|
|
@ -658,8 +670,18 @@ def playlists(
|
||||||
db.query(PlexPlaylistItem.id).filter_by(playlist_id=pl.id, item_id=contains_id).first()
|
db.query(PlexPlaylistItem.id).filter_by(playlist_id=pl.id, item_id=contains_id).first()
|
||||||
is not None
|
is not None
|
||||||
)
|
)
|
||||||
|
if group_ids is not None:
|
||||||
|
card["group_in"] = (
|
||||||
|
db.query(func.count(PlexPlaylistItem.id))
|
||||||
|
.filter(PlexPlaylistItem.playlist_id == pl.id, PlexPlaylistItem.item_id.in_(group_ids or [0]))
|
||||||
|
.scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
out.append(card)
|
out.append(card)
|
||||||
return {"playlists": out}
|
resp: dict = {"playlists": out}
|
||||||
|
if group_ids is not None:
|
||||||
|
resp["group_size"] = len(group_ids)
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
@router.post("/playlists")
|
@router.post("/playlists")
|
||||||
|
|
@ -694,10 +716,18 @@ def playlist_detail(pid: int, user: User = Depends(current_user), db: Session =
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
shows = {
|
shows = {
|
||||||
sh.id: sh.title
|
sh.id: sh
|
||||||
for sh in db.query(PlexShow).filter(PlexShow.id.in_([it.show_id for it in items if it.show_id] or [0]))
|
for sh in db.query(PlexShow).filter(PlexShow.id.in_([it.show_id for it in items if it.show_id] or [0]))
|
||||||
}
|
}
|
||||||
cards = [_leaf_card(it, states.get(it.id), shows.get(it.show_id)) for it in items]
|
cards = [
|
||||||
|
_leaf_card(
|
||||||
|
it,
|
||||||
|
states.get(it.id),
|
||||||
|
shows[it.show_id].title if it.show_id in shows else None,
|
||||||
|
shows[it.show_id].rating_key if it.show_id in shows else None,
|
||||||
|
)
|
||||||
|
for it in items
|
||||||
|
]
|
||||||
return {"id": pl.id, "title": pl.title, "items": cards}
|
return {"id": pl.id, "title": pl.title, "items": cards}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -748,6 +778,65 @@ def playlist_remove_item(pid: int, item_rating_key: str, user: User = Depends(cu
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
def _items_by_rks(db: Session, rks: list) -> list[PlexItem]:
|
||||||
|
"""Resolve rating_keys to PlexItems, preserving the input order (drops unknown keys)."""
|
||||||
|
order = [str(k) for k in rks if str(k)]
|
||||||
|
if not order:
|
||||||
|
return []
|
||||||
|
by_rk = {it.rating_key: it for it in db.query(PlexItem).filter(PlexItem.rating_key.in_(order))}
|
||||||
|
seen: set[str] = set()
|
||||||
|
out: list[PlexItem] = []
|
||||||
|
for rk in order:
|
||||||
|
it = by_rk.get(rk)
|
||||||
|
if it is not None and rk not in seen:
|
||||||
|
seen.add(rk)
|
||||||
|
out.append(it)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/playlists/{pid}/items/bulk")
|
||||||
|
def playlist_add_bulk(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||||||
|
"""Append many items at once (a whole season/show). Already-present items are skipped; the input
|
||||||
|
order is preserved for the newly-added ones. Returns how many were added + the new total."""
|
||||||
|
pl = _own_playlist_or_404(db, pid, user)
|
||||||
|
items = _items_by_rks(db, payload.get("item_rating_keys") or [])
|
||||||
|
existing = {row[0] for row in db.query(PlexPlaylistItem.item_id).filter_by(playlist_id=pid)}
|
||||||
|
pos = int(db.query(func.coalesce(func.max(PlexPlaylistItem.position), -1)).filter_by(playlist_id=pid).scalar())
|
||||||
|
added = 0
|
||||||
|
for it in items:
|
||||||
|
if it.id in existing:
|
||||||
|
continue
|
||||||
|
pos += 1
|
||||||
|
db.add(PlexPlaylistItem(playlist_id=pid, item_id=it.id, position=pos))
|
||||||
|
existing.add(it.id)
|
||||||
|
added += 1
|
||||||
|
if added:
|
||||||
|
pl.updated_at = datetime.now(timezone.utc)
|
||||||
|
db.commit()
|
||||||
|
total = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pid).scalar() or 0
|
||||||
|
return {"added": added, "item_count": total}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/playlists/{pid}/items/remove-bulk")
|
||||||
|
def playlist_remove_bulk(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||||||
|
"""Remove many items at once (a whole season/show, or a multi-select). Returns how many were
|
||||||
|
removed + the new total."""
|
||||||
|
pl = _own_playlist_or_404(db, pid, user)
|
||||||
|
ids = [it.id for it in _items_by_rks(db, payload.get("item_rating_keys") or [])]
|
||||||
|
removed = 0
|
||||||
|
if ids:
|
||||||
|
removed = (
|
||||||
|
db.query(PlexPlaylistItem)
|
||||||
|
.filter(PlexPlaylistItem.playlist_id == pid, PlexPlaylistItem.item_id.in_(ids))
|
||||||
|
.delete(synchronize_session=False)
|
||||||
|
)
|
||||||
|
if removed:
|
||||||
|
pl.updated_at = datetime.now(timezone.utc)
|
||||||
|
db.commit()
|
||||||
|
total = db.query(func.count(PlexPlaylistItem.id)).filter_by(playlist_id=pid).scalar() or 0
|
||||||
|
return {"removed": removed, "item_count": total}
|
||||||
|
|
||||||
|
|
||||||
@router.put("/playlists/{pid}/order")
|
@router.put("/playlists/{pid}/order")
|
||||||
def reorder_playlist(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
def reorder_playlist(pid: int, payload: dict, user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||||||
"""Set the playlist order from an explicit list of item rating_keys (0-based positions)."""
|
"""Set the playlist order from an explicit list of item rating_keys (0-based positions)."""
|
||||||
|
|
|
||||||
|
|
@ -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 { useTranslation } from "react-i18next";
|
||||||
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
|
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 { api, type PlexCard, type PlexFilters, type PlexPerson } from "../lib/api";
|
||||||
import { useDebounced } from "../lib/useDebounced";
|
import { useDebounced } from "../lib/useDebounced";
|
||||||
import { useHistorySubview } from "../lib/history";
|
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.
|
// Lazy: the rich player (pulls in hls.js) loads only when something is first played.
|
||||||
const PlexPlayer = lazy(() => import("./PlexPlayer"));
|
const PlexPlayer = lazy(() => import("./PlexPlayer"));
|
||||||
|
|
@ -461,6 +462,9 @@ function PlexShowView({
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const q = useQuery({ queryKey: ["plex-show", showId], queryFn: () => api.plexShow(showId) });
|
const q = useQuery({ queryKey: ["plex-show", showId], queryFn: () => api.plexShow(showId) });
|
||||||
const d = q.data;
|
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 (
|
return (
|
||||||
<div className="p-4 max-w-[1200px] mx-auto">
|
<div className="p-4 max-w-[1200px] mx-auto">
|
||||||
|
|
@ -488,41 +492,74 @@ function PlexShowView({
|
||||||
{d.show.summary && (
|
{d.show.summary && (
|
||||||
<p className="text-sm text-muted mt-2 line-clamp-6 leading-relaxed">{d.show.summary}</p>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{d.seasons.map((se) => (
|
{d.seasons.map((se) => (
|
||||||
<div key={se.id} className="mb-6">
|
<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">
|
<div className="flex flex-col divide-y divide-border/60">
|
||||||
{se.episodes.map((ep) => {
|
{se.episodes.map((ep) => {
|
||||||
const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched";
|
const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched";
|
||||||
return (
|
return (
|
||||||
<button
|
<div key={ep.id} className="flex items-center gap-3 py-2 group">
|
||||||
key={ep.id}
|
<button onClick={() => onPlay(ep)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
|
||||||
onClick={() => onPlay(ep)}
|
<div className="relative w-28 aspect-video rounded-lg overflow-hidden bg-card border border-border shrink-0">
|
||||||
className="flex items-center gap-3 py-2 text-left group"
|
<img src={ep.thumb} alt="" loading="lazy" className="w-full h-full object-cover" />
|
||||||
>
|
{ep.status === "watched" && (
|
||||||
<div className="relative w-28 aspect-video rounded-lg overflow-hidden bg-card border border-border shrink-0">
|
<span className="absolute top-1 right-1 text-[9px] bg-black/70 text-white px-1 rounded">
|
||||||
<img src={ep.thumb} alt="" loading="lazy" className="w-full h-full object-cover" />
|
✓
|
||||||
{ep.status === "watched" && (
|
</span>
|
||||||
<span className="absolute top-1 right-1 text-[9px] bg-black/70 text-white px-1 rounded">
|
)}
|
||||||
✓
|
{inProgress && <div className="absolute bottom-0 inset-x-0 h-0.5 bg-accent" />}
|
||||||
</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>
|
</div>
|
||||||
{ep.summary && (
|
<div className="min-w-0 flex-1">
|
||||||
<div className="text-xs text-muted line-clamp-2 mt-0.5">{ep.summary}</div>
|
<div className="text-sm font-medium truncate">
|
||||||
)}
|
<span className="text-muted mr-1.5">{ep.episode_number}.</span>
|
||||||
<div className="text-[11px] text-muted mt-0.5">{dur(ep.duration_seconds)}</div>
|
{ep.title}
|
||||||
</div>
|
</div>
|
||||||
</button>
|
{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>
|
</div>
|
||||||
|
|
@ -530,6 +567,8 @@ function PlexShowView({
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{addTarget && <PlexPlaylistAdd target={addTarget} onClose={() => setAddTarget(null)} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -526,7 +526,10 @@ export default function PlexInfo({
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{playlistOpen && (
|
{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>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,60 @@
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
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 { api, type PlexPlaylist } from "../lib/api";
|
||||||
import Modal from "./Modal";
|
import Modal from "./Modal";
|
||||||
|
|
||||||
// "Add this title to a playlist" dialog — per-user (every user has their own playlists), opened from
|
// What we're adding: a single leaf (movie/episode) or a whole group (a season or an entire show, as a
|
||||||
// the movie info page. Lists my playlists with an in/out toggle (seeded from the backend's has_item)
|
// set of episode rating_keys). Groups get a tri-state (none / some / all) per playlist.
|
||||||
// and a field to create a new one seeded with this title. Playlists are personal (no admin gate).
|
export type PlexAddTarget =
|
||||||
export default function PlexPlaylistAdd({
|
| { kind: "single"; ratingKey: string; title: string }
|
||||||
item,
|
| { kind: "group"; ratingKeys: string[]; title: string };
|
||||||
onClose,
|
|
||||||
}: {
|
// "Add to playlist" dialog — per-user (every user has their own playlists). Opened from the movie info
|
||||||
item: { id: string; title: string };
|
// page (single) and the show page (single episode / whole season / whole show). Lists my playlists with
|
||||||
onClose: () => void;
|
// 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 { t } = useTranslation();
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const [newName, setNewName] = useState("");
|
const [newName, setNewName] = useState("");
|
||||||
const [busy, setBusy] = useState(false);
|
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({
|
const listQ = useQuery({
|
||||||
queryKey: ["plex-playlists", "contains", item.id],
|
queryKey: isGroup
|
||||||
queryFn: () => api.plexPlaylists(item.id),
|
? ["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 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"] });
|
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) {
|
async function toggle(p: PlexPlaylist) {
|
||||||
if (busy) return;
|
if (busy) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
const cur = isIn(p);
|
const allIn = inCount(p) >= size;
|
||||||
try {
|
try {
|
||||||
if (cur) await api.plexPlaylistRemoveItem(p.id, item.id);
|
if (isGroup) {
|
||||||
else await api.plexPlaylistAddItem(p.id, item.id);
|
if (allIn) await api.plexPlaylistRemoveBulk(p.id, target.ratingKeys);
|
||||||
setOverride((m) => new Map(m).set(p.id, !cur));
|
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();
|
refresh();
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
|
|
@ -48,9 +66,15 @@ export default function PlexPlaylistAdd({
|
||||||
if (!title || busy) return;
|
if (!title || busy) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
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("");
|
setNewName("");
|
||||||
setOverride((m) => new Map(m).set(pl.id, true));
|
|
||||||
refresh();
|
refresh();
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
|
|
@ -58,7 +82,7 @@ export default function PlexPlaylistAdd({
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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">
|
<div className="mb-3 flex gap-2">
|
||||||
<input
|
<input
|
||||||
value={newName}
|
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>
|
<p className="py-4 text-center text-sm text-muted">{t("plex.playlistAdd.none")}</p>
|
||||||
) : (
|
) : (
|
||||||
playlists.map((p) => {
|
playlists.map((p) => {
|
||||||
const inIt = isIn(p);
|
const n = inCount(p);
|
||||||
|
const all = n >= size;
|
||||||
|
const partial = n > 0 && n < size;
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={p.id}
|
key={p.id}
|
||||||
onClick={() => toggle(p)}
|
onClick={() => toggle(p)}
|
||||||
disabled={busy}
|
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 ${
|
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
|
<span
|
||||||
className={`grid h-5 w-5 shrink-0 place-items-center rounded border ${
|
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>
|
||||||
<span className="min-w-0 flex-1 truncate">{p.title}</span>
|
<span className="min-w-0 flex-1 truncate">{p.title}</span>
|
||||||
<span className="shrink-0 text-xs text-muted">
|
{isGroup ? (
|
||||||
{t("plex.playlistAdd.count", { count: p.item_count })}
|
<span className="shrink-0 text-xs text-muted tabular-nums">
|
||||||
</span>
|
{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>
|
</button>
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,300 @@
|
||||||
import { useState } from "react";
|
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
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 { api, type PlexCard } from "../lib/api";
|
||||||
|
import { getAccountRaw, LS, setAccountRaw } from "../lib/storage";
|
||||||
import { useConfirm } from "./ConfirmProvider";
|
import { useConfirm } from "./ConfirmProvider";
|
||||||
|
|
||||||
// A playlist's ordered items — reorder (up/down), remove, rename, delete, and "Play all" (which opens
|
// A playlist's items, grouped for readability: movies stay standalone, while a run of episodes from the
|
||||||
// the player with the whole ordered list as its queue). Rendered as a PlexBrowse subview.
|
// 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({
|
export default function PlexPlaylistView({
|
||||||
playlistId,
|
playlistId,
|
||||||
onBack,
|
onBack,
|
||||||
|
|
@ -22,38 +310,52 @@ export default function PlexPlaylistView({
|
||||||
const [renaming, setRenaming] = useState(false);
|
const [renaming, setRenaming] = useState(false);
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [busy, setBusy] = useState(false);
|
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 q = useQuery({ queryKey: ["plex-playlist", playlistId], queryFn: () => api.plexPlaylist(playlistId) });
|
||||||
const items: PlexCard[] = q.data?.items ?? [];
|
// Local optimistic copy so drag/remove are instant; re-synced whenever the query returns.
|
||||||
const order = items.map((i) => i.id);
|
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 = () => {
|
const invalidate = () => {
|
||||||
qc.invalidateQueries({ queryKey: ["plex-playlist", playlistId] });
|
qc.invalidateQueries({ queryKey: ["plex-playlist", playlistId] });
|
||||||
qc.invalidateQueries({ queryKey: ["plex-playlists"] });
|
qc.invalidateQueries({ queryKey: ["plex-playlists"] });
|
||||||
};
|
};
|
||||||
|
|
||||||
async function move(idx: number, dir: -1 | 1) {
|
function commit(next: PlexCard[]) {
|
||||||
const to = idx + dir;
|
setItems(next);
|
||||||
if (busy || to < 0 || to >= order.length) return;
|
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);
|
setBusy(true);
|
||||||
const next = [...order];
|
const set = new Set(keys);
|
||||||
[next[idx], next[to]] = [next[to], next[idx]];
|
setItems((prev) => prev.filter((i) => !set.has(i.id)));
|
||||||
try {
|
try {
|
||||||
await api.plexReorderPlaylist(playlistId, next);
|
if (keys.length === 1) await api.plexPlaylistRemoveItem(playlistId, keys[0]);
|
||||||
invalidate();
|
else await api.plexPlaylistRemoveBulk(playlistId, keys);
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function remove(itemRk: string) {
|
|
||||||
if (busy) return;
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
await api.plexPlaylistRemoveItem(playlistId, itemRk);
|
|
||||||
invalidate();
|
invalidate();
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rename() {
|
async function rename() {
|
||||||
const title = name.trim();
|
const title = name.trim();
|
||||||
if (!title) return;
|
if (!title) return;
|
||||||
|
|
@ -69,8 +371,79 @@ export default function PlexPlaylistView({
|
||||||
onBack();
|
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 (
|
return (
|
||||||
<div className="w-[90%] max-w-[1100px] mx-auto p-4">
|
<div className="mx-auto w-[90%] max-w-[1100px] p-4">
|
||||||
<button
|
<button
|
||||||
onClick={onBack}
|
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"
|
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>
|
</button>
|
||||||
|
|
||||||
<div className="glass rounded-2xl p-4 sm:p-6">
|
<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">
|
<div className="mb-4 flex flex-wrap items-center gap-3">
|
||||||
{renaming ? (
|
{renaming ? (
|
||||||
<input
|
<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>
|
<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
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setName(q.data?.title ?? "");
|
setName(q.data?.title ?? "");
|
||||||
|
|
@ -127,56 +504,19 @@ export default function PlexPlaylistView({
|
||||||
) : items.length === 0 ? (
|
) : items.length === 0 ? (
|
||||||
<p className="py-6 text-center text-sm text-muted">{t("plex.playlist.empty")}</p>
|
<p className="py-6 text-center text-sm text-muted">{t("plex.playlist.empty")}</p>
|
||||||
) : (
|
) : (
|
||||||
<ol className="space-y-1.5">
|
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
|
||||||
{items.map((it, idx) => (
|
<SortableContext items={blocks.map((b) => b.id)} strategy={verticalListSortingStrategy}>
|
||||||
<li key={it.id} className="glass-card flex items-center gap-3 rounded-lg p-2">
|
<div className="space-y-1.5">
|
||||||
<span className="w-5 shrink-0 text-center text-xs text-muted">{idx + 1}</span>
|
{blocks.map((b) =>
|
||||||
<button
|
b.kind === "movie" ? (
|
||||||
onClick={() => onPlay(it.id, order)}
|
<MovieRow key={b.id} item={b.item} ctx={ctx} />
|
||||||
className="group flex min-w-0 flex-1 items-center gap-3 text-left"
|
) : (
|
||||||
>
|
<ShowGroup key={b.id} block={b} ctx={ctx} />
|
||||||
<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">
|
</div>
|
||||||
<Play className="h-5 w-5 text-white" fill="currentColor" />
|
</SortableContext>
|
||||||
</div>
|
</DndContext>
|
||||||
</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>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -158,7 +158,8 @@
|
||||||
"newPlaceholder": "Name der neuen Playlist…",
|
"newPlaceholder": "Name der neuen Playlist…",
|
||||||
"create": "Erstellen",
|
"create": "Erstellen",
|
||||||
"none": "Noch keine Playlists. Erstelle oben eine.",
|
"none": "Noch keine Playlists. Erstelle oben eine.",
|
||||||
"count": "{{count}} Titel"
|
"count": "{{count}} Titel",
|
||||||
|
"groupProgress": "{{in}} / {{size}}"
|
||||||
},
|
},
|
||||||
"playlist": {
|
"playlist": {
|
||||||
"section": "Playlists",
|
"section": "Playlists",
|
||||||
|
|
@ -172,6 +173,16 @@
|
||||||
"empty": "Diese Playlist ist leer. Füge Titel über deren Infoseite hinzu.",
|
"empty": "Diese Playlist ist leer. Füge Titel über deren Infoseite hinzu.",
|
||||||
"up": "Nach oben",
|
"up": "Nach oben",
|
||||||
"down": "Nach unten",
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -158,7 +158,8 @@
|
||||||
"newPlaceholder": "New playlist name…",
|
"newPlaceholder": "New playlist name…",
|
||||||
"create": "Create",
|
"create": "Create",
|
||||||
"none": "No playlists yet. Create one above.",
|
"none": "No playlists yet. Create one above.",
|
||||||
"count": "{{count}} items"
|
"count": "{{count}} items",
|
||||||
|
"groupProgress": "{{in}} / {{size}}"
|
||||||
},
|
},
|
||||||
"playlist": {
|
"playlist": {
|
||||||
"section": "Playlists",
|
"section": "Playlists",
|
||||||
|
|
@ -172,6 +173,16 @@
|
||||||
"empty": "This playlist is empty. Add titles from their info page.",
|
"empty": "This playlist is empty. Add titles from their info page.",
|
||||||
"up": "Move up",
|
"up": "Move up",
|
||||||
"down": "Move down",
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -158,7 +158,8 @@
|
||||||
"newPlaceholder": "Új lista neve…",
|
"newPlaceholder": "Új lista neve…",
|
||||||
"create": "Létrehozás",
|
"create": "Létrehozás",
|
||||||
"none": "Még nincs lista. Hozz létre egyet fent.",
|
"none": "Még nincs lista. Hozz létre egyet fent.",
|
||||||
"count": "{{count}} elem"
|
"count": "{{count}} elem",
|
||||||
|
"groupProgress": "{{in}} / {{size}}"
|
||||||
},
|
},
|
||||||
"playlist": {
|
"playlist": {
|
||||||
"section": "Lejátszási listák",
|
"section": "Lejátszási listák",
|
||||||
|
|
@ -172,6 +173,16 @@
|
||||||
"empty": "Ez a lista üres. Adj hozzá címeket az info-oldalukról.",
|
"empty": "Ez a lista üres. Adj hozzá címeket az info-oldalukról.",
|
||||||
"up": "Fel",
|
"up": "Fel",
|
||||||
"down": "Le",
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -653,6 +653,7 @@ export interface PlexCard {
|
||||||
season_number?: number | null; // episode
|
season_number?: number | null; // episode
|
||||||
episode_number?: number | null; // episode
|
episode_number?: number | null; // episode
|
||||||
show_title?: string | null; // episode (in a mixed playlist)
|
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
|
summary?: string | null; // episode
|
||||||
}
|
}
|
||||||
export interface PlexBrowseResult {
|
export interface PlexBrowseResult {
|
||||||
|
|
@ -737,6 +738,7 @@ export interface PlexPlaylist {
|
||||||
item_count: number;
|
item_count: number;
|
||||||
thumb?: string | null;
|
thumb?: string | null;
|
||||||
has_item?: boolean; // only when the list was fetched with ?contains=<rating_key>
|
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 {
|
export interface PlexPlaylistDetail {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -1178,11 +1180,25 @@ export const api = {
|
||||||
plexSetCollectionEditable: (rk: string, editable: boolean): Promise<PlexCollection> =>
|
plexSetCollectionEditable: (rk: string, editable: boolean): Promise<PlexCollection> =>
|
||||||
req(`/api/plex/collections/${encodeURIComponent(rk)}/editable`, { method: "POST", body: JSON.stringify({ editable }) }),
|
req(`/api/plex/collections/${encodeURIComponent(rk)}/editable`, { method: "POST", body: JSON.stringify({ editable }) }),
|
||||||
// --- Playlists (Siftlode-native, per-user, ordered) ---
|
// --- Playlists (Siftlode-native, per-user, ordered) ---
|
||||||
plexPlaylists: (contains?: string): Promise<{ playlists: PlexPlaylist[] }> =>
|
// `contains`=single rating_key → per-playlist has_item; `containsGroup`=a set of rating_keys (a whole
|
||||||
req(`/api/plex/playlists${contains ? `?contains=${encodeURIComponent(contains)}` : ""}`),
|
// 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}`),
|
plexPlaylist: (id: number): Promise<PlexPlaylistDetail> => req(`/api/plex/playlists/${id}`),
|
||||||
plexCreatePlaylist: (title: string, item_rating_key?: string): Promise<PlexPlaylist> =>
|
plexCreatePlaylist: (title: string, item_rating_key?: string): Promise<PlexPlaylist> =>
|
||||||
req(`/api/plex/playlists`, { method: "POST", body: JSON.stringify({ title, item_rating_key }) }),
|
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> =>
|
plexRenamePlaylist: (id: number, title: string): Promise<PlexPlaylist> =>
|
||||||
req(`/api/plex/playlists/${id}`, { method: "PATCH", body: JSON.stringify({ title }) }),
|
req(`/api/plex/playlists/${id}`, { method: "PATCH", body: JSON.stringify({ title }) }),
|
||||||
plexDeletePlaylist: (id: number): Promise<{ deleted: number }> =>
|
plexDeletePlaylist: (id: number): Promise<{ deleted: number }> =>
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ export const LS = {
|
||||||
plexShow: "siftlode.plexShow",
|
plexShow: "siftlode.plexShow",
|
||||||
plexSort: "siftlode.plexSort",
|
plexSort: "siftlode.plexSort",
|
||||||
plexFilters: "siftlode.plexFilters",
|
plexFilters: "siftlode.plexFilters",
|
||||||
|
plexPlaylistLayout: "siftlode.plexPlaylistLayout",
|
||||||
notifHistory: "siftlode.notifications",
|
notifHistory: "siftlode.notifications",
|
||||||
notifSettings: "siftlode.notifSettings",
|
notifSettings: "siftlode.notifSettings",
|
||||||
onboardingDismissed: "siftlode.onboarding.dismissed",
|
onboardingDismissed: "siftlode.onboarding.dismissed",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue