All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 1m36s
181 lines
8.6 KiB
TypeScript
181 lines
8.6 KiB
TypeScript
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, duration, 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';
|
||
import { Spinner } from '../ui/primitives';
|
||
|
||
/** 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 = () => {
|
||
const player = usePlayer.getState();
|
||
if (!player.postPlayDismissed) player.cancelCountdown();
|
||
};
|
||
const move = (event: MouseEvent) => {
|
||
if (event.movementX !== 0 || event.movementY !== 0) cancel();
|
||
};
|
||
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('mousemove', move, { capture: true, passive: true });
|
||
window.addEventListener('wheel', cancel, { capture: true, passive: true });
|
||
return () => {
|
||
window.removeEventListener('keydown', key, true);
|
||
window.removeEventListener('pointerdown', cancel, true);
|
||
window.removeEventListener('mousemove', move, 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" onClick={() => episodes ? choose(entry) : void browse(entry)} aria-current={entry.id === item.id ? 'true' : undefined}>
|
||
<div className="up-next-card-art">
|
||
{server && (entry.thumb || entry.art) && <img src={server.image(episodes ? entry.thumb : entry.art || entry.thumb, 360, 202)} alt="" loading="lazy" draggable={false} />}
|
||
</div>
|
||
<b>{episodes ? `${entry.index}. ${entry.title}` : entry.title}</b>
|
||
<small>{entry.id === item.id ? 'Now playing' : entry.id === st.nextUp?.id ? 'Up next' : episodes ? duration(entry.duration) : entry.year || ''}</small>
|
||
</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>
|
||
{!st.fullscreen && <div className="up-next-window-controls"><WindowControls /></div>}
|
||
<div className="up-next-header" data-tauri-drag-region={isNative ? true : undefined}>
|
||
<div className="up-next-now">
|
||
<button ref={video} className="up-next-video" onClick={watch} aria-label={`Return to ${item.title}`} />
|
||
<div className="up-next-caption"><span>{episodeLabel(item)} · {item.title}</span><small>−{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 || !st.episodeContextReady ? 'Up next' : 'More to watch'}</span>
|
||
<TitleArt item={item} maxWidth={280} maxHeight={52} as="h2" />
|
||
{upcoming ? <>
|
||
<h1>{upcoming.title}</h1>
|
||
<Facts item={{ ...upcoming, viewOffset: 0, originallyAvailableAt: '' }} 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>
|
||
</div>
|
||
</> : st.episodeContextReady ? <p className="up-next-summary">You’ve reached the end of this series.</p> : <Spinner size={24} />}
|
||
</div>
|
||
</div>
|
||
<div className="up-next-rows">
|
||
{rail(item.parentIndex ? `Season ${item.parentIndex}` : 'Episodes', season, true)}
|
||
{rail('Related shows', related, false)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|