Kaleido-Desktop/src/screens/Item.tsx
Elijah 328a93695a
All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 1m24s
Release Kaleido Desktop 0.1.0-beta.13
- Automatic intro/credits skip waits a configurable delay (default 5 s) with a filling
  "Skipping intro" button; pausing, seeking or pressing a key cancels it, and seeking
  into an intro never auto-skips it.
- Watch-state queries refetch on window focus, and Continue Watching / next episode
  poll every minute while visible, so progress from other Plex apps shows up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:57:23 -07:00

593 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useMemo, useState, type ReactNode } from 'react';
import * as api from '../plex/api';
import type { Item } from '../plex/types';
import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
import { useServer } from '../app/session';
import { useSettings } from '../app/settings';
import { goBack, navigate, useRouter } from '../app/router';
import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format';
import { Backdrop } from '../ui/Backdrop';
import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives';
import { Icon } from '../ui/Icon';
import { openMenu } from '../ui/overlays';
import { useDownloads } from '../downloads/store';
import { playThemeMusic, stopThemeMusic } from '../player/theme';
export function ItemScreen({ id }: { id: string }) {
const q = useItem(id);
const item = q.data;
useEffect(() => {
if (item?.theme && item.type !== 'collection') playThemeMusic(item.theme);
}, [item?.theme]);
useEffect(() => () => stopThemeMusic(), []);
if (q.isError) return <div className="page-pad top"><ErrorState error={q.error} onRetry={() => q.refetch()} /></div>;
if (!item) return <PageLoader />;
switch (item.type) {
case 'show':
return <ShowDetail item={item} />;
case 'season':
return <SeasonDetail item={item} />;
case 'episode':
return <EpisodeDetail item={item} />;
case 'collection':
return <CollectionDetail item={item} />;
default:
return <MovieDetail item={item} />;
}
}
// —— Shared pieces ————————————————————————————————————————————————
/** Long descriptions open in place when clicked, and close again the same way. */
function Synopsis({ text }: { item: Item; text: string }) {
const [clamped, setClamped] = useState(false);
const [open, setOpen] = useState(false);
useEffect(() => setOpen(false), [text]);
if (!text) return null;
const toggle = () => (clamped || open) && setOpen(!open);
return (
<div className="synopsis-wrap">
<p
className={`synopsis${open ? ' open' : ''}${clamped || open ? ' expandable' : ''}`}
role={clamped || open ? 'button' : undefined}
tabIndex={clamped || open ? 0 : undefined}
aria-expanded={clamped || open ? open : undefined}
title={clamped && !open ? 'Show the full description' : undefined}
onClick={toggle}
onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), toggle())}
ref={(el) => {
if (el && !open) setClamped(el.scrollHeight > el.clientHeight + 2);
}}
>
{text}
</p>
</div>
);
}
function WatchedButton({ item }: { item: Item }) {
const percent = useSettings((s) => s.watchedPercent);
const watched = isWatched(item, percent);
return (
<Button variant="ghost" icon={watched ? 'check' : 'plus'} onClick={() => setWatched(item, !watched)} className={watched ? 'is-on' : ''}>
{watched ? 'Watched' : 'Mark watched'}
</Button>
);
}
function DownloadButton({ item }: { item: Item }) {
const downloads = useDownloads();
const isSeries = item.type === 'show' || item.type === 'season';
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
if (isSeries) return <IconButton round icon="download" label={item.type === 'show' ? 'Download unwatched episodes' : 'Download season'} onClick={() => downloads.startAll(item)} />;
if (dl?.status === 'completed') return <IconButton round icon="downloaded" label="Downloaded" className="on" onClick={() => navigate({ name: 'downloads' })} />;
if (dl) {
const pct = dl.total ? Math.round((dl.received / dl.total) * 100) : 0;
return (
<button className="circle-btn download-progress" aria-label={`Downloading ${pct}%`} title={`Downloading ${pct}%`} onClick={() => navigate({ name: 'downloads' })}>
<svg viewBox="0 0 36 36" width="42" height="42">
<circle cx="18" cy="18" r="15" fill="none" stroke="rgba(255,255,255,.2)" strokeWidth="2.4" />
<circle cx="18" cy="18" r="15" fill="none" stroke="currentColor" strokeWidth="2.4" strokeDasharray={`${pct * 0.94} 100`} transform="rotate(-90 18 18)" strokeLinecap="round" />
</svg>
</button>
);
}
return <IconButton round icon="download" label="Download" onClick={() => downloads.start(item)} />;
}
function MoreButton({ item, onDeleted }: { item: Item; onDeleted?: () => void }) {
return <IconButton round icon="dots" label="More actions" onClick={(e) => openMenu(itemMenu(item, { detail: true, onDeleted }), e.currentTarget)} />;
}
function TrailerButton({ item }: { item: Item }) {
const trailer = item.extras.find((e) => e.subtype === 'trailer' && e.media.length);
if (!trailer) return null;
return (
<Button variant="ghost" icon="film" onClick={() => playItem(trailer, { resume: false })}>
Trailer
</Button>
);
}
function DetailHero({ item, backdropItem, children, title, below }: { item: Item; backdropItem?: Item; children: ReactNode; title?: ReactNode; below?: ReactNode }) {
return (
<>
<Backdrop item={backdropItem ?? item} className="detail-backdrop" />
<header className="detail-hero">
<div className="detail-head">
{title ?? <TitleArt item={item} maxWidth={440} maxHeight={140} />}
{children}
</div>
{below}
</header>
</>
);
}
function CastRow({ item, title = 'Cast & Crew' }: { item: Item; title?: string }) {
const people = [
...item.roles.map((r) => ({ id: r.id, name: r.tag, role: r.role, thumb: r.thumb })),
...item.directors.map((d) => ({ id: d.id, name: d.tag, role: 'Director', thumb: (d as any).thumb ?? item.raw?.Director?.find((x: any) => x.tag === d.tag)?.thumb })),
...item.writers.slice(0, 3).map((d) => ({ id: d.id, name: d.tag, role: 'Writer', thumb: item.raw?.Writer?.find((x: any) => x.tag === d.tag)?.thumb })),
];
if (!people.length) return null;
return (
<Shelf title={title} kind="people">
{people.map((p, i) => (
<PersonCard key={`${p.id}-${i}`} name={p.name} role={p.role} thumb={p.thumb} onClick={p.id ? () => navigate({ name: 'person', id: p.id, title: p.name, thumb: p.thumb }) : undefined} />
))}
</Shelf>
);
}
function ExtrasRow({ item }: { item: Item }) {
const extras = item.extras.filter((e) => e.media.length);
if (!extras.length) return null;
return (
<Shelf title="Trailers & Extras" kind="landscape">
{extras.map((e) => (
<article key={e.id} className="card landscape extra" role="button" tabIndex={0} onClick={() => playItem(e, { resume: false })} onKeyDown={(ev) => ev.key === 'Enter' && playItem(e, { resume: false })}>
<ExtraCover item={e} />
<div className="card-caption">
<div className="card-title">{e.title}</div>
<div className="card-meta">{[extraLabel(e), duration(e.duration)].filter(Boolean).join(' · ')}</div>
</div>
</article>
))}
</Shelf>
);
}
function ExtraCover({ item }: { item: Item }) {
const server = useServer();
return (
<div className="card-cover">
<Artwork src={server.image(item.thumb, 400, 225)} />
<div className="card-hover" />
<span className="extra-play">
<Icon name="play" size={18} />
</span>
</div>
);
}
function RelatedRows({ item }: { item: Item }) {
const related = useRelated(item.id);
const hubs = (related.data ?? []).map((h) => ({ ...h, items: h.items.filter((i) => i.id !== item.id && ['movie', 'show'].includes(i.type)) })).filter((h) => h.items.length);
return (
<>
{hubs.slice(0, 3).map((h) => (
<HubShelf key={h.id} title={h.title} items={h.items} landscape={false} />
))}
</>
);
}
function AboutPanel({ item }: { item: Item }) {
const m = item.media[0];
const rows: [string, ReactNode][] = [];
const tags = (list: { tag: string; id: string }[], filter: string, limit = 3) =>
list.slice(0, limit).map((t, i) => (
<span key={t.tag}>
{i > 0 && ', '}
{filter === 'person' ? (
<button className="inline-link" onClick={() => t.id && navigate({ name: 'person', id: t.id, title: t.tag })}>
{t.tag}
</button>
) : (
t.tag
)}
</span>
));
if (item.directors.length) rows.push([item.directors.length > 1 ? 'Directors' : 'Director', tags(item.directors, 'person')]);
if (item.writers.length) rows.push(['Writers', tags(item.writers, 'person')]);
if (item.studio) rows.push([item.type === 'show' || item.type === 'episode' ? 'Network' : 'Studio', item.studio]);
if (item.originallyAvailableAt) rows.push([item.type === 'show' ? 'Premiered' : 'Released', date(item.originallyAvailableAt)]);
if (item.genres.length) rows.push(['Genres', item.genres.map((g) => g.tag).join(', ')]);
if (item.countries.length) rows.push(['Country', item.countries.map((c) => c.tag).join(', ')]);
if (item.contentRating) rows.push(['Rated', item.contentRating]);
if (item.duration && item.type !== 'show') rows.push(['Runtime', duration(item.duration)]);
for (const s of item.scores) rows.push([`${s.source}${s.kind === 'critic' ? ' critics' : ''}`, s.source === 'Rotten Tomatoes' ? `${Math.round(s.value * 10)}%` : `${s.value.toFixed(1)} / 10`]);
if (item.collections.length) rows.push(['Collections', item.collections.map((c) => c.tag).join(', ')]);
if (item.labels.length) rows.push(['Labels', item.labels.map((c) => c.tag).join(', ')]);
if (item.editionTitle) rows.push(['Edition', item.editionTitle]);
if (m) {
rows.push(['Video', [resolutionLabel(m), m.dynamicRange, m.videoCodec.toUpperCase(), m.videoFrameRate].filter(Boolean).join(' · ')]);
rows.push(['Audio', [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels), m.atmos ? 'Atmos' : ''].filter(Boolean).join(' · ')]);
if (m.bitrate) rows.push(['Bitrate', bitrate(m.bitrate)]);
const size = m.parts.reduce((a, p) => a + p.size, 0);
if (size) rows.push(['File size', fileSize(size)]);
if (item.media.length > 1) rows.push(['Versions', `${item.media.length} available`]);
}
if (item.addedAt) rows.push(['Added', date(item.addedAt)]);
return (
<aside className="about-panel">
<div className="about-head">
<h3>About</h3>
</div>
{item.tagline && <p className="about-tagline">“{item.tagline}”</p>}
{rows.map(([k, v]) => (
<div className="about-line" key={k}>
<span>{k}</span>
<strong>{v}</strong>
</div>
))}
{(m || canManage()) && (
<div className="about-actions">
{m && (
<Button variant="outline" size="sm" icon="info" onClick={() => openDialog({ kind: 'info', item })}>
Media info
</Button>
)}
{canManage() && (
<Button variant="outline" size="sm" icon="edit" onClick={() => openDialog({ kind: 'edit', item })}>
Edit
</Button>
)}
</div>
)}
</aside>
);
}
// —— Movie ——————————————————————————————————————————————————————————
function MovieDetail({ item }: { item: Item }) {
const resume = item.viewOffset > 0 && !isWatched(item);
return (
<div className="detail movie">
<DetailHero item={item}>
<Facts item={item} />
<Synopsis item={item} text={item.summary} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
{resume ? `Resume · ${remaining(item)}` : 'Play'}
</Button>
{resume && (
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
From beginning
</Button>
)}
<TrailerButton item={item} />
<WatchedButton item={item} />
<DownloadButton item={item} />
<MoreButton item={item} onDeleted={goBack} />
</div>
{resume && (
<div className="detail-progress">
<span className="progress-bar">
<i style={{ width: `${(item.viewOffset / item.duration) * 100}%` }} />
</span>
</div>
)}
<div className="detail-tech">{technicalLine(item.media[0])}</div>
</DetailHero>
<div className="detail-body">
<div className="detail-main">
<CastRow item={item} />
<ExtrasRow item={item} />
<RelatedRows item={item} />
</div>
<AboutPanel item={item} />
</div>
</div>
);
}
// —— Shows and seasons ————————————————————————————————————————————
function EpisodeRow({ ep }: { ep: Item }) {
const server = useServer();
const percent = useSettings((s) => s.watchedPercent);
const watched = isWatched(ep, percent);
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
return (
<div
className="episode-row"
role="button"
tabIndex={0}
onClick={() => openItem(ep)}
onKeyDown={(e) => e.key === 'Enter' && openItem(ep)}
onContextMenu={(e) => {
e.preventDefault();
openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY });
}}
>
<div className="episode-index">{ep.index || '–'}</div>
<div className="episode-pic">
<Artwork src={server.image(ep.thumb, 320, 180)} />
<button
className="episode-play"
aria-label={`Play ${ep.title}`}
onClick={(e) => {
e.stopPropagation();
playWithVersion(ep);
}}
>
<Icon name="play" size={18} />
</button>
{p > 0 && !watched && (
<span className="progress-line">
<i style={{ width: `${p * 100}%` }} />
</span>
)}
</div>
<div className="episode-text">
<h3>
{ep.title}
{watched && <Icon name="check" size={15} className="episode-watched" />}
</h3>
<div className="episode-meta">
{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
</div>
{ep.summary && <p>{ep.summary}</p>}
</div>
<button
className="icon-btn episode-more"
aria-label="More"
onClick={(e) => {
e.stopPropagation();
openMenu(itemMenu(ep), e.currentTarget);
}}
>
<Icon name="dots" size={18} />
</button>
</div>
);
}
function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) {
const saved = useRouter((s) => s.current.state.season as string | undefined);
const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id);
useEffect(() => {
if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id);
}, [seasons, initialSeason]);
const episodes = useChildren(seasonId);
const season = seasons.find((s) => s.id === seasonId);
if (!seasons.length) return null;
return (
<section className="episodes">
<div className="episodes-head">
<h2>Episodes</h2>
{showPicker && seasons.length > 1 && (
<Select
value={seasonId!}
label="Season"
options={seasons.map((s) => ({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
onChange={(v) => {
setSeasonId(v);
useRouter.getState().setState({ season: v });
}}
/>
)}
{season && (
<span className="episodes-sub">
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
</span>
)}
</div>
{season?.summary && <p className="season-summary">{season.summary}</p>}
<div className="episode-list">
{episodes.isLoading && <PageLoader />}
{episodes.data?.map((ep) => <EpisodeRow key={ep.id} ep={ep} />)}
{episodes.data && !episodes.data.length && <EmptyState icon="tv" title="No episodes" />}
</div>
</section>
);
}
function ShowDetail({ item }: { item: Item }) {
const seasons = useChildren(item.id);
const server = useServer();
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), PROGRESS);
const nextEp = next.data;
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
const percent = useSettings((s) => s.watchedPercent);
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
void server;
return (
<div className="detail show">
<DetailHero item={item}>
<Facts item={item} />
<Synopsis item={item} text={item.summary} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" onClick={() => (nextEp ? playWithVersion(nextEp) : playItem(item))}>
{playLabel}
</Button>
<Button variant="ghost" icon="shuffle" onClick={() => shuffleItem(item)}>
Shuffle
</Button>
<TrailerButton item={item} />
<WatchedButton item={item} />
<DownloadButton item={item} />
<MoreButton item={item} onDeleted={goBack} />
</div>
{nextEp && (
<div className="detail-tech">
Up next: {episodeLabel(nextEp)} · {nextEp.title}
</div>
)}
</DetailHero>
<div className="detail-body">
<div className="detail-main">
{seasonList.length > 1 && (
<Shelf title="Seasons">
{seasonList.map((s) => (
<PosterCard key={s.id} item={s} caption="episodes" />
))}
</Shelf>
)}
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
<CastRow item={item} />
<ExtrasRow item={item} />
<RelatedRows item={item} />
</div>
<AboutPanel item={item} />
</div>
</div>
);
}
function SeasonDetail({ item }: { item: Item }) {
const show = useItem(item.parentId);
const siblings = useChildren(item.parentId);
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
const episodes = useChildren(item.id);
const percent = useSettings((s) => s.watchedPercent);
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
const showItem = show.data;
return (
<div className="detail season">
<DetailHero
item={item}
backdropItem={showItem ?? item}
title={
<>
{showItem ? (
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
<TitleArt item={showItem} maxWidth={340} maxHeight={96} as="h2" />
</button>
) : (
<h2 className="title-text small">{item.parentTitle}</h2>
)}
<h1 className="detail-subtitle">{item.title}</h1>
</>
}
>
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
</Button>
<WatchedButton item={item} />
<DownloadButton item={item} />
<MoreButton item={item} onDeleted={goBack} />
</div>
</DetailHero>
<div className="detail-body single">
<div className="detail-main">
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
{showItem && <CastRow item={showItem} />}
</div>
</div>
</div>
);
}
function EpisodeDetail({ item }: { item: Item }) {
const show = useItem(item.grandparentId);
const siblings = useChildren(item.parentId);
const resume = item.viewOffset > 0 && !isWatched(item);
const showItem = show.data;
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
const ordered = useMemo(() => [...others.slice(startIndex), ...others.slice(0, startIndex)], [siblings.data, item.id]);
return (
<div className="detail episode">
<DetailHero
item={item}
backdropItem={{ ...item, art: item.thumb, grandparentArt: item.thumb, ultraBlur: showItem?.ultraBlur ?? item.ultraBlur }}
title={
<>
{showItem ? (
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
<TitleArt item={showItem} maxWidth={300} maxHeight={84} as="h2" />
</button>
) : (
<h2 className="title-text small">{item.grandparentTitle}</h2>
)}
<h1 className="detail-subtitle">{item.title}</h1>
</>
}
>
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
<Synopsis item={item} text={item.summary} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
{resume ? `Resume · ${remaining(item)}` : 'Play'}
</Button>
{resume && (
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
From beginning
</Button>
)}
<WatchedButton item={item} />
<DownloadButton item={item} />
<MoreButton item={item} onDeleted={goBack} />
</div>
<div className="detail-tech">{technicalLine(item.media[0])}</div>
</DetailHero>
<div className="detail-body">
<div className="detail-main">
{ordered.length > 0 && (
<Shelf title={`More from ${item.parentTitle || `Season ${item.parentIndex}`}`} kind="landscape" onViewAll={() => navigate({ name: 'item', id: item.parentId })}>
{ordered.map((e) => (
<LandscapeCard key={e.id} item={e} episodeStyle />
))}
</Shelf>
)}
<CastRow item={item.roles.length ? item : (showItem ?? item)} title={item.roles.length ? 'Cast & Guest Stars' : 'Cast & Crew'} />
</div>
<AboutPanel item={item} />
</div>
</div>
);
}
// —— Collections ——————————————————————————————————————————————————
function CollectionDetail({ item }: { item: Item }) {
const members = useServerQuery(['collectionItems', item.id], (s) => api.collectionItems(s, item.id));
const list = members.data ?? [];
const backdropItem = item.art ? item : list.find((m) => m.art);
return (
<div className="detail collection">
<DetailHero item={item} backdropItem={backdropItem} title={<h1 className="title-text">{item.title}</h1>}>
<div className="facts">
<span className="fact">{list.length ? `${list.length} titles` : 'Collection'}</span>
{item.contentRating && <span className="badge">{item.contentRating}</span>}
</div>
<Synopsis item={item} text={item.summary} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" disabled={!list.length} onClick={() => list[0] && playWithVersion(list.find((m) => !isWatched(m)) ?? list[0])}>
Play
</Button>
<MoreButton item={item} />
</div>
</DetailHero>
<div className="detail-body single">
<div className="detail-main">
{members.isLoading && <PageLoader />}
<div className="poster-grid auto">
{list.map((m) => (
<PosterCard key={m.id} item={m} />
))}
</div>
</div>
</div>
</div>
);
}