/*
WATCH VIEW — full-screen player at /watch/:type/:id[/:season/:episode].
Flow:
1. TMDB details (+ season for tv) and api.streams start in parallel.
2. Streams arrive per provider over SSE and are ranked as they land.
Playback starts after a short grace window (immediately on a ≥1080p
hls/file hit, 1.5s after the first playable stream, or on `done`).
3. Fatal errors / startup stalls fail over to the next ranked source.
4. Progress is persisted with the v4 semantics (storage.resume).
5. TV: prefetch next episode at 80%, "Next episode" card at the credits.
export render(root, params) → cleanup()
*/
import * as api from '../api.js';
import * as tmdb from '../tmdb.js';
import * as router from '../router.js';
import { resume, keyFor, prefs } from '../storage.js';
import { h, formatSeconds } from '../util.js';
import { createPlayer } from '../ui/player.js';
const GRACE_MS = 1500;
const CONTROLS_HIDE_MS = 3000;
const NEXT_COUNTDOWN = 10;
const CREDITS_SEC = 30;
/* ---- icons (static markup) ------------------------------------------------ */
const I = {
play: '',
pause: '',
back: '',
rew: '',
fwd: '',
vol: '',
volLow: '',
mute: '',
cc: '',
gear: '',
sources: '',
episodes: '',
next: '',
pip: '',
full: '',
unfull: '',
close: '',
check: '',
};
function icon(name) {
const span = document.createElement('span');
span.className = 'pl-ico';
span.innerHTML = I[name];
return span;
}
function btn(cls, iconName, label, onClick) {
const b = h(`button.pl-btn${cls ? `.${cls}` : ''}`, { type: 'button', 'aria-label': label, title: label });
if (iconName) b.appendChild(icon(iconName));
if (onClick) b.addEventListener('click', (e) => {
e.stopPropagation();
onClick(e);
});
return b;
}
function setIcon(b, name) {
const ico = b.querySelector('.pl-ico');
if (ico) ico.innerHTML = I[name];
}
/* ---- source ranking ------------------------------------------------------- */
const KIND_LABEL = { hls: 'HLS', file: 'MP4', remux: 'Remux', torrent: 'Torrent' };
function kindOf(s) {
return (s.playback && s.playback.kind) || 'file';
}
export function scoreStream(s, lastProvider) {
const px = Number(s.pixels) || 0;
// compress 4K so a browser-friendly 1080p beats a heavy 4K remux/torrent
const q = px >= 2160 ? 1150 : px || 400;
const kind = kindOf(s);
let score = q;
if (kind === 'remux') score -= 150;
else if (kind === 'torrent') score -= 320 - Math.min(Number(s.seeds) || 0, 100);
if (s.playback && s.playback.fallback) score += 40; // direct-capable
if (lastProvider && s.provider === lastProvider) score += 100;
return score;
}
function isPlayable(s) {
return !!(s && s.playback && s.playback.url && KIND_LABEL[kindOf(s)]);
}
function fmtSize(s) {
const b = Number(s.size) || 0;
if (b > 0) {
if (b >= 1e9) return `${(b / 1e9).toFixed(b >= 1e10 ? 0 : 1)} GB`;
return `${Math.round(b / 1e6)} MB`;
}
return s.sizeText || '';
}
function kindBadge(s) {
const k = kindOf(s);
if (k === 'file') return String(s.type || 'mp4').toUpperCase() === 'WEBM' ? 'WebM' : 'MP4';
if (k === 'remux') return `${String(s.type || 'mkv').toUpperCase()} · remux`;
if (k === 'torrent') return s.seeds != null ? `Torrent · ${s.seeds} seeds` : 'Torrent';
return 'HLS';
}
function sourceName(s) {
const n = String(s.title || s.name || '').trim();
return n.toLowerCase() === String(s.provider || '').toLowerCase() ? '' : n;
}
function qualityLabel(s) {
const px = Number(s.pixels) || 0;
if (px >= 2160) return '4K';
if (px) return `${px}p`;
return s.quality || 'SD?';
}
/* ---- url helpers ----------------------------------------------------------- */
function watchPath(type, id, season, episode) {
return type === 'tv' ? `/watch/tv/${id}/${season}/${episode}` : `/watch/movie/${id}`;
}
function replaceUrl(path) {
// the router calls update() for same-route changes, which we handle in place
try {
router.navigate(path, { replace: true });
} catch (e) {
/* router not started (tests) */
}
}
let activeView = null;
/** Router hook: same-route change (e.g. another episode) handled in place. */
export function update(params) {
return activeView ? activeView.update(params) : false;
}
/* ---- view ------------------------------------------------------------------ */
export function render(root, params = {}) {
const type = params.type === 'tv' ? 'tv' : 'movie';
const id = String(params.id || '');
const isTv = type === 'tv';
const disposers = [];
const listen = (target, name, fn, opts) => {
target.addEventListener(name, fn, opts);
disposers.push(() => target.removeEventListener(name, fn, opts));
};
let destroyed = false;
const state = {
details: null,
season: isTv ? Number(params.season) || 1 : null,
episode: isTv ? Number(params.episode) || 1 : null,
seasonData: null, // tmdb.season() for state.season
browseSeason: null,
streams: new Map(), // id → stream
ranked: [],
failed: new Set(),
providers: new Map(), // name → {status, ms, count}
providerNames: [],
done: false,
current: null,
started: false,
graceTimer: null,
sse: null,
lastPersist: 0,
prefetched: false,
nextDismissed: false,
nextTimer: null,
loadGen: 0,
};
const showKey = `${type}:${id}`;
const lastProviderMap = () => prefs.get('lastProvider', {}) || {};
const lastProvider = () => lastProviderMap()[showKey] || '';
/* ---- DOM ------------------------------------------------------------- */
const video = h('video.pl-video', { playsinline: true, preload: 'auto' });
video.setAttribute('webkit-playsinline', '');
const backdrop = h('div.pl-backdrop');
const scrim = h('div.pl-scrim');
// loading overlay
const ldLogo = h('img.pl-load__logo', { alt: '', hidden: true });
const ldTitle = h('h1.pl-load__title');
const ldSub = h('p.pl-load__sub');
const ldStatus = h('div.pl-load__status', 'Finding sources…');
const ldCount = h('div.pl-load__count');
const ldBar = h('div.pl-load__bar', h('span'));
const ldTicker = h('ul.pl-load__ticker', { 'aria-live': 'polite' });
const ldTorrent = h('div.pl-load__torrent', { hidden: true });
const ldPick = h('button.pl-chip-btn', { type: 'button' }, 'Choose source');
const loading = h(
'div.pl-load',
h('div.pl-load__inner', ldLogo, ldTitle, ldSub, h('div.pl-ring'), ldStatus, ldCount, ldBar, ldTorrent, ldTicker, ldPick),
);
// top bar
const backBtn = btn('pl-back', 'back', 'Back', goBack);
const topTitle = h('div.pl-top__title');
const topSub = h('div.pl-top__sub');
const top = h('div.pl-top', backBtn, h('div.pl-top__text', topTitle, topSub));
// center
const bigPlay = btn('pl-bigplay', 'play', 'Play', () => player.toggle());
const spinner = h('div.pl-spin', h('div.pl-ring'));
const centerMsg = h('div.pl-center-msg');
const rippleL = h('div.pl-ripple.pl-ripple--l', icon('rew'), h('span', '10s'));
const rippleR = h('div.pl-ripple.pl-ripple--r', icon('fwd'), h('span', '10s'));
// seek bar
const seekBuf = h('div.pl-seek__buf');
const seekFill = h('div.pl-seek__fill');
const seekHover = h('div.pl-seek__hover');
const seekThumb = h('div.pl-seek__thumb');
const seekTip = h('div.pl-seek__tip');
const seek = h(
'div.pl-seek',
{ role: 'slider', tabindex: '0', 'aria-label': 'Seek', 'aria-valuemin': '0' },
h('div.pl-seek__track', seekBuf, seekHover, seekFill),
seekThumb,
seekTip,
);
// controls row
const playBtn = btn('', 'play', 'Play (k)', () => player.toggle());
const rewBtn = btn('', 'rew', 'Back 10s (j)', () => skip(-10));
const fwdBtn = btn('', 'fwd', 'Forward 10s (l)', () => skip(10));
const muteBtn = btn('', 'vol', 'Mute (m)', () => setMuted(!video.muted));
const volFill = h('div.pl-vol__fill');
const vol = h('div.pl-vol', { role: 'slider', 'aria-label': 'Volume', tabindex: '0' }, h('div.pl-vol__track', volFill));
const timeEl = h('div.pl-time', '0:00 / 0:00');
const nextBtn = btn('pl-next-btn', 'next', 'Next episode (n)', () => playNext());
const epBtn = btn('', 'episodes', 'Episodes', () => togglePanel('episodes'));
const ccBtn = btn('', 'cc', 'Subtitles (c)', () => toggleMenu('cc', ccBtn));
const gearBtn = btn('', 'gear', 'Quality & audio', () => toggleMenu('gear', gearBtn));
const srcBtn = btn('pl-src-btn', 'sources', 'Sources', () => togglePanel('sources'));
const srcCount = h('span.pl-src-btn__count');
srcBtn.appendChild(srcCount);
const pipBtn = btn('', 'pip', 'Picture in picture', togglePip);
const fullBtn = btn('', 'full', 'Fullscreen (f)', toggleFullscreen);
const qualityTag = h('span.pl-qtag');
if (!isTv) {
nextBtn.hidden = true;
epBtn.hidden = true;
}
if (!document.pictureInPictureEnabled) pipBtn.hidden = true;
const controls = h(
'div.pl-bottom',
seek,
h(
'div.pl-row',
playBtn,
rewBtn,
fwdBtn,
h('div.pl-volwrap', muteBtn, vol),
timeEl,
h('div.pl-spacer'),
qualityTag,
nextBtn,
epBtn,
ccBtn,
gearBtn,
srcBtn,
pipBtn,
fullBtn,
),
);
// menus + panels
const menu = h('div.pl-menu', { hidden: true, role: 'menu' });
const srcList = h('div.pl-panel__list');
const srcHead = h('div.pl-panel__meta');
const provList = h('ul.pl-provs');
const srcPanel = h(
'aside.pl-panel.pl-panel--sources',
{ 'aria-label': 'Sources' },
h('header.pl-panel__head', h('div', h('h2', 'Sources'), srcHead), btn('', 'close', 'Close', () => closePanels())),
srcList,
h('details.pl-provs-wrap', h('summary', 'Providers'), provList),
);
const epSelect = h('select.pl-select', { 'aria-label': 'Season' });
const epList = h('div.pl-panel__list.pl-eps');
const epPanel = h(
'aside.pl-panel.pl-panel--episodes',
{ 'aria-label': 'Episodes' },
h('header.pl-panel__head', h('div', h('h2', 'Episodes'), epSelect), btn('', 'close', 'Close', () => closePanels())),
epList,
);
// next episode card
const nextImg = h('div.pl-nextcard__img');
const nextLabel = h('div.pl-nextcard__label');
const nextName = h('div.pl-nextcard__name');
const nextPlay = h('button.pl-nextcard__play', { type: 'button' }, icon('play'), h('span', 'Play now'));
const nextCancel = h('button.pl-nextcard__cancel', { type: 'button' }, 'Cancel');
const nextCard = h(
'div.pl-nextcard',
{ hidden: true },
nextImg,
h('div.pl-nextcard__body', nextLabel, nextName, h('div.pl-nextcard__actions', nextPlay, nextCancel)),
);
const toastBox = h('div.pl-toasts', { 'aria-live': 'polite' });
const el = h(
'div.pl',
{ 'data-phase': 'finding', tabindex: '-1' },
backdrop,
video,
scrim,
h('div.pl-center', bigPlay, spinner, centerMsg),
rippleL,
rippleR,
loading,
top,
controls,
menu,
srcPanel,
epPanel,
nextCard,
toastBox,
);
root.replaceChildren(el);
document.documentElement.classList.add('pl-open');
disposers.push(() => document.documentElement.classList.remove('pl-open'));
try {
el.focus({ preventScroll: true });
} catch (e) {
/* ignore */
}
/* ---- toast ------------------------------------------------------------ */
function toast(msg, kind) {
const t = h(`div.pl-toast${kind ? `.pl-toast--${kind}` : ''}`, msg);
toastBox.appendChild(t);
requestAnimationFrame(() => t.classList.add('is-in'));
setTimeout(() => {
t.classList.remove('is-in');
setTimeout(() => t.remove(), 400);
}, 3200);
}
/* ---- phase / header ----------------------------------------------------- */
function setPhase(p) {
el.dataset.phase = p;
}
function episodeObj(n) {
const eps = (state.seasonData && state.seasonData.episodes) || [];
return eps.find((e) => e.episode_number === n) || null;
}
function renderTitles() {
const d = state.details;
const name = d ? d.title || d.name || '' : '';
const fallback = isTv ? 'TV show' : 'Movie';
const title = name || fallback;
let sub = '';
if (isTv) {
const ep = episodeObj(state.episode);
sub = `S${state.season} · E${state.episode}${ep && ep.name ? ` — ${ep.name}` : ''}`;
} else if (d) {
const yr = String(d.release_date || '').slice(0, 4);
sub = [yr, d.runtime ? `${Math.floor(d.runtime / 60)}h ${d.runtime % 60}m` : ''].filter(Boolean).join(' · ');
}
topTitle.textContent = title;
topSub.textContent = sub;
ldTitle.textContent = title;
ldSub.textContent = sub;
if (d) {
document.title = `${isTv ? `${title} S${state.season}E${state.episode}` : title} — bug.tv`;
const logo = tmdb.logoFor ? tmdb.logoFor(d) : null;
if (logo && logo.file_path) {
ldLogo.src = tmdb.img(logo.file_path, 'w500');
ldLogo.alt = title;
ldLogo.hidden = false;
ldTitle.hidden = true;
ldLogo.onerror = () => {
ldLogo.hidden = true;
ldTitle.hidden = false;
};
}
const ep = isTv ? episodeObj(state.episode) : null;
const bdPath = d.backdrop_path || (ep && ep.still_path);
if (bdPath) {
const url = tmdb.img(bdPath, 'w1280');
backdrop.style.backgroundImage = `url("${url.replace(/"/g, '%22')}")`;
if (!video.poster) video.poster = url;
}
}
}
/* ---- metadata ------------------------------------------------------------ */
async function loadMeta() {
try {
const d = await tmdb.details(type, id);
if (destroyed) return;
state.details = d;
} catch (e) {
console.warn('[watch] details failed', e);
}
if (isTv) await loadSeason(state.season);
renderTitles();
renderNextButton();
}
const seasonCache = new Map();
async function fetchSeason(n) {
if (seasonCache.has(n)) return seasonCache.get(n);
const p = tmdb.season(id, n).catch(() => null);
seasonCache.set(n, p);
return p;
}
async function loadSeason(n) {
const data = await fetchSeason(n);
if (destroyed) return;
if (n === state.season) state.seasonData = data;
renderEpisodesPanel(n);
}
/* ---- next episode ----------------------------------------------------------- */
function seasonList() {
const d = state.details;
return ((d && d.seasons) || []).filter((s) => s.season_number > 0 && (s.episode_count || 0) > 0);
}
function nextEpisodeRef() {
if (!isTv) return null;
const eps = (state.seasonData && state.seasonData.episodes) || [];
const sorted = eps.slice().sort((a, b) => a.episode_number - b.episode_number);
const nxt = sorted.find((e) => e.episode_number > state.episode);
const today = new Date().toISOString().slice(0, 10);
if (nxt) {
if (nxt.air_date && nxt.air_date > today) return null;
return { season: state.season, episode: nxt.episode_number, ep: nxt };
}
const nextSeason = seasonList().find((s) => s.season_number > state.season);
if (nextSeason && !(nextSeason.air_date && nextSeason.air_date > today)) {
return { season: nextSeason.season_number, episode: 1, ep: null };
}
if (!state.seasonData && !state.details) return { season: state.season, episode: state.episode + 1, ep: null };
return null;
}
function renderNextButton() {
if (!isTv) return;
nextBtn.hidden = !nextEpisodeRef();
}
function playNext() {
const n = nextEpisodeRef();
if (!n) return;
switchEpisode(n.season, n.episode);
}
async function showNextCard(fromEnded) {
if (!isTv || state.nextDismissed || !nextCard.hidden) return;
const n = nextEpisodeRef();
if (!n) return;
let ep = n.ep;
if (!ep && n.season !== state.season) {
const data = await fetchSeason(n.season);
ep = data && (data.episodes || []).find((e) => e.episode_number === n.episode);
}
if (destroyed || state.nextDismissed) return;
nextImg.style.backgroundImage = ep && ep.still_path ? `url("${tmdb.img(ep.still_path, 'w300')}")` : backdrop.style.backgroundImage;
nextName.textContent = `S${n.season} · E${n.episode}${ep && ep.name ? ` — ${ep.name}` : ''}`;
nextCard.hidden = false;
requestAnimationFrame(() => nextCard.classList.add('is-in'));
const auto = prefs.get('autoplayNext', true) !== false;
clearInterval(state.nextTimer);
if (!auto) {
nextLabel.textContent = 'Up next';
return;
}
let left = NEXT_COUNTDOWN;
nextLabel.textContent = `Next episode in ${left}s`;
nextCard.style.setProperty('--countdown', `${NEXT_COUNTDOWN}s`);
nextCard.classList.add('is-counting');
state.nextTimer = setInterval(() => {
if (video.paused && !video.ended && !fromEnded) return; // pause holds the countdown
left--;
nextLabel.textContent = `Next episode in ${left}s`;
if (left <= 0) {
clearInterval(state.nextTimer);
playNext();
}
}, 1000);
}
function hideNextCard() {
clearInterval(state.nextTimer);
nextCard.classList.remove('is-in', 'is-counting');
nextCard.hidden = true;
}
nextPlay.addEventListener('click', (e) => {
e.stopPropagation();
playNext();
});
nextCancel.addEventListener('click', (e) => {
e.stopPropagation();
state.nextDismissed = true;
hideNextCard();
});
/* ---- streams ------------------------------------------------------------------ */
function rerank() {
const lp = lastProvider();
state.ranked = [...state.streams.values()]
.filter(isPlayable)
.map((s) => ({ s, score: scoreStream(s, lp) }))
.sort((a, b) => b.score - a.score)
.map((x) => x.s);
}
function startStreams() {
const gen = ++state.loadGen;
if (state.sse) state.sse.close();
state.streams.clear();
state.ranked = [];
state.failed.clear();
state.providers.clear();
state.providerNames = [];
state.done = false;
state.started = false;
state.eager = false;
state.current = null;
clearTimeout(state.graceTimer);
state.graceTimer = null;
renderProviders();
renderSources();
const p = { tmdb: id, type };
if (isTv) {
p.season = state.season;
p.episode = state.episode;
}
const t0 = performance.now();
state.sse = api.streams(p, {
onMeta(m) {
if (gen !== state.loadGen) return;
state.providerNames = m.providers || [];
for (const n of state.providerNames) if (!state.providers.has(n)) state.providers.set(n, { status: 'pending' });
renderProviders();
},
onStreams(ev) {
if (gen !== state.loadGen) return;
let best = null;
for (const s of ev.streams || []) {
if (!s || !s.id) s.id = `${ev.provider}:${s.playback && s.playback.url}`;
if (!s.provider) s.provider = ev.provider;
if (state.streams.has(s.id)) continue;
state.streams.set(s.id, s);
if (isPlayable(s) && (!best || (s.pixels || 0) > (best.pixels || 0))) best = s;
}
rerank();
renderSources();
if (!best || state.started) return;
if (state.eager) return beginPlayback('eager'); // a previous source failed: don't wait
const k = kindOf(best);
if ((best.pixels || 0) >= 1080 && (k === 'hls' || k === 'file')) beginPlayback('fast');
else if (!state.graceTimer) state.graceTimer = setTimeout(() => beginPlayback('grace'), GRACE_MS);
},
onProvider(pv) {
if (gen !== state.loadGen) return;
state.providers.set(pv.name, pv);
if (!state.providerNames.includes(pv.name)) state.providerNames.push(pv.name);
renderProviders();
},
onDone() {
if (gen !== state.loadGen) return;
state.done = true;
for (const [n, v] of state.providers) if (v.status === 'pending') state.providers.set(n, { status: 'timeout' });
renderProviders();
console.info(`[watch] sources done in ${Math.round(performance.now() - t0)}ms, ${state.ranked.length} playable`);
if (!state.started) beginPlayback('done');
else if (!state.current) tryNext();
},
onError(e) {
console.warn('[watch] streams error', e);
},
});
}
function beginPlayback(why) {
if (state.started || destroyed) return;
clearTimeout(state.graceTimer);
const first = state.ranked.find((s) => !state.failed.has(s.id));
if (!first) {
if (state.done) showNoSources();
return;
}
state.started = true;
state.eager = false;
console.info(`[watch] start (${why}) with`, first.provider, qualityLabel(first), kindOf(first));
const rec = resume.get(currentKey());
const startAt = rec && rec.t > 10 ? rec.t : 0;
playStream(first, startAt);
if (startAt > 10) toast(`Resuming at ${formatSeconds(startAt)}`);
}
function showNoSources() {
setPhase('error');
const failed = state.failed.size;
ldStatus.textContent = failed ? 'None of the sources would play.' : 'No sources found for this title.';
ldCount.textContent = failed ? `${failed} source${failed === 1 ? '' : 's'} failed` : '';
}
function playStream(s, startAt) {
state.current = s;
qualityTag.textContent = qualityLabel(s);
if (!state.playingOnce) setPhase('starting');
ldStatus.textContent = `Starting ${s.provider} · ${qualityLabel(s)} ${kindBadge(s)}`;
player.load(s, { startAt, autoplay: true });
applyVolume();
renderSources();
renderMenus();
}
function switchTo(s, reason) {
const t = player.currentTime();
playStream(s, t > 1 ? t : (resume.get(currentKey()) || {}).t || 0);
if (reason) toast(reason);
}
function tryNext(msg) {
const next = state.ranked.find((s) => !state.failed.has(s.id) && s !== state.current);
if (!next) {
state.current = null;
if (state.done) {
showNoSources();
if (state.playingOnce) toast('No more sources to try', 'err');
} else {
setPhase(state.playingOnce ? 'buffering' : 'finding');
ldStatus.textContent = 'Waiting for more sources…';
state.started = false; // the next streams event restarts playback
state.eager = true;
}
return;
}
switchTo(next, msg ? `${msg} — trying ${next.provider} ${qualityLabel(next)}` : null);
}
/* ---- player --------------------------------------------------------------------- */
const player = createPlayer(video, {
onState(st) {
if (destroyed) return;
switch (st.phase) {
case 'playing':
state.playingOnce = true;
setPhase('playing');
rememberProvider();
break;
case 'ready':
case 'blocked':
case 'paused':
if (state.playingOnce || st.phase !== 'paused') setPhase('paused');
state.playingOnce = state.playingOnce || st.phase === 'blocked' || st.phase === 'ready';
break;
case 'buffering':
case 'seeking':
case 'loading':
case 'fallback':
if (state.playingOnce) setPhase('buffering');
else ldStatus.textContent = st.message || 'Loading…';
centerMsg.textContent = st.phase === 'fallback' ? 'Switching to relay…' : '';
break;
case 'torrent': {
if (state.playingOnce) setPhase('buffering');
ldStatus.textContent = st.message || 'Connecting to peers…';
break;
}
case 'ended':
resume.remove(currentKey());
if (isTv) showNextCard(true);
setPhase('paused');
break;
default:
break;
}
syncPlayIcon();
showControls();
},
onError(err) {
if (destroyed) return;
const s = err.stream || state.current;
if (s) state.failed.add(s.id);
console.warn('[watch] source failed', s && s.provider, err.code, err.message);
renderSources();
tryNext(`${(s && s.provider) || 'Source'} failed`);
},
onLevels() {
renderMenus();
const lv = player.playingLevel();
if (lv && lv.height) qualityTag.textContent = lv.height >= 2160 ? '4K' : `${lv.height}p`;
},
onAudioTracks() {
renderMenus();
},
onTorrent(st) {
const parts = [];
if (st.peers != null) parts.push(`${st.peers} peer${st.peers === 1 ? '' : 's'}`);
if (st.downSpeed != null) parts.push(`${(st.downSpeed / 1e6).toFixed(1)} MB/s`);
if (st.progress != null) parts.push(`${Math.round(st.progress * 100)}%`);
const text = parts.join(' · ');
ldTorrent.hidden = !text;
ldTorrent.textContent = text;
if (state.playingOnce && el.dataset.phase === 'buffering') centerMsg.textContent = text;
},
});
function rememberProvider() {
const s = state.current;
if (!s) return;
const map = lastProviderMap();
if (map[showKey] !== s.provider) {
map[showKey] = s.provider;
prefs.set('lastProvider', map);
}
// pick subtitles once per source
autoSubtitles();
}
/* ---- subtitles --------------------------------------------------------------- */
let subsAppliedFor = null;
let activeSub = -1;
function autoSubtitles() {
const s = state.current;
if (!s || subsAppliedFor === s.id) return;
subsAppliedFor = s.id;
const lang = String(prefs.get('subtitleLang', '') || '');
const list = player.subtitles();
activeSub = -1;
if (lang && lang !== 'off') {
const hit = list.find((x) => x.lang.toLowerCase().startsWith(lang.toLowerCase())) ||
list.find((x) => x.label.toLowerCase().startsWith(lang.toLowerCase()));
if (hit) activeSub = hit.index;
}
player.setSubtitle(activeSub);
renderMenus();
}
function chooseSub(i, remember = true) {
activeSub = i;
player.setSubtitle(i).then((ok) => {
if (!ok) toast('Could not load subtitles', 'err');
});
if (remember) {
const sub = player.subtitles()[i];
prefs.set('subtitleLang', sub ? sub.lang || sub.label : '');
}
renderMenus();
}
function toggleCc() {
const list = player.subtitles();
if (!list.length) return toast('No subtitles for this source');
if (activeSub >= 0) chooseSub(-1);
else {
const lang = String(prefs.get('subtitleLang', '') || 'en');
const hit = list.find((x) => x.lang.toLowerCase().startsWith(lang.toLowerCase())) || list[0];
chooseSub(hit.index);
}
toast(activeSub >= 0 ? `Subtitles: ${player.subtitles()[activeSub].label}` : 'Subtitles off');
}
function applySubSize() {
el.dataset.subsize = prefs.get('subtitleSize', 'm');
}
applySubSize();
/* ---- menus ----------------------------------------------------------------- */
let openMenu = null;
function menuItem(label, active, onClick, hint) {
const b = h('button.pl-menu__item', { type: 'button', role: 'menuitemradio', 'aria-checked': String(!!active) });
b.appendChild(h('span.pl-menu__check', active ? icon('check') : null));
b.appendChild(h('span.pl-menu__label', label));
if (hint) b.appendChild(h('span.pl-menu__hint', hint));
b.addEventListener('click', (e) => {
e.stopPropagation();
onClick();
});
return b;
}
function renderMenus() {
const subs = player.subtitles();
ccBtn.classList.toggle('is-on', activeSub >= 0);
ccBtn.classList.toggle('is-dim', !subs.length);
if (!openMenu) return;
menu.replaceChildren();
if (openMenu === 'cc') {
menu.appendChild(h('div.pl-menu__head', 'Subtitles'));
menu.appendChild(menuItem('Off', activeSub < 0, () => chooseSub(-1)));
if (!subs.length) menu.appendChild(h('div.pl-menu__empty', 'This source has no subtitles'));
for (const s of subs) menu.appendChild(menuItem(s.label, s.index === activeSub, () => chooseSub(s.index), s.lang && !s.label.toLowerCase().includes(s.lang.toLowerCase()) ? s.lang : ''));
menu.appendChild(h('div.pl-menu__head', 'Size'));
const size = prefs.get('subtitleSize', 'm');
const row = h('div.pl-menu__seg');
for (const [k, label] of [['s', 'Small'], ['m', 'Medium'], ['l', 'Large'], ['xl', 'Huge']]) {
const b = h(`button.pl-seg${k === size ? '.is-on' : ''}`, { type: 'button' }, label);
b.addEventListener('click', (e) => {
e.stopPropagation();
prefs.set('subtitleSize', k);
applySubSize();
renderMenus();
});
row.appendChild(b);
}
menu.appendChild(row);
} else if (openMenu === 'gear') {
const levels = player.levels();
const cur = player.currentLevel();
menu.appendChild(h('div.pl-menu__head', 'Quality'));
if (levels.length) {
const playing = player.playingLevel();
menu.appendChild(menuItem('Auto', cur < 0, () => player.setLevel(-1), cur < 0 && playing ? playing.label : ''));
for (const l of levels.slice().sort((a, b) => b.height - a.height || b.bitrate - a.bitrate)) {
menu.appendChild(menuItem(l.label, l.index === cur, () => player.setLevel(l.index), l.bitrate ? `${(l.bitrate / 1e6).toFixed(1)} Mbps` : ''));
}
} else {
menu.appendChild(h('div.pl-menu__empty', state.current ? `${qualityLabel(state.current)} · fixed by source` : 'No source yet'));
}
const tracks = player.audioTracks();
if (tracks.length > 1) {
menu.appendChild(h('div.pl-menu__head', 'Audio'));
const ca = player.currentAudioTrack();
for (const t of tracks) menu.appendChild(menuItem(t.label, t.index === ca, () => player.setAudioTrack(t.index), t.lang && !t.label.toLowerCase().includes(t.lang.toLowerCase()) ? t.lang : ''));
}
menu.appendChild(h('div.pl-menu__head', 'Speed'));
const seg = h('div.pl-menu__seg');
for (const r of [0.75, 1, 1.25, 1.5, 2]) {
const b = h(`button.pl-seg${video.playbackRate === r ? '.is-on' : ''}`, { type: 'button' }, `${r}×`);
b.addEventListener('click', (e) => {
e.stopPropagation();
video.playbackRate = r;
renderMenus();
});
seg.appendChild(b);
}
menu.appendChild(seg);
}
}
function toggleMenu(name, anchor) {
if (openMenu === name) return closeMenu();
closePanels();
openMenu = name;
menu.hidden = false;
renderMenus();
const r = anchor.getBoundingClientRect();
const host = el.getBoundingClientRect();
menu.style.right = `${Math.max(12, host.right - r.right - 40)}px`;
requestAnimationFrame(() => menu.classList.add('is-in'));
showControls();
}
function closeMenu() {
openMenu = null;
menu.classList.remove('is-in');
menu.hidden = true;
}
/* ---- panels ------------------------------------------------------------------ */
let openPanel = null;
function togglePanel(name) {
if (openPanel === name) return closePanels();
closeMenu();
closePanels();
openPanel = name;
const p = name === 'sources' ? srcPanel : epPanel;
p.classList.add('is-open');
el.classList.add('has-panel');
if (name === 'episodes') renderEpisodesPanel(state.browseSeason || state.season);
showControls();
}
function closePanels() {
openPanel = null;
srcPanel.classList.remove('is-open');
epPanel.classList.remove('is-open');
el.classList.remove('has-panel');
}
ldPick.addEventListener('click', (e) => {
e.stopPropagation();
togglePanel('sources');
});
function renderProviders() {
const names = state.providerNames.length ? state.providerNames : [...state.providers.keys()];
const total = names.length;
let finished = 0;
for (const n of names) {
const v = state.providers.get(n);
if (v && v.status && v.status !== 'pending') finished++;
}
const playable = state.ranked.length;
ldCount.textContent = total
? `${finished}/${total} providers · ${playable} source${playable === 1 ? '' : 's'}`
: 'Contacting server…';
ldBar.firstChild.style.width = total ? `${(finished / total) * 100}%` : '6%';
srcHead.textContent = total ? `${finished}/${total} providers${state.done ? '' : ' · searching…'}` : '';
const order = { ok: 0, pending: 1, empty: 2, timeout: 3, error: 4 };
const sorted = names
.map((n) => ({ n, v: state.providers.get(n) || { status: 'pending' } }))
.sort((a, b) => (order[a.v.status] ?? 5) - (order[b.v.status] ?? 5) || (a.v.ms || 0) - (b.v.ms || 0));
const mk = ({ n, v }) =>
h(
`li.pl-prov.pl-prov--${v.status || 'pending'}`,
{ title: v.error || '' },
h('span.pl-prov__dot'),
h('span.pl-prov__name', n),
v.status === 'ok' && v.count ? h('span.pl-prov__count', String(v.count)) : null,
h('span.pl-prov__ms', v.status === 'pending' ? '…' : v.ms != null ? `${v.ms < 1000 ? `${v.ms}ms` : `${(v.ms / 1000).toFixed(1)}s`}` : v.status),
);
ldTicker.replaceChildren(...sorted.slice(0, 14).map(mk));
provList.replaceChildren(...sorted.map(mk));
}
function renderSources() {
const list = state.ranked;
srcCount.textContent = list.length ? String(list.length) : '';
srcBtn.classList.toggle('is-searching', !state.done);
if (!list.length) {
srcList.replaceChildren(h('div.pl-panel__empty', state.done ? 'No playable sources.' : 'Searching providers…'));
renderProviders();
return;
}
const items = list.map((s) => {
const current = state.current && s.id === state.current.id;
const failed = state.failed.has(s.id);
const badges = [
h(`span.pl-badge.pl-badge--q${(s.pixels || 0) >= 2160 ? '.is-4k' : (s.pixels || 0) >= 1080 ? '.is-hd' : ''}`, qualityLabel(s)),
h(`span.pl-badge.pl-badge--${kindOf(s)}`, kindBadge(s)),
];
const size = fmtSize(s);
if (size) badges.push(h('span.pl-badge', size));
if (s.audio) badges.push(h('span.pl-badge', String(s.audio).toUpperCase()));
if (s.language) badges.push(h('span.pl-badge', s.language));
if (s.subtitles && s.subtitles.length) badges.push(h('span.pl-badge', `CC ${s.subtitles.length}`));
if (s.playback && s.playback.fallback) badges.push(h('span.pl-badge.pl-badge--direct', 'Direct'));
if (failed) badges.push(h('span.pl-badge.pl-badge--fail', 'Failed'));
const b = h(
`button.pl-source${current ? '.is-current' : ''}${failed ? '.is-failed' : ''}`,
{ type: 'button' },
h('div.pl-source__top', h('span.pl-source__prov', s.provider || 'unknown'), current ? h('span.pl-source__now', 'Playing') : null),
h('div.pl-source__name', sourceName(s)),
h('div.pl-source__badges', badges),
);
b.addEventListener('click', (e) => {
e.stopPropagation();
state.failed.delete(s.id);
state.started = true;
switchTo(s, `Switching to ${s.provider} ${qualityLabel(s)}`);
closePanels();
});
return b;
});
srcList.replaceChildren(...items);
renderProviders();
}
async function renderEpisodesPanel(n) {
if (!isTv) return;
const seasons = seasonList();
state.browseSeason = n;
epSelect.replaceChildren(
...(seasons.length ? seasons : [{ season_number: n, name: `Season ${n}` }]).map((s) =>
h('option', { value: String(s.season_number), selected: s.season_number === n }, s.name || `Season ${s.season_number}`),
),
);
if (openPanel !== 'episodes' && n !== state.season) return;
const data = await fetchSeason(n);
if (destroyed || state.browseSeason !== n) return;
const eps = ((data && data.episodes) || []).slice().sort((a, b) => a.episode_number - b.episode_number);
if (!eps.length) {
epList.replaceChildren(h('div.pl-panel__empty', 'No episodes listed'));
return;
}
let currentEl = null;
const items = eps.map((ep) => {
const current = n === state.season && ep.episode_number === state.episode;
const rec = resume.get(keyFor({ type, tmdbId: Number(id), season: n, episode: ep.episode_number }));
const pct = rec && rec.d ? Math.min(100, (rec.t / rec.d) * 100) : 0;
const still = ep.still_path ? tmdb.img(ep.still_path, 'w300') : '';
const b = h(
`button.pl-ep${current ? '.is-current' : ''}`,
{ type: 'button' },
h(
'div.pl-ep__thumb',
still ? h('img', { src: still, alt: '', loading: 'lazy' }) : h('span', String(ep.episode_number)),
pct > 0 ? h('div.pl-ep__prog', h('span', { style: { width: `${pct}%` } })) : null,
current ? h('div.pl-ep__now', 'Now playing') : null,
),
h(
'div.pl-ep__body',
h('div.pl-ep__num', `E${ep.episode_number}${ep.runtime ? ` · ${ep.runtime}m` : ''}`),
h('div.pl-ep__name', ep.name || `Episode ${ep.episode_number}`),
ep.overview ? h('div.pl-ep__ov', ep.overview) : null,
),
);
b.addEventListener('click', (e) => {
e.stopPropagation();
closePanels();
if (!current) switchEpisode(n, ep.episode_number);
});
if (current) currentEl = b;
return b;
});
epList.replaceChildren(...items);
if (currentEl) {
// not scrollIntoView: that would also scroll the (clipped) player root
requestAnimationFrame(() => {
epList.scrollTop = Math.max(0, currentEl.offsetTop - epList.offsetTop - epList.clientHeight / 2 + currentEl.offsetHeight / 2);
});
}
}
epSelect.addEventListener('change', () => renderEpisodesPanel(Number(epSelect.value)));
epSelect.addEventListener('click', (e) => e.stopPropagation());
/* ---- episodes switching -------------------------------------------------- */
async function switchEpisode(season, episode) {
persistProgress(true);
hideNextCard();
state.nextDismissed = false;
state.prefetched = false;
state.playingOnce = false;
subsAppliedFor = null;
player.stop();
state.season = season;
state.episode = episode;
const qs = params.query && String(params.query);
replaceUrl(watchPath(type, id, season, episode) + (qs ? `?${qs}` : ''));
setPhase('finding');
ldStatus.textContent = 'Finding sources…';
ldTorrent.hidden = true;
renderTitles();
startStreams();
if (!state.seasonData || state.seasonData.season_number !== season) {
state.seasonData = null;
await loadSeason(season);
renderTitles();
}
renderNextButton();
}
/* ---- resume persistence (v4 semantics) ------------------------------------ */
function currentKey() {
return keyFor({ type, tmdbId: Number(id), season: state.season, episode: state.episode });
}
function persistProgress(force) {
if (!state.current || !state.playingOnce) return;
const d = player.duration();
if (!d || !isFinite(d)) return;
const t = player.currentTime();
if (t < 10) return;
const key = currentKey();
if (t >= d - 15 || t / d >= 0.95) {
resume.remove(key);
return;
}
const now = Date.now();
if (!force && now - state.lastPersist < 3000) return;
state.lastPersist = now;
const det = state.details;
const ep = isTv ? episodeObj(state.episode) : null;
resume.save({
key,
type,
tmdbId: Number(id),
season: isTv ? state.season : undefined,
episode: isTv ? state.episode : undefined,
show: det ? det.name || det.title || '' : '',
title: ep ? ep.name || '' : '',
poster: det && det.poster_path ? tmdb.img(det.poster_path, 'w342') : '',
backdrop: det && det.backdrop_path ? tmdb.img(det.backdrop_path, 'w780') : '',
still: ep && ep.still_path ? tmdb.img(ep.still_path, 'w300') : undefined,
t,
d,
at: now,
provider: state.current ? state.current.provider : '',
});
}
function onProgress() {
persistProgress(false);
if (!isTv) return;
const d = player.duration();
const t = player.currentTime();
if (!d) return;
if (!state.prefetched && t / d >= 0.8) {
state.prefetched = true;
const n = nextEpisodeRef();
if (n) api.prefetch({ tmdb: id, type, season: n.season, episode: n.episode });
}
if (d - t <= CREDITS_SEC && d > 120 && !video.paused) showNextCard(false);
}
listen(video, 'timeupdate', onProgress);
listen(video, 'pause', () => persistProgress(true));
listen(video, 'seeked', () => persistProgress(true));
listen(window, 'pagehide', () => persistProgress(true));
listen(document, 'visibilitychange', () => {
if (document.hidden) persistProgress(true);
});
/* ---- transport UI ------------------------------------------------------------ */
let scrubbing = false;
let scrubT = 0;
function syncPlayIcon() {
const playing = !video.paused && !video.ended;
setIcon(playBtn, playing ? 'pause' : 'play');
playBtn.setAttribute('aria-label', playing ? 'Pause (k)' : 'Play (k)');
setIcon(bigPlay, 'play');
}
function paintTime() {
const d = player.duration();
const t = scrubbing ? scrubT : player.currentTime();
timeEl.textContent = d ? `${formatSeconds(t)} / ${formatSeconds(d)}` : formatSeconds(t);
const pct = d ? Math.min(100, (t / d) * 100) : 0;
seekFill.style.width = `${pct}%`;
seekThumb.style.left = `${pct}%`;
seek.setAttribute('aria-valuenow', String(Math.floor(t)));
seek.setAttribute('aria-valuemax', String(Math.floor(d || 0)));
seek.setAttribute('aria-valuetext', formatSeconds(t));
if (d) {
const ranges = player.buffered();
const tt = player.currentTime();
const r = ranges.find(([a, b]) => tt >= a - 1 && tt <= b + 1) || ranges[ranges.length - 1];
if (r) {
seekBuf.style.left = `${(r[0] / d) * 100}%`;
seekBuf.style.width = `${Math.max(0, ((r[1] - r[0]) / d) * 100)}%`;
} else seekBuf.style.width = '0';
}
}
const tick = setInterval(() => {
if (!document.hidden) paintTime();
}, 250);
disposers.push(() => clearInterval(tick));
function seekRatio(clientX) {
const r = seek.getBoundingClientRect();
return Math.min(1, Math.max(0, (clientX - r.left) / r.width));
}
listen(seek, 'pointermove', (e) => {
const d = player.duration();
if (!d) return;
const ratio = seekRatio(e.clientX);
seekTip.textContent = formatSeconds(ratio * d);
seekTip.style.left = `${ratio * 100}%`;
seekHover.style.width = `${ratio * 100}%`;
seek.classList.add('is-hover');
if (scrubbing) {
scrubT = ratio * d;
paintTime();
}
});
listen(seek, 'pointerleave', () => !scrubbing && seek.classList.remove('is-hover'));
listen(seek, 'pointerdown', (e) => {
const d = player.duration();
if (!d) return;
e.stopPropagation();
scrubbing = true;
seek.classList.add('is-scrub');
seek.setPointerCapture(e.pointerId);
scrubT = seekRatio(e.clientX) * d;
paintTime();
});
const endScrub = (e) => {
if (!scrubbing) return;
scrubbing = false;
seek.classList.remove('is-scrub', 'is-hover');
const d = player.duration();
if (d && e.type === 'pointerup') player.seek(seekRatio(e.clientX) * d);
paintTime();
};
listen(seek, 'pointerup', endScrub);
listen(seek, 'pointercancel', endScrub);
listen(seek, 'click', (e) => e.stopPropagation());
function skip(delta) {
const d = player.duration();
let t = player.currentTime() + delta;
if (d) t = Math.min(d - 1, t);
player.seek(Math.max(0, t));
showControls();
}
/* ---- volume ------------------------------------------------------------------ */
function applyVolume() {
const v = Number(prefs.get('volume', 1));
video.volume = isFinite(v) ? Math.min(1, Math.max(0, v)) : 1;
video.muted = !!prefs.get('muted', false);
paintVolume();
}
function paintVolume() {
const v = video.muted ? 0 : video.volume;
volFill.style.width = `${v * 100}%`;
vol.setAttribute('aria-valuenow', String(Math.round(v * 100)));
setIcon(muteBtn, v === 0 ? 'mute' : v < 0.5 ? 'volLow' : 'vol');
}
function setVolume(v) {
v = Math.min(1, Math.max(0, v));
video.volume = v;
video.muted = v === 0;
prefs.set('volume', Math.round(v * 100) / 100);
prefs.set('muted', video.muted);
paintVolume();
}
function setMuted(m) {
video.muted = m;
if (!m && video.volume === 0) video.volume = 0.5;
prefs.set('muted', m);
paintVolume();
}
let volDrag = false;
const volAt = (e) => {
const r = vol.getBoundingClientRect();
setVolume((e.clientX - r.left) / r.width);
};
listen(vol, 'pointerdown', (e) => {
e.stopPropagation();
volDrag = true;
vol.setPointerCapture(e.pointerId);
volAt(e);
});
listen(vol, 'pointermove', (e) => volDrag && volAt(e));
listen(vol, 'pointerup', () => (volDrag = false));
listen(vol, 'click', (e) => e.stopPropagation());
listen(video, 'volumechange', paintVolume);
applyVolume();
/* ---- fullscreen / pip ------------------------------------------------------------ */
function isFull() {
return !!(document.fullscreenElement || document.webkitFullscreenElement);
}
function toggleFullscreen() {
if (isFull()) (document.exitFullscreen || document.webkitExitFullscreen).call(document);
else if (el.requestFullscreen) el.requestFullscreen().catch(() => {});
else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen();
else if (video.webkitEnterFullscreen) video.webkitEnterFullscreen();
}
listen(document, 'fullscreenchange', () => setIcon(fullBtn, isFull() ? 'unfull' : 'full'));
function togglePip() {
if (document.pictureInPictureElement) document.exitPictureInPicture().catch(() => {});
else video.requestPictureInPicture().catch(() => toast('Picture-in-picture unavailable', 'err'));
}
/* ---- controls visibility / gestures ---------------------------------------------- */
let hideTimer = null;
// lift subtitle cues above the control bar while it is visible
function liftCues(up) {
for (const t of Array.from(video.textTracks)) {
if (t.mode !== 'showing' || !t.cues) continue;
for (const c of Array.from(t.cues)) {
try {
c.line = up ? -4 : 'auto';
} catch (e) {
/* ignore */
}
}
}
}
function setUi(on) {
if (el.classList.contains('show-ui') === on) return;
el.classList.toggle('show-ui', on);
liftCues(on);
}
listen(video.textTracks, 'change', () => liftCues(el.classList.contains('show-ui')));
function showControls() {
setUi(true);
clearTimeout(hideTimer);
hideTimer = setTimeout(() => {
if (!video.paused && !scrubbing && !openMenu && !openPanel) setUi(false);
}, CONTROLS_HIDE_MS);
}
function hideControls() {
if (video.paused || openMenu || openPanel) return;
clearTimeout(hideTimer);
setUi(false);
}
disposers.push(() => clearTimeout(hideTimer));
listen(el, 'pointermove', (e) => e.pointerType !== 'touch' && showControls());
listen(el, 'mouseleave', () => hideControls());
function ripple(side) {
const r = side < 0 ? rippleL : rippleR;
r.classList.remove('is-on');
void r.offsetWidth;
r.classList.add('is-on');
}
// Surface taps: video, scrim and the center layer.
let clickTimer = null;
let lastTap = 0;
function onSurface(e) {
if (e.target.closest('.pl-btn, .pl-bottom, .pl-top, .pl-menu, .pl-panel, .pl-nextcard, .pl-load button')) return;
if (openMenu) return closeMenu();
if (openPanel) return closePanels();
if (el.dataset.phase === 'finding' || el.dataset.phase === 'starting' || el.dataset.phase === 'error') return;
const touch = e.pointerType === 'touch' || (e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents);
const now = Date.now();
const r = el.getBoundingClientRect();
const x = (e.clientX - r.left) / r.width;
if (touch) {
if (now - lastTap < 300) {
clearTimeout(clickTimer);
lastTap = 0;
if (x < 0.35) {
skip(-10);
ripple(-1);
} else if (x > 0.65) {
skip(10);
ripple(1);
} else toggleFullscreen();
return;
}
lastTap = now;
clickTimer = setTimeout(() => {
if (el.classList.contains('show-ui')) hideControls();
else showControls();
}, 280);
return;
}
clearTimeout(clickTimer);
clickTimer = setTimeout(() => {
player.toggle();
showControls();
}, 220);
}
listen(el, 'click', onSurface);
listen(el, 'dblclick', (e) => {
if (e.target.closest('.pl-btn, .pl-bottom, .pl-top, .pl-menu, .pl-panel, .pl-nextcard')) return;
clearTimeout(clickTimer);
toggleFullscreen();
});
disposers.push(() => clearTimeout(clickTimer));
/* ---- keyboard ------------------------------------------------------------------ */
function onKey(e) {
if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return;
const tag = ((e.target && e.target.tagName) || '').toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
const k = e.key;
const handled = () => {
e.preventDefault();
showControls();
};
switch (k) {
case ' ':
case 'k':
case 'K':
if (tag === 'button' && k === ' ') return;
handled();
player.toggle();
break;
case 'j':
case 'J':
handled();
skip(-10);
ripple(-1);
break;
case 'l':
case 'L':
handled();
skip(10);
ripple(1);
break;
case 'ArrowLeft':
handled();
skip(-5);
break;
case 'ArrowRight':
handled();
skip(5);
break;
case 'ArrowUp':
handled();
setVolume((video.muted ? 0 : video.volume) + 0.05);
break;
case 'ArrowDown':
handled();
setVolume((video.muted ? 0 : video.volume) - 0.05);
break;
case 'm':
case 'M':
handled();
setMuted(!video.muted);
break;
case 'f':
case 'F':
handled();
toggleFullscreen();
break;
case 'c':
case 'C':
handled();
toggleCc();
break;
case 'n':
case 'N':
if (!isTv) return;
handled();
playNext();
break;
case 'Escape':
if (openMenu) {
e.preventDefault();
closeMenu();
} else if (openPanel) {
e.preventDefault();
closePanels();
} else if (!nextCard.hidden) {
e.preventDefault();
state.nextDismissed = true;
hideNextCard();
} else if (!isFull()) {
e.preventDefault();
goBack();
}
break;
default:
break;
}
}
listen(document, 'keydown', onKey);
/* ---- back ------------------------------------------------------------------ */
function goBack() {
persistProgress(true);
if (isFull()) {
try {
(document.exitFullscreen || document.webkitExitFullscreen).call(document);
} catch (e) {
/* ignore */
}
}
const fallback = `/title/${type}/${id}`;
if (typeof router.back === 'function') router.back(fallback);
else router.navigate(fallback);
}
/* ---- boot ---------------------------------------------------------------------- */
renderTitles();
showControls();
if (!id) {
setPhase('error');
ldStatus.textContent = 'Missing title id.';
} else {
startStreams();
loadMeta();
}
const view = {
update(p) {
if ((p.type === 'tv' ? 'tv' : 'movie') !== type || String(p.id) !== id) return false;
if (!isTv) return true;
const s = Number(p.season) || 1;
const e = Number(p.episode) || 1;
if (s !== state.season || e !== state.episode) switchEpisode(s, e);
return true;
},
};
activeView = view;
return function cleanup() {
persistProgress(true);
destroyed = true;
if (activeView === view) activeView = null;
if (state.sse) state.sse.close();
clearTimeout(state.graceTimer);
clearInterval(state.nextTimer);
player.destroy();
for (const d of disposers) d();
try {
video.pause();
} catch (e) {
/* ignore */
}
if (document.pictureInPictureElement === video) document.exitPictureInPicture().catch(() => {});
if (isFull()) document.exitFullscreen().catch(() => {});
};
}