Release Kaleido Desktop 0.1.0-beta.15
All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 2m7s

This commit is contained in:
Elijah 2026-11-11 23:29:47 -07:00
parent 59e00cde4b
commit 0361a98fa4
13 changed files with 711 additions and 128 deletions

View file

@ -14,6 +14,7 @@ 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;
@ -527,7 +528,8 @@ function SkipButton() {
if (!marker) return;
settled.current.add(key);
setPending(null);
seek(marker.end / 1000);
if (marker.type === 'credits' && item?.type === 'episode') usePlayer.getState().showPostPlay();
else seek(marker.end / 1000);
};
const cancel = () => {
if (!pending) return;
@ -568,7 +570,6 @@ function SkipButton() {
}, [counting]);
if (!marker || mode === 'off' || countdown !== null) return null;
if (marker.type === 'credits' && nextUp) return null;
const what = marker.type === 'intro' ? 'intro' : 'credits';
const elapsed = counting ? Math.max(0, position - counting.from) : 0;
return (
@ -588,41 +589,6 @@ function SkipButton() {
);
}
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;
@ -844,6 +810,9 @@ export function PlayerOverlay() {
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;
@ -951,6 +920,7 @@ export function PlayerOverlay() {
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;
@ -1036,7 +1006,6 @@ export function PlayerOverlay() {
)}
<SkipButton />
<PostPlay />
{!st.error && (
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>

179
src/player/PostPlay.tsx Normal file
View file

@ -0,0 +1,179 @@
import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { usePlayer } from './store';
import { mpv } from './engine';
import { isNative } from '../platform/native';
import { useSession } from '../app/session';
import { navigate } from '../app/router';
import { clock, episodeLabel } from '../app/format';
import * as api from '../plex/api';
import type { Item } from '../plex/types';
import { Backdrop } from '../ui/Backdrop';
import { Facts, TitleArt } from '../ui/media';
import { Icon } from '../ui/Icon';
import { WindowControls } from '../app/TopBar';
/** One Up Next screen, with a transparent opening over the native video. */
export function PostPlay() {
const st = usePlayer();
const server = useSession((s) => s.server);
const root = useRef<HTMLDivElement>(null);
const video = useRef<HTMLButtonElement>(null);
const play = useRef<HTMLButtonElement>(null);
const currentEpisode = useRef<HTMLButtonElement>(null);
const [season, setSeason] = useState<Item[]>([]);
const [related, setRelated] = useState<Item[]>([]);
const [details, setDetails] = useState<Item | null>(null);
const item = st.item!;
const upcoming = details?.id === st.nextUp?.id ? details : st.nextUp;
const counting = st.countdown !== null;
useEffect(() => {
currentEpisode.current?.scrollIntoView({ block: 'nearest', inline: 'center' });
}, [season]);
useEffect(() => {
if (!server) return;
let alive = true;
if (item.parentId) api.children(server, item.parentId).then((items) => alive && setSeason(items), () => {});
if (item.grandparentId) api.related(server, item.grandparentId).then((hubs) => {
const seen = new Set<string>([item.grandparentId]);
const shows = hubs.flatMap((h) => h.items).filter((i) => i.type === 'show' && !seen.has(i.id) && !!seen.add(i.id));
if (alive) setRelated(shows);
}, () => {});
return () => { alive = false; };
}, [server, item.id]);
useEffect(() => {
if (!server || !st.nextUp) return;
let alive = true;
api.metadata(server, st.nextUp.id).then((next) => alive && setDetails(next), () => {});
return () => { alive = false; };
}, [server, st.nextUp?.id]);
useEffect(() => {
const previous = document.activeElement as HTMLElement | null;
(play.current ?? video.current)?.focus({ preventScroll: true });
const cancel = () => usePlayer.getState().cancelCountdown();
const key = (e: KeyboardEvent) => {
cancel();
if (e.key === 'Escape' || e.key === 'Backspace') {
e.preventDefault();
e.stopImmediatePropagation();
usePlayer.getState().dismissPostPlay();
} else if (e.key === 'F11' || (e.key.toLowerCase() === 'f' && !e.ctrlKey && !e.metaKey && !e.altKey)) {
e.preventDefault();
usePlayer.getState().toggleFullscreen();
} else if (e.key === 'Tab') {
// Keep keyboard focus in the player, including after Shift+Tab.
const buttons = [...root.current!.querySelectorAll<HTMLButtonElement>('button:not(:disabled)')];
const first = buttons[0], last = buttons[buttons.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last?.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first?.focus(); }
}
};
window.addEventListener('keydown', key, true);
window.addEventListener('pointerdown', cancel, true);
window.addEventListener('wheel', cancel, { capture: true, passive: true });
return () => {
window.removeEventListener('keydown', key, true);
window.removeEventListener('pointerdown', cancel, true);
window.removeEventListener('wheel', cancel, true);
if (previous?.isConnected) previous.focus({ preventScroll: true });
};
}, []);
useEffect(() => {
const el = video.current;
if (!el) return;
let frame = 0;
const place = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const r = el.getBoundingClientRect();
const style = root.current!.style;
for (const [key, value] of Object.entries({ x: r.x, y: r.y, w: r.width, h: r.height })) style.setProperty(`--up-video-${key}`, `${value}px`);
const dpr = window.devicePixelRatio || 1;
if (isNative) mpv.rect({ x: r.x * dpr - 1, y: r.y * dpr - 1, width: r.width * dpr + 2, height: r.height * dpr + 2 }).catch(() => {});
root.current!.classList.add('placed');
});
};
const observer = new ResizeObserver(place);
observer.observe(el);
window.addEventListener('resize', place);
place();
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
window.removeEventListener('resize', place);
if (isNative) mpv.rect(null).catch(() => {});
};
}, []);
const watch = () => {
if (st.ended) st.togglePause();
st.dismissPostPlay();
};
const choose = (episode: Item) => {
if (episode.id === item.id) watch();
else st.play(episode, { resume: true, quality: st.quality });
};
const browse = async (show: Item) => {
await st.close();
navigate({ name: 'item', id: show.id, title: show.title });
};
const rail = (label: string, items: Item[], episodes: boolean) => items.length > 0 && (
<section className="up-next-rail" aria-label={label}>
<h2>{label}</h2>
<div className="up-next-cards">
{items.map((entry) => (
<button key={entry.id} ref={entry.id === item.id ? currentEpisode : undefined} className={`up-next-card${episodes ? '' : ' poster'}`} onClick={() => episodes ? choose(entry) : void browse(entry)} aria-current={entry.id === item.id ? 'true' : undefined}>
<div className="up-next-card-art">
{server && entry.thumb && <img src={server.image(entry.thumb, episodes ? 360 : 220, episodes ? 202 : 330)} alt="" loading="lazy" draggable={false} />}
{(entry.id === item.id || entry.id === st.nextUp?.id) && <span>{entry.id === item.id ? 'Now playing' : 'Up next'}</span>}
</div>
<b>{episodes ? `${episodeLabel(entry)} · ${entry.title}` : entry.title}</b>
</button>
))}
</div>
</section>
);
return (
<div className="player up-next" ref={root} role="dialog" aria-modal="true" aria-labelledby="up-next-heading">
<div className="up-next-scene">{server && <Backdrop item={upcoming ?? item} />}</div>
<header className="up-next-toolbar" data-tauri-drag-region={isNative ? true : undefined}>
<button className="up-next-back" onClick={watch} title="Return to video (Esc)"><Icon name="arrowLeft" size={18} /> Return to video</button>
<button className="up-next-back" onClick={() => st.close()}>Done watching</button>
{st.fullscreen && <button className="up-next-back" onClick={() => st.toggleFullscreen()} aria-label="Exit full screen" title="Exit full screen (F11)"><Icon name="collapse" size={18} /></button>}
{!st.fullscreen && <WindowControls />}
</header>
<div className="up-next-header">
<div className="up-next-now">
<button ref={video} className="up-next-video" onClick={watch} aria-label={`Return to ${item.title}`}><span><Icon name="expand" size={20} /> Return to video</span></button>
<div className="up-next-caption"><span>{episodeLabel(item)} · {item.title}</span><small>{st.ended ? 'Finished' : `−${clock(Math.max(0, st.duration - st.position))}`}</small></div>
<div className="up-next-progress"><i style={{ width: `${st.duration ? Math.min(100, st.position / st.duration * 100) : 0}%` }} /></div>
</div>
<div className="up-next-details">
<span className="micro" id="up-next-heading">{upcoming ? 'Up next' : 'More to watch'}</span>
<TitleArt item={item} maxWidth={280} maxHeight={52} as="h2" />
{upcoming ? <>
<h1>{upcoming.title}</h1>
<Facts item={upcoming} withFormats={false} />
{upcoming.summary && <p className="up-next-summary">{upcoming.summary}</p>}
<div className="actions">
<button ref={play} className={`up-next-play${counting ? ' counting' : ''}`} style={{ '--p': `${counting && st.countdownTotal ? (1 - st.countdown! / st.countdownTotal) * 100 : 0}%` } as CSSProperties} onClick={() => st.playNext()}>
<span><Icon name="play" size={18} /> Play next episode</span>
</button>
{counting && <button className="up-next-cancel" onClick={() => st.cancelCountdown()}>Cancel autoplay</button>}
</div>
<p className="up-next-hint" role="status">{counting ? 'Autoplay is on · Click, scroll or press any key to cancel' : 'Autoplay is off for this episode'}</p>
</> : <p className="up-next-summary">You’ve reached the end of this series.</p>}
</div>
</div>
<div className="up-next-rows">
{rail(item.parentIndex ? `Season ${item.parentIndex}` : 'Episodes', season, true)}
{rail('Related shows', related, false)}
</div>
</div>
);
}

