Kaleido-Desktop/src/ui/media.tsx
Elijah 43c168da95 Address the first beta's bugs and requested changes
Startup now uses the Android iris animation, and playback can continue
in a corner miniplayer while browsing (the video is drawn into a corner
rectangle beneath a matching hole in the page). The player keeps the
window controls, hides its chrome when the pointer leaves, and gains
audio/subtitle tracks, audio sync, source bitrate and playback details
in its options. Subtitles can be styled in Settings with a live preview.
Categories replace Collections, the A–Z rail magnifies, descriptions
expand in place, downloads can be removed in bulk, and search keeps its
results while typing.

Fixes scroll jank from per-card and scrolling backdrop blurs, the hidden
colour wash, the cubic volume curve, loud theme music, the search focus
ring, a stray nav indicator, Continue Watching previews and the TV Shows
header overlap. Removes the star rating, the duplicate Settings menu
entry and the server settings' Show advanced switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 18:06:54 -07:00

353 lines
14 KiB
TypeScript

import { memo, useEffect, useRef, useState, type ReactNode } from 'react';
import type { Item } from '../plex/types';
import { useServer } 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' }) {
const server = useServer();
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)
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>
);
}