Kaleido-Desktop/src/ui/media.tsx
Elijah 8755d16735
All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 1m22s
Fix playback, account, download and library bugs found in review
- Clear cached library data when the account or profile behind the
  server connection changes, not only on Home user switches.
- TitleArt falls back to the title when there is no server, so the
  player no longer crashes offline.
- Playback keeps the server it started on: progress, watched state and
  transcodes never go to a server selected later, a download only
  reports to its own server, and switching account or server ends a
  stream from the old one.
- Closing or replacing playback during setup can no longer start the
  file afterwards.
- Transcodes save the chosen audio/subtitle tracks on the server before
  starting (and name them in the request), apply the language and
  subtitle preferences, and keep the current tracks across quality
  changes.
- Offline playback saves its resume point and watched count in the
  download's metadata.
- Download tasks take over from a previous task for the same title only
  after it exits, and pause/remove stay wired to the current task.
- Downloads prefer a single-file version and refuse split ones instead
  of saving only part one.
- Download artwork is named per file, so episodes in one season folder
  no longer overwrite or delete each other's images.
- Library grids refetch loaded pages when the cache is invalidated.
- Request timeouts and cancellation also cover the response body.
- Hero rotation resumes after being scrolled back into view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:41:12 -07:00

354 lines
14 KiB
TypeScript