169
src/player/store.test.ts Normal file
View file

@ -0,0 +1,169 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { MpvEvent } from './engine';
const harness = vi.hoisted(() => {
const memory = new Map<string, string>();
vi.stubGlobal('localStorage', { getItem: (k: string) => memory.get(k) ?? null, setItem: (k: string, v: string) => memory.set(k, v), removeItem: (k: string) => memory.delete(k) });
vi.stubGlobal('document', { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } });
return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true };
});
vi.mock('../platform/native', () => ({
isNative: true, invoke: vi.fn().mockResolvedValue(undefined), keepAwake: vi.fn(),
win: { isFullscreen: vi.fn().mockResolvedValue(false), setFullscreen: vi.fn(), onResized: vi.fn() },
}));
vi.mock('./engine', () => ({ mpv: {
init: vi.fn().mockResolvedValue(undefined), set: vi.fn().mockResolvedValue(undefined),
command: vi.fn().mockResolvedValue(undefined), show: vi.fn().mockResolvedValue(undefined),
rect: vi.fn().mockResolvedValue(undefined),
on: vi.fn(async (cb: typeof harness.event) => { harness.event = cb; return () => {}; }),
} }));
vi.mock('../app/session', async () => {
const { create } = await import('zustand');
return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only' }, connection: { local: true } })) };
});
vi.mock('../downloads/store', () => ({ useDownloads: { getState: () => ({ items: [] }) } }));
vi.mock('../app/queries', () => ({ invalidateLibrary: vi.fn() }));
vi.mock('../ui/overlays', () => ({ toast: vi.fn() }));
vi.mock('./theme', () => ({ stopThemeMusic: vi.fn() }));
vi.mock('./miniWindow', () => ({ bridgeMiniWindow: vi.fn(), hideMiniWindow: vi.fn(), showMiniWindow: vi.fn(), separateMini: false }));
vi.mock('./enhance', () => ({ followVideoSize: vi.fn(), noteMpvLog: vi.fn(), requestEnhancement: vi.fn().mockResolvedValue(undefined), watchPerformance: vi.fn() }));
vi.mock('../plex/playback', () => ({ directUrl: () => 'test://video', previewUrl: () => '', reportTimeline: vi.fn().mockResolvedValue({}), stopTranscode: vi.fn(), transcodeUrl: () => '' }));
vi.mock('../plex/api', () => ({ allLeaves: vi.fn(async () => harness.next), metadata: vi.fn(), setWatched: vi.fn().mockResolvedValue(undefined) }));
import { usePlayer } from './store';
import { useSettings } from '../app/settings';
import { parseItem } from '../plex/parse';
import { mpv } from './engine';
import * as api from '../plex/api';
const episode = (id = '1') => parseItem({ ratingKey: id, type: 'episode', title: `Episode ${id}`, grandparentRatingKey: 'show', duration: 100000,
Marker: [{ id: 'credits', type: 'credits', startTimeOffset: 80000, endTimeOffset: 90000 }],
Media: [{ Part: [{ key: '/video', Stream: [{ id: 'audio', streamType: 2 }] }] }],
});
const time = (position: number) => harness.event({ type: 'property', name: 'time-pos', value: position });
const eof = () => harness.event({ type: 'end-file', reason: 'eof' });
beforeEach(async () => {
vi.useFakeTimers();
vi.stubGlobal('performance', { now: () => Date.now() });
Object.assign(document, { hidden: false, hasFocus: () => harness.focused });
harness.focused = true;
useSettings.setState({ autoplayNext: true, countdownSeconds: 5, skipCredits: 'auto', watchedPercent: 95 });
const current = episode();
harness.next = [current, episode('2')];
vi.mocked(api.metadata).mockResolvedValue(current);
await usePlayer.getState().play(current, { resume: false });
await Promise.resolve();
usePlayer.setState({ firstFrame: true });
});
afterEach(async () => {
await usePlayer.getState().close();
vi.useRealTimers();
});
describe('Up Next playback lifecycle', () => {
it('opens immediately at any episode credits marker with a single countdown', () => {
time(81);
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5, countdownTotal: 5 });
});
it('leaves button-only credits to the viewer, and opens on a deliberate skip', () => {
useSettings.setState({ skipCredits: 'button' });
time(81);
vi.advanceTimersByTime(2000);
time(83);
expect(usePlayer.getState().postPlay).toBe(false);
usePlayer.getState().showPostPlay();
expect(usePlayer.getState().postPlay).toBe(true);
});
it('opens at EOF even when automatic credit skipping is off', () => {
useSettings.setState({ skipCredits: 'off' });
eof();
expect(usePlayer.getState()).toMatchObject({ postPlay: true, ended: true, countdown: 5 });
});
it('plays the next episode exactly once after the configured delay', () => {
const next = vi.fn().mockResolvedValue(undefined);
const original = usePlayer.getState().playNext;
usePlayer.setState({ playNext: next });
time(81);
vi.advanceTimersByTime(5100);
expect(next).toHaveBeenCalledOnce();
vi.advanceTimersByTime(5000);
expect(next).toHaveBeenCalledOnce();
usePlayer.setState({ playNext: original });
});
it('cancels autoplay while keeping the screen open, including across EOF', () => {
time(81);
usePlayer.getState().cancelCountdown();
eof();
vi.advanceTimersByTime(10000);
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true });
});
it('returns to credits without reopening on the next time event or EOF', () => {
time(81);
usePlayer.getState().dismissPostPlay();
time(82);
eof();
expect(usePlayer.getState()).toMatchObject({ postPlay: false, countdown: null });
});
it.each(['hidden', 'unfocused', 'paused', 'mini'] as const)('holds the countdown while %s', (reason) => {
time(81);
if (reason === 'hidden') Object.assign(document, { hidden: true });
if (reason === 'unfocused') harness.focused = false;
if (reason === 'paused') usePlayer.setState({ paused: true });
if (reason === 'mini') usePlayer.setState({ mini: true });
vi.advanceTimersByTime(20000);
expect(usePlayer.getState().countdown).toBe(5);
Object.assign(document, { hidden: false });
harness.focused = true;
usePlayer.setState({ paused: false, mini: false });
vi.advanceTimersByTime(1000);
expect(usePlayer.getState().countdown).toBeCloseTo(4);
});
it('keeps counting at EOF even when mpv reports pause', () => {
eof();
usePlayer.setState({ paused: true });
vi.advanceTimersByTime(1000);
expect(usePlayer.getState().countdown).toBeCloseTo(4);
});
it('shows a finale without an autoplay target', () => {
usePlayer.setState({ nextUp: null });
eof();
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null });
});
it('respects autoplay off', () => {
useSettings.setState({ autoplayNext: false });
time(81);
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null });
});
it('treats a seek into credits as a choice to watch them', () => {
usePlayer.getState().seek(81);
time(81);
vi.advanceTimersByTime(2000);
time(83);
expect(usePlayer.getState().postPlay).toBe(false);
expect(mpv.command).toHaveBeenCalledWith('seek', '81.000', 'absolute+exact');
});
it.each(['ended', 'button'] as const)('waits for slow episode context after %s', async (reason) => {
let resolve!: (items: ReturnType<typeof episode>[]) => void;
vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await usePlayer.getState().play(episode(), { resume: false });
usePlayer.setState({ firstFrame: true });
useSettings.setState({ skipCredits: 'button' });
if (reason === 'ended') eof();
else usePlayer.getState().showPostPlay();
expect(usePlayer.getState().postPlay).toBe(false);
resolve([episode(), episode('2')]);
await vi.waitFor(() => expect(usePlayer.getState().postPlay).toBe(true));
expect(usePlayer.getState().nextUp?.id).toBe('2');
expect(usePlayer.getState().countdownTotal).toBe(5);
expect(usePlayer.getState().countdown).toBeGreaterThan(4.9);
expect(usePlayer.getState().countdown).toBeLessThanOrEqual(5);
});
it('clears Up Next and its timer when playback closes', async () => {
time(81);
await usePlayer.getState().close();
vi.advanceTimersByTime(10000);
expect(usePlayer.getState()).toMatchObject({ open: false, postPlay: false, countdown: null });
});
});

