Kaleido-Desktop/src/player/PlayerOverlay.tsx
Elijah 70530e30e2
All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 1m29s
Release Kaleido Desktop 0.1.0-beta.18
Rebuild the Up Next screen on Kaleido's own components:
- Backdrop, colour wash, buttons and cards from the title pages; the
  credits play in a top-left frame with a matching hole in the page.
- Season and related rows use Shelf, so they scroll with side arrows
  instead of scrollbars; the season row starts at the playing episode.
- Returning to the video at the end no longer restarts the episode.
- Compact layout for short windows; Mac window buttons stay visible.
- Restore the flat Episodes and markers settings.

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

1077 lines
43 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 PointerEvent as ReactPointerEvent, 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 { separateMini } from './miniWindow';
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';
import { PostPlay } from './PostPlay';
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>
);
}
/** A seek that lands inside a marker this recently means the viewer chose to be there. */
const SEEK_GRACE_MS = 1500;
const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock']);
/**
* Skip intro / Skip credits. With "Skip automatically" the button counts down for the
* chosen delay, filling as it goes, then skips. Pausing, seeking or pressing a key
* before then keeps watching: the button stays as a plain skip for the rest of the marker.
*/
function SkipButton() {
const item = usePlayer((s) => s.item);
const position = usePlayer((s) => s.position);
const seek = usePlayer((s) => s.seek);
const countdown = usePlayer((s) => s.countdown);
const postPlayDismissed = usePlayer((s) => s.postPlayDismissed);
const paused = usePlayer((s) => s.paused);
const ready = usePlayer((s) => s.firstFrame);
const lastSeek = usePlayer((s) => s.lastSeek);
const skipIntro = useSettings((s) => s.skipIntro);
const skipCredits = useSettings((s) => s.skipCredits);
const delay = useSettings((s) => s.autoSkipDelay);
// Markers already skipped, or whose automatic skip was cancelled, don't count down again.
const settled = useRef(new Set<string>());
const [pending, setPending] = useState<{ key: string; from: number } | null>(null);
const ms = position * 1000;
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
const key = item && marker ? `${item.id}:${marker.type}:${marker.start}` : '';
const episodeCredits = marker?.type === 'credits' && item?.type === 'episode';
const mode = marker?.type === 'intro' ? skipIntro : episodeCredits ? 'button' : skipCredits;
const auto = !!marker && !episodeCredits && mode === 'auto';
const counting = pending && pending.key === key ? pending : null;
const skip = () => {
if (!marker) return;
settled.current.add(key);
setPending(null);
if (marker.type === 'credits' && item?.type === 'episode') usePlayer.getState().showPostPlay();
else seek(marker.end / 1000);
};
const cancel = () => {
if (!pending) return;
settled.current.add(pending.key);
setPending(null);
};
// Start counting once an automatic marker is playing.
useEffect(() => {
if (!auto || !ready || paused || settled.current.has(key) || pending?.key === key) return;
if (Date.now() - usePlayer.getState().lastSeek < SEEK_GRACE_MS) {
settled.current.add(key);
return;
}
if (delay <= 0) return skip();
setPending({ key, from: usePlayer.getState().position });
}, [key, auto, ready, paused, delay]);
// Count playback time, so buffering doesn't eat into the delay.
useEffect(() => {
if (counting && position - counting.from >= delay) skip();
else if (pending && !counting) setPending(null);
}, [position, key]);
// Pausing or seeking means the viewer is watching.
useEffect(() => {
if (paused) cancel();
}, [paused]);
useEffect(cancel, [lastSeek]);
useEffect(() => {
if (!counting) return;
const onKey = (e: KeyboardEvent) => {
if (!MODIFIER_KEYS.has(e.key)) cancel();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [counting]);
if (!marker || (episodeCredits && !postPlayDismissed) || mode === 'off' || countdown !== null) return null;
const what = marker.type === 'intro' ? 'intro' : 'credits';
const elapsed = counting ? Math.max(0, position - counting.from) : 0;
return (
<button
className={`skip-button${counting ? ' counting' : ''}`}
style={counting ? { ['--p' as string]: `${Math.min(1, elapsed / delay) * 100}%` } : undefined}
title={counting ? 'Click to skip now. Pause, seek or press any key to keep watching.' : undefined}
onClick={(e) => {
e.stopPropagation();
skip();
}}
onDoubleClick={(e) => e.stopPropagation()}
>
<span>{counting ? `Skipping ${what}` : `Skip ${what}`}</span>
<Icon name="skipNext" size={16} />
</button>
);
}
/** 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>
);
}
/** Where the miniplayer was dragged to: its distance from the window's right and bottom edges. */
type MiniPos = { x: number; y: number };
const MINI_POS_KEY = 'kaleido.miniPosition';
const MINI_MARGIN = 8;
let miniPos: MiniPos | null | undefined;
function savedMiniPos(): MiniPos | null {
if (miniPos === undefined) {
try {
const p = JSON.parse(localStorage.getItem(MINI_POS_KEY) ?? 'null');
miniPos = p && Number.isFinite(p.x) && Number.isFinite(p.y) ? p : null;
} catch {
miniPos = null;
}
}
return miniPos ?? null;
}
/** Keeps the whole box inside the window. */
function clampMini(el: HTMLElement, pos: MiniPos): MiniPos {
const cs = getComputedStyle(el);
const maxX = window.innerWidth - parseFloat(cs.width) - MINI_MARGIN;
const maxY = window.innerHeight - parseFloat(cs.height) - MINI_MARGIN;
return { x: Math.round(Math.max(MINI_MARGIN, Math.min(maxX, pos.x))), y: Math.round(Math.max(MINI_MARGIN, Math.min(maxY, pos.y))) };
}
/** The box and the page's hole for the video (base.css) both follow these. */
function applyMiniPos(pos: MiniPos | null) {
const root = document.documentElement.style;
if (!pos) {
root.removeProperty('--mini-x');
root.removeProperty('--mini-y');
return;
}
root.setProperty('--mini-x', `${pos.x}px`);
root.setProperty('--mini-y', `${pos.y}px`);
}
/**
* Playing in the corner while browsing, and draggable anywhere in the window.
* 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);
const placeVideo = useRef(() => {});
useEffect(() => {
const el = box.current;
if (!el) return;
let frame = 0;
const fit = () => {
const saved = savedMiniPos();
applyMiniPos(saved && clampMini(el, saved));
};
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(() => {});
});
};
placeVideo.current = place;
const onResize = () => {
fit();
place();
};
onResize();
const ro = new ResizeObserver(place);
ro.observe(el);
window.addEventListener('resize', onResize);
return () => {
cancelAnimationFrame(frame);
ro.disconnect();
window.removeEventListener('resize', onResize);
};
}, []);
const startDrag = (e: ReactPointerEvent) => {
const el = box.current;
if (e.button !== 0 || !el) return;
const cs = getComputedStyle(el);
const start = { px: e.clientX, py: e.clientY, x: parseFloat(cs.right), y: parseFloat(cs.bottom) };
let dragging = false;
const move = (ev: PointerEvent) => {
const dx = ev.clientX - start.px;
const dy = ev.clientY - start.py;
if (!dragging && Math.hypot(dx, dy) < 5) return;
dragging = true;
el.classList.add('dragging');
miniPos = clampMini(el, { x: start.x - dx, y: start.y - dy });
applyMiniPos(miniPos);
placeVideo.current();
};
const up = () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
window.removeEventListener('pointercancel', up);
if (!dragging) return;
el.classList.remove('dragging');
localStorage.setItem(MINI_POS_KEY, JSON.stringify(miniPos));
// Letting go after a drag isn't a click on the button under the pointer.
const swallow = (c: MouseEvent) => {
c.stopPropagation();
c.preventDefault();
};
window.addEventListener('click', swallow, { capture: true, once: true });
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
window.addEventListener('pointercancel', up);
};
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' : ''}`} onPointerDown={startDrag} 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) => {
// Up Next owns Tab, Space/Enter and Escape; player shortcuts must not
// seek or change volume while a viewer is browsing its episode rows.
if (usePlayer.getState().postPlay) return;
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 'p':
case 'P':
if (e.shiftKey && p.prevUp) p.playPrevious();
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 && !st.postPlay && !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;
// On Windows the miniplayer is a window of its own (miniWindow.ts).
if (st.mini) return separateMini ? null : <MiniPlayer />;
if (st.postPlay && !st.error) return <PostPlay key={st.item.id} />;
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 />
{!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">
<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-center">
{/* Both episode buttons stay for episodes (dimmed at either end) so play/pause holds its place. */}
{item.type === 'episode' && (
<button
className="player-icon"
aria-label="Previous episode"
title={st.prevUp ? `Previous: ${episodeLabel(st.prevUp)} ${st.prevUp.title}` : undefined}
disabled={!st.prevUp}
onClick={() => st.playPrevious()}
>
<Icon name="skipPrev" size={22} />
</button>
)}
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
<Icon name="replay10" size={24} />
</button>
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={28} />
</button>
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
<Icon name="forward10" size={24} />
</button>
{item.type === 'episode' && (
<button
className="player-icon"
aria-label="Next episode"
title={st.nextUp ? `Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}` : undefined}
disabled={!st.nextUp}
onClick={() => st.playNext()}
>
<Icon name="skipNext" size={22} />
</button>
)}
</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>
);
}