push
This commit is contained in:
1 parent
bcf05e8063
commit
f37985b4c8
109 files changed
+22810
-6143
No files matched your search
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
actions.js — shared title actions: links, play/resume targets, My List toggle, share.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import { href } from '../router.js';
|
||||
import { resume, myList, progressOf } from '../storage.js';
|
||||
import { icon } from './icons.js';
|
||||
import { toast } from './toast.js';
|
||||
|
||||
export function titlePath(type, id) {
|
||||
return `/title/${type === 'tv' ? 'tv' : 'movie'}/${id}`;
|
||||
}
|
||||
|
||||
export function watchPath(type, id, season, episode) {
|
||||
if (type === 'tv') return `/watch/tv/${id}/${season || 1}/${episode || 1}`;
|
||||
return `/watch/movie/${id}`;
|
||||
}
|
||||
|
||||
export const titleHref = (type, id) => href(titlePath(type, id));
|
||||
export const watchHref = (type, id, s, e) => href(watchPath(type, id, s, e));
|
||||
|
||||
/*
|
||||
Where "Play" should go for a title, using resume data.
|
||||
details (optional, tv) lets us advance past a finished episode and pick the first real season.
|
||||
→ { path, label, record, progress }
|
||||
*/
|
||||
export function playTarget(type, id, details) {
|
||||
const recs = resume.forShow(type === 'tv' ? 'tv' : 'movie', id);
|
||||
const rec = recs[0] || null;
|
||||
if (type !== 'tv') {
|
||||
const p = progressOf(rec);
|
||||
if (rec && p > 0.01 && p < 0.95) return { path: watchPath('movie', id), label: 'Resume', record: rec, progress: p };
|
||||
return { path: watchPath('movie', id), label: 'Play', record: null, progress: 0 };
|
||||
}
|
||||
if (rec) {
|
||||
let s = Number(rec.season) || 1;
|
||||
let e = Number(rec.episode) || 1;
|
||||
const p = progressOf(rec);
|
||||
if (p >= 0.95 && details) {
|
||||
const seasons = (details.seasons || []).filter((x) => x.season_number > 0);
|
||||
const cur = seasons.find((x) => x.season_number === s);
|
||||
if (cur && e < cur.episode_count) e += 1;
|
||||
else if (seasons.some((x) => x.season_number === s + 1)) {
|
||||
s += 1;
|
||||
e = 1;
|
||||
}
|
||||
return { path: watchPath('tv', id, s, e), label: `Play S${s} E${e}`, record: rec, progress: 0 };
|
||||
}
|
||||
return { path: watchPath('tv', id, s, e), label: `Continue S${s} E${e}`, record: rec, progress: p };
|
||||
}
|
||||
let first = 1;
|
||||
if (details && Array.isArray(details.seasons)) {
|
||||
const real = details.seasons.filter((x) => x.season_number > 0 && x.episode_count > 0);
|
||||
if (real.length) first = real[0].season_number;
|
||||
}
|
||||
return { path: watchPath('tv', id, first, 1), label: 'Play', record: null, progress: 0 };
|
||||
}
|
||||
|
||||
// "+ My List" toggle button; item = { type, id, title, poster_path, backdrop_path, year, rating }
|
||||
export function myListButton(item, opts = {}) {
|
||||
const btn = h('button', { type: 'button', class: opts.className || 'btn btn--glass' });
|
||||
function paint() {
|
||||
const on = myList.has(item.type, item.id);
|
||||
btn.classList.toggle('is-on', on);
|
||||
btn.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||
btn.setAttribute('aria-label', on ? 'Remove from My List' : 'Add to My List');
|
||||
btn.title = on ? 'Remove from My List' : 'Add to My List';
|
||||
btn.replaceChildren(...[icon(on ? 'check' : 'plus'), opts.iconOnly ? null : h('span', on ? 'In My List' : 'My List')].filter(Boolean));
|
||||
}
|
||||
btn.dataset.mylist = `${item.type}:${item.id}`;
|
||||
btn._paint = paint;
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const on = myList.toggle(item);
|
||||
toast(on ? `Added “${item.title}” to My List` : `Removed “${item.title}” from My List`);
|
||||
});
|
||||
paint();
|
||||
return btn;
|
||||
}
|
||||
|
||||
// one global listener repaints every toggle for the changed title
|
||||
window.addEventListener('bugtv:mylist', (e) => {
|
||||
const d = e.detail || {};
|
||||
document.querySelectorAll(`[data-mylist="${d.type}:${d.id}"]`).forEach((b) => b._paint && b._paint());
|
||||
});
|
||||
|
||||
export async function shareTitle(title, path) {
|
||||
const url = new URL(href(path), location.href).toString();
|
||||
try {
|
||||
if (navigator.share) {
|
||||
await navigator.share({ title, url });
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e && e.name === 'AbortError') return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
toast('Link copied to clipboard');
|
||||
} catch (e) {
|
||||
toast(url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
card.js — media cards.
|
||||
posterCard(item) 2:3 poster, hover lift + quick info
|
||||
wideCard(item, { progress, kicker, meta, href, onRemove, image }) 16:9 backdrop, title overlay
|
||||
logoCard({ name, logo, href }) network/studio tile
|
||||
skeletonCard(variant)
|
||||
grid(items, render?) responsive poster grid
|
||||
`item` is the shape from tmdb.toItem(): { type, id, title, year, rating, poster_path, backdrop_path, overview }.
|
||||
Every card root carries class "card" and its focus target is the <a class="card__link">.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import { img, srcset } from '../tmdb.js';
|
||||
import { titleHref, playTarget } from './actions.js';
|
||||
import { navigate } from '../router.js';
|
||||
import { icon } from './icons.js';
|
||||
|
||||
function typeLabel(type) {
|
||||
return type === 'tv' ? 'Series' : 'Movie';
|
||||
}
|
||||
|
||||
function ratingNode(r) {
|
||||
if (!r || r <= 0) return null;
|
||||
return h('span.rating', icon('star', { size: 12 }), Number(r).toFixed(1));
|
||||
}
|
||||
|
||||
function image(path, sizes, alt, sizesAttr, cls = 'card__img') {
|
||||
if (!path) return null;
|
||||
const el = h('img', {
|
||||
class: cls,
|
||||
src: img(path, sizes[1] || sizes[0]),
|
||||
srcset: srcset(path, sizes),
|
||||
sizes: sizesAttr,
|
||||
alt: alt || '',
|
||||
loading: 'lazy',
|
||||
decoding: 'async',
|
||||
});
|
||||
el.addEventListener('load', () => el.classList.add('is-loaded'), { once: true });
|
||||
el.addEventListener('error', () => el.remove(), { once: true });
|
||||
return el;
|
||||
}
|
||||
|
||||
// the hover play button skips the title page and starts playback (resuming if there's progress)
|
||||
function playButton(item, size, extraClass = '') {
|
||||
return h(`span.card__play${extraClass}`, {
|
||||
role: 'button',
|
||||
'aria-label': `Play ${item.title}`,
|
||||
title: 'Play',
|
||||
onclick: (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
navigate(playTarget(item.type, item.id).path);
|
||||
},
|
||||
}, icon('play', { size }));
|
||||
}
|
||||
|
||||
export function posterCard(item, opts = {}) {
|
||||
const meta = [item.year, typeLabel(item.type)].filter(Boolean).join(' · ');
|
||||
return h('div.card.card--poster', { role: 'listitem' },
|
||||
h('a.card__link', { href: opts.href || titleHref(item.type, item.id), 'aria-label': `${item.title}${item.year ? ` (${item.year})` : ''}` },
|
||||
h('div.card__media',
|
||||
h('div.card__fallback', h('span', item.title)),
|
||||
image(item.poster_path, ['w185', 'w342', 'w500'], '', '(max-width: 720px) 34vw, 200px'),
|
||||
opts.rank ? h('span.card__rank', String(opts.rank)) : null,
|
||||
h('div.card__hover',
|
||||
playButton(item, 18),
|
||||
h('div.card__hover-meta', ratingNode(item.rating), item.year ? h('span', item.year) : null),
|
||||
),
|
||||
opts.progress > 0 ? h('div.progress.card__progress', h('i', { style: { width: `${Math.round(opts.progress * 100)}%` } })) : null,
|
||||
),
|
||||
h('div.card__body',
|
||||
h('div.card__title', item.title),
|
||||
h('div.card__meta', opts.meta || meta),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function wideCard(item, opts = {}) {
|
||||
const path = opts.image !== undefined ? opts.image : item.backdrop_path;
|
||||
const imgEl = typeof path === 'string' && /^https?:/.test(path)
|
||||
? h('img.card__img', { src: path, alt: '', loading: 'lazy', decoding: 'async', onload: (e) => e.target.classList.add('is-loaded'), onerror: (e) => e.target.remove() })
|
||||
: image(path, ['w300', 'w780'], '', '(max-width: 720px) 75vw, 340px');
|
||||
const card = h('div.card.card--wide', { role: 'listitem' },
|
||||
h('a.card__link', { href: opts.href || titleHref(item.type, item.id), 'aria-label': [item.title, opts.kicker, opts.meta].filter(Boolean).join(' — ') },
|
||||
h('div.card__media',
|
||||
h('div.card__fallback', h('span', item.title)),
|
||||
imgEl,
|
||||
h('div.card__shade'),
|
||||
h('div.card__overlay',
|
||||
opts.kicker ? h('div.card__kicker', opts.kicker) : null,
|
||||
h('div.card__title', item.title),
|
||||
opts.meta ? h('div.card__meta', opts.meta) : h('div.card__meta', ratingNode(item.rating), [item.year, typeLabel(item.type)].filter(Boolean).join(' · ')),
|
||||
opts.progress != null ? h('div.progress', h('i', { style: { width: `${Math.round(Math.min(1, opts.progress) * 100)}%` } })) : null,
|
||||
),
|
||||
playButton(item, 22, '.card__play--center'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (opts.onRemove) {
|
||||
card.appendChild(h('button.card__remove', {
|
||||
type: 'button',
|
||||
'aria-label': `Remove ${item.title} from Continue Watching`,
|
||||
title: 'Remove',
|
||||
onclick: (e) => {
|
||||
e.preventDefault();
|
||||
opts.onRemove(card);
|
||||
},
|
||||
}, icon('close', { size: 16 })));
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
export function logoCard({ name, logo, href }) {
|
||||
return h('div.card.card--logo', { role: 'listitem' },
|
||||
h('a.card__link', { href, 'aria-label': name },
|
||||
h('div.card__media',
|
||||
logo ? h('img.card__logo', { src: img(logo, 'w300'), alt: name, loading: 'lazy', decoding: 'async', onerror: (e) => { e.target.replaceWith(h('span.card__logo-text', name)); } }) : h('span.card__logo-text', name),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function skeletonCard(variant = 'poster') {
|
||||
return h('div.card.card--skeleton', { class: `card--${variant}`, 'aria-hidden': 'true' },
|
||||
h('div.card__media.skeleton'),
|
||||
variant === 'poster' ? h('div.card__body', h('div.skeleton.skeleton--line'), h('div.skeleton.skeleton--line.skeleton--short')) : null,
|
||||
);
|
||||
}
|
||||
|
||||
export function grid(items, render = (it) => posterCard(it)) {
|
||||
return h('div.grid', { role: 'list' }, items.map(render));
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
cast.js — "Top Cast" carousel: round avatars, name + character.
|
||||
castRow(credits, { limit = 15 }) → row section (or null when there is no cast).
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import { img } from '../tmdb.js';
|
||||
import { row } from './row.js';
|
||||
import { icon } from './icons.js';
|
||||
|
||||
function initials(name) {
|
||||
return String(name || '?').split(/\s+/).slice(0, 2).map((p) => p[0] || '').join('').toUpperCase();
|
||||
}
|
||||
|
||||
export function castCard(p) {
|
||||
const avatar = p.profile_path
|
||||
? h('img.cast__img', { src: img(p.profile_path, 'w185'), alt: '', loading: 'lazy', decoding: 'async', onerror: (e) => e.target.replaceWith(h('span.cast__initials', initials(p.name))) })
|
||||
: h('span.cast__initials', initials(p.name) || icon('user'));
|
||||
return h('div.card.card--cast', { role: 'listitem' },
|
||||
h('div.cast', { tabindex: '0', 'data-focus': '', 'aria-label': `${p.name}${p.character ? ` as ${p.character}` : ''}` },
|
||||
h('div.cast__avatar', avatar),
|
||||
h('div.cast__text',
|
||||
h('div.cast__name', p.name),
|
||||
p.character ? h('div.cast__role', p.character) : null)));
|
||||
}
|
||||
|
||||
export function castRow(credits, opts = {}) {
|
||||
const cast = ((credits && credits.cast) || []).slice(0, opts.limit || 15);
|
||||
if (!cast.length) return null;
|
||||
return row({ title: opts.title || 'Top Cast', variant: 'cast', items: cast, render: castCard, lazy: false });
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
episodes.js — season picker + episode cards for a tv title page.
|
||||
episodesSection(details, { season }) → <section class="episodes">
|
||||
Season tabs (≤ 7 seasons) or a dropdown; cards show still, "E3 · title", synopsis,
|
||||
runtime, air date and resume progress; click → /watch/tv/:id/:s/:e.
|
||||
*/
|
||||
import { h, runtimeLabel, plural } from '../util.js';
|
||||
import { img, season as fetchSeason } from '../tmdb.js';
|
||||
import { resume, keyFor, progressOf } from '../storage.js';
|
||||
import { watchHref } from './actions.js';
|
||||
import { icon } from './icons.js';
|
||||
|
||||
function episodeCard(show, ep) {
|
||||
const rec = resume.get(keyFor({ type: 'tv', tmdbId: show.id, season: ep.season_number, episode: ep.episode_number }));
|
||||
const p = progressOf(rec);
|
||||
const future = ep.air_date && new Date(ep.air_date) > new Date();
|
||||
const still = ep.still_path || show.backdrop_path;
|
||||
const imgEl = still
|
||||
? h('img.card__img', {
|
||||
src: img(still, 'w300'),
|
||||
srcset: `${img(still, 'w300')} 300w, ${img(still, 'w780')} 780w`,
|
||||
sizes: '(max-width: 720px) 92vw, 320px',
|
||||
alt: '', loading: 'lazy', decoding: 'async',
|
||||
class: ep.still_path ? null : 'is-fallback',
|
||||
onload: (e) => e.target.classList.add('is-loaded'),
|
||||
onerror: (e) => e.target.remove(),
|
||||
})
|
||||
: null;
|
||||
const left = rec && rec.d ? Math.max(0, rec.d - rec.t) : 0;
|
||||
const metaBits = [
|
||||
future ? `Airs ${new Date(ep.air_date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}` : null,
|
||||
!future && p > 0.01 && p < 0.95 ? `${runtimeLabel(Math.round(left / 60)) || '1m'} left` : null,
|
||||
!future && p >= 0.95 ? 'Watched' : null,
|
||||
ep.runtime ? runtimeLabel(ep.runtime) : null,
|
||||
].filter(Boolean);
|
||||
return h('div.card.card--episode', { role: 'listitem', class: [future ? 'is-future' : null, p >= 0.95 ? 'is-watched' : null] },
|
||||
h('a.card__link', { href: watchHref('tv', show.id, ep.season_number, ep.episode_number), 'aria-label': `Episode ${ep.episode_number}: ${ep.name}` },
|
||||
h('div.card__media',
|
||||
h('div.card__fallback', h('span', `E${ep.episode_number}`)),
|
||||
imgEl,
|
||||
h('div.card__shade'),
|
||||
h('span.ep__num', `E${ep.episode_number}`),
|
||||
h('span.card__play.card__play--center', icon('play', { size: 22 })),
|
||||
p > 0.01 ? h('div.progress.card__progress', h('i', { style: { width: `${Math.round(p * 100)}%` } })) : null),
|
||||
h('div.ep__body',
|
||||
h('div.ep__title', ep.name || `Episode ${ep.episode_number}`),
|
||||
metaBits.length ? h('div.ep__meta', metaBits.join(' · ')) : null,
|
||||
ep.overview ? h('p.ep__overview', ep.overview) : null)));
|
||||
}
|
||||
|
||||
export function episodesSection(show, opts = {}) {
|
||||
const seasons = (show.seasons || []).filter((s) => s.season_number > 0 && (s.episode_count > 0 || s.air_date));
|
||||
if (!seasons.length && show.seasons && show.seasons.length) seasons.push(...show.seasons);
|
||||
const specials = (show.seasons || []).find((s) => s.season_number === 0 && s.episode_count > 0);
|
||||
if (specials && seasons.length && !seasons.includes(specials)) seasons.push(specials);
|
||||
if (!seasons.length) return null;
|
||||
|
||||
let current = seasons.find((s) => s.season_number === Number(opts.season)) || seasons[0];
|
||||
const heading = h('h2.section__title');
|
||||
const list = h('div.episodes__grid', { role: 'list', 'aria-live': 'polite' });
|
||||
const label = (s) => (s.season_number === 0 ? 'Specials' : `Season ${s.season_number}`);
|
||||
|
||||
let picker;
|
||||
const tabs = [];
|
||||
if (seasons.length <= 10) {
|
||||
picker = h('div.tabs', { role: 'tablist', 'aria-label': 'Seasons' },
|
||||
seasons.map((s) => {
|
||||
const t = h('button.tab', { type: 'button', role: 'tab', 'aria-selected': 'false', onclick: () => select(s) }, label(s));
|
||||
t._season = s;
|
||||
tabs.push(t);
|
||||
return t;
|
||||
}));
|
||||
picker.addEventListener('keydown', (e) => {
|
||||
const i = tabs.indexOf(document.activeElement);
|
||||
if (i < 0 || (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft')) return;
|
||||
e.preventDefault();
|
||||
const j = (i + (e.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
|
||||
tabs[j].focus();
|
||||
select(tabs[j]._season);
|
||||
});
|
||||
} else {
|
||||
const sel = h('select.select', { 'aria-label': 'Season', onchange: (e) => select(seasons.find((s) => String(s.season_number) === e.target.value)) },
|
||||
seasons.map((s) => h('option', { value: String(s.season_number) }, `${label(s)}${s.episode_count ? ` · ${s.episode_count} ep` : ''}`)));
|
||||
picker = h('div.select-wrap', sel, icon('down', { size: 18 }));
|
||||
picker._sel = sel;
|
||||
}
|
||||
|
||||
let reqId = 0;
|
||||
async function select(s) {
|
||||
if (!s) return;
|
||||
current = s;
|
||||
tabs.forEach((t) => {
|
||||
const on = t._season === s;
|
||||
t.classList.toggle('is-active', on);
|
||||
t.setAttribute('aria-selected', on ? 'true' : 'false');
|
||||
t.tabIndex = on ? 0 : -1;
|
||||
});
|
||||
if (picker._sel) picker._sel.value = String(s.season_number);
|
||||
heading.textContent = s.episode_count ? plural(s.episode_count, 'episode') : label(s);
|
||||
const my = ++reqId;
|
||||
list.replaceChildren(...Array.from({ length: Math.min(s.episode_count || 6, 8) }, () =>
|
||||
h('div.card.card--episode.card--skeleton', h('div.card__media.skeleton'), h('div.ep__body', h('div.skeleton.skeleton--line'), h('div.skeleton.skeleton--line.skeleton--short')))));
|
||||
try {
|
||||
const data = await fetchSeason(show.id, s.season_number);
|
||||
if (my !== reqId) return;
|
||||
const eps = data.episodes || [];
|
||||
heading.textContent = `${label(s)} · ${plural(eps.length, 'episode')}`;
|
||||
list.replaceChildren(...eps.map((ep) => episodeCard(show, ep)));
|
||||
if (!eps.length) list.replaceChildren(h('p.muted', 'No episodes listed yet.'));
|
||||
} catch (e) {
|
||||
if (my !== reqId) return;
|
||||
list.replaceChildren(h('p.muted', `Could not load episodes: ${e.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
const section = h('section.section.episodes', { id: 'episodes' },
|
||||
h('div.section__head', heading, picker),
|
||||
list);
|
||||
section.refresh = () => select(current);
|
||||
select(current);
|
||||
return section;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
hero.js — rotating billboard for the home page.
|
||||
|
||||
billboard(items, { eyebrow: (i) => string, interval = 8000 }) → { el, destroy() }
|
||||
items: tmdb.toItem() shapes (need backdrop_path). Details (logo art, genres, certification,
|
||||
runtime/seasons) are fetched per slide and patched in when they arrive.
|
||||
*/
|
||||
import { h, runtimeLabel, plural, reducedMotion } from '../util.js';
|
||||
import { details as fetchDetails, img, logoFor, certificationFor } from '../tmdb.js';
|
||||
import { href } from '../router.js';
|
||||
import { icon } from './icons.js';
|
||||
import { playTarget, titlePath, myListButton } from './actions.js';
|
||||
|
||||
function backdrop(path, eager) {
|
||||
const el = h('img.hero__img', {
|
||||
src: img(path, 'w1280'),
|
||||
srcset: `${img(path, 'w780')} 780w, ${img(path, 'w1280')} 1280w, ${img(path, 'original')} 1920w`,
|
||||
sizes: '100vw',
|
||||
alt: '',
|
||||
decoding: 'async',
|
||||
loading: eager ? 'eager' : 'lazy',
|
||||
fetchpriority: eager ? 'high' : 'low',
|
||||
});
|
||||
el.addEventListener('load', () => el.classList.add('is-loaded'), { once: true });
|
||||
return el;
|
||||
}
|
||||
|
||||
function slide(item, i, opts) {
|
||||
const titleText = h('h2.hero__title', item.title);
|
||||
const titleBox = h('div.hero__titlebox', titleText);
|
||||
const meta = h('div.hero__meta',
|
||||
item.rating > 0 ? h('span.rating.rating--lg', icon('star', { size: 16 }), item.rating.toFixed(1)) : null,
|
||||
item.year ? h('span', item.year) : null,
|
||||
h('span.chip', item.type === 'tv' ? 'Series' : 'Movie'),
|
||||
);
|
||||
const play = h('a.btn.btn--primary.btn--lg', { href: href(playTarget(item.type, item.id).path) }, icon('play'), h('span', playTarget(item.type, item.id).label));
|
||||
const more = h('a.btn.btn--glass.btn--lg', { href: href(titlePath(item.type, item.id)) }, icon('info'), h('span', 'More Info'));
|
||||
const el = h('article.hero__slide', { 'aria-roledescription': 'slide', 'aria-label': `${i + 1} of ${opts.count}: ${item.title}`, 'aria-hidden': i === 0 ? 'false' : 'true' },
|
||||
h('div.hero__media', backdrop(item.backdrop_path, i === 0)),
|
||||
h('div.hero__scrim'),
|
||||
h('div.hero__content.container',
|
||||
opts.eyebrow ? h('div.hero__eyebrow', icon('fire', { size: 18 }), opts.eyebrow(i, item)) : null,
|
||||
titleBox,
|
||||
meta,
|
||||
item.overview ? h('p.hero__overview', item.overview) : null,
|
||||
h('div.hero__actions', play, more, myListButton(item, { className: 'btn btn--icon btn--glass btn--lg', iconOnly: true })),
|
||||
),
|
||||
);
|
||||
if (i !== 0) el.inert = true;
|
||||
|
||||
el._hydrate = async () => {
|
||||
let d;
|
||||
try {
|
||||
d = await fetchDetails(item.type, item.id);
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
const logo = logoFor(d);
|
||||
if (logo) {
|
||||
const im = h('img.hero__logo', { src: img(logo.file_path, 'w500'), alt: item.title, decoding: 'async' });
|
||||
im.addEventListener('load', () => {
|
||||
titleBox.classList.add('has-logo');
|
||||
titleText.classList.add('sr-only');
|
||||
}, { once: true });
|
||||
im.addEventListener('error', () => im.remove(), { once: true });
|
||||
titleBox.prepend(im);
|
||||
}
|
||||
const genres = (d.genres || []).slice(0, 3).map((g) => g.name);
|
||||
const cert = certificationFor(d);
|
||||
const extra = item.type === 'tv'
|
||||
? d.number_of_seasons ? plural(d.number_of_seasons, 'Season') : ''
|
||||
: runtimeLabel(d.runtime);
|
||||
meta.replaceChildren(...[
|
||||
item.rating > 0 ? h('span.rating.rating--lg', icon('star', { size: 16 }), item.rating.toFixed(1)) : null,
|
||||
item.year ? h('span', item.year) : null,
|
||||
extra ? h('span', extra) : null,
|
||||
genres.length ? h('span.hero__genres', genres.join(' · ')) : null,
|
||||
cert ? h('span.chip.chip--outline', cert) : null,
|
||||
].filter(Boolean));
|
||||
const target = playTarget(item.type, item.id, d);
|
||||
play.href = href(target.path);
|
||||
play.lastChild.textContent = target.label;
|
||||
};
|
||||
return el;
|
||||
}
|
||||
|
||||
export function billboard(items, opts = {}) {
|
||||
const data = (items || []).filter((x) => x && x.backdrop_path).slice(0, opts.max || 5);
|
||||
const interval = opts.interval || 8000;
|
||||
if (!data.length) return { el: h('div.hero.hero--empty'), destroy() {} };
|
||||
|
||||
const slides = data.map((it, i) => slide(it, i, { count: data.length, eyebrow: opts.eyebrow }));
|
||||
const dots = data.map((it, i) => h('button.hero__dot', { type: 'button', 'aria-label': `Show ${it.title}`, style: { '--dur': `${interval}ms` } }, h('i')));
|
||||
const el = h('section.hero', { 'aria-roledescription': 'carousel', 'aria-label': 'Featured' },
|
||||
h('div.hero__slides', slides),
|
||||
data.length > 1 ? h('div.hero__dots.container', h('div.hero__dots-inner', dots)) : null,
|
||||
);
|
||||
|
||||
let cur = 0;
|
||||
let timer = null;
|
||||
let paused = false;
|
||||
let destroyed = false;
|
||||
|
||||
function show(i) {
|
||||
const nextI = (i + data.length) % data.length;
|
||||
slides.forEach((s, k) => {
|
||||
const on = k === nextI;
|
||||
s.classList.toggle('is-active', on);
|
||||
s.setAttribute('aria-hidden', on ? 'false' : 'true');
|
||||
s.inert = !on;
|
||||
});
|
||||
dots.forEach((d, k) => {
|
||||
d.classList.toggle('is-active', k === nextI);
|
||||
d.setAttribute('aria-current', k === nextI ? 'true' : 'false');
|
||||
});
|
||||
cur = nextI;
|
||||
// restart the dot fill animation
|
||||
const fill = dots[cur] && dots[cur].firstChild;
|
||||
if (fill) {
|
||||
fill.style.animation = 'none';
|
||||
void fill.offsetWidth;
|
||||
fill.style.animation = '';
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
clearTimeout(timer);
|
||||
if (destroyed || paused || document.hidden || data.length < 2 || reducedMotion()) return;
|
||||
timer = setTimeout(() => show(cur + 1), interval);
|
||||
}
|
||||
|
||||
function setPaused(p) {
|
||||
paused = p;
|
||||
el.classList.toggle('is-paused', p);
|
||||
if (p) clearTimeout(timer);
|
||||
else schedule();
|
||||
}
|
||||
|
||||
dots.forEach((d, i) => d.addEventListener('click', () => show(i)));
|
||||
el.addEventListener('mouseenter', () => setPaused(true));
|
||||
el.addEventListener('mouseleave', () => setPaused(false));
|
||||
el.addEventListener('focusin', () => setPaused(true));
|
||||
el.addEventListener('focusout', (e) => {
|
||||
if (!el.contains(e.relatedTarget)) setPaused(false);
|
||||
});
|
||||
el.addEventListener('keydown', (e) => {
|
||||
if (e.target.closest('.hero__dots') && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
|
||||
e.preventDefault();
|
||||
show(cur + (e.key === 'ArrowRight' ? 1 : -1));
|
||||
dots[cur].focus();
|
||||
}
|
||||
});
|
||||
// swipe on touch
|
||||
let sx = null;
|
||||
el.addEventListener('touchstart', (e) => { sx = e.touches[0].clientX; }, { passive: true });
|
||||
el.addEventListener('touchend', (e) => {
|
||||
if (sx == null) return;
|
||||
const dx = e.changedTouches[0].clientX - sx;
|
||||
sx = null;
|
||||
if (Math.abs(dx) > 50) show(cur + (dx < 0 ? 1 : -1));
|
||||
});
|
||||
const onVis = () => (document.hidden ? clearTimeout(timer) : schedule());
|
||||
document.addEventListener('visibilitychange', onVis);
|
||||
|
||||
show(0);
|
||||
slides[0]._hydrate();
|
||||
setTimeout(() => slides.slice(1).forEach((s) => s._hydrate()), 600);
|
||||
|
||||
return {
|
||||
el,
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
clearTimeout(timer);
|
||||
document.removeEventListener('visibilitychange', onVis);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
icons.js — inline SVG icons (stroke style, 24×24). icon(name, { size, fill }) → <svg>.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
|
||||
const P = {
|
||||
play: [['path', { d: 'M7 4.5v15a1 1 0 0 0 1.5.86l12.5-7.5a1 1 0 0 0 0-1.72L8.5 3.64A1 1 0 0 0 7 4.5z', fill: 'currentColor', stroke: 'none' }]],
|
||||
info: [['circle', { cx: 12, cy: 12, r: 9.5 }], ['path', { d: 'M12 11v6M12 7.5v.01' }]],
|
||||
plus: [['path', { d: 'M12 5v14M5 12h14' }]],
|
||||
check: [['path', { d: 'M5 12.5l4.5 4.5L19 7.5' }]],
|
||||
search: [['circle', { cx: 11, cy: 11, r: 7 }], ['path', { d: 'M20.5 20.5L16 16' }]],
|
||||
settings: [['circle', { cx: 12, cy: 12, r: 3 }], ['path', { d: 'M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z' }]],
|
||||
home: [['path', { d: 'M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z' }]],
|
||||
film: [['rect', { x: 3, y: 3, width: 18, height: 18, rx: 2.5 }], ['path', { d: 'M7 3v18M17 3v18M3 8h4M3 16h4M17 8h4M17 16h4M3 12h18' }]],
|
||||
tv: [['rect', { x: 2.5, y: 6.5, width: 19, height: 13, rx: 2.5 }], ['path', { d: 'M8 2.5l4 4 4-4' }]],
|
||||
bookmark: [['path', { d: 'M6 3.5h12a.5.5 0 0 1 .5.5v17l-6.5-4.5L5.5 21V4a.5.5 0 0 1 .5-.5z' }]],
|
||||
share: [['circle', { cx: 18, cy: 5, r: 2.5 }], ['circle', { cx: 6, cy: 12, r: 2.5 }], ['circle', { cx: 18, cy: 19, r: 2.5 }], ['path', { d: 'M8.2 13.3l7.6 4.4M15.8 6.3l-7.6 4.4' }]],
|
||||
trailer: [['rect', { x: 3, y: 4, width: 18, height: 16, rx: 2.5 }], ['path', { d: 'M10 9v6l5-3z', fill: 'currentColor' }]],
|
||||
star: [['path', { d: 'M12 2.8l2.8 5.8 6.3.9-4.6 4.4 1.1 6.3L12 17.2l-5.6 3 1.1-6.3L2.9 9.5l6.3-.9z', fill: 'currentColor', stroke: 'none' }]],
|
||||
close: [['path', { d: 'M6 6l12 12M18 6L6 18' }]],
|
||||
left: [['path', { d: 'M15 18l-6-6 6-6' }]],
|
||||
right: [['path', { d: 'M9 6l6 6-6 6' }]],
|
||||
down: [['path', { d: 'M6 9l6 6 6-6' }]],
|
||||
back: [['path', { d: 'M19 12H5M11 18l-6-6 6-6' }]],
|
||||
trash: [['path', { d: 'M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3' }]],
|
||||
user: [['circle', { cx: 12, cy: 8, r: 4 }], ['path', { d: 'M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6' }]],
|
||||
spark: [['path', { d: 'M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6' }]],
|
||||
fire: [['path', { d: 'M12 22c4 0 7-2.7 7-6.6 0-3.6-2.4-5.7-4-8.4-.5 2-1.6 3.2-3 3.4.4-3-1-6-4-8.4.2 3.3-1.4 5.5-2.8 7.4C4.2 11 3 12.6 3 15.4 3 19.3 6 22 10 22z' }]],
|
||||
list: [['path', { d: 'M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01' }]],
|
||||
};
|
||||
|
||||
export function icon(name, opts = {}) {
|
||||
const size = opts.size || 20;
|
||||
const parts = P[name] || P.info;
|
||||
return h('svg', {
|
||||
class: ['icon', opts.class],
|
||||
viewBox: '0 0 24 24',
|
||||
width: size,
|
||||
height: size,
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
'stroke-width': opts.stroke || 2,
|
||||
'stroke-linecap': 'round',
|
||||
'stroke-linejoin': 'round',
|
||||
'aria-hidden': 'true',
|
||||
focusable: 'false',
|
||||
}, parts.map(([tag, attrs]) => h(tag, attrs)));
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
modal.js — accessible dialog. openModal(content, { label, wide, onClose }) → close()
|
||||
trailerModal(youtubeKey, title) plays a YouTube trailer in an iframe.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import { icon } from './icons.js';
|
||||
|
||||
export function openModal(content, opts = {}) {
|
||||
const prevFocus = document.activeElement;
|
||||
const closeBtn = h('button.modal__close.icon-btn', { type: 'button', 'aria-label': 'Close' }, icon('close'));
|
||||
const dialog = h('div.modal__dialog', { class: opts.wide ? 'modal__dialog--wide' : null, role: 'dialog', 'aria-modal': 'true', 'aria-label': opts.label || 'Dialog', tabindex: '-1' }, closeBtn, content);
|
||||
const backdrop = h('div.modal', dialog);
|
||||
let closed = false;
|
||||
|
||||
function close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
backdrop.classList.remove('is-open');
|
||||
document.documentElement.classList.remove('has-modal');
|
||||
setTimeout(() => backdrop.remove(), 250);
|
||||
if (opts.onClose) opts.onClose();
|
||||
if (prevFocus && prevFocus.focus) prevFocus.focus();
|
||||
}
|
||||
|
||||
function onKey(e) {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
close();
|
||||
} else if (e.key === 'Tab') {
|
||||
const f = dialog.querySelectorAll('button, [href], input, select, textarea, iframe, [tabindex]:not([tabindex="-1"])');
|
||||
if (!f.length) return;
|
||||
const first = f[0];
|
||||
const last = f[f.length - 1];
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
closeBtn.addEventListener('click', close);
|
||||
backdrop.addEventListener('click', (e) => {
|
||||
if (e.target === backdrop) close();
|
||||
});
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
document.body.appendChild(backdrop);
|
||||
document.documentElement.classList.add('has-modal');
|
||||
requestAnimationFrame(() => {
|
||||
backdrop.classList.add('is-open');
|
||||
closeBtn.focus();
|
||||
});
|
||||
return close;
|
||||
}
|
||||
|
||||
export function trailerModal(key, title) {
|
||||
const frame = h('iframe.modal__video', {
|
||||
src: `https://www.youtube-nocookie.com/embed/${encodeURIComponent(key)}?autoplay=1&rel=0&modestbranding=1`,
|
||||
title: title ? `${title} — trailer` : 'Trailer',
|
||||
allow: 'autoplay; encrypted-media; picture-in-picture; fullscreen',
|
||||
allowfullscreen: true,
|
||||
referrerpolicy: 'strict-origin-when-cross-origin',
|
||||
});
|
||||
return openModal(h('div.modal__media', frame), { label: title ? `${title} trailer` : 'Trailer', wide: true });
|
||||
}
|
||||
@@ -0,0 +1,764 @@
|
||||
/*
|
||||
PLAYER ENGINE — plays one Stream (docs/api.md "Stream") in a <video>.
|
||||
|
||||
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime })
|
||||
load(stream, { startAt, autoplay }) start a source (tears down the previous one)
|
||||
play() / pause() / toggle()
|
||||
seek(t) absolute seconds (offset-aware for remux)
|
||||
currentTime() / duration() / buffered() → [[start,end]…] in absolute seconds
|
||||
levels() / setLevel(i) hls.js quality, -1 = auto
|
||||
audioTracks() / setAudioTrack(i)
|
||||
subtitles() / setSubtitle(i) stream.subtitles, -1 = off (fetched → blob VTT)
|
||||
destroy()
|
||||
|
||||
playback.kind:
|
||||
hls hls.js (or native HLS on Safari)
|
||||
file <video src>, native range seeking
|
||||
remux <video src=url?start=t>, clock = offset + video.currentTime,
|
||||
seeking outside the buffer reloads with a new start, duration
|
||||
from `${path}/probe`
|
||||
torrent poll playback.status every 1s until ready, then remux-style
|
||||
(status.file.remux) or file-style playback of playback.url
|
||||
|
||||
Direct → fallback: when playback.fallback exists and the direct url fails
|
||||
(fatal hls network error, <video> error, or no metadata within 8s) the
|
||||
engine silently reloads the fallback at the same position. Anything that
|
||||
fails after that is reported to onError({ fatal: true }) so the caller can
|
||||
move on to the next source.
|
||||
*/
|
||||
import { resolveUrl } from '../config.js';
|
||||
|
||||
const DIRECT_TIMEOUT_MS = 8000;
|
||||
const STARTUP_TIMEOUT_MS = 12000;
|
||||
const TORRENT_TIMEOUT_MS = 90000;
|
||||
|
||||
let hlsPromise = null;
|
||||
export function loadHls() {
|
||||
if (window.Hls) return Promise.resolve(window.Hls);
|
||||
if (hlsPromise) return hlsPromise;
|
||||
hlsPromise = new Promise((resolve) => {
|
||||
const s = document.createElement('script');
|
||||
s.src = new URL('../../vendor/hls.min.js', import.meta.url).href;
|
||||
s.async = true;
|
||||
s.onload = () => resolve(window.Hls || null);
|
||||
s.onerror = () => {
|
||||
hlsPromise = null;
|
||||
resolve(null);
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
});
|
||||
return hlsPromise;
|
||||
}
|
||||
|
||||
function abs(url) {
|
||||
if (!url) return '';
|
||||
if (/^(https?:|blob:|data:)/i.test(url)) return url;
|
||||
try {
|
||||
return resolveUrl(url);
|
||||
} catch (e) {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function splitUrl(url) {
|
||||
const i = url.indexOf('?');
|
||||
return i < 0 ? [url, ''] : [url.slice(0, i), url.slice(i + 1)];
|
||||
}
|
||||
|
||||
/** url with ?start=<t> set (keeps other params). */
|
||||
export function withStart(url, t) {
|
||||
const [path, qs] = splitUrl(url);
|
||||
const q = new URLSearchParams(qs);
|
||||
if (t > 0) q.set('start', String(Math.floor(t)));
|
||||
else q.delete('start');
|
||||
const s = q.toString();
|
||||
return s ? `${path}?${s}` : path;
|
||||
}
|
||||
|
||||
/** `/v1/remux/<token>?x` → `/v1/remux/<token>/probe?x` */
|
||||
export function probeUrl(url) {
|
||||
const [path, qs] = splitUrl(url);
|
||||
const q = new URLSearchParams(qs);
|
||||
q.delete('start');
|
||||
const s = q.toString();
|
||||
return `${path.replace(/\/+$/, '')}/probe${s ? `?${s}` : ''}`;
|
||||
}
|
||||
|
||||
export function createPlayer(video, handlers = {}) {
|
||||
const h = {
|
||||
onState() {},
|
||||
onError() {},
|
||||
onLevels() {},
|
||||
onAudioTracks() {},
|
||||
onTorrent() {},
|
||||
...handlers,
|
||||
};
|
||||
|
||||
let token = 0;
|
||||
let stream = null;
|
||||
let hls = null;
|
||||
let mode = ''; // hls | native-hls | file | remux
|
||||
let offset = 0;
|
||||
let knownDuration = 0;
|
||||
let mediaUrl = '';
|
||||
let usingFallback = false;
|
||||
let started = false;
|
||||
let wantPlay = true;
|
||||
let pendingTime = null;
|
||||
let timers = [];
|
||||
let subIndex = -1;
|
||||
let subTrackEl = null;
|
||||
const subCache = new Map();
|
||||
let lastTorrent = null;
|
||||
let probeInfo = null; // remux/torrent ffprobe summary
|
||||
let remuxAudio = null; // absolute ffprobe audio index (?audio=)
|
||||
let mediaRetries = 0;
|
||||
let netRetries = 0;
|
||||
|
||||
const emit = (phase, extra) => h.onState({ phase, ...extra });
|
||||
const later = (fn, ms, my) => {
|
||||
const id = setTimeout(() => {
|
||||
if (my === token) fn();
|
||||
}, ms);
|
||||
timers.push(id);
|
||||
return id;
|
||||
};
|
||||
const clearTimers = () => {
|
||||
for (const id of timers) {
|
||||
clearTimeout(id);
|
||||
clearInterval(id);
|
||||
}
|
||||
timers = [];
|
||||
};
|
||||
|
||||
/* ---- teardown -------------------------------------------------------- */
|
||||
|
||||
function teardownMedia() {
|
||||
if (hls) {
|
||||
try {
|
||||
hls.destroy();
|
||||
} catch (e) {
|
||||
/* already gone */
|
||||
}
|
||||
hls = null;
|
||||
}
|
||||
video.removeAttribute('src');
|
||||
try {
|
||||
video.load();
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function removeSubTrack() {
|
||||
if (subTrackEl) subTrackEl.remove();
|
||||
subTrackEl = null;
|
||||
}
|
||||
|
||||
function reset() {
|
||||
token++;
|
||||
clearTimers();
|
||||
teardownMedia();
|
||||
removeSubTrack();
|
||||
mode = '';
|
||||
offset = 0;
|
||||
knownDuration = 0;
|
||||
started = false;
|
||||
pendingTime = null;
|
||||
usingFallback = false;
|
||||
mediaRetries = 0;
|
||||
netRetries = 0;
|
||||
lastTorrent = null;
|
||||
probeInfo = null;
|
||||
remuxAudio = null;
|
||||
}
|
||||
|
||||
/* ---- errors ---------------------------------------------------------- */
|
||||
|
||||
function fail(my, message, code) {
|
||||
if (my !== token) return;
|
||||
// direct url failed before playing → try the server fallback once
|
||||
if (!usingFallback && stream && stream.playback && stream.playback.fallback && (mode === 'hls' || mode === 'file' || mode === 'native-hls')) {
|
||||
const at = pendingTime != null ? pendingTime : currentTime();
|
||||
usingFallback = true;
|
||||
emit('fallback', { message: 'Switching to relay…' });
|
||||
startMedia(stream.playback.fallback, at, /* keepFallbackFlag */ true);
|
||||
return;
|
||||
}
|
||||
clearTimers();
|
||||
h.onError({ fatal: true, message: message || 'Playback failed', code: code || 'error', stream });
|
||||
}
|
||||
|
||||
/* ---- media start ----------------------------------------------------- */
|
||||
|
||||
function armWatchdogs(my) {
|
||||
// a direct url that hasn't produced metadata quickly is treated as failed
|
||||
if (!usingFallback && stream.playback && stream.playback.fallback) {
|
||||
later(() => {
|
||||
if (video.readyState < 1) fail(my, 'Direct source timed out', 'direct-timeout');
|
||||
}, DIRECT_TIMEOUT_MS, my);
|
||||
}
|
||||
later(() => {
|
||||
if (!started && video.readyState < 3 && !(video.paused && video.readyState >= 2)) {
|
||||
fail(my, 'Source stalled while starting', 'stall');
|
||||
}
|
||||
}, STARTUP_TIMEOUT_MS, my);
|
||||
}
|
||||
|
||||
async function startHls(url, startAt, my) {
|
||||
const Hls = await loadHls();
|
||||
if (my !== token) return;
|
||||
const nativeOk = video.canPlayType('application/vnd.apple.mpegurl');
|
||||
if (!Hls || !Hls.isSupported()) {
|
||||
if (nativeOk) {
|
||||
mode = 'native-hls';
|
||||
startFile(url, startAt, my);
|
||||
return;
|
||||
}
|
||||
fail(my, 'HLS is not supported in this browser', 'unsupported');
|
||||
return;
|
||||
}
|
||||
mode = 'hls';
|
||||
const inst = new Hls({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: false,
|
||||
startLevel: -1,
|
||||
capLevelToPlayerSize: true,
|
||||
maxBufferLength: 30,
|
||||
maxMaxBufferLength: 120,
|
||||
backBufferLength: 60,
|
||||
progressive: true,
|
||||
startPosition: startAt > 0 ? startAt : -1,
|
||||
testBandwidth: true,
|
||||
fragLoadPolicy: {
|
||||
default: {
|
||||
maxTimeToFirstByteMs: 10000,
|
||||
maxLoadTimeMs: 120000,
|
||||
timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0 },
|
||||
errorRetry: { maxNumRetry: 3, retryDelayMs: 1000, maxRetryDelayMs: 8000 },
|
||||
},
|
||||
},
|
||||
});
|
||||
hls = inst;
|
||||
const E = Hls.Events;
|
||||
inst.on(E.MANIFEST_PARSED, () => {
|
||||
if (my !== token) return;
|
||||
h.onLevels(levels(), inst.currentLevel);
|
||||
if (wantPlay) tryPlay(my);
|
||||
});
|
||||
inst.on(E.LEVEL_SWITCHED, () => my === token && h.onLevels(levels(), inst.currentLevel));
|
||||
inst.on(E.AUDIO_TRACKS_UPDATED, () => my === token && h.onAudioTracks(audioTracks(), inst.audioTrack));
|
||||
inst.on(E.AUDIO_TRACK_SWITCHED, () => my === token && h.onAudioTracks(audioTracks(), inst.audioTrack));
|
||||
inst.on(E.ERROR, (evt, data) => {
|
||||
if (my !== token || !data.fatal) return;
|
||||
if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
|
||||
mediaRetries++;
|
||||
if (mediaRetries === 1) inst.recoverMediaError();
|
||||
else if (mediaRetries === 2) {
|
||||
inst.swapAudioCodec();
|
||||
inst.recoverMediaError();
|
||||
} else fail(my, `Media error: ${data.details}`, 'media');
|
||||
return;
|
||||
}
|
||||
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
|
||||
// before playback started, a network error on the direct url means CORS/blocked
|
||||
if (!started && !usingFallback && stream.playback.fallback) return fail(my, data.details, 'network');
|
||||
const manifestish = /manifest|level/i.test(data.details || '');
|
||||
if (started && !manifestish && netRetries < 3) {
|
||||
netRetries++;
|
||||
later(() => inst.startLoad(), 1500 * netRetries, my);
|
||||
return;
|
||||
}
|
||||
fail(my, `Network error: ${data.details}`, 'network');
|
||||
return;
|
||||
}
|
||||
fail(my, `Stream error: ${data.details}`, 'other');
|
||||
});
|
||||
inst.loadSource(url);
|
||||
inst.attachMedia(video);
|
||||
}
|
||||
|
||||
function startFile(url, startAt, my) {
|
||||
if (!mode) mode = 'file';
|
||||
video.src = url;
|
||||
if (startAt > 0) {
|
||||
pendingTime = startAt;
|
||||
const seekTo = () => {
|
||||
if (my !== token) return;
|
||||
const d = video.duration;
|
||||
let t = startAt;
|
||||
if (isFinite(d) && d > 0) t = Math.min(t, Math.max(0, d - 5));
|
||||
try {
|
||||
video.currentTime = t;
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
pendingTime = null;
|
||||
};
|
||||
video.addEventListener('loadedmetadata', seekTo, { once: true });
|
||||
}
|
||||
if (wantPlay) tryPlay(my);
|
||||
}
|
||||
|
||||
function startRemux(url, startAt, my) {
|
||||
mode = 'remux';
|
||||
offset = Math.max(0, Math.floor(startAt || 0));
|
||||
if (!knownDuration) {
|
||||
// torrent: /v1/torrent/<token>/probe (sibling of /status); remux: <token>/probe
|
||||
const pb = stream && stream.playback;
|
||||
const probe = pb && pb.kind === 'torrent' && pb.status ? abs(pb.status).replace(/\/status(\?|$)/, '/probe$1') : probeUrl(url);
|
||||
fetch(probe)
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((p) => {
|
||||
if (my !== token || !p) return;
|
||||
if (p.duration > 0) knownDuration = p.duration;
|
||||
probeInfo = p;
|
||||
emit('probe', { probe: p });
|
||||
h.onAudioTracks(audioTracks(), currentAudioTrack());
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
video.src = remuxSrc(offset);
|
||||
syncOffset(offset, my);
|
||||
if (wantPlay) tryPlay(my);
|
||||
}
|
||||
|
||||
function startMedia(url, startAt, keepFallback) {
|
||||
const prevSub = subIndex;
|
||||
const keepFlag = keepFallback ? usingFallback : false;
|
||||
const keptDuration = knownDuration;
|
||||
const prevTorrentMode = mode === 'remux' ? 'remux' : null;
|
||||
clearTimers();
|
||||
teardownMedia();
|
||||
token++;
|
||||
const my = token;
|
||||
usingFallback = keepFlag;
|
||||
started = false;
|
||||
pendingTime = startAt > 0 ? startAt : null;
|
||||
mediaUrl = abs(url);
|
||||
emit('loading', { message: usingFallback ? 'Connecting through relay…' : 'Loading…', fallback: usingFallback });
|
||||
armWatchdogs(my);
|
||||
|
||||
const kind = stream.playback ? stream.playback.kind : 'file';
|
||||
if (kind === 'hls') startHls(mediaUrl, startAt, my);
|
||||
else if (kind === 'remux' || prevTorrentMode === 'remux' || (kind === 'torrent' && lastTorrent && lastTorrent.file && lastTorrent.file.remux)) {
|
||||
knownDuration = keptDuration;
|
||||
startRemux(mediaUrl, startAt, my);
|
||||
} else {
|
||||
mode = 'file';
|
||||
startFile(mediaUrl, startAt, my);
|
||||
}
|
||||
if (prevSub >= 0) setSubtitle(prevSub);
|
||||
}
|
||||
|
||||
function startTorrent(startAt, my) {
|
||||
const statusUrl = abs(stream.playback.status);
|
||||
const began = Date.now();
|
||||
emit('torrent', { message: 'Connecting to peers…', torrent: null });
|
||||
let polling = false;
|
||||
const poll = async () => {
|
||||
if (my !== token || polling) return;
|
||||
polling = true;
|
||||
let st = null;
|
||||
try {
|
||||
const r = await fetch(statusUrl);
|
||||
if (r.ok) st = await r.json();
|
||||
} catch (e) {
|
||||
/* retry next tick */
|
||||
}
|
||||
polling = false;
|
||||
if (my !== token) return;
|
||||
if (st) {
|
||||
lastTorrent = st;
|
||||
h.onTorrent(st);
|
||||
}
|
||||
if (!mode) {
|
||||
if (st && st.ready) {
|
||||
if (st.file && st.file.duration > 0) knownDuration = st.file.duration;
|
||||
else if (st.duration > 0) knownDuration = st.duration;
|
||||
const url = abs(stream.playback.url);
|
||||
mediaUrl = url;
|
||||
emit('loading', { message: 'Buffering…' });
|
||||
armWatchdogs(my);
|
||||
if (st.file && st.file.remux) startRemux(url, startAt, my);
|
||||
else {
|
||||
mode = 'file';
|
||||
startFile(withStart(url, 0), startAt, my);
|
||||
}
|
||||
if (subIndex >= 0) setSubtitle(subIndex);
|
||||
} else {
|
||||
emit('torrent', { message: st && st.peers ? 'Downloading…' : 'Connecting to peers…', torrent: st });
|
||||
if (Date.now() - began > TORRENT_TIMEOUT_MS && !(st && st.peers > 0)) {
|
||||
fail(my, 'No peers for this torrent', 'torrent-timeout');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
poll();
|
||||
let tick = 0;
|
||||
const id = setInterval(() => {
|
||||
// 1s while waiting for the torrent, every 3s once playing (stats only)
|
||||
tick++;
|
||||
if (!mode || tick % 3 === 0) poll();
|
||||
}, 1000);
|
||||
timers.push(id);
|
||||
}
|
||||
|
||||
function tryPlay(my) {
|
||||
const p = video.play();
|
||||
if (p && p.catch) {
|
||||
p.catch((e) => {
|
||||
if (my !== token) return;
|
||||
if (e && e.name === 'NotAllowedError') emit('blocked', { message: 'Press play to start' });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- video events ---------------------------------------------------- */
|
||||
|
||||
const on = (name, fn) => video.addEventListener(name, fn);
|
||||
const listeners = [];
|
||||
const bind = (name, fn) => {
|
||||
on(name, fn);
|
||||
listeners.push([name, fn]);
|
||||
};
|
||||
|
||||
bind('loadedmetadata', () => {
|
||||
if (!stream) return;
|
||||
emit('metadata', { duration: duration() });
|
||||
});
|
||||
bind('playing', () => {
|
||||
if (!stream) return;
|
||||
started = true;
|
||||
emit('playing');
|
||||
});
|
||||
bind('canplay', () => {
|
||||
if (!stream) return;
|
||||
if (video.paused) emit('ready');
|
||||
});
|
||||
bind('waiting', () => stream && emit('buffering', { message: 'Buffering…' }));
|
||||
bind('pause', () => stream && emit('paused'));
|
||||
bind('ended', () => stream && emit('ended'));
|
||||
bind('error', () => {
|
||||
if (!stream || !mode || mode === 'hls') return;
|
||||
const err = video.error;
|
||||
// remux: retry once from the current position before giving up
|
||||
fail(token, err ? `Video error ${err.code}${err.message ? `: ${err.message}` : ''}` : 'Video error', 'video');
|
||||
});
|
||||
|
||||
/* ---- public: load ---------------------------------------------------- */
|
||||
|
||||
function load(s, opts = {}) {
|
||||
reset();
|
||||
stream = s;
|
||||
wantPlay = opts.autoplay !== false;
|
||||
const startAt = Math.max(0, Number(opts.startAt) || 0);
|
||||
const pb = s.playback || { kind: 'file', url: s.url };
|
||||
if (pb.kind === 'torrent') {
|
||||
const my = token;
|
||||
pendingTime = startAt || null;
|
||||
startTorrent(startAt, my);
|
||||
return;
|
||||
}
|
||||
startMedia(pb.url, startAt, false);
|
||||
}
|
||||
|
||||
/* ---- public: transport ----------------------------------------------- */
|
||||
|
||||
function currentTime() {
|
||||
if (pendingTime != null && video.readyState < 1) return pendingTime;
|
||||
const t = video.currentTime || 0;
|
||||
return mode === 'remux' ? offset + t : t;
|
||||
}
|
||||
|
||||
function duration() {
|
||||
if (mode === 'remux') {
|
||||
if (knownDuration > 0) return knownDuration;
|
||||
const d = video.duration;
|
||||
return isFinite(d) && d > 0 ? offset + d : 0;
|
||||
}
|
||||
const d = video.duration;
|
||||
if (isFinite(d) && d > 0) return d;
|
||||
return knownDuration || 0;
|
||||
}
|
||||
|
||||
function buffered() {
|
||||
const out = [];
|
||||
const b = video.buffered;
|
||||
const add = mode === 'remux' ? offset : 0;
|
||||
for (let i = 0; i < b.length; i++) out.push([b.start(i) + add, b.end(i) + add]);
|
||||
return out;
|
||||
}
|
||||
|
||||
function seek(t) {
|
||||
if (!stream || !mode) return;
|
||||
const d = duration();
|
||||
if (d > 0) t = Math.min(t, Math.max(0, d - 1));
|
||||
t = Math.max(0, t);
|
||||
if (mode !== 'remux') {
|
||||
try {
|
||||
video.currentTime = t;
|
||||
} catch (e) {
|
||||
/* not seekable yet */
|
||||
}
|
||||
return;
|
||||
}
|
||||
const rel = t - offset;
|
||||
const b = video.buffered;
|
||||
for (let i = 0; i < b.length; i++) {
|
||||
if (rel >= b.start(i) && rel <= b.end(i) - 0.5) {
|
||||
video.currentTime = rel;
|
||||
return;
|
||||
}
|
||||
}
|
||||
reloadRemux(t);
|
||||
}
|
||||
|
||||
// the remux begins at the keyframe at/before t, not t itself: ask the server which one
|
||||
function syncOffset(t, my) {
|
||||
if (!(t > 0)) return;
|
||||
const pb = stream && stream.playback;
|
||||
const base = pb && pb.kind === 'torrent' && pb.status ? abs(pb.status).replace(/\/status(\?|$)/, '/probe$1') : probeUrl(mediaUrl);
|
||||
fetch(`${base}${base.includes('?') ? '&' : '?'}start=${t}`)
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((p) => {
|
||||
if (my === token && p && Number.isFinite(p.keyframe) && p.keyframe <= t) offset = p.keyframe;
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
function remuxSrc(t) {
|
||||
let u = withStart(mediaUrl, t);
|
||||
if (remuxAudio != null) u += `${u.includes('?') ? '&' : '?'}audio=${remuxAudio}`;
|
||||
return u;
|
||||
}
|
||||
|
||||
// restart the remux at t (seek outside the buffer, or audio track change)
|
||||
function reloadRemux(t) {
|
||||
const my = ++token;
|
||||
clearTimers();
|
||||
const wasPlaying = !video.paused || wantPlay;
|
||||
wantPlay = wasPlaying;
|
||||
offset = Math.floor(t);
|
||||
pendingTime = offset;
|
||||
started = false;
|
||||
emit('seeking', { message: 'Seeking…' });
|
||||
video.src = remuxSrc(offset);
|
||||
syncOffset(offset, my);
|
||||
armWatchdogs(my);
|
||||
if (lastTorrent || (stream.playback && stream.playback.kind === 'torrent')) {
|
||||
// keep torrent stats ticking after a remux seek
|
||||
const statusUrl = abs(stream.playback.status);
|
||||
const id = setInterval(() => {
|
||||
fetch(statusUrl)
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((st) => {
|
||||
if (st && my === token) {
|
||||
lastTorrent = st;
|
||||
h.onTorrent(st);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}, 3000);
|
||||
timers.push(id);
|
||||
}
|
||||
video.addEventListener('loadedmetadata', () => my === token && (pendingTime = null), { once: true });
|
||||
if (wasPlaying) tryPlay(my);
|
||||
}
|
||||
|
||||
function play() {
|
||||
wantPlay = true;
|
||||
tryPlay(token);
|
||||
}
|
||||
function pause() {
|
||||
wantPlay = false;
|
||||
video.pause();
|
||||
}
|
||||
function toggle() {
|
||||
if (video.paused || video.ended) play();
|
||||
else pause();
|
||||
}
|
||||
|
||||
/* ---- public: tracks -------------------------------------------------- */
|
||||
|
||||
function levels() {
|
||||
if (!hls || !hls.levels) return [];
|
||||
return hls.levels.map((l, i) => ({
|
||||
index: i,
|
||||
height: l.height || 0,
|
||||
width: l.width || 0,
|
||||
bitrate: l.bitrate || 0,
|
||||
label: l.height ? `${l.height}p` : l.bitrate ? `${Math.round(l.bitrate / 1000)} kbps` : `Level ${i + 1}`,
|
||||
}));
|
||||
}
|
||||
function setLevel(i) {
|
||||
if (!hls) return;
|
||||
hls.currentLevel = i;
|
||||
hls.loadLevel = i;
|
||||
h.onLevels(levels(), i);
|
||||
}
|
||||
function currentLevel() {
|
||||
if (!hls) return -1;
|
||||
return hls.autoLevelEnabled ? -1 : hls.currentLevel;
|
||||
}
|
||||
function playingLevel() {
|
||||
if (!hls || hls.currentLevel < 0 || !hls.levels) return null;
|
||||
return levels()[hls.currentLevel] || null;
|
||||
}
|
||||
|
||||
function probeAudio() {
|
||||
return mode === 'remux' && probeInfo && Array.isArray(probeInfo.audio) ? probeInfo.audio : [];
|
||||
}
|
||||
function audioTracks() {
|
||||
if (hls && hls.audioTracks) {
|
||||
return hls.audioTracks.map((t, i) => ({ index: i, lang: t.lang || '', label: t.name || t.lang || `Track ${i + 1}` }));
|
||||
}
|
||||
return probeAudio().map((a, i) => ({
|
||||
index: i,
|
||||
lang: a.lang || '',
|
||||
label: a.title || [a.lang ? a.lang.toUpperCase() : `Track ${i + 1}`, a.codec, a.channels ? `${a.channels}ch` : ''].filter(Boolean).join(' · '),
|
||||
}));
|
||||
}
|
||||
function setAudioTrack(i) {
|
||||
if (hls) {
|
||||
hls.audioTrack = i;
|
||||
return;
|
||||
}
|
||||
const list = probeAudio();
|
||||
if (!list[i] || list[i].index === remuxAudio) return;
|
||||
remuxAudio = list[i].index;
|
||||
reloadRemux(currentTime());
|
||||
h.onAudioTracks(audioTracks(), i);
|
||||
}
|
||||
function currentAudioTrack() {
|
||||
if (hls) return hls.audioTrack;
|
||||
const list = probeAudio();
|
||||
if (!list.length) return -1;
|
||||
if (remuxAudio != null) return list.findIndex((a) => a.index === remuxAudio);
|
||||
const def = list.findIndex((a) => a.default);
|
||||
return def >= 0 ? def : 0;
|
||||
}
|
||||
|
||||
function subtitles() {
|
||||
return ((stream && stream.subtitles) || []).map((s, i) => ({
|
||||
index: i,
|
||||
lang: s.lang || s.language || '',
|
||||
label: s.label || s.name || s.lang || `Subtitles ${i + 1}`,
|
||||
url: s.url,
|
||||
}));
|
||||
}
|
||||
|
||||
async function vttBlob(url) {
|
||||
if (subCache.has(url)) return subCache.get(url);
|
||||
const p = fetch(abs(url))
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.text();
|
||||
})
|
||||
.then((text) => {
|
||||
if (!/^\uFEFF?WEBVTT/.test(text)) text = `WEBVTT\n\n${text.replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, '$1.$2')}`;
|
||||
return URL.createObjectURL(new Blob([text], { type: 'text/vtt' }));
|
||||
});
|
||||
subCache.set(url, p);
|
||||
p.catch(() => subCache.delete(url));
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Remux restarts the clock at `offset`; shift cues so they still line up. */
|
||||
function shiftTrack(track) {
|
||||
if (mode !== 'remux' || !offset || !track || !track.cues) return;
|
||||
const my = offset;
|
||||
for (const cue of Array.from(track.cues)) {
|
||||
if (cue._orig == null) {
|
||||
cue._orig = [cue.startTime, cue.endTime];
|
||||
}
|
||||
cue.startTime = cue._orig[0] - my;
|
||||
cue.endTime = cue._orig[1] - my;
|
||||
}
|
||||
}
|
||||
|
||||
async function setSubtitle(i) {
|
||||
subIndex = i;
|
||||
removeSubTrack();
|
||||
for (const t of Array.from(video.textTracks)) t.mode = 'disabled';
|
||||
const list = subtitles();
|
||||
if (i < 0 || !list[i]) return true;
|
||||
const my = token;
|
||||
let url;
|
||||
try {
|
||||
url = await vttBlob(list[i].url);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
if (my !== token || subIndex !== i) return true;
|
||||
const el = document.createElement('track');
|
||||
el.kind = 'subtitles';
|
||||
el.label = list[i].label;
|
||||
if (list[i].lang) el.srclang = list[i].lang;
|
||||
el.src = url;
|
||||
el.default = true;
|
||||
el.addEventListener('load', () => {
|
||||
el.track.mode = 'showing';
|
||||
shiftTrack(el.track);
|
||||
});
|
||||
video.appendChild(el);
|
||||
subTrackEl = el;
|
||||
el.track.mode = 'showing';
|
||||
return true;
|
||||
}
|
||||
|
||||
// re-align subtitle cues after a remux reload
|
||||
bind('loadeddata', () => {
|
||||
if (subTrackEl && subTrackEl.track) shiftTrack(subTrackEl.track);
|
||||
});
|
||||
|
||||
function stop() {
|
||||
reset();
|
||||
stream = null;
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
reset();
|
||||
stream = null;
|
||||
for (const [n, fn] of listeners) video.removeEventListener(n, fn);
|
||||
for (const p of subCache.values()) p.then((u) => URL.revokeObjectURL(u)).catch(() => {});
|
||||
subCache.clear();
|
||||
}
|
||||
|
||||
return {
|
||||
load,
|
||||
stop,
|
||||
play,
|
||||
pause,
|
||||
toggle,
|
||||
seek,
|
||||
currentTime,
|
||||
duration,
|
||||
buffered,
|
||||
levels,
|
||||
setLevel,
|
||||
currentLevel,
|
||||
playingLevel,
|
||||
audioTracks,
|
||||
setAudioTrack,
|
||||
currentAudioTrack,
|
||||
subtitles,
|
||||
setSubtitle,
|
||||
destroy,
|
||||
get stream() {
|
||||
return stream;
|
||||
},
|
||||
get mode() {
|
||||
return mode;
|
||||
},
|
||||
get usingFallback() {
|
||||
return usingFallback;
|
||||
},
|
||||
get torrent() {
|
||||
return lastTorrent;
|
||||
},
|
||||
get started() {
|
||||
return started;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
row.js — horizontal carousel row.
|
||||
|
||||
row({
|
||||
title, moreHref?, variant: 'poster'|'wide'|'logo'|'cast',
|
||||
items?: array, load?: () => Promise<array>, render: (item, i) => Node,
|
||||
lazy = true, skeletons = 8, className?
|
||||
}) → <section class="row"> with .setItems(items) for live refreshes.
|
||||
|
||||
- Loads when it nears the viewport (IntersectionObserver) and shows skeletons meanwhile.
|
||||
- Removes itself (hidden) when it ends up empty or the load fails.
|
||||
- Arrow buttons on pointer devices; scroll-snap + swipe on touch.
|
||||
- Keyboard: ←/→ move focus between cards, Home/End jump to the ends.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import { skeletonCard } from './card.js';
|
||||
import { icon } from './icons.js';
|
||||
|
||||
const io = 'IntersectionObserver' in window
|
||||
? new IntersectionObserver((entries) => {
|
||||
for (const e of entries) {
|
||||
if (e.isIntersecting && e.target._load) {
|
||||
io.unobserve(e.target);
|
||||
e.target._load();
|
||||
}
|
||||
}
|
||||
}, { rootMargin: '600px 0px' })
|
||||
: null;
|
||||
|
||||
export function row(opts) {
|
||||
const variant = opts.variant || 'poster';
|
||||
const track = h('div.row__track', { role: 'list', 'aria-label': opts.title || '' });
|
||||
const prev = h('button.row__arrow.row__arrow--prev', { type: 'button', 'aria-label': 'Scroll left', tabindex: '-1' }, icon('left', { size: 22 }));
|
||||
const next = h('button.row__arrow.row__arrow--next', { type: 'button', 'aria-label': 'Scroll right', tabindex: '-1' }, icon('right', { size: 22 }));
|
||||
const titleEl = opts.title ? h('h2.row__title', opts.title) : null;
|
||||
const header = opts.title || opts.moreHref
|
||||
? h('div.row__head', titleEl, opts.moreHref ? h('a.row__more', { href: opts.moreHref }, 'See all', icon('right', { size: 16 })) : null)
|
||||
: null;
|
||||
const section = h('section.row', { class: [`row--${variant}`, opts.className] }, header, h('div.row__viewport', prev, track, next));
|
||||
|
||||
for (let i = 0; i < (opts.skeletons || (variant === 'wide' ? 5 : 8)); i++) track.appendChild(skeletonCard(variant === 'cast' ? 'cast' : variant));
|
||||
|
||||
function updateArrows() {
|
||||
const max = track.scrollWidth - track.clientWidth - 2;
|
||||
prev.classList.toggle('is-hidden', track.scrollLeft <= 2);
|
||||
next.classList.toggle('is-hidden', track.scrollLeft >= max);
|
||||
}
|
||||
|
||||
function scrollByPage(dir) {
|
||||
const amount = Math.max(track.clientWidth * 0.85, 200);
|
||||
track.scrollBy({ left: dir * amount, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
prev.addEventListener('click', () => scrollByPage(-1));
|
||||
next.addEventListener('click', () => scrollByPage(1));
|
||||
track.addEventListener('scroll', updateArrows, { passive: true });
|
||||
if ('ResizeObserver' in window) new ResizeObserver(updateArrows).observe(track);
|
||||
|
||||
track.addEventListener('keydown', (e) => {
|
||||
const links = [...track.querySelectorAll(':scope > .card > .card__link, :scope > .card > [data-focus]')];
|
||||
const i = links.indexOf(document.activeElement);
|
||||
if (i < 0) return;
|
||||
let j = -1;
|
||||
if (e.key === 'ArrowRight') j = Math.min(links.length - 1, i + 1);
|
||||
else if (e.key === 'ArrowLeft') j = Math.max(0, i - 1);
|
||||
else if (e.key === 'Home') j = 0;
|
||||
else if (e.key === 'End') j = links.length - 1;
|
||||
if (j < 0) return;
|
||||
e.preventDefault();
|
||||
links[j].focus({ preventScroll: true });
|
||||
links[j].scrollIntoView({ inline: 'nearest', block: 'nearest', behavior: 'smooth' });
|
||||
});
|
||||
|
||||
section.setItems = (items) => {
|
||||
const list = (items || []).filter(Boolean);
|
||||
if (!list.length) {
|
||||
section.hidden = true;
|
||||
track.replaceChildren();
|
||||
return;
|
||||
}
|
||||
section.hidden = false;
|
||||
track.replaceChildren(...list.map((it, i) => opts.render(it, i)).filter(Boolean));
|
||||
section.classList.add('is-loaded');
|
||||
requestAnimationFrame(updateArrows);
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
const items = opts.items || (opts.load ? await opts.load() : []);
|
||||
section.setItems(items);
|
||||
} catch (e) {
|
||||
console.warn(`row "${opts.title}" failed:`, e);
|
||||
section.hidden = true;
|
||||
}
|
||||
};
|
||||
|
||||
if (opts.items && opts.lazy !== true) {
|
||||
section.setItems(opts.items);
|
||||
} else if (io && opts.lazy !== false) {
|
||||
section._load = load;
|
||||
io.observe(section);
|
||||
} else {
|
||||
load();
|
||||
}
|
||||
return section;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
toast.js — transient notifications. toast(message, { error, timeout, action: { label, onClick } })
|
||||
Also exposed as window.bugtv.toast for non-module callers.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
|
||||
let stack = null;
|
||||
|
||||
function ensureStack() {
|
||||
if (stack && document.body.contains(stack)) return stack;
|
||||
stack = document.getElementById('toasts') || h('div#toasts.toasts', { role: 'status', 'aria-live': 'polite' });
|
||||
if (!stack.isConnected) document.body.appendChild(stack);
|
||||
return stack;
|
||||
}
|
||||
|
||||
export function toast(message, opts = {}) {
|
||||
const el = h('div.toast', { class: opts.error ? 'toast--error' : null },
|
||||
h('span.toast__msg', String(message)),
|
||||
opts.action ? h('button.toast__action', { type: 'button', onclick: () => { opts.action.onClick(); dismiss(); } }, opts.action.label) : null);
|
||||
ensureStack().appendChild(el);
|
||||
requestAnimationFrame(() => el.classList.add('is-shown'));
|
||||
let done = false;
|
||||
function dismiss() {
|
||||
if (done) return;
|
||||
done = true;
|
||||
el.classList.remove('is-shown');
|
||||
setTimeout(() => el.remove(), 300);
|
||||
}
|
||||
setTimeout(dismiss, opts.timeout || (opts.error ? 6000 : 3500));
|
||||
return dismiss;
|
||||
}
|
||||
|
||||
export function errorToast(err, fallback) {
|
||||
return toast(err && err.message ? err.message : fallback || 'Something went wrong', { error: true });
|
||||
}
|
||||
Reference in new issue
Block a user