View file

@ -71,6 +71,8 @@ interface PlayerState {
/** The episode before this one, for the previous-episode button. */
prevUp: Item | null;
countdown: number | null;
countdownTotal: number;
postPlay: boolean;
postPlayDismissed: boolean;
fullscreen: boolean;
/** Playing in the corner while browsing. */
@ -100,6 +102,8 @@ interface PlayerState {
playNext(): Promise<void>;
playPrevious(): Promise<void>;
cancelCountdown(): void;
showPostPlay(): void;
dismissPostPlay(): void;
toggleFullscreen(): Promise<void>;
previewAt(seconds: number): string;
}
@ -116,6 +120,8 @@ let unlisten: (() => void) | null = null;
let loadToken = 0;
let wasFullscreenBeforePlay = false;
let pendingExternal: Track | null = null;
let neighboursReady = false;
let postPlayRequested = false;
/**
* The server this playback belongs to, fixed when it starts. Progress, watched state
@ -334,23 +340,32 @@ async function findNeighbours(item: Item): Promise<{ prevUp: Item | null; nextUp
function startCountdown() {
const st = usePlayer.getState();
if (!st.nextUp || st.countdown !== null || st.postPlayDismissed) return;
if (!st.open || st.error || st.item?.type !== 'episode' || st.postPlay || st.postPlayDismissed) return;
const settings = useSettings.getState();
if (!settings.autoplayNext) {
usePlayer.setState({ countdown: -1 });
return;
}
usePlayer.setState({ countdown: settings.countdownSeconds });
// Don't mistake a slow context request for the end of the series.
if (!neighboursReady) return;
postPlayRequested = false;
const total = st.nextUp && settings.autoplayNext ? settings.countdownSeconds : 0;
usePlayer.setState({ postPlay: true, countdown: total > 0 ? total : null, countdownTotal: total });
if (total <= 0) return;
let lastTick = performance.now();
countdownTimer && clearInterval(countdownTimer);
countdownTimer = setInterval(() => {
const c = usePlayer.getState().countdown;
if (c === null || c < 0) return;
if (c <= 1) {
clearInterval(countdownTimer!);
countdownTimer = null;
usePlayer.getState().playNext();
} else usePlayer.setState({ countdown: c - 1 });
}, 1000);
const now = performance.now();
// Never spend time hidden, in the separate miniplayer, or behind another app.
// Cap a delayed tick so sleep / a suspended web view cannot skip an episode.
const elapsed = Math.min((now - lastTick) / 1000, 0.1);
lastTick = now;
const current = usePlayer.getState();
if (!current.open || !current.postPlay || current.error || current.countdown === null) return stopCountdown();
if (document.hidden || !document.hasFocus() || current.mini || (current.paused && !current.ended)) return;
const remaining = Math.max(0, current.countdown - elapsed);
usePlayer.setState({ countdown: remaining });
if (remaining === 0) {
stopCountdown();
current.playNext();
}
}, 50);
}
function stopCountdown() {
@ -624,9 +639,9 @@ function fallbackAfterError() {
function maybeCredits(pos: number) {
const st = usePlayer.getState();
if (st.item?.type !== 'episode' || !st.nextUp || st.countdown !== null) return;
const credits = st.item.markers.find((m) => m.type === 'credits' && (m.final || m.end >= st.item!.duration - 5000));
if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits !== 'off') startCountdown();
if (st.item?.type !== 'episode' || !st.firstFrame || st.paused || st.postPlayDismissed || Date.now() - st.lastSeek < 1500) return;
const credits = st.item.markers.find((m) => m.type === 'credits');
if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits === 'auto') startCountdown();
}
function onEnded() {
@ -635,7 +650,7 @@ function onEnded() {
usePlayer.setState({ ended: true });
report('stopped');
checkScrobble();
if (st.nextUp) startCountdown();
if (st.item?.type === 'episode') startCountdown();
}
export const usePlayer = create<PlayerState>((set, get) => ({
@ -668,6 +683,8 @@ export const usePlayer = create<PlayerState>((set, get) => ({
nextUp: null,
prevUp: null,
countdown: null,
countdownTotal: 0,
postPlay: false,
postPlayDismissed: false,
fullscreen: false,
mini: false,
@ -680,6 +697,8 @@ export const usePlayer = create<PlayerState>((set, get) => ({
// Closing or starting something else while this one is still setting up wins.
const stale = () => token !== loadToken;
const prefs = useSettings.getState();
neighboursReady = false;
postPlayRequested = false;
stopThemeMusic();
stopCountdown();
if (!isNative) {
@ -725,6 +744,8 @@ export const usePlayer = create<PlayerState>((set, get) => ({
nextUp: null,
prevUp: null,
countdown: null,
countdownTotal: 0,
postPlay: false,
postPlayDismissed: false,
chapters: [],
audioTracks: [],
@ -829,7 +850,18 @@ export const usePlayer = create<PlayerState>((set, get) => ({
const st = get();
if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing');
}, 10000);
findNeighbours(item).then((n) => token === loadToken && set(n));
findNeighbours(item).then((n) => {
if (token !== loadToken) return;
neighboursReady = true;
set(n);
const current = get();
// Metadata may arrive after EOF / the credits. Open only once it is known
// whether there is a next episode, without restarting a cancelled timer.
if (!current.postPlay) {
if (postPlayRequested || current.ended) startCountdown();
else maybeCredits(current.position);
}
});
} catch (e: any) {
if (token !== loadToken) return;
set({ error: e?.message ?? String(e), buffering: false });
@ -857,7 +889,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
await mpv.command('stop').catch(() => {});
await mpv.show(false).catch(() => {});
}
set({ open: false, mini: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false });
set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false });
// Closing the full player hands back the window it found; closing the
// miniplayer leaves browsing as it is, full screen or not.
if (!st.mini) {
@ -879,11 +911,9 @@ export const usePlayer = create<PlayerState>((set, get) => ({
seek(seconds) {
const st = get();
const target = Math.max(0, Math.min(seconds, (st.duration || seconds) - 0.5));
set({ position: target, ended: false, lastSeek: Date.now() });
if (st.countdown !== null) {
stopCountdown();
set({ countdown: null });
}
const choseCredits = st.item?.type === 'episode' && st.item.markers.some((m) => m.type === 'credits' && target * 1000 >= m.start && target * 1000 < m.end);
set({ position: target, ended: false, lastSeek: Date.now(), ...(choseCredits ? { postPlayDismissed: true } : {}) });
if (st.postPlay) st.dismissPostPlay();
mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {});
},
@ -919,6 +949,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
async minimize() {
const st = get();
if (!st.open || st.mini) return;
if (st.postPlay) st.dismissPostPlay();
// Full screen stays for browsing; Esc or the window controls leave it.
set({ mini: true });
if (separateMini) {
@ -991,6 +1022,18 @@ export const usePlayer = create<PlayerState>((set, get) => ({
set({ countdown: null, postPlayDismissed: true });
},
showPostPlay() {
// A deliberate Skip credits can reopen a screen previously dismissed.
postPlayRequested = true;
set({ postPlayDismissed: false });
startCountdown();
},
dismissPostPlay() {
stopCountdown();
set({ countdown: null, postPlay: false, postPlayDismissed: true });
},
async toggleFullscreen() {
const fs = await win.isFullscreen().catch(() => false);
await win.setFullscreen(!fs);

View file

@ -192,10 +192,10 @@ export function AppSettings({ tab }: { tab: string }) {
<Pref label="Skip intros">
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
</Pref>
<Pref label="Skip credits">
<Pref label="Skip credits" description="For episodes, opens Up Next while the credits keep playing. Show button lets you choose when; Skip automatically opens it as credits begin.">
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
</Pref>
<Pref label="Automatic skip delay" description="How long the button counts down before skipping automatically. Pause, seek or press any key to keep watching instead.">
<Pref label="Automatic skip delay" description="Delay for intros and movie credits. Episode credits use the single Up Next countdown below. Pause, seek or press any key to cancel a skip.">
<Select
value={s.autoSkipDelay}
disabled={s.skipIntro !== 'auto' && s.skipCredits !== 'auto'}
@ -206,7 +206,7 @@ export function AppSettings({ tab }: { tab: string }) {
<Pref label="Play the next episode automatically">
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
</Pref>
<Pref label="Countdown" description="Seconds before the next episode starts.">
<Pref label="Countdown" description="Seconds before Up Next plays the next episode. Click, scroll or press any key to cancel. Pauses while Kaleido is in the background.">
<Select value={s.countdownSeconds} disabled={!s.autoplayNext} onChange={(v) => set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
</Pref>
<Pref label="Arrow-key seek">

View file

@ -655,9 +655,8 @@ html.os-macos:not(.window-fullscreen) .player-top {
min-width: 340px;
}
/* Skip & post-play: above the bottom chrome, whose title row spans the full width behind them. */
.skip-button,
.post-play {
/* The skip button sits above the bottom chrome. */
.skip-button {
z-index: 1;
}
.skip-button {
@ -705,74 +704,281 @@ html.os-macos:not(.window-fullscreen) .player-top {
.skip-button > * {
position: relative;
}
.post-play {
position: absolute;
right: clamp(24px, 3.5vw, 56px);
bottom: 150px;
/* Up Next keeps a stationary opening over the native video;
only the rows scroll. */
.up-next {
display: flex;
gap: 16px;
align-items: center;
width: min(520px, calc(100vw - 48px));
padding: 14px;
border-radius: 14px;
background: rgba(20, 22, 24, 0.88);
backdrop-filter: blur(20px);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.6),
inset 0 0 0 1px rgba(255, 255, 255, 0.12);
animation: rise-in 360ms var(--ease-out);
flex-direction: column;
--up-gutter: clamp(28px, 4vw, 64px);
}
.post-play-art {
.up-next-scene {
position: absolute;
inset: 0;
background: var(--bg);
pointer-events: none;
}
.up-next.placed .up-next-scene {
-webkit-mask-image: linear-gradient(#000 0 0), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 90'%3E%3Crect width='160' height='90' rx='3'/%3E%3C/svg%3E");
-webkit-mask-size: 100% 100%, var(--up-video-w) var(--up-video-h);
-webkit-mask-position: 0 0, var(--up-video-x) var(--up-video-y);
-webkit-mask-repeat: no-repeat;
-webkit-mask-composite: xor;
mask-composite: exclude;
}
.up-next-toolbar {
position: relative;
width: 180px;
display: flex;
align-items: center;
gap: 24px;
flex: none;
height: 62px;
padding: 0 var(--up-gutter);
}
.up-next-toolbar > .up-next-back:first-child {
margin-right: auto;
}
.up-next-toolbar .window-controls {
margin-right: calc(-1 * var(--up-gutter));
}
html.os-macos:not(.window-fullscreen) .up-next-toolbar {
padding-left: max(var(--up-gutter), var(--traffic-lights));
}
.up-next-back, .up-next-cancel {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #b6bdbf;
padding: 8px 0;
}
.up-next-back:hover, .up-next-cancel:hover {
color: #fff;
}
.up-next-header {
position: relative;
display: grid;
grid-template-columns: minmax(240px, 37%) minmax(0, 1fr);
gap: clamp(28px, 4vw, 64px);
padding: 14px var(--up-gutter) 26px;
flex: none;
}
.up-next-now {
min-width: 0;
}
.up-next-video {
display: block;
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
border-radius: 8px;
overflow: hidden;
flex: none;
background: #000;
outline: 1px solid #ffffff30;
outline-offset: 2px;
}
.post-play-art img {
.up-next-video > span {
position: absolute;
inset: 0;
display: flex;
gap: 8px;
align-items: center;
justify-content: center;
border-radius: inherit;
background: #0007;
opacity: 0;
transition: opacity 150ms;
font-size: 14px;
}
.up-next-video:hover > span, .up-next-video:focus-visible > span {
opacity: 1;
}
.up-next-caption {
display: flex;
justify-content: space-between;
gap: 12px;
margin: 14px 0 8px;
font-size: 12px;
color: #b8bfc1;
}
.up-next-caption > span {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.up-next-caption small {
flex: none;
font-variant-numeric: tabular-nums;
}
.up-next-progress {
height: 3px;
border-radius: 2px;
background: #ffffff25;
overflow: hidden;
}
.up-next-progress i {
display: block;
height: 100%;
background: var(--accent);
}
.up-next-details {
min-width: 0;
align-self: center;
}
.up-next-details .micro {
display: block;
margin-bottom: 10px;
color: #a5adaf;
}
.up-next-details .title-art {
margin-bottom: 10px;
}
.up-next-details h1 {
margin: 10px 0;
font-size: clamp(22px, 2vw, 30px);
line-height: 1.2;
letter-spacing: -.025em;
}
.up-next-summary {
color: #b6bdbf;
font-size: 13px;
line-height: 1.65;
margin: 12px 0 18px;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
max-width: 720px;
}
.up-next-play {
position: relative;
overflow: hidden;
min-height: 42px;
padding: 0 20px;
border-radius: 6px;
background: #eee;
color: #101214;
font-size: 13px;
font-weight: 650;
}
.up-next-play.counting {
background: #999;
}
.up-next-play.counting::before {
content: '';
position: absolute;
inset: 0 auto 0 0;
width: var(--p);
background: #f4f4f4;
transition: width 60ms linear;
}
.up-next-play > span {
position: relative;
display: flex;
align-items: center;
gap: 8px;
}
.up-next-play:hover {
box-shadow: 0 0 0 2px #ffffff40;
}
.up-next-hint {
font-size: 11px;
color: #90999c;
margin: 10px 0 0;
}
.up-next-rows {
position: relative;
overflow-y: auto;
min-height: 0;
padding: 0 var(--up-gutter) 32px;
scrollbar-gutter: stable;
}
.up-next-rail {
margin-bottom: 24px;
}
.up-next-rail h2 {
font-size: 18px;
font-weight: 650;
margin: 0 0 14px;
}
.up-next-cards {
display: flex;
gap: 16px;
overflow-x: auto;
padding: 4px 4px 14px;
scroll-snap-type: x proximity;
}
.up-next-card {
flex: 0 0 clamp(190px, 20vw, 280px);
min-width: 0;
text-align: left;
scroll-snap-align: start;
}
.up-next-card-art {
position: relative;
background: #202427;
aspect-ratio: 16 / 9;
border-radius: 7px;
overflow: hidden;
outline: 1px solid #ffffff15;
}
.up-next-card-art img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 180ms;
}
.post-play-ring {
.up-next-card:hover img {
transform: scale(1.035);
}
.up-next-card-art > span {
position: absolute;
inset: 0;
margin: auto;
width: 46px;
height: 46px;
transform: rotate(-90deg);
left: 8px;
bottom: 8px;
background: #0b0d0fe6;
border-radius: 4px;
padding: 4px 7px;
font-size: 10px;
font-weight: 650;
}
.post-play-ring circle {
fill: rgba(0, 0, 0, 0.45);
stroke: #fff;
stroke-width: 3;
stroke-dasharray: 107;
animation: ring 8s linear forwards;
}
@keyframes ring {
from {
stroke-dashoffset: 107;
}
to {
stroke-dashoffset: 0;
}
}
.post-play-text {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.post-play-text b {
font-size: 14px;
.up-next-card > b {
display: block;
font-size: 12px;
font-weight: 550;
margin-top: 10px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.post-play-text .actions {
margin-top: 6px;
.up-next-card.poster {
flex-basis: clamp(120px, 12vw, 170px);
}
.up-next-card.poster .up-next-card-art {
aspect-ratio: 2 / 3;
}
.up-next button:focus-visible {
outline: 2px solid #fff;
outline-offset: 3px;
}
@media (max-height: 720px) {
.up-next-header {
grid-template-columns: minmax(220px, 32%) minmax(0, 1fr);
gap: 28px;
padding-top: 8px;
padding-bottom: 22px;
}
.up-next-details .title-art {
max-height: 38px;
}
.up-next-details h1 {
font-size: 22px;
margin: 6px 0;
}
.up-next-summary {
-webkit-line-clamp: 2;
margin: 8px 0 12px;
}
.up-next-details .micro {
margin-bottom: 6px;
}
}
.player-error {
position: absolute;