Kaleido-Desktop/src/player/PlayerOverlay.tsx
Elijah Kuntz 7d0803481b Port Kaleido Desktop to macOS
macOS (Apple silicon) now plays, browses and updates like Windows:

- Video: libmpv's render API draws into a CAOpenGLLayer beneath the
  WKWebView, with the miniplayer rectangle, HDR passthrough through
  extended dynamic range (PQ/BT.2020) and display-sleep prevention.
- Window: native traffic lights on the top bar's centre line, hidden
  with the player's controls; the page's caption buttons are Windows-only.
- Interface: macOS shortcut labels (⌘K, ⌘[, ⌃⌘F), Plex identifies the
  player as a Mac, and header values are kept ASCII (Mac computer names
  usually contain a curly apostrophe).
- The window appears without waiting for an animation frame, which
  WKWebView doesn't run in a hidden window.
- Credentials: release builds use the Keychain and are signed with a
  lasting self-signed certificate so access survives updates; debug
  builds keep tokens in a private file to avoid prompts on every rebuild.
- Bundling: scripts/fetch-libmpv.sh makes Homebrew's libmpv and its
  libraries self-contained; scripts/build.sh builds the .app, .dmg and
  signed update archive.

Releases now carry both platforms: publish-release.mjs uploads each
machine's build into one release, and update-manifest.mjs writes the
feed from that release's assets, refusing while a platform is missing.

The updater uses a new signing key (public key in tauri.conf.json), so
existing installs must be reinstalled once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:14:40 -07:00

927 lines
37 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 { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { usePlayer } from './store';
import { useSession } from '../app/session';
import { useSettings, QUALITY_LABEL, UPSCALING, type Quality, type SubtitleBox, type Upscaling } from '../app/settings';
import { bitrate, channelLabel, clock, episodeLabel, resolutionLabel } from '../app/format';
import { Icon } from '../ui/Icon';
import { Facts, TitleArt } from '../ui/media';
import { Button, Spinner } from '../ui/primitives';
import { win, isNative } from '../platform/native';
import { WindowControls } from '../app/TopBar';
import { navigate } from '../app/router';
import { mpv } from './engine';
import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance';
import { toast } from '../ui/overlays';
import type { Item } from '../plex/types';
const HIDE_AFTER = 3000;
/**
* Controls show on pointer movement and hide after a few seconds of stillness,
* or straight away when the pointer leaves the window. They stay while paused
* (until the pointer leaves) and while a panel is open or the timeline is held.
*/
function useAutoHide(paused: boolean, pinned: boolean) {
const [visible, setVisible] = useState(true);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const state = useRef({ paused, pinned });
state.current = { paused, pinned };
const poke = useCallback(() => {
setVisible(true);
if (timer.current) clearTimeout(timer.current);
timer.current = null;
if (!state.current.paused && !state.current.pinned) timer.current = setTimeout(() => setVisible(false), HIDE_AFTER);
}, []);
useEffect(() => {
poke();
}, [paused, pinned, poke]);
useEffect(() => {
const leave = () => {
if (state.current.pinned) return;
if (timer.current) clearTimeout(timer.current);
timer.current = null;
setVisible(false);
};
const root = document.documentElement;
root.addEventListener('mouseleave', leave);
return () => {
root.removeEventListener('mouseleave', leave);
if (timer.current) clearTimeout(timer.current);
};
}, []);
return { visible, poke };
}
function Timeline({ onScrub }: { onScrub: (active: boolean) => void }) {
const position = usePlayer((s) => s.position);
const duration = usePlayer((s) => s.duration);
const cacheTime = usePlayer((s) => s.cacheTime);
const chapters = usePlayer((s) => s.chapters);
const markers = usePlayer((s) => s.item?.markers ?? []);
const seek = usePlayer((s) => s.seek);
const previewAt = usePlayer((s) => s.previewAt);
const ref = useRef<HTMLDivElement>(null);
const [hover, setHover] = useState<{ x: number; t: number } | null>(null);
const [drag, setDrag] = useState<number | null>(null);
const timeAt = (clientX: number) => {
const r = ref.current!.getBoundingClientRect();
const f = Math.min(1, Math.max(0, (clientX - r.left) / r.width));
return { f, t: f * duration, x: clientX - r.left };
};
useEffect(() => {
if (drag === null) return;
const move = (e: PointerEvent) => {
const { t, x } = timeAt(e.clientX);
setDrag(t);
setHover({ x, t });
};
const up = (e: PointerEvent) => {
const { t } = timeAt(e.clientX);
seek(t);
setDrag(null);
setHover(null);
onScrub(false);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up, { once: true });
return () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
};
}, [drag !== null]);
const shown = drag ?? position;
const pct = duration ? (shown / duration) * 100 : 0;
const buffered = duration ? Math.min(100, (Math.max(cacheTime, position) / duration) * 100) : 0;
const preview = hover ? previewAt(hover.t) : '';
const chapter = hover ? [...chapters].reverse().find((c) => c.time <= hover.t) : null;
const width = ref.current?.clientWidth ?? 0;
return (
<div
className={`timeline${drag !== null ? ' dragging' : ''}`}
ref={ref}
onPointerMove={(e) => {
if (drag === null && duration) {
const { t, x } = timeAt(e.clientX);
setHover({ x, t });
}
}}
onPointerLeave={() => drag === null && setHover(null)}
onPointerDown={(e) => {
if (!duration) return;
e.preventDefault();
const { t, x } = timeAt(e.clientX);
setDrag(t);
setHover({ x, t });
onScrub(true);
}}
role="slider"
aria-label="Seek"
aria-valuemin={0}
aria-valuemax={Math.round(duration)}
aria-valuenow={Math.round(position)}
>
<div className="timeline-track">
<div className="timeline-buffered" style={{ width: `${buffered}%` }} />
<div className="timeline-played" style={{ width: `${pct}%` }} />
{duration > 0 &&
markers
.filter((m) => m.type === 'intro' || m.type === 'credits')
.map((m) => <div key={m.id + m.start} className={`timeline-marker ${m.type}`} style={{ left: `${(m.start / 1000 / duration) * 100}%`, width: `${((m.end - m.start) / 1000 / duration) * 100}%` }} />)}
{duration > 0 && chapters.slice(1).map((c) => <div key={c.time} className="timeline-chapter" style={{ left: `${(c.time / duration) * 100}%` }} />)}
</div>
<div className="timeline-thumb" style={{ left: `${pct}%` }} />
{hover && (
<div className="timeline-preview" style={{ left: Math.min(Math.max(hover.x, 110), width - 110) }}>
{preview && <img src={preview} alt="" draggable={false} />}
<div className="timeline-preview-text">
{chapter && chapters.length > 1 && <span>{chapter.title}</span>}
<b>{clock(hover.t, duration >= 3600)}</b>
</div>
</div>
)}
</div>
);
}
function Panel({ title, onClose, onBack, children, className = '' }: { title: string; onClose: () => void; onBack?: () => void; children: ReactNode; className?: string }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation();
(onBack ?? onClose)();
}
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose, onBack]);
return (
<div className={`player-panel ${className}`} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
<div className="player-panel-title">
{onBack && (
<button className="panel-back" onClick={onBack} aria-label="Back">
<Icon name="back" size={15} />
</button>
)}
{title}
</div>
{children}
</div>
);
}
function Option({ selected, label, detail, disabled, onClick }: { selected: boolean; label: string; detail?: string; disabled?: boolean; onClick: () => void }) {
return (
<button className={`panel-option${selected ? ' selected' : ''}`} disabled={disabled} onClick={onClick}>
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
<span className="panel-label">
{label}
{detail && <small>{detail}</small>}
</span>
</button>
);
}
function TracksPanel({ onClose }: { onClose: () => void }) {
const st = usePlayer();
return (
<Panel title="Audio & Subtitles" onClose={onClose} className="tracks">
<div className="panel-columns">
<div>
<h4>Audio</h4>
{st.audioTracks.map((t) => (
<Option key={t.key} selected={t.key === st.audioKey} label={t.label} detail={t.detail} onClick={() => st.selectAudio(t.key)} />
))}
{!st.audioTracks.length && <div className="panel-empty">No audio tracks</div>}
</div>
<div>
<h4>Subtitles</h4>
<Option selected={!st.subKey} label="Off" onClick={() => st.selectSubtitle('')} />
{st.subTracks.map((t) => (
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => st.selectSubtitle(t.key)} />
))}
{st.subKey && st.delivery?.mode !== 'transcode' && <Stepper label="Timing" value={st.subDelay} onChange={st.setSubDelay} />}
</div>
</div>
</Panel>
);
}
function Stepper({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) {
return (
<div className="panel-delay">
<span>{label}</span>
<button onClick={() => onChange(Math.round((value - 0.1) * 10) / 10)} aria-label={`${label} earlier`}>
−
</button>
<b>
{value > 0 ? '+' : ''}
{value.toFixed(1)}s
</b>
<button onClick={() => onChange(Math.round((value + 0.1) * 10) / 10)} aria-label={`${label} later`}>
+
</button>
</div>
);
}
const SUB_SIZES = [
{ value: 0.8, label: 'Small' },
{ value: 1, label: 'Normal' },
{ value: 1.25, label: 'Large' },
{ value: 1.5, label: 'Extra large' },
];
const SUB_BOXES: { value: SubtitleBox; label: string }[] = [
{ value: 'none', label: 'None' },
{ value: 'translucent', label: 'Translucent' },
{ value: 'solid', label: 'Solid' },
];
type SettingsView = 'main' | 'audio' | 'subtitles' | 'quality' | 'upscaling' | 'speed' | 'version' | 'chapters' | 'subSize' | 'subBox';
/** True once `flag` has stayed true for `ms` (a quick blip never shows). */
function useLasting(flag: boolean, ms: number) {
const [on, setOn] = useState(false);
useEffect(() => {
if (!flag) return setOn(false);
const t = setTimeout(() => setOn(true), ms);
return () => clearTimeout(t);
}, [flag, ms]);
return on;
}
/** Polls what mpv's renderer is doing while a panel shows it. */
function useDiagnostics(enabled: boolean) {
const [d, setD] = useState<Diagnostics | null>(null);
useEffect(() => {
if (!enabled || !isNative) return;
let alive = true;
const tick = () => readDiagnostics().then((x) => alive && setD(x), () => {});
tick();
const t = setInterval(tick, 1000);
return () => {
alive = false;
clearInterval(t);
};
}, [enabled]);
return d;
}
/** Requested vs running tier, for the panel row. */
function upscalingValue(requested: Upscaling, active: Upscaling, bypass: boolean) {
if (bypass) return 'Off (comparing)';
return active === requested ? UPSCALING[requested].label : `${UPSCALING[active].label} (${UPSCALING[requested].label} failed)`;
}
function SettingsPanel({ onClose }: { onClose: () => void }) {
const st = usePlayer();
const prefs = useSettings();
const [view, setView] = useState<SettingsView>('main');
const diag = useDiagnostics(view === 'main' || view === 'upscaling');
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
const media = st.item?.media ?? [];
const source = media[st.mediaIndex];
const local = st.delivery?.mode === 'local';
const back = () => setView('main');
const audio = st.audioTracks.find((t) => t.key === st.audioKey);
const sub = st.subTracks.find((t) => t.key === st.subKey);
const qualityLabel = (q: Quality) => (q === 'original' ? `Original${source?.bitrate ? ` · ${bitrate(source.bitrate)}` : ''}` : QUALITY_LABEL[q]);
if (view === 'audio')
return (
<Panel title="Audio" onClose={onClose} onBack={back}>
{st.audioTracks.map((t) => (
<Option key={t.key} selected={t.key === st.audioKey} label={t.label} detail={t.detail} onClick={() => (st.selectAudio(t.key), back())} />
))}
{!st.audioTracks.length && <div className="panel-empty">No audio tracks</div>}
{st.delivery?.mode !== 'transcode' && <Stepper label="Audio sync" value={st.audioDelay} onChange={st.setAudioDelay} />}
</Panel>
);
if (view === 'subtitles')
return (
<Panel title="Subtitles" onClose={onClose} onBack={back}>
<Option selected={!st.subKey} label="Off" onClick={() => (st.selectSubtitle(''), back())} />
{st.subTracks.map((t) => (
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => (st.selectSubtitle(t.key), back())} />
))}
{st.subKey && st.delivery?.mode !== 'transcode' && <Stepper label="Subtitle timing" value={st.subDelay} onChange={st.setSubDelay} />}
</Panel>
);
if (view === 'quality')
return (
<Panel title="Quality" onClose={onClose} onBack={back}>
{(Object.keys(QUALITY_LABEL) as Quality[]).map((q) => (
<Option
key={q}
selected={st.quality === q}
label={qualityLabel(q)}
detail={q === 'original' ? [resolutionLabel(source), source?.videoCodec.toUpperCase(), 'Direct play of the source file'].filter(Boolean).join(' · ') : 'Converted by your Plex server'}
onClick={() => (st.setQuality(q), onClose())}
/>
))}
</Panel>
);
if (view === 'upscaling')
return (
<Panel title="Upscaling" onClose={onClose} onBack={back} className="upscaling">
{UPSCALING_ORDER.map((m) => (
<Option
key={m}
selected={prefs.upscaling === m}
label={UPSCALING[m].label}
detail={!tierAvailable(m) ? 'Needs an NVIDIA RTX graphics card on Windows' : hasFailed(m) ? 'Couldn’t start on this computer' : UPSCALING[m].detail}
disabled={!tierAvailable(m)}
onClick={() => prefs.set('upscaling', m)}
/>
))}
<div className="panel-subhead">Stages</div>
<Option selected={prefs.enhanceDeband} label="Debanding" detail="Smooths banding in gradients" onClick={() => prefs.set('enhanceDeband', !prefs.enhanceDeband)} />
<Option selected={prefs.enhanceSharpen} label="Sharpening" detail="AMD CAS · SDR only" onClick={() => prefs.set('enhanceSharpen', !prefs.enhanceSharpen)} />
<Option selected={prefs.enhanceDenoise} label="Denoising" detail="Non-local means, at any size · Balanced tier, SDR only" onClick={() => prefs.set('enhanceDenoise', !prefs.enhanceDenoise)} />
<button className={`panel-compare${st.enhance.bypass ? ' on' : ''}`} onClick={() => toggleBypass()}>
{st.enhance.bypass ? 'Turn enhancement back on' : 'Compare with enhancement off'}
<kbd>B</kbd>
</button>
{diag && (
<div className="panel-stats">
<div>
<span>Running</span>
<b>{diag.stages.length ? diag.stages.join(' · ') : 'Standard scaling'}</b>
</div>
{diag.input && (
<div>
<span>Size</span>
<b>
{diag.input} → {diag.output}
</b>
</div>
)}
<div>
<span>GPU time</span>
<b className={diag.gpuMs > diag.budgetMs * 0.8 ? 'warn' : ''}>
{diag.gpuMs.toFixed(1)} ms per frame <small>of {diag.budgetMs.toFixed(0)} ms</small>
</b>
</div>
<div>
<span>Dropped</span>
<b>{diag.dropped} frames</b>
</div>
</div>
)}
</Panel>
);
if (view === 'speed')
return (
<Panel title="Playback speed" onClose={onClose} onBack={back}>
{speeds.map((s) => (
<Option key={s} selected={Math.abs(st.speed - s) < 0.01} label={s === 1 ? 'Normal' : `${s}×`} onClick={() => (st.setSpeed(s), back())} />
))}
</Panel>
);
if (view === 'version')
return (
<Panel title="Version" onClose={onClose} onBack={back}>
{media.map((m, i) => (
<Option
key={m.id}
selected={st.mediaIndex === i}
label={m.title || [resolutionLabel(m), m.videoCodec.toUpperCase()].filter(Boolean).join(' ')}
detail={[m.container.toUpperCase(), bitrate(m.bitrate), [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' ')].filter(Boolean).join(' · ')}
onClick={() => (st.selectVersion(i), onClose())}
/>
))}
</Panel>
);
if (view === 'chapters')
return (
<Panel title="Chapters" onClose={onClose} onBack={back} className="chapters">
{st.chapters.map((c, i) => (
<Option
key={c.time}
selected={st.position >= c.time && st.position < (st.chapters[i + 1]?.time ?? Infinity)}
label={c.title}
detail={clock(c.time)}
onClick={() => (st.seek(c.time), onClose())}
/>
))}
</Panel>
);
if (view === 'subSize')
return (
<Panel title="Subtitle size" onClose={onClose} onBack={back}>
{SUB_SIZES.map((o) => (
<Option key={o.value} selected={prefs.subtitleScale === o.value} label={o.label} onClick={() => (prefs.set('subtitleScale', o.value), back())} />
))}
</Panel>
);
if (view === 'subBox')
return (
<Panel title="Subtitle background" onClose={onClose} onBack={back}>
{SUB_BOXES.map((o) => (
<Option key={o.value} selected={prefs.subtitleBox === o.value} label={o.label} onClick={() => (prefs.set('subtitleBox', o.value), back())} />
))}
</Panel>
);
const row = (label: string, value: string, go: () => void, disabled = false) => (
<button className="panel-row" onClick={go} disabled={disabled}>
<span>{label}</span>
<b>{value}</b>
<Icon name="next" size={14} />
</button>
);
const v = st.video;
const stats: [string, string][] = [
['Playback', st.delivery?.mode === 'direct' ? 'Direct play' : st.delivery?.mode === 'transcode' ? `Converting to ${QUALITY_LABEL[st.quality]}` : local ? 'Downloaded file' : ''],
];
if (v && v.width > 0)
stats.push(['Video', [`${v.width}×${v.height}`, v.codec.toUpperCase(), source?.dynamicRange, v.hwdec && v.hwdec !== 'no' ? 'Hardware decoding' : 'Software decoding'].filter(Boolean).join(' · ')]);
if (audio) stats.push(['Audio', [audio.label, audio.detail].filter(Boolean).join(' · ')]);
if (diag && st.enhance.active !== 'off' && !st.enhance.bypass) stats.push(['Upscaling', [...diag.stages, `${diag.gpuMs.toFixed(1)} ms`].join(' · ')]);
if (source?.bitrate && !local) stats.push(['Bitrate', st.delivery?.mode === 'transcode' ? `${bitrate(source.bitrate)} source` : bitrate(source.bitrate)]);
if (source?.container) stats.push(['Container', source.container.toUpperCase()]);
return (
<Panel title="Playback" onClose={onClose}>
{row('Audio', audio ? audio.label : st.audioTracks.length ? 'Choose' : 'None', () => setView('audio'), !st.audioTracks.length)}
{row('Subtitles', sub ? sub.label : 'Off', () => setView('subtitles'))}
{!local && row('Quality', qualityLabel(st.quality), () => setView('quality'))}
{row('Upscaling', upscalingValue(prefs.upscaling, st.enhance.active, st.enhance.bypass), () => setView('upscaling'))}
{row('Speed', st.speed === 1 ? 'Normal' : `${st.speed}×`, () => setView('speed'))}
{media.length > 1 && !local && row('Version', `${st.mediaIndex + 1} of ${media.length}`, () => setView('version'))}
{st.chapters.length > 1 && row('Chapters', `${st.chapters.length}`, () => setView('chapters'))}
{row('Subtitle size', SUB_SIZES.find((o) => o.value === prefs.subtitleScale)?.label ?? 'Custom', () => setView('subSize'))}
{row('Subtitle background', SUB_BOXES.find((o) => o.value === prefs.subtitleBox)?.label ?? '', () => setView('subBox'))}
<div className="panel-stats">
{stats.map(([k, val]) => (
<div key={k}>
<span>{k}</span>
<b>{val}</b>
</div>
))}
</div>
</Panel>
);
}
function Volume() {
const volume = usePlayer((s) => s.volume);
const muted = usePlayer((s) => s.muted);
const setVolume = usePlayer((s) => s.setVolume);
const toggleMute = usePlayer((s) => s.toggleMute);
const icon = muted || volume === 0 ? 'mute' : volume < 50 ? 'volumeLow' : 'volume';
return (
<div className="volume">
<button className="player-icon" aria-label={muted ? 'Unmute' : 'Mute'} onClick={toggleMute}>
<Icon name={icon} size={22} />
</button>
<input
type="range"
min={0}
max={100}
value={muted ? 0 : Math.min(100, volume)}
onChange={(e) => setVolume(Number(e.target.value))}
style={{ ['--v' as string]: `${muted ? 0 : Math.min(100, volume)}%` }}
aria-label="Volume"
/>
</div>
);
}
function SkipButton() {
const item = usePlayer((s) => s.item);
const position = usePlayer((s) => s.position);
const seek = usePlayer((s) => s.seek);
const nextUp = usePlayer((s) => s.nextUp);
const countdown = usePlayer((s) => s.countdown);
const skipIntro = useSettings((s) => s.skipIntro);
const skipCredits = useSettings((s) => s.skipCredits);
const autoSkipped = useRef(new Set<string>());
const ms = position * 1000;
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
const mode = marker?.type === 'intro' ? skipIntro : skipCredits;
useEffect(() => {
if (marker && mode === 'auto' && !autoSkipped.current.has(marker.id + marker.start) && !(marker.type === 'credits' && nextUp)) {
autoSkipped.current.add(marker.id + marker.start);
seek(marker.end / 1000);
}
}, [marker?.id, marker?.start, mode]);
if (!marker || mode === 'off' || countdown !== null) return null;
if (marker.type === 'credits' && nextUp) return null;
return (
<button className="skip-button" onClick={() => seek(marker.end / 1000)}>
{marker.type === 'intro' ? 'Skip intro' : 'Skip credits'}
<Icon name="skipNext" size={16} />
</button>
);
}
function PostPlay() {
const server = useSession((s) => s.server);
const nextUp = usePlayer((s) => s.nextUp);
const countdown = usePlayer((s) => s.countdown);
const playNext = usePlayer((s) => s.playNext);
const cancel = usePlayer((s) => s.cancelCountdown);
if (!nextUp || countdown === null || !server) return null;
return (
<div className="post-play" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
<div className="post-play-art">
<img src={server.image(nextUp.thumb, 360, 202)} alt="" draggable={false} />
{countdown > 0 && (
<svg className="post-play-ring" viewBox="0 0 40 40">
<circle cx="20" cy="20" r="17" />
</svg>
)}
</div>
<div className="post-play-text">
<span className="micro">Next episode{countdown > 0 ? ` in ${countdown}` : ''}</span>
<b>
{episodeLabel(nextUp)} · {nextUp.title}
</b>
<div className="actions">
<Button variant="primary" size="sm" icon="play" onClick={playNext}>
Play now
</Button>
<Button variant="ghost" size="sm" onClick={cancel}>
{countdown > 0 ? 'Cancel' : 'Dismiss'}
</Button>
</div>
</div>
</div>
);
}
/** The title opens its show or movie page, with playback moving to the miniplayer. */
function openFromPlayer(id: string | undefined) {
if (!id) return;
usePlayer.getState().minimize();
navigate({ name: 'item', id });
}
function TitleBlock({ item }: { item: Item }) {
const linkable = item.type === 'movie' || item.type === 'episode';
const art = <TitleArt item={item.type === 'episode' ? { ...item, logo: item.raw?.Image?.find?.((i: any) => i.type === 'clearLogo')?.url ?? '' } : item} maxWidth={240} maxHeight={60} as="h2" />;
return (
<div className="player-title">
{linkable ? (
<button className="player-title-link" title={`Go to ${item.type === 'episode' ? item.grandparentTitle : item.title}`} onClick={() => openFromPlayer(item.type === 'episode' ? item.grandparentId : item.id)}>
{art}
</button>
) : (
art
)}
{item.type === 'episode' && (
<button className="player-episode" title="Go to this episode" onClick={() => openFromPlayer(item.id)}>
{episodeLabel(item)} · {item.title}
</button>
)}
{item.type !== 'clip' && <Facts item={item} withFormats={false} episode={false} />}
</div>
);
}
/**
* Playing in the corner while browsing. The native video is drawn into this
* box's rectangle and the page has a matching hole (see `html.player-mini`).
*/
function MiniPlayer() {
const st = usePlayer();
const box = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = box.current;
if (!el) return;
let frame = 0;
const place = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
// The layout box, not getBoundingClientRect: transforms (an entrance
// animation) must not move the video away from the page's hole.
const cs = getComputedStyle(el);
const width = parseFloat(cs.width);
const height = parseFloat(cs.height);
const x = window.innerWidth - parseFloat(cs.right) - width;
const y = window.innerHeight - parseFloat(cs.bottom) - height;
const dpr = window.devicePixelRatio || 1;
// A pixel of overdraw on each side keeps the hole covered at any scale.
if (isNative) mpv.rect({ x: x * dpr - 1, y: y * dpr - 1, width: width * dpr + 2, height: height * dpr + 2 }).catch(() => {});
});
};
place();
const ro = new ResizeObserver(place);
ro.observe(el);
window.addEventListener('resize', place);
return () => {
cancelAnimationFrame(frame);
ro.disconnect();
window.removeEventListener('resize', place);
};
}, []);
if (!st.item) return null;
const item = st.item;
const loading = !st.firstFrame && !st.error;
const pct = st.duration ? Math.min(100, (st.position / st.duration) * 100) : 0;
return (
<div ref={box} className={`mini-player${loading || st.error ? ' loading' : ''}`} onDoubleClick={() => st.expand()}>
<div className="mini-scrim" />
<div className="mini-top">
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => st.expand()}>
<Icon name="expand" size={17} />
</button>
<button className="mini-icon" aria-label="Stop playback" title="Close" onClick={() => st.close()}>
<Icon name="x" size={18} />
</button>
</div>
<div className="mini-center">
{(loading || st.buffering) && !st.error ? (
<Spinner size={30} />
) : st.error ? (
<span className="mini-error">Playback stopped</span>
) : (
<>
<button className="mini-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
<Icon name="replay10" size={22} />
</button>
<button className="mini-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
</button>
<button className="mini-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
<Icon name="forward10" size={22} />
</button>
</>
)}
</div>
<div className="mini-caption">
<b>{item.type === 'episode' ? item.grandparentTitle : item.title}</b>
{item.type === 'episode' && (
<span>
{episodeLabel(item)} · {item.title}
</span>
)}
</div>
<div className="mini-progress">
<i style={{ width: `${pct}%` }} />
</div>
</div>
);
}
export function PlayerOverlay() {
const st = usePlayer();
const server = useSession((s) => s.server);
const [panel, setPanel] = useState<'' | 'tracks' | 'settings'>('');
const [scrubbing, setScrubbing] = useState(false);
const [flash, setFlash] = useState<{ icon: string; key: number } | null>(null);
const { visible, poke } = useAutoHide(st.paused || st.ended, !!panel || scrubbing || st.countdown !== null);
const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const seekStep = useSettings((s) => s.seekStep);
const preparing = useLasting(st.enhance.preparing, PREPARING_NOTICE_MS);
const showFlash = (icon: string) => setFlash({ icon, key: Date.now() });
useEffect(() => {
if (!st.open || st.mini) setPanel('');
}, [st.open, st.mini]);
useEffect(() => {
if (!st.open || st.mini) return;
const onKey = async (e: KeyboardEvent) => {
if ((e.target as HTMLElement)?.tagName === 'INPUT' && (e.target as HTMLInputElement).type !== 'range') return;
const p = usePlayer.getState();
let handled = true;
switch (e.key) {
case ' ':
case 'k':
case 'K':
p.togglePause();
showFlash(p.paused ? 'play' : 'pause');
break;
case 'ArrowLeft':
case 'j':
case 'J':
p.seekBy(e.shiftKey ? -60 : e.key === 'ArrowLeft' ? -seekStep : -10);
showFlash('replay10');
break;
case 'ArrowRight':
case 'l':
case 'L':
p.seekBy(e.shiftKey ? 60 : e.key === 'ArrowRight' ? seekStep : 10);
showFlash('forward10');
break;
case 'ArrowUp':
p.setVolume(p.volume + 5);
break;
case 'ArrowDown':
p.setVolume(p.volume - 5);
break;
case 'm':
case 'M':
p.toggleMute();
break;
case 'f':
case 'F':
case 'F11':
p.toggleFullscreen();
break;
case 'n':
case 'N':
if (e.shiftKey && p.nextUp) p.playNext();
else handled = false;
break;
case 'u':
case 'U': {
const prefs = useSettings.getState();
const tiers = UPSCALING_ORDER.filter(tierAvailable);
const next = tiers[(tiers.indexOf(prefs.upscaling) + 1) % tiers.length];
prefs.set('upscaling', next);
// Confirm what is actually running once it's applied.
requestEnhancement().then(() => {
if (useSettings.getState().upscaling === next) toast(`Upscaling: ${upscalingValue(next, usePlayer.getState().enhance.active, false)}`);
});
break;
}
case 'b':
case 'B':
toggleBypass();
break;
case 'c':
case 'C': {
const subs = p.subTracks;
const i = subs.findIndex((t) => t.key === p.subKey);
p.selectSubtitle(i + 1 < subs.length ? subs[i + 1].key : '');
break;
}
case 'Escape': {
const fs = await win.isFullscreen().catch(() => false);
if (fs) p.toggleFullscreen();
else p.minimize();
break;
}
case 'Backspace':
p.minimize();
break;
case 'Home':
p.seek(0);
break;
default:
if (/^[0-9]$/.test(e.key) && p.duration) p.seek((Number(e.key) / 10) * p.duration);
else handled = false;
}
if (handled) {
e.preventDefault();
e.stopPropagation();
poke();
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [st.open, st.mini, seekStep, poke]);
// The macOS traffic lights fade with the rest of the player's chrome.
const chromeHidden = st.open && !st.mini && !visible && st.firstFrame && !st.error;
useEffect(() => {
if (!chromeHidden) return;
win.setButtonsVisible(false);
return () => void win.setButtonsVisible(true);
}, [chromeHidden]);
if (!st.open || !st.item) return null;
if (st.mini) return <MiniPlayer />;
const item = st.item;
const loading = !st.firstFrame && !st.error;
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
const hideChrome = !visible && !loading && !st.error;
return (
<div
className={`player${hideChrome ? ' idle' : ''}${loading ? ' loading' : ''}`}
onMouseMove={poke}
onClick={() => {
if (panel) return setPanel('');
if (clickTimer.current) return;
clickTimer.current = setTimeout(() => {
clickTimer.current = null;
if (!loading && !st.error) {
st.togglePause();
showFlash(st.paused ? 'play' : 'pause');
}
}, 220);
}}
onDoubleClick={() => {
if (clickTimer.current) clearTimeout(clickTimer.current);
clickTimer.current = null;
st.toggleFullscreen();
}}
onWheel={(e) => st.setVolume(st.volume + (e.deltaY < 0 ? 5 : -5))}
>
{(loading || st.error) && server && (
<div className="player-cover">
{art && <img src={server.image(art, 1280, 720, { blur: 0 })} alt="" />}
<div className="player-cover-scrim" />
</div>
)}
<div className="player-gradient top" />
<div className="player-gradient bottom" />
<div className="player-top" data-tauri-drag-region={isNative ? true : undefined} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
<button className="player-back" onClick={() => st.minimize()} aria-label="Back to browsing" title="Keep playing in the corner">
<Icon name="arrowLeft" size={22} />
</button>
{!st.fullscreen && <WindowControls />}
</div>
{(loading || st.buffering || st.seeking || preparing) && !st.error && (
<div className="player-center">
<Spinner size={44} />
{preparing && (
<p className="player-preparing">
Preparing {UPSCALING[st.enhance.active].label} upscaling
<small>First time on this computer only</small>
</p>
)}
</div>
)}
{flash && !loading && (
<div className="player-flash" key={flash.key}>
<Icon name={flash.icon} size={34} />
</div>
)}
{st.error && (
<div className="player-error" onClick={(e) => e.stopPropagation()}>
<Icon name="alert" size={28} />
<h2>Playback stopped</h2>
<p>{st.error}</p>
<div className="actions">
{st.terminated ? (
<Button variant="primary" onClick={() => st.close()}>
Close
</Button>
) : (
<>
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
Try converting
</Button>
<Button variant="ghost" onClick={() => st.close()}>
Close
</Button>
</>
)}
</div>
</div>
)}
<SkipButton />
<PostPlay />
{!st.error && (
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
<div className="player-bottom-head">
<TitleBlock item={item} />
<div className="player-delivery">{st.delivery?.mode === 'transcode' ? st.delivery.label : st.delivery?.mode === 'local' ? 'Offline' : ''}</div>
</div>
<Timeline onScrub={setScrubbing} />
<div className="player-controls">
<div className="player-controls-left">
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
</button>
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
<Icon name="replay10" size={24} />
</button>
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
<Icon name="forward10" size={24} />
</button>
{st.nextUp && (
<button className="player-icon" aria-label="Next episode" title={`Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}`} onClick={() => st.playNext()}>
<Icon name="skipNext" size={22} />
</button>
)}
<Volume />
<span className="player-time">
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
</span>
</div>
<div className="player-controls-right">
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
<Icon name="captions" size={23} />
</button>
<button className={`player-icon${panel === 'settings' ? ' on' : ''}`} aria-label="Playback settings" onClick={() => setPanel(panel === 'settings' ? '' : 'settings')}>
<Icon name="settings" size={22} />
</button>
<button className="player-icon" aria-label={st.fullscreen ? 'Exit full screen' : 'Full screen'} onClick={() => st.toggleFullscreen()}>
<Icon name={st.fullscreen ? 'collapse' : 'expand'} size={21} />
</button>
</div>
</div>
{panel === 'tracks' && <TracksPanel onClose={() => setPanel('')} />}
{panel === 'settings' && <SettingsPanel onClose={() => setPanel('')} />}
</div>
)}
</div>
);
}