import { memo, useEffect, useRef, useState, type ReactNode } from 'react';
import type { Item } from '../plex/types';
import { useServer, useSession } from '../app/session';
import { useSettings } from '../app/settings';
import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format';
import { itemMenu, openItem, playWithVersion } from '../app/actions';
import { Artwork } from './primitives';
import { Icon } from './Icon';
import { openMenu } from './overlays';
import { previewHandlers } from './HoverPreview';
import rtHot from '../assets/rt-hot.svg';
import rtStale from '../assets/rt-stale.svg';
import imdb from '../assets/imdb.svg';
// —— Ratings and facts ————————————————————————————————————————————
export function Ratings({ item, compact }: { item: Item; compact?: boolean }) {
const audience = item.scores.filter((s) => s.kind === 'audience');
const rt = audience.find((s) => s.source === 'Rotten Tomatoes');
const im = audience.find((s) => s.source === 'IMDb');
const fallback = !rt && !im ? audience.find((s) => s.source === 'TVDB' || s.source === 'TMDB') : null;
if (!rt && !im && !fallback) return null;
return (
<span className={`ratings${compact ? ' compact' : ''}`}>
{rt && (
<span className="rating" title="Rotten Tomatoes audience score">
<img src={rt.value >= 6 ? rtHot : rtStale} alt="Rotten Tomatoes" />
{Math.round(rt.value * 10)}%
</span>
)}
{im && (
<span className="rating" title="IMDb rating">
<img src={imdb} alt="IMDb" className="imdb" />
{im.value.toFixed(1)}
</span>
)}
{fallback && (
<span className="rating" title={`${fallback.source} rating`}>
<Icon name="starFill" size={13} style={{ color: '#e9c46a' }} />
{fallback.value.toFixed(1)}
</span>
)}
</span>
);
}
export function FormatBadges({ item }: { item: Item }) {
const badges = formatBadges(item);
if (!badges.length) return null;
return (
<span className="format-badges">
{badges.map((b) => (
<span key={b} className="badge">
{b}
</span>
))}
</span>
);
}
/** "TV-MA · 2014 · Drama / Mystery · 1h 58m · [RT] [IMDb] · 4K HDR" */
export function Facts({ item, withFormats = true, episode = true, children }: { item: Item; withFormats?: boolean; episode?: boolean; children?: ReactNode }) {
const parts: ReactNode[] = [];
if (item.type === 'episode') {
if (episode) parts.push(<span key="ep">{episodeLabel(item)}</span>);
if (item.originallyAvailableAt) parts.push(<span key="date">{new Date(item.originallyAvailableAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}</span>);
} else if (item.year) parts.push(<span key="y">{item.year}</span>);
if (item.genres.length && item.type !== 'episode') parts.push(<span key="g">{item.genres.slice(0, 2).map((g) => g.tag).join(' / ')}</span>);
if (item.type === 'show') {
if (item.childCount) parts.push(<span key="s">{item.childCount} season{item.childCount === 1 ? '' : 's'}</span>);
} else if (item.type === 'season') {
if (item.leafCount) parts.push(<span key="e">{item.leafCount} episodes</span>);
} else if (item.viewOffset && item.duration) parts.push(<span key="r">{remaining(item)}</span>);
else if (item.duration) parts.push(<span key="d">{duration(item.duration)}</span>);
return (
<div className="facts">
{item.contentRating && <span className="badge">{item.contentRating.replace(/^gb\//, '')}</span>}
{parts.map((p, i) => (
<span key={i} className="fact">
{i > 0 && <span className="fact-sep">·</span>}
{p}
</span>
))}
<Ratings item={item} />
{withFormats && <FormatBadges item={item} />}
{children}
</div>
);
}
/** Original clear-logo artwork, falling back to the title in type. */
export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight = 130, as: As = 'h1' }: { item: Item; logo?: string; className?: string; maxWidth?: number; maxHeight?: number; as?: 'h1' | 'h2' }) {
// The player shows this offline too, where there is no server to draw the logo from.
const server = useSession((s) => s.server);
const path = logo ?? item.logo;
const [failed, setFailed] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => {
setFailed(false);
setReady(false);
}, [path]);
const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title;
if (!path || failed || !server)
return (
<As className={`title-text ${className}`} style={{ maxWidth: maxWidth * 1.4 }}>
{title}
</As>
);
return (
<As className={`title-art ${className}`} style={{ maxWidth, height: maxHeight }}>
<img
src={server.image(path, maxWidth, maxHeight, { format: 'png' })}
alt={title}
draggable={false}
className={ready ? 'ready' : ''}
onLoad={() => setReady(true)}
onError={() => setFailed(true)}
style={{ maxWidth, maxHeight }}
/>
</As>
);
}
// —— Card decorations —————————————————————————————————————————————
function WatchBadge({ item }: { item: Item }) {
const percent = useSettings((s) => s.watchedPercent);
if (isWatched(item, percent))
return (
<span className="watch-badge" title="Watched">
<Icon name="check" size={13} strokeWidth={2.4} />
</span>
);
if ((item.type === 'show' || item.type === 'season') && item.leafCount && item.viewedLeafCount > 0)
return (
<span className="watch-badge count" title={`${remainingEpisodes(item)} episodes left`}>
{remainingEpisodes(item)}
</span>
);
if ((item.type === 'show' || item.type === 'season') && item.leafCount && item.viewedLeafCount === 0) return null;
return null;
}
function ProgressLine({ item }: { item: Item }) {
const p = progress(item);
if (!p || p > 0.995) return null;
return (
<span className="progress-line">
<i style={{ width: `${Math.max(3, p * 100)}%` }} />
</span>
);
}
function useCardHandlers(item: Item, ctx: { continueWatching?: boolean } = {}) {
return {
onClick: () => openItem(item),
onContextMenu: (e: React.MouseEvent) => {
e.preventDefault();
openMenu(itemMenu(item, ctx), { x: e.clientX, y: e.clientY });
},
onKeyDown: (e: React.KeyboardEvent) => {
if (e.key === 'Enter') openItem(item);
if (e.key === ' ') {
e.preventDefault();
playWithVersion(item);
}
},
};
}
function CardActions({ item, ctx }: { item: Item; ctx?: { continueWatching?: boolean } }) {
const playable = ['movie', 'episode', 'show', 'season', 'clip'].includes(item.type);
return (
<div className="card-actions">
{playable && (
<button
className="card-play"
aria-label={`Play ${item.title}`}
onClick={(e) => {
e.stopPropagation();
playWithVersion(item);
}}
>
<Icon name="play" size={18} />
</button>
)}
<button
className="card-more"
aria-label="More"
onClick={(e) => {
e.stopPropagation();
openMenu(itemMenu(item, ctx), e.currentTarget as HTMLElement);
}}
>
<Icon name="dots" size={18} />
</button>
</div>
);
}
// —— Cards ——————————————————————————————————————————————————————————
export const PosterCard = memo(function PosterCard({ item, caption = 'year', className = '' }: { item: Item; caption?: 'year' | 'none' | 'episodes' | 'role'; className?: string }) {
const server = useServer();
const handlers = useCardHandlers(item);
const path = art.poster(item);
let meta: ReactNode = null;
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? (item.leafCount ? `${item.leafCount} episodes` : '') : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
if (caption === 'episodes') meta = item.leafCount ? `${item.leafCount} episodes` : '';
if (caption === 'role') meta = (item as any).roleName ?? item.year;
return (
<article className={`card poster ${className}`} role="button" tabIndex={0} aria-label={item.title} {...handlers} {...previewHandlers(item)}>
<div className="card-cover">
<Artwork src={server.image(path, 240, 360)} alt="" fallback={<span className="cover-fallback">{displayTitle(item)}</span>} />
<div className="card-hover" />
<CardActions item={item} />
<WatchBadge item={item} />
<ProgressLine item={item} />
</div>
{caption !== 'none' && (
<div className="card-caption">
<div className="card-title" title={item.type === 'season' ? item.title : displayTitle(item)}>
{item.type === 'season' ? item.title : displayTitle(item)}
</div>
{meta ? <div className="card-meta">{meta}</div> : null}
</div>
)}
</article>
);
});
export const LandscapeCard = memo(function LandscapeCard({ item, continueWatching, showTitle = true, episodeStyle = false }: { item: Item; continueWatching?: boolean; showTitle?: boolean; episodeStyle?: boolean }) {
const server = useServer();
const handlers = useCardHandlers(item, { continueWatching });
const isEp = item.type === 'episode';
const path = isEp ? item.thumb || item.grandparentArt : art.landscape(item);
const title = episodeStyle && isEp ? `${item.index}. ${item.title}` : displayTitle(item);
const meta = isEp
? episodeStyle
? [duration(item.duration), item.viewOffset ? remaining(item) : ''].filter(Boolean).join(' · ')
: `${episodeLabel(item)} ${item.title}`
: item.viewOffset
? remaining(item)
: [item.year, duration(item.duration)].filter(Boolean).join(' · ');
return (
<article className="card landscape" role="button" tabIndex={0} aria-label={title} {...handlers} {...previewHandlers(item)}>
<div className="card-cover">
<Artwork src={server.image(path, 400, 225)} alt="" fallback={<span className="cover-fallback">{title}</span>} />
{!isEp && item.logo && continueWatching && (
<div className="card-logo">
<img src={server.image(item.logo, 220, 70, { format: 'png' })} alt="" draggable={false} />
</div>
)}
<div className="card-hover" />
<CardActions item={item} ctx={{ continueWatching }} />
{episodeStyle && <WatchBadge item={item} />}
<ProgressLine item={item} />
</div>
{showTitle && (
<div className="card-caption">
<div className="card-title" title={title}>
{title}
</div>
<div className="card-meta">{meta}</div>
</div>
)}
</article>
);
});
export function PersonCard({ name, role, thumb, onClick }: { name: string; role?: string; thumb?: string; onClick?: () => void }) {
const server = useServer();
const initials = name
.split(/\s+/)
.map((x) => x[0])
.slice(0, 2)
.join('');
return (
<button className="person-card" onClick={onClick} disabled={!onClick}>
<div className="person-photo">
{thumb ? <Artwork src={server.image(thumb, 160, 160)} alt="" fallback={<span>{initials}</span>} /> : <span>{initials}</span>}
</div>
<b>{name}</b>
{role && <small>{role}</small>}
</button>
);
}
// —— Shelf ——————————————————————————————————————————————————————————
export function Shelf({ title, subtitle, onViewAll, children, className = '', kind = 'poster' }: { title: ReactNode; subtitle?: ReactNode; onViewAll?: () => void; children: ReactNode; className?: string; kind?: 'poster' | 'landscape' | 'people' | 'wide' }) {
const row = useRef<HTMLDivElement>(null);
const [edges, setEdges] = useState({ start: true, end: false });
const update = () => {
const el = row.current;
if (!el) return;
const start = el.scrollLeft < 8;
const end = el.scrollLeft + el.clientWidth >= el.scrollWidth - 8;
// Runs on every scroll event; re-render only when an edge changes.
setEdges((prev) => (prev.start === start && prev.end === end ? prev : { start, end }));
};
useEffect(() => {
update();
const el = row.current;
if (!el) return;
const ro = new ResizeObserver(update);
ro.observe(el);
return () => ro.disconnect();
}, [children]);
const page = (dir: number) => {
const el = row.current;
if (!el) return;
el.scrollBy({ left: dir * (el.clientWidth - 120), behavior: 'smooth' });
};
return (
<section className={`shelf-section ${className}`}>
<div className="shelf-head">
<h2>
{onViewAll ? (
<button className="shelf-title-link" onClick={onViewAll}>
{title}
<Icon name="next" size={16} />
</button>
) : (
title
)}
{subtitle && <small>{subtitle}</small>}
</h2>
</div>
<div className="shelf-wrap">
<button className={`shelf-paddle prev${edges.start ? ' hidden' : ''}`} aria-label="Scroll left" onClick={() => page(-1)} tabIndex={-1}>
<Icon name="back" size={26} />
</button>
<div className={`shelf ${kind}`} ref={row} onScroll={update}>
{children}
</div>
<button className={`shelf-paddle next${edges.end ? ' hidden' : ''}`} aria-label="Scroll right" onClick={() => page(1)} tabIndex={-1}>
<Icon name="next" size={26} />
</button>
</div>
</section>
);
}
/** A hub shelf with the right card style for its contents. */
export function HubShelf({ title, items, onViewAll, continueWatching, landscape }: { title: string; items: Item[]; onViewAll?: () => void; continueWatching?: boolean; landscape?: boolean }) {
if (!items.length) return null;
const wide = landscape ?? (continueWatching || items.every((i) => i.type === 'episode' || i.type === 'clip'));
return (
<Shelf title={title} onViewAll={onViewAll} kind={wide ? 'landscape' : 'poster'}>
{items.map((i) => (wide ? <LandscapeCard key={i.id} item={i} continueWatching={continueWatching} /> : <PosterCard key={i.id} item={i} />))}
</Shelf>
);
}