push
This commit is contained in:
1 parent
bcf05e8063
commit
f37985b4c8
109 files changed
+22810
-6143
No files matched your search
@@ -0,0 +1,91 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<meta name="theme-color" content="#09090b">
|
||||
<meta name="description" content="bug tv — stream movies and series.">
|
||||
<!-- API base default; replaced at build time (empty → https://api-tv.bug.tools). -->
|
||||
<meta name="bug-tv-api" content="">
|
||||
<!-- Path the site is served under (history routing); "/" for a domain root. -->
|
||||
<meta name="bug-tv-root" content="/">
|
||||
<title>bug tv</title>
|
||||
<script>
|
||||
/* Router mode + <base> so assets resolve from deep links (/title/tv/1399) and file://. */
|
||||
(function () {
|
||||
var l = location;
|
||||
var m = document.querySelector('meta[name="bug-tv-root"]');
|
||||
var root = m && m.content && !/^@.*@$/.test(m.content) ? m.content : '/';
|
||||
if (root.slice(-1) !== '/') root += '/';
|
||||
var fileish = l.protocol === 'file:' || /\.html?$/i.test(l.pathname);
|
||||
var hash = fileish || /^#\//.test(l.hash);
|
||||
var base = document.createElement('base');
|
||||
base.href = fileish ? l.href.split('#')[0] : l.origin + root;
|
||||
document.head.appendChild(base);
|
||||
window.__BUGTV_ROUTER = { mode: hash ? 'hash' : 'history', root: root };
|
||||
})();
|
||||
</script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="preconnect" href="https://image.tmdb.org">
|
||||
<link rel="preconnect" href="https://api.themoviedb.org">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
|
||||
<link rel="icon" type="image/svg+xml" href="img/bug.svg">
|
||||
<link rel="stylesheet" href="css/tokens.css">
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<link rel="stylesheet" href="css/components.css">
|
||||
<link rel="stylesheet" href="css/pages.css">
|
||||
<link rel="stylesheet" href="css/player.css">
|
||||
<link rel="modulepreload" href="js/router.js">
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#app">Skip to content</a>
|
||||
|
||||
<header class="site-header is-over-hero">
|
||||
<div class="site-header__inner container">
|
||||
<a class="brand" data-href="/" aria-label="bug tv home">
|
||||
<img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span>
|
||||
</a>
|
||||
<nav class="site-nav" aria-label="Primary">
|
||||
<a class="site-nav__link" data-nav data-href="/">Home</a>
|
||||
<a class="site-nav__link" data-nav data-href="/movies">Movies</a>
|
||||
<a class="site-nav__link" data-nav data-href="/tv">Series</a>
|
||||
<a class="site-nav__link" data-nav data-href="/list">My List</a>
|
||||
</nav>
|
||||
<div class="site-header__actions">
|
||||
<form class="header-search" role="search">
|
||||
<button class="header-search__icon" type="button" tabindex="-1" aria-hidden="true"><span data-icon="search"></span></button>
|
||||
<input type="search" name="q" placeholder="Search titles" autocomplete="off" spellcheck="false" aria-label="Search movies and series">
|
||||
<kbd class="header-search__kbd" aria-hidden="true">/</kbd>
|
||||
</form>
|
||||
<a class="icon-btn header-search-link" data-nav data-href="/search" aria-label="Search" title="Search"><span data-icon="search"></span></a>
|
||||
<a class="icon-btn" data-nav data-href="/settings" aria-label="Settings" title="Settings"><span data-icon="settings"></span></a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="app" class="app" aria-live="polite"></main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="container site-footer__inner">
|
||||
<span class="brand brand--sm"><img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span></span>
|
||||
<span class="site-footer__note">bug tv doesn't host files — it links to third-party sources. Metadata by TMDB.</span>
|
||||
<span class="site-footer__api">api · <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<nav class="tabbar" aria-label="Primary">
|
||||
<a class="tabbar__link" data-nav data-href="/"><span data-icon="home" data-size="22"></span><span>Home</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/movies"><span data-icon="film" data-size="22"></span><span>Movies</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/tv"><span data-icon="tv" data-size="22"></span><span>Series</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/search"><span data-icon="search" data-size="22"></span><span>Search</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/list"><span data-icon="bookmark" data-size="22"></span><span>My List</span></a>
|
||||
</nav>
|
||||
|
||||
<div id="toasts" class="toasts" role="status" aria-live="polite"></div>
|
||||
|
||||
<noscript><p style="padding:2rem;color:#fff">bug tv needs JavaScript.</p></noscript>
|
||||
<script type="module" src="js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+160
-149
@@ -1,196 +1,207 @@
|
||||
/*
|
||||
BASE — reset, typography, page frame (header/footer/container).
|
||||
Layout-level stuff only; reusable widgets live in components.css.
|
||||
base.css — reset, typography, layout shell (header, footer, tab bar), utilities.
|
||||
*/
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
|
||||
html {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
text-size-adjust: 100%;
|
||||
scrollbar-color: var(--surface-3) var(--bg);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
html.has-modal { overflow: hidden; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--text-md);
|
||||
line-height: var(--leading-normal);
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: var(--font);
|
||||
font-size: var(--fs-base);
|
||||
line-height: var(--lh);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
overflow-x: hidden;
|
||||
padding-bottom: var(--tabbar-h);
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
display: block;
|
||||
}
|
||||
img, svg, video, iframe { display: block; max-width: 100%; }
|
||||
img { color: transparent; }
|
||||
h1, h2, h3, h4, p { margin: 0; }
|
||||
h1, h2, h3 { line-height: var(--lh-tight); letter-spacing: -0.01em; }
|
||||
a { color: inherit; text-decoration: none; }
|
||||
button, input, select, textarea { font: inherit; color: inherit; }
|
||||
button { cursor: pointer; background: none; border: 0; padding: 0; }
|
||||
[hidden] { display: none !important; }
|
||||
::selection { background: var(--accent); color: var(--accent-ink); }
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
:focus { outline: none; }
|
||||
:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; border-radius: var(--r-sm); }
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
.sr-only {
|
||||
position: absolute !important;
|
||||
width: 1px; height: 1px;
|
||||
padding: 0; margin: -1px;
|
||||
overflow: hidden; clip: rect(0 0 0 0);
|
||||
white-space: nowrap; border: 0;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
margin: 0;
|
||||
line-height: var(--leading-tight);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 1px var(--space-1);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-surface-2);
|
||||
border: 1px solid var(--color-border);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* ---- page frame ---------------------------------------------------------- */
|
||||
|
||||
.container {
|
||||
max-width: var(--container-max);
|
||||
margin: 0 auto;
|
||||
padding-left: var(--container-pad);
|
||||
padding-right: var(--container-pad);
|
||||
width: 100%;
|
||||
padding-inline: var(--gutter);
|
||||
}
|
||||
|
||||
.page {
|
||||
padding-top: var(--space-5);
|
||||
padding-bottom: var(--space-8);
|
||||
.muted { color: var(--text-3); }
|
||||
.center { text-align: center; }
|
||||
|
||||
.skip-link {
|
||||
position: fixed; top: 8px; left: 8px; z-index: 200;
|
||||
padding: 10px 16px; border-radius: var(--r-md);
|
||||
background: var(--accent); color: var(--accent-ink); font-weight: var(--fw-bold);
|
||||
transform: translateY(-150%);
|
||||
transition: transform var(--dur) var(--ease);
|
||||
}
|
||||
.skip-link:focus { transform: none; }
|
||||
|
||||
/* ---- header ---------------------------------------------------------------- */
|
||||
.app { min-height: calc(100vh - 120px); }
|
||||
.app:focus { outline: none; }
|
||||
|
||||
/* ---- header ------------------------------------------------------------------- */
|
||||
.site-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 50;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
background: var(--color-bg);
|
||||
background: color-mix(in srgb, var(--color-bg) 85%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
position: fixed; inset: 0 0 auto 0; z-index: var(--z-header);
|
||||
height: var(--header-h);
|
||||
background: var(--overlay);
|
||||
background-origin: border-box;
|
||||
-webkit-backdrop-filter: saturate(160%) blur(18px);
|
||||
backdrop-filter: saturate(160%) blur(18px);
|
||||
border-bottom: 1px solid var(--border);
|
||||
transition: background var(--dur) var(--ease), border-color var(--dur) var(--ease), backdrop-filter var(--dur) var(--ease);
|
||||
}
|
||||
.site-header.is-over-hero:not(.is-solid) {
|
||||
background: linear-gradient(180deg, rgba(0, 0, 0, 0.72) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%);
|
||||
-webkit-backdrop-filter: none;
|
||||
backdrop-filter: none;
|
||||
border-bottom-color: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.site-header__inner {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto 1fr;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
height: var(--header-height);
|
||||
height: 100%;
|
||||
display: flex; align-items: center; gap: var(--sp-7);
|
||||
}
|
||||
|
||||
.brand {
|
||||
font-size: var(--text-xl);
|
||||
font-weight: var(--font-weight-bold);
|
||||
letter-spacing: -0.02em;
|
||||
display: inline-flex; align-items: center; gap: 10px;
|
||||
font-weight: var(--fw-heavy); font-size: 1.3rem; letter-spacing: -0.03em;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.brand__mark {
|
||||
display: block; width: 32px; height: 32px;
|
||||
filter: drop-shadow(0 2px 10px var(--accent-glow));
|
||||
}
|
||||
.brand__word span { color: var(--accent); }
|
||||
.brand--sm { font-size: 1rem; }
|
||||
.brand--sm .brand__mark { width: 24px; height: 24px; filter: none; }
|
||||
|
||||
.site-nav { display: flex; gap: var(--sp-2); }
|
||||
.site-nav__link {
|
||||
position: relative;
|
||||
padding: 8px 12px; border-radius: var(--r-md);
|
||||
color: var(--text-2); font-weight: var(--fw-semi); font-size: 0.95rem;
|
||||
transition: color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease);
|
||||
}
|
||||
.site-nav__link:hover { color: var(--text); }
|
||||
.site-nav__link.is-active { color: var(--text); }
|
||||
.site-nav__link.is-active::after {
|
||||
content: ""; position: absolute; left: 50%; bottom: 0;
|
||||
width: 18px; height: 3px; border-radius: 3px; background: var(--accent);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.brand span {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
.site-header__actions { margin-left: auto; display: flex; align-items: center; gap: var(--sp-2); }
|
||||
|
||||
.site-header__nav {
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
.header-search {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
width: 260px; height: 42px; padding: 0 10px 0 12px;
|
||||
border-radius: var(--r-pill);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border: 1px solid var(--glass-border);
|
||||
transition: width var(--dur) var(--ease), background var(--dur) var(--ease), border-color var(--dur) var(--ease);
|
||||
}
|
||||
|
||||
.site-header__nav a {
|
||||
padding: var(--space-2) var(--space-4);
|
||||
border-radius: var(--radius-full);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--color-text-dim);
|
||||
transition: background 120ms ease, color 120ms ease;
|
||||
.header-search:focus-within { width: 320px; background: rgba(0, 0, 0, 0.55); border-color: rgba(255, 255, 255, 0.4); }
|
||||
.header-search__icon { color: var(--text-2); display: grid; place-items: center; }
|
||||
.header-search input {
|
||||
flex: 1; min-width: 0; height: 100%;
|
||||
background: none; border: 0; outline: none;
|
||||
font-size: var(--fs-sm); font-weight: var(--fw-medium);
|
||||
}
|
||||
|
||||
.site-header__nav a:hover {
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
.header-search input::placeholder { color: var(--text-3); }
|
||||
.header-search input::-webkit-search-cancel-button { filter: invert(1) opacity(0.5); }
|
||||
.header-search__kbd {
|
||||
font-family: var(--font-mono); font-size: var(--fs-2xs); color: var(--text-3);
|
||||
border: 1px solid var(--border-strong); border-radius: 5px; padding: 1px 6px;
|
||||
}
|
||||
|
||||
.site-header__nav a.is-active {
|
||||
color: var(--color-accent-text);
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
.site-header__actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
/* ---- icon buttons ----------------------------------------------------------- */
|
||||
.header-search:focus-within .header-search__kbd { display: none; }
|
||||
.header-search-link { display: none !important; }
|
||||
|
||||
.icon-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border: none;
|
||||
border-radius: var(--radius-full);
|
||||
background: transparent;
|
||||
color: var(--color-text-dim);
|
||||
cursor: pointer;
|
||||
transition: background 120ms ease, color 120ms ease;
|
||||
display: inline-grid; place-items: center;
|
||||
width: 42px; height: 42px; border-radius: var(--r-pill);
|
||||
color: var(--text-2);
|
||||
transition: color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease);
|
||||
}
|
||||
.icon-btn:hover, .icon-btn.is-active { color: var(--text); background: var(--glass); }
|
||||
|
||||
.icon-btn:hover {
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.icon-btn.is-active {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
|
||||
.icon-btn svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
/* ---- footer ------------------------------------------------------------------ */
|
||||
|
||||
/* ---- footer ------------------------------------------------------------------- */
|
||||
.site-footer {
|
||||
border-top: 1px solid var(--color-border);
|
||||
padding: var(--space-4) 0 var(--space-5);
|
||||
color: var(--color-text-faint);
|
||||
font-size: var(--text-xs);
|
||||
margin-top: var(--sp-10);
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--text-3); font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.site-footer .container {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
.site-footer__inner {
|
||||
display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-7);
|
||||
padding-block: var(--sp-7);
|
||||
}
|
||||
.site-footer__note { flex: 1; min-width: 220px; }
|
||||
.site-footer a { color: var(--text-2); }
|
||||
.site-footer a:hover { color: var(--accent); }
|
||||
|
||||
.site-footer a {
|
||||
color: var(--color-text-dim);
|
||||
/* ---- mobile tab bar ------------------------------------------------------------- */
|
||||
.tabbar { display: none; }
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.site-header__inner { gap: var(--sp-5); }
|
||||
.site-nav__link { padding-inline: 8px; }
|
||||
.header-search, .header-search:focus-within { width: 200px; }
|
||||
}
|
||||
|
||||
.site-footer a:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* ---- responsive ---------------------------------------------------------------- */
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.site-header__nav a {
|
||||
padding: var(--space-2) var(--space-3);
|
||||
.site-nav, .header-search { display: none; }
|
||||
.header-search-link { display: inline-grid !important; }
|
||||
.site-header__actions { gap: 0; }
|
||||
.brand { font-size: 1.15rem; }
|
||||
.brand__mark { width: 28px; height: 28px; }
|
||||
.tabbar {
|
||||
position: fixed; inset: auto 0 0 0; z-index: var(--z-tabbar);
|
||||
display: grid; grid-template-columns: repeat(5, 1fr);
|
||||
height: var(--tabbar-h);
|
||||
padding-bottom: env(safe-area-inset-bottom, 0px);
|
||||
background: rgba(12, 12, 15, 0.92);
|
||||
-webkit-backdrop-filter: blur(18px);
|
||||
backdrop-filter: blur(18px);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.tabbar__link {
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
|
||||
color: var(--text-3); font-size: var(--fs-2xs); font-weight: var(--fw-semi);
|
||||
}
|
||||
.tabbar__link.is-active { color: var(--text); }
|
||||
.tabbar__link.is-active .icon { color: var(--accent); }
|
||||
.site-footer { margin-top: var(--sp-8); }
|
||||
}
|
||||
|
||||
/* the player takes over the screen; it renders its own chrome */
|
||||
body[data-route="watch"] .site-header,
|
||||
body[data-route="watch"] .site-footer,
|
||||
body[data-route="watch"] .tabbar { display: none; }
|
||||
body[data-route="watch"] { padding-bottom: 0; }
|
||||
+420
-716
File diff suppressed because it is too large.
Load diff
+179
-763
@@ -1,782 +1,198 @@
|
||||
/*
|
||||
PAGES — page-specific layout: home, search, watch.
|
||||
Widget styling lives in components.css; this file only positions
|
||||
page-level blocks and handles responsive behavior.
|
||||
*/
|
||||
pages.css — page-level layout: home, title, search, list/browse, settings.
|
||||
*/
|
||||
.page--padded { padding-top: calc(var(--header-h) + clamp(20px, 3vw, 40px)); }
|
||||
.page--center { min-height: 70vh; display: grid; place-items: center; padding-top: var(--header-h); }
|
||||
.page__head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: clamp(20px, 2.5vw, 32px); }
|
||||
.page__title { font-size: var(--fs-2xl); font-weight: var(--fw-heavy); letter-spacing: -0.03em; }
|
||||
.page__eyebrow { color: var(--accent); font-size: var(--fs-xs); font-weight: var(--fw-heavy); letter-spacing: 0.1em; text-transform: uppercase; margin-bottom: 6px; }
|
||||
.section { margin-top: clamp(28px, 3.5vw, 48px); }
|
||||
.section__head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; margin-bottom: 18px; }
|
||||
.section__title { font-size: clamp(1.1rem, 0.95rem + 0.6vw, 1.45rem); font-weight: var(--fw-heavy); letter-spacing: -0.02em; }
|
||||
|
||||
/* ---- home: hero carousel ------------------------------------------------------ */
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
height: clamp(440px, 72vh, 640px);
|
||||
margin: calc(-1 * var(--space-5)) 0 var(--space-6);
|
||||
overflow: hidden;
|
||||
background: var(--color-surface);
|
||||
/* ---- home ---------------------------------------------------------------------------- */
|
||||
.hero-slot { min-height: clamp(560px, 88vh, 920px); }
|
||||
.hero-slot > .hero--empty { height: var(--header-h); }
|
||||
.rows { position: relative; z-index: 2; margin-top: clamp(-120px, -9vh, -60px); }
|
||||
.rows > .row:first-child { margin-top: 0; }
|
||||
@media (max-width: 720px) {
|
||||
.hero-slot { min-height: max(560px, 82svh); }
|
||||
.rows { margin-top: -24px; }
|
||||
}
|
||||
|
||||
.hero__slides,
|
||||
.hero__slide {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
/* ---- title page -------------------------------------------------------------------------- */
|
||||
.title-hero {
|
||||
position: relative; overflow: hidden;
|
||||
min-height: clamp(540px, 82vh, 860px);
|
||||
display: flex; align-items: flex-end;
|
||||
}
|
||||
|
||||
.hero__slide {
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 600ms ease, visibility 0s linear 600ms;
|
||||
}
|
||||
|
||||
.hero__slide.is-active {
|
||||
z-index: 1;
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transition: opacity 600ms ease;
|
||||
}
|
||||
|
||||
.hero__backdrop {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transform: scale(1.04);
|
||||
transition: transform 8s ease;
|
||||
}
|
||||
|
||||
.hero__slide.is-active .hero__backdrop {
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
.hero__scrim {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
.title-hero .hero__media { position: absolute; inset: 0; }
|
||||
.title-hero .hero__img { opacity: 1; object-position: center 25%; }
|
||||
.title-hero .hero__scrim {
|
||||
background:
|
||||
linear-gradient(90deg, rgba(0, 0, 0, 0.84) 0%, rgba(0, 0, 0, 0.58) 45%, rgba(0, 0, 0, 0.22) 75%, rgba(0, 0, 0, 0.05) 100%),
|
||||
linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.18) 45%, rgba(0, 0, 0, 0.05) 100%);
|
||||
linear-gradient(90deg, rgba(9, 9, 11, 0.92) 0%, rgba(9, 9, 11, 0.6) 32%, transparent 68%),
|
||||
linear-gradient(0deg, var(--bg) 0%, rgba(9, 9, 11, 0.55) 26%, transparent 55%),
|
||||
linear-gradient(180deg, rgba(9, 9, 11, 0.6) 0%, transparent 24%);
|
||||
}
|
||||
.title-hero__content {
|
||||
position: relative; z-index: 2;
|
||||
display: flex; flex-direction: column; align-items: flex-start; gap: 16px;
|
||||
padding-top: calc(var(--header-h) + 40px); padding-bottom: clamp(28px, 4vw, 56px);
|
||||
max-width: calc(min(760px, 64vw) + var(--gutter) * 2);
|
||||
animation: rise var(--dur-slow) var(--ease) both;
|
||||
}
|
||||
.title-hero--loading { background: linear-gradient(180deg, var(--surface) 0%, var(--bg) 100%); }
|
||||
.title-hero__title { font-size: var(--fs-hero); font-weight: var(--fw-heavy); letter-spacing: -0.035em; line-height: 1.02; text-wrap: balance; text-shadow: 0 2px 30px rgba(0, 0, 0, 0.5); }
|
||||
.title-hero__tagline { color: var(--text-2); font-style: italic; font-size: var(--fs-md); }
|
||||
@keyframes rise { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } }
|
||||
|
||||
.story { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(260px, 1fr); gap: clamp(24px, 4vw, 72px); }
|
||||
.story__text { margin-top: 12px; color: var(--text-2); font-size: 1rem; line-height: 1.7; max-width: 80ch; }
|
||||
.facts { margin: 0; display: grid; gap: 12px; align-content: start; padding: 20px 22px; border-radius: var(--r-lg); background: var(--surface); border: 1px solid var(--border); }
|
||||
.facts__row { display: grid; grid-template-columns: 110px 1fr; gap: 12px; font-size: var(--fs-sm); }
|
||||
.facts dt { color: var(--text-3); font-weight: var(--fw-semi); }
|
||||
.facts dd { margin: 0; color: var(--text); font-weight: var(--fw-semi); }
|
||||
.container-row { margin-top: clamp(20px, 3vw, 40px); }
|
||||
|
||||
/* cast */
|
||||
.cast {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 8px 12px 8px 8px; border-radius: var(--r-pill);
|
||||
transition: background var(--dur-fast);
|
||||
}
|
||||
.cast:hover, .cast:focus-visible { background: var(--surface-2); }
|
||||
.cast:focus-visible { outline: none; box-shadow: var(--ring); }
|
||||
.cast__avatar {
|
||||
flex-shrink: 0; width: 56px; height: 56px; border-radius: 50%; overflow: hidden;
|
||||
background: var(--surface-3); display: grid; place-items: center;
|
||||
box-shadow: 0 0 0 2px var(--border);
|
||||
}
|
||||
.cast__img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.cast__initials { font-weight: var(--fw-heavy); color: var(--text-2); }
|
||||
.cast__text { min-width: 0; }
|
||||
.cast__name { font-size: var(--fs-sm); font-weight: var(--fw-bold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.cast__role { font-size: var(--fs-xs); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* episodes */
|
||||
.episodes .section__head { border-bottom: 1px solid var(--border); padding-bottom: 0; align-items: flex-end; }
|
||||
.episodes .section__head .tabs { border-bottom: 0; order: -1; flex-basis: 100%; }
|
||||
.episodes .section__head .section__title { padding-bottom: 12px; font-size: var(--fs-md); color: var(--text-2); }
|
||||
.episodes .section__head .select-wrap { margin-bottom: 12px; }
|
||||
.episodes__grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(290px, 100%), 1fr)); gap: 28px 18px; }
|
||||
.card--episode .card__media { aspect-ratio: 16 / 9; }
|
||||
.ep__num {
|
||||
position: absolute; left: 10px; bottom: 10px; z-index: 1;
|
||||
padding: 2px 8px; border-radius: var(--r-xs);
|
||||
background: rgba(0, 0, 0, 0.65); font-size: var(--fs-xs); font-weight: var(--fw-heavy);
|
||||
}
|
||||
.card--episode .card__progress { left: 0; right: 0; bottom: 0; border-radius: 0; height: 4px; }
|
||||
.card--episode .card__shade { opacity: 0.6; }
|
||||
.ep__body { padding: 12px 2px 0; }
|
||||
.ep__title { font-weight: var(--fw-bold); font-size: 0.98rem; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.ep__meta { margin-top: 3px; font-size: var(--fs-xs); color: var(--text-3); font-weight: var(--fw-semi); }
|
||||
.ep__overview {
|
||||
margin-top: 6px; font-size: var(--fs-sm); color: var(--text-2); line-height: 1.5;
|
||||
display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
|
||||
}
|
||||
.card--episode.is-future { opacity: 0.55; }
|
||||
.card--episode.is-watched .ep__meta { color: var(--accent); }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.story { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.title-hero { min-height: auto; padding-top: 52vw; }
|
||||
.title-hero .hero__media { bottom: auto; height: 78vw; }
|
||||
.title-hero .hero__img { object-position: center; }
|
||||
.title-hero .hero__scrim {
|
||||
background: linear-gradient(0deg, var(--bg) 0%, var(--bg) calc(100% - 78vw), rgba(9, 9, 11, 0.4) calc(100% - 30vw), rgba(9, 9, 11, 0.35) 100%);
|
||||
}
|
||||
.title-hero__content { max-width: none; padding-top: 0; gap: 12px; }
|
||||
.title-hero__title { font-size: 2.2rem; }
|
||||
.title-hero .hero__logo { max-height: 90px; max-width: 75%; }
|
||||
.title-hero .hero__actions { width: 100%; }
|
||||
.title-hero .hero__actions .btn--primary { flex-basis: 100%; }
|
||||
.title-hero .hero__actions .btn--glass:not(.btn--icon) { flex: 1; }
|
||||
.title-hero .hero__actions .btn--lg { height: 46px; padding: 0 16px; font-size: 0.95rem; }
|
||||
.title-hero .hero__actions .btn--lg.btn--icon { width: 46px; padding: 0; }
|
||||
.facts__row { grid-template-columns: 96px 1fr; }
|
||||
.card--episode .card__link { display: grid; grid-template-columns: 42% minmax(0, 1fr); gap: 12px; align-items: start; }
|
||||
.card--episode .ep__body { padding: 0; }
|
||||
.card--episode .ep__overview { -webkit-line-clamp: 3; line-clamp: 3; font-size: var(--fs-xs); }
|
||||
.card--episode.card--skeleton { display: grid; grid-template-columns: 42% minmax(0, 1fr); gap: 12px; }
|
||||
.episodes__grid { gap: 16px; }
|
||||
}
|
||||
|
||||
.hero__fade {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: 34%;
|
||||
background: linear-gradient(to top, var(--color-bg) 2%, color-mix(in srgb, var(--color-bg) 72%, transparent) 58%, transparent 100%);
|
||||
pointer-events: none;
|
||||
/* ---- search ----------------------------------------------------------------------------- */
|
||||
.search-field {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
height: 60px; padding: 0 20px; margin-bottom: clamp(24px, 3vw, 40px);
|
||||
border-radius: var(--r-lg); background: var(--surface); border: 1px solid var(--border-strong);
|
||||
color: var(--text-3);
|
||||
transition: border-color var(--dur-fast), box-shadow var(--dur-fast);
|
||||
}
|
||||
.search-field:focus-within { border-color: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft); color: var(--text); }
|
||||
.search-field__input { flex: 1; min-width: 0; height: 100%; border: 0; background: none; outline: none; font-size: 1.15rem; font-weight: var(--fw-semi); color: var(--text); }
|
||||
.search-field__input::placeholder { color: var(--text-3); }
|
||||
.search-field__input::-webkit-search-cancel-button { filter: invert(1) opacity(0.5); }
|
||||
.page--padded > .page__title { font-size: var(--fs-lg); margin-bottom: 20px; }
|
||||
@media (max-width: 720px) { .search-field { height: 52px; } .search-field__input { font-size: 1rem; } }
|
||||
|
||||
.hero__inner {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
max-width: var(--container-max);
|
||||
padding: 0 var(--container-pad);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
}
|
||||
.load-more { height: 1px; }
|
||||
|
||||
.hero__content {
|
||||
max-width: 620px;
|
||||
padding-bottom: clamp(72px, 12vh, 112px);
|
||||
}
|
||||
|
||||
.hero__kicker {
|
||||
display: inline-block;
|
||||
margin-bottom: var(--space-3);
|
||||
padding: 4px 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
backdrop-filter: blur(8px);
|
||||
color: rgba(255, 255, 255, 0.78);
|
||||
font-size: var(--text-xs);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.hero__logo {
|
||||
max-width: min(420px, 60vw);
|
||||
max-height: 140px;
|
||||
object-fit: contain;
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.hero__title {
|
||||
font-size: clamp(2.2rem, 5vw, 3.6rem);
|
||||
line-height: 1.05;
|
||||
letter-spacing: -0.03em;
|
||||
text-shadow: 0 2px 24px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.hero__meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: var(--space-4);
|
||||
color: rgba(255, 255, 255, 0.78);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.hero__rating {
|
||||
color: var(--color-star);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.hero__dot {
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
.hero__meta .badge {
|
||||
border-color: rgba(255, 255, 255, 0.18);
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.88);
|
||||
}
|
||||
|
||||
.hero__overview {
|
||||
max-width: 58ch;
|
||||
margin-top: var(--space-4);
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: var(--text-sm);
|
||||
line-height: 1.6;
|
||||
text-shadow: 0 1px 12px rgba(0, 0, 0, 0.35);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.hero__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
margin-top: var(--space-5);
|
||||
}
|
||||
|
||||
.hero__play {
|
||||
padding: 10px 24px;
|
||||
font-size: var(--text-md);
|
||||
}
|
||||
|
||||
.hero__play svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.hero__arrow {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border: none;
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(10, 10, 10, 0.42);
|
||||
color: #fff;
|
||||
backdrop-filter: blur(8px);
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: opacity 160ms ease, background 120ms ease;
|
||||
}
|
||||
|
||||
.hero:hover .hero__arrow,
|
||||
.hero__arrow:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.hero__arrow:hover {
|
||||
background: rgba(10, 10, 10, 0.65);
|
||||
}
|
||||
|
||||
.hero__arrow svg {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
.hero__arrow--prev {
|
||||
left: 20px;
|
||||
}
|
||||
|
||||
.hero__arrow--next {
|
||||
right: 20px;
|
||||
}
|
||||
|
||||
.hero__dots {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
bottom: var(--space-5);
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.hero__dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(255, 255, 255, 0.32);
|
||||
cursor: pointer;
|
||||
transition: width 160ms ease, background 160ms ease;
|
||||
}
|
||||
|
||||
.hero__dot.is-active {
|
||||
width: 24px;
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
/* ---- search ------------------------------------------------------------------ */
|
||||
|
||||
.search-bar {
|
||||
margin-bottom: var(--space-5);
|
||||
}
|
||||
|
||||
.search-bar__form {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.search-bar__input {
|
||||
flex: 1;
|
||||
font-size: var(--text-md);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
}
|
||||
|
||||
.search-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.search-count {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
/* ---- watch: player (.player-wrap + controls live in components.css) ------------- */
|
||||
|
||||
.player-status {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-3);
|
||||
background: rgba(0, 0, 0, 0.75);
|
||||
color: var(--color-text-dim);
|
||||
font-size: var(--text-sm);
|
||||
text-align: center;
|
||||
padding: var(--space-5);
|
||||
}
|
||||
|
||||
.player-status h3 {
|
||||
font-size: var(--text-md);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.player-status .spinner {
|
||||
margin-bottom: var(--space-1);
|
||||
}
|
||||
|
||||
/* ---- watch: toolbar (source popup lives in components.css with the player) ---------- */
|
||||
|
||||
.watch-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
margin: var(--space-4) 0 var(--space-5);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-text-dim);
|
||||
}
|
||||
|
||||
.watch-toolbar__source {
|
||||
font-weight: var(--font-weight-semibold);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.watch-toolbar__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ---- settings ------------------------------------------------------------------ */
|
||||
|
||||
.settings {
|
||||
display: grid;
|
||||
grid-template-columns: 200px minmax(0, 1fr);
|
||||
gap: var(--space-6);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.settings__nav {
|
||||
position: sticky;
|
||||
top: calc(var(--header-height) + var(--space-5));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.settings__navlink {
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: var(--radius-full);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--color-text-dim);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.settings__navlink:hover {
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.settings__navlink.is-active {
|
||||
color: var(--color-accent-text);
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
.settings__content {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.settings__card {
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--color-surface);
|
||||
padding: var(--space-5);
|
||||
scroll-margin-top: calc(var(--header-height) + var(--space-4));
|
||||
}
|
||||
|
||||
.settings__card h2 {
|
||||
font-size: var(--text-xl);
|
||||
margin-bottom: var(--space-2);
|
||||
}
|
||||
|
||||
.settings__hint {
|
||||
color: var(--color-text-dim);
|
||||
font-size: var(--text-sm);
|
||||
margin-bottom: var(--space-4);
|
||||
max-width: 60ch;
|
||||
}
|
||||
|
||||
.settings__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin: var(--space-4) 0;
|
||||
}
|
||||
|
||||
.settings__status {
|
||||
font-size: var(--text-sm);
|
||||
min-height: 1.2em;
|
||||
}
|
||||
|
||||
.settings__status--ok {
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
.settings__status--err {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.provider-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: var(--space-2);
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
/* ---- settings ---------------------------------------------------------------------------- */
|
||||
.settings__layout { display: grid; grid-template-columns: 200px minmax(0, 1fr); gap: clamp(24px, 4vw, 56px); align-items: start; }
|
||||
.settings-nav { position: sticky; top: calc(var(--header-h) + 24px); display: flex; flex-direction: column; gap: 2px; }
|
||||
.settings-nav__link { text-align: left; padding: 10px 14px; border-radius: var(--r-md); color: var(--text-2); font-weight: var(--fw-bold); font-size: var(--fs-sm); }
|
||||
.settings-nav__link:hover { background: var(--surface); color: var(--text); }
|
||||
.settings__cards { display: flex; flex-direction: column; gap: 20px; max-width: 980px; }
|
||||
.settings-card { padding: clamp(18px, 2.4vw, 28px); border-radius: var(--r-lg); background: var(--surface); border: 1px solid var(--border); scroll-margin-top: calc(var(--header-h) + 20px); }
|
||||
.settings-card__head { margin-bottom: 18px; }
|
||||
.settings-card__title { font-size: var(--fs-lg); font-weight: var(--fw-heavy); }
|
||||
.settings-card__desc { margin-top: 4px; color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.field-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--border); }
|
||||
.field-row__label { font-weight: var(--fw-bold); }
|
||||
.switch-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 0 4px; cursor: pointer; }
|
||||
.switch-row__text { display: flex; flex-direction: column; gap: 2px; font-weight: var(--fw-bold); }
|
||||
.switch-row__text small { color: var(--text-3); font-weight: var(--fw-medium); font-size: var(--fs-xs); }
|
||||
.input-row { display: flex; gap: 8px; }
|
||||
.input-row .input { flex: 1; min-width: 0; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.toolbar__actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
|
||||
.provider-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; margin-top: 14px; }
|
||||
.provider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface-2);
|
||||
cursor: pointer;
|
||||
transition: border-color 120ms ease;
|
||||
position: relative; display: flex; align-items: center; gap: 12px;
|
||||
padding: 10px 12px; border-radius: var(--r-md);
|
||||
background: var(--bg-elev); border: 1px solid var(--border);
|
||||
cursor: pointer; transition: border-color var(--dur-fast), background var(--dur-fast);
|
||||
}
|
||||
|
||||
.provider:hover {
|
||||
border-color: var(--color-border-strong);
|
||||
.provider:hover { border-color: var(--border-strong); }
|
||||
.provider input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.provider__check {
|
||||
flex-shrink: 0; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 6px;
|
||||
border: 1.5px solid var(--border-strong); color: transparent;
|
||||
transition: background var(--dur-fast), border-color var(--dur-fast), color var(--dur-fast);
|
||||
}
|
||||
.provider input:checked ~ .provider__check { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.provider:has(input:checked) { border-color: rgba(192, 132, 252, 0.35); background: rgba(192, 132, 252, 0.06); }
|
||||
.provider input:focus-visible ~ .provider__check { box-shadow: var(--ring); }
|
||||
.provider__text { min-width: 0; display: flex; flex-direction: column; }
|
||||
.provider__name { font-weight: var(--fw-bold); font-size: var(--fs-sm); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.provider__meta { display: flex; align-items: center; gap: 6px; font-size: var(--fs-2xs); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.health { flex-shrink: 0; width: 7px; height: 7px; border-radius: 50%; background: var(--surface-3); }
|
||||
.health--good { background: var(--accent); }
|
||||
.health--fair { background: var(--warn); }
|
||||
.health--bad { background: var(--danger); }
|
||||
|
||||
.provider input[type="checkbox"] {
|
||||
flex: 0 0 auto;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: 0;
|
||||
accent-color: var(--color-accent);
|
||||
cursor: pointer;
|
||||
@media (max-width: 900px) {
|
||||
.settings__layout { grid-template-columns: 1fr; }
|
||||
.settings-nav { position: static; flex-direction: row; overflow-x: auto; scrollbar-width: none; margin: 0 calc(var(--gutter) * -1); padding: 0 var(--gutter); }
|
||||
.settings-nav__link { flex-shrink: 0; background: var(--surface); }
|
||||
}
|
||||
|
||||
.provider__name {
|
||||
font-size: var(--text-sm);
|
||||
font-weight: var(--font-weight-medium);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ---- responsive ---------------------------------------------------------------- */
|
||||
|
||||
@media (max-width: 720px) {
|
||||
:root {
|
||||
--card-width: 132px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
height: clamp(360px, 58vh, 520px);
|
||||
margin-bottom: var(--space-5);
|
||||
}
|
||||
|
||||
.hero__content {
|
||||
padding-bottom: 64px;
|
||||
}
|
||||
|
||||
.hero__overview {
|
||||
-webkit-line-clamp: 2;
|
||||
}
|
||||
|
||||
.hero__arrow {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.search-bar__form {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.settings {
|
||||
grid-template-columns: 1fr;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.settings__nav {
|
||||
position: static;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.settings__card {
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
|
||||
.watch-page .page--watch {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.watch-page .site-header {
|
||||
background: transparent;
|
||||
border-bottom-color: transparent;
|
||||
backdrop-filter: none;
|
||||
}
|
||||
|
||||
.watch-page.is-scrolled .site-header {
|
||||
background: color-mix(in srgb, var(--color-bg) 85%, transparent);
|
||||
border-bottom-color: var(--color-border);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
.watch-hero {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
margin-top: calc(var(--header-height) * -1);
|
||||
min-height: min(85svh, 900px);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
overflow: hidden;
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.watch-hero__backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -2;
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-color: var(--color-surface);
|
||||
}
|
||||
|
||||
.watch-hero__scrim {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
background:
|
||||
linear-gradient(
|
||||
180deg,
|
||||
color-mix(in srgb, var(--color-bg) 20%, transparent) 0%,
|
||||
color-mix(in srgb, var(--color-bg) 55%, transparent) 55%,
|
||||
var(--color-bg) 100%
|
||||
),
|
||||
linear-gradient(
|
||||
90deg,
|
||||
color-mix(in srgb, var(--color-bg) 85%, transparent) 0%,
|
||||
transparent 65%
|
||||
);
|
||||
}
|
||||
|
||||
.watch-hero__inner {
|
||||
width: 100%;
|
||||
max-width: var(--container-max);
|
||||
margin: 0 auto;
|
||||
padding: calc(var(--header-height) + var(--space-8)) var(--container-pad) var(--space-8);
|
||||
}
|
||||
|
||||
.watch-hero__logo {
|
||||
max-width: min(420px, 60vw);
|
||||
max-height: 140px;
|
||||
object-fit: contain;
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.watch-hero__title {
|
||||
margin: 0;
|
||||
font-size: clamp(2.2rem, 6vw, 4.5rem);
|
||||
line-height: 1.02;
|
||||
letter-spacing: -0.035em;
|
||||
}
|
||||
|
||||
.watch-hero__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
margin-top: var(--space-4);
|
||||
color: var(--color-text-dim);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.watch-hero__rating {
|
||||
color: var(--color-star);
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.watch-hero__dot {
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
.watch-hero__genres {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
|
||||
.watch-hero__overview {
|
||||
max-width: 72ch;
|
||||
margin: var(--space-4) 0 0;
|
||||
color: var(--color-text-dim);
|
||||
line-height: 1.55;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 4;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.watch-hero__actions {
|
||||
margin-top: var(--space-6);
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.watch-hero__actions .btn--primary {
|
||||
padding: var(--space-3) var(--space-6);
|
||||
font-size: var(--text-md);
|
||||
}
|
||||
|
||||
.watch-episodes {
|
||||
padding: var(--space-8) 0;
|
||||
}
|
||||
|
||||
.watch-episodes__title {
|
||||
margin: 0 0 var(--space-4);
|
||||
font-size: var(--text-xl);
|
||||
}
|
||||
|
||||
.season-tabs {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
overflow-x: auto;
|
||||
padding-bottom: var(--space-2);
|
||||
margin-bottom: var(--space-5);
|
||||
}
|
||||
|
||||
.episode-shelf {
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(220px, 1fr);
|
||||
gap: var(--space-4);
|
||||
overflow-x: auto;
|
||||
scroll-snap-type: x mandatory;
|
||||
padding: var(--space-2) var(--space-2) var(--space-3);
|
||||
scroll-padding: var(--space-2);
|
||||
}
|
||||
|
||||
.episode-shelf__loading,
|
||||
.episode-shelf__empty {
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 180px;
|
||||
}
|
||||
|
||||
.episode-card {
|
||||
scroll-snap-align: start;
|
||||
text-align: left;
|
||||
border: 1px solid var(--color-border);
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.episode-card--current {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.episode-card__thumb {
|
||||
position: relative;
|
||||
display: block;
|
||||
aspect-ratio: 16 / 9;
|
||||
width: 100%;
|
||||
background: var(--color-surface-2);
|
||||
}
|
||||
|
||||
.episode-card__thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.episode-card__thumb--empty {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: var(--text-2xl);
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
.episode-card__progress {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
.episode-card__body {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.episode-card__num {
|
||||
color: var(--color-text-faint);
|
||||
font-size: var(--text-xs);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.episode-card__title {
|
||||
font-weight: 600;
|
||||
color: var(--color-text-dim);
|
||||
}
|
||||
|
||||
.episode-card__meta {
|
||||
color: var(--color-text-dim);
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
|
||||
.player-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 100;
|
||||
background: #000;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.player-overlay[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
body.player-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body.player-open .player-overlay {
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.player-overlay__close {
|
||||
position: absolute;
|
||||
top: var(--space-4);
|
||||
right: var(--space-4);
|
||||
z-index: 20;
|
||||
background: color-mix(in srgb, #000 60%, transparent);
|
||||
color: #fff;
|
||||
border: 1px solid rgb(255 255 255 / 20%);
|
||||
}
|
||||
|
||||
#playerOverlay .player-wrap {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
aspect-ratio: auto;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
#playerOverlay .watch-toolbar {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
bottom: var(--space-5);
|
||||
z-index: 2;
|
||||
background: color-mix(in srgb, #000 65%, transparent);
|
||||
border: 1px solid rgb(255 255 255 / 10%);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.watch-hero {
|
||||
min-height: 70svh;
|
||||
}
|
||||
|
||||
.watch-hero__inner {
|
||||
padding-bottom: var(--space-6);
|
||||
}
|
||||
|
||||
.watch-hero__actions .btn--primary {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.episode-shelf {
|
||||
grid-auto-columns: minmax(160px, 80vw);
|
||||
}
|
||||
|
||||
.player-overlay__close {
|
||||
top: var(--space-2);
|
||||
right: var(--space-2);
|
||||
}
|
||||
.input-row { flex-wrap: wrap; }
|
||||
.input-row .input { flex-basis: 100%; }
|
||||
.provider-grid { grid-template-columns: 1fr; }
|
||||
.input--sm { max-width: none; flex: 1; }
|
||||
}
|
||||
+1292
File diff suppressed because it is too large.
Load diff
+114
-60
@@ -1,68 +1,122 @@
|
||||
/*
|
||||
============================================================================
|
||||
DESIGN TOKENS — the only file you need to touch to restyle the whole UI.
|
||||
Every color, font size, spacing step, radius and shadow used elsewhere
|
||||
references a variable defined here. Change a value and it applies everywhere.
|
||||
============================================================================
|
||||
tokens.css — design tokens. Every color, size, radius, shadow and duration used by the
|
||||
UI comes from here; retheme by editing this file only.
|
||||
*/
|
||||
|
||||
:root {
|
||||
/* ---- palette (retheme here) ----------------------------------------- */
|
||||
--color-bg: #0a0a0a; /* page background */
|
||||
--color-surface: #141414; /* cards, panels */
|
||||
--color-surface-hover: #1d1d1d; /* hover state for surfaces */
|
||||
--color-surface-2: #1a1a1a; /* inputs, alt surfaces */
|
||||
--color-border: #262626; /* default borders */
|
||||
--color-border-strong: #3a3a3a; /* visible borders / hover borders */
|
||||
--color-text: #f2f2f2; /* primary text */
|
||||
--color-text-dim: #9a9a9a; /* secondary text */
|
||||
--color-text-faint: #5c5c5c; /* tertiary text */
|
||||
--color-accent: #c084fc; /* brand / primary action color */
|
||||
--color-accent-hover: #d8b4fe;
|
||||
--color-accent-text: #12071f; /* text on accent buttons */
|
||||
--color-danger: #ff6b6b;
|
||||
--color-success: #c084fc;
|
||||
--color-star: #ffc94d; /* rating stars */
|
||||
color-scheme: dark;
|
||||
|
||||
/* ---- typography ------------------------------------------------------ */
|
||||
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--text-xs: 0.75rem;
|
||||
--text-sm: 0.875rem;
|
||||
--text-md: 1rem;
|
||||
--text-lg: 1.125rem;
|
||||
--text-xl: 1.375rem;
|
||||
--text-2xl: 1.75rem;
|
||||
--text-3xl: 2.25rem;
|
||||
--leading-tight: 1.2;
|
||||
--leading-normal: 1.55;
|
||||
--font-weight-normal: 400;
|
||||
--font-weight-medium: 500;
|
||||
--font-weight-semibold: 600;
|
||||
--font-weight-bold: 700;
|
||||
/* palette */
|
||||
--bg: #09090b;
|
||||
--bg-elev: #0f0f12;
|
||||
--surface: #15151a;
|
||||
--surface-2: #1c1c22;
|
||||
--surface-3: #26262d;
|
||||
--overlay: rgba(9, 9, 11, 0.82);
|
||||
--glass: rgba(255, 255, 255, 0.1);
|
||||
--glass-hover: rgba(255, 255, 255, 0.18);
|
||||
--glass-border: rgba(255, 255, 255, 0.16);
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--border-strong: rgba(255, 255, 255, 0.16);
|
||||
--text: #f4f4f6;
|
||||
--text-2: #b6b6c0;
|
||||
--text-3: #7c7c88;
|
||||
--accent: #c084fc;
|
||||
--accent-hover: #d8b4fe;
|
||||
--accent-ink: #12071f;
|
||||
--accent-soft: rgba(192, 132, 252, 0.16);
|
||||
--accent-glow: rgba(192, 132, 252, 0.4);
|
||||
--star: #f5c518;
|
||||
--danger: #ff5f5f;
|
||||
--warn: #f5a524;
|
||||
--ok: var(--accent);
|
||||
--focus: #ffffff;
|
||||
|
||||
/* ---- spacing (4px scale) ---------------------------------------------- */
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 24px;
|
||||
--space-6: 32px;
|
||||
--space-7: 48px;
|
||||
--space-8: 64px;
|
||||
/* type */
|
||||
--font: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
|
||||
--fs-2xs: 0.6875rem;
|
||||
--fs-xs: 0.75rem;
|
||||
--fs-sm: 0.875rem;
|
||||
--fs-base: 1rem;
|
||||
--fs-md: 1.125rem;
|
||||
--fs-lg: 1.375rem;
|
||||
--fs-xl: 1.75rem;
|
||||
--fs-2xl: clamp(1.75rem, 1.2rem + 1.6vw, 2.5rem);
|
||||
--fs-hero: clamp(2.4rem, 1.4rem + 4vw, 4.75rem);
|
||||
--lh-tight: 1.1;
|
||||
--lh: 1.55;
|
||||
--fw-medium: 500;
|
||||
--fw-semi: 600;
|
||||
--fw-bold: 700;
|
||||
--fw-heavy: 800;
|
||||
|
||||
/* ---- shape ------------------------------------------------------------- */
|
||||
--radius-sm: 8px;
|
||||
--radius-md: 12px;
|
||||
--radius-lg: 16px;
|
||||
--radius-full: 999px;
|
||||
--shadow-1: 0 2px 8px rgba(0, 0, 0, 0.45);
|
||||
--shadow-2: 0 12px 40px rgba(0, 0, 0, 0.6);
|
||||
/* spacing (4px base) */
|
||||
--sp-1: 4px;
|
||||
--sp-2: 8px;
|
||||
--sp-3: 12px;
|
||||
--sp-4: 16px;
|
||||
--sp-5: 20px;
|
||||
--sp-6: 24px;
|
||||
--sp-7: 32px;
|
||||
--sp-8: 40px;
|
||||
--sp-9: 48px;
|
||||
--sp-10: 64px;
|
||||
--sp-11: 80px;
|
||||
--max-w: 1680px;
|
||||
--gutter: max(clamp(16px, 4vw, 56px), calc((100vw - var(--max-w)) / 2));
|
||||
|
||||
/* ---- layout ------------------------------------------------------------ */
|
||||
--container-max: 1280px;
|
||||
--container-pad: var(--space-5);
|
||||
--header-height: 64px;
|
||||
--poster-aspect: 2 / 3; /* 2:3 poster cards */
|
||||
--card-width: 160px; /* poster card width in carousels */
|
||||
--player-aspect: 16 / 9;
|
||||
/* layout */
|
||||
--header-h: 72px;
|
||||
--tabbar-h: 0px;
|
||||
--row-gap: clamp(10px, 1vw, 16px);
|
||||
--card-poster-w: clamp(128px, 12.5vw, 210px);
|
||||
--card-wide-w: clamp(250px, 23vw, 380px);
|
||||
--card-logo-w: clamp(150px, 15vw, 220px);
|
||||
|
||||
/* radii */
|
||||
--r-xs: 4px;
|
||||
--r-sm: 6px;
|
||||
--r-md: 10px;
|
||||
--r-lg: 14px;
|
||||
--r-xl: 20px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* shadows */
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-md: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
--shadow-lg: 0 18px 50px rgba(0, 0, 0, 0.6);
|
||||
--ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--focus);
|
||||
|
||||
/* motion */
|
||||
--ease: cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
--ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);
|
||||
--dur-fast: 140ms;
|
||||
--dur: 240ms;
|
||||
--dur-slow: 600ms;
|
||||
--dur-fade: 900ms;
|
||||
|
||||
/* z layers */
|
||||
--z-header: 50;
|
||||
--z-tabbar: 55;
|
||||
--z-modal: 100;
|
||||
--z-toast: 110;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
:root {
|
||||
--header-h: 60px;
|
||||
--tabbar-h: calc(62px + env(safe-area-inset-bottom, 0px));
|
||||
--card-poster-w: 31vw;
|
||||
--card-wide-w: 74vw;
|
||||
--card-logo-w: 40vw;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:root {
|
||||
--dur-fast: 0ms;
|
||||
--dur: 0ms;
|
||||
--dur-slow: 0ms;
|
||||
--dur-fade: 0ms;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"><path fill="#AA8DD8" d="M7.415 4c1-1 .25-4-1.438-4s-1.562 2-.562 2 1 2 1 3 1-1 1-1zM3.232 5.72c1-1 .25-4-1.438-4s-1.562 2-.562 2 1 2 1 3 1-1 1-1z"/><path fill="#744EAA" d="M29.607 32.856c.189.808 1.227 2.28 2.032 2.091.806-.19 1.077-1.971.888-2.777-.189-.808-.998-1.307-1.804-1.117-.805.19-1.306.997-1.116 1.803zm-5.434.649c.003.83.681 2.498 1.509 2.495.828-.004 1.494-1.677 1.491-2.506-.003-.829-.677-1.497-1.505-1.495-.828.004-1.498.677-1.495 1.506zm-5.271-2.446c-.326.764-.365 2.563.396 2.89.763.324 2.037-.947 2.363-1.71.325-.762-.028-1.643-.789-1.97-.762-.325-1.643.027-1.97.79zm-5.031-11.04c-.812.172-2.308 1.173-2.139 1.983.173.81 1.945 1.124 2.757.953.811-.171 1.329-.967 1.16-1.777-.172-.81-.965-1.33-1.778-1.159zm-2.037-5c-.812.172-2.308 1.173-2.139 1.983.173.81 1.945 1.124 2.757.953.811-.171 1.329-.967 1.16-1.777-.172-.81-.966-1.33-1.778-1.159z"/><path fill="#9266CC" d="M27.244 34c2.831 0 4.926-.877 5.266-1.027 2.271-1.01 3.293-3.669 2.284-5.939-.999-2.25-3.616-3.275-5.872-2.314-.133.05-1.793.649-3.343-.072-1.851-.861-2.995-3.309-3.628-5.209-.144-.43-.385-1.274-.686-2.316-1.866-6.471-2.832-8.285-3.983-9.82C13.571 2.352 7.69 2.007 4.799 2.587c-2.437.487-4.018 2.858-3.53 5.295.488 2.438 2.86 4.02 5.296 3.53.162-.026 2.204-.306 3.424 1.169.643 1.287 2.08 5.128 2.63 7.034.346 1.199.629 2.171.794 2.667 1.773 5.317 4.666 8.893 8.603 10.629C23.868 33.729 25.67 34 27.244 34z"/><circle fill="#FFF" cx="6.682" cy="5" r="1"/><path d="M30.923 32.964c-.089 0-.18-.012-.269-.036-.532-.148-.844-.699-.696-1.231.757-2.722-.77-4.542-.785-4.56-.359-.419-.312-1.051.107-1.41.418-.359 1.051-.312 1.41.107.092.107 2.234 2.66 1.195 6.397-.122.443-.525.733-.962.733zm-7.199-.563c-.245 0-.49-.089-.684-.27-.403-.378-.424-1.011-.047-1.414 1.485-1.587 1.453-4.193 1.452-4.22-.016-.552.419-1.012.972-1.028.542-.005 1.013.419 1.028.972.004.139.073 3.437-1.991 5.644-.197.21-.464.316-.73.316zm-8.542-8.696c-.48 0-.904-.347-.985-.837-.09-.544.278-1.06.823-1.149 3.074-.51 4.774-2.377 4.791-2.396.365-.41.998-.449 1.409-.084.412.365.453.993.091 1.406-.087.099-2.156 2.415-5.964 3.046-.056.01-.111.014-.165.014zm2.921 4.857c-.425 0-.819-.272-.954-.698-.166-.526.126-1.089.652-1.255 2.693-.853 3.88-2.83 3.892-2.85.28-.477.892-.637 1.368-.357.477.279.636.893.357 1.368-.063.108-1.595 2.663-5.013 3.744-.101.033-.203.048-.302.048zm-4.619-10.67c-.496 0-.927-.369-.991-.875-.069-.548.319-1.048.867-1.118 2.689-.34 4.657-1.971 4.676-1.988.422-.354 1.053-.303 1.408.119.356.421.305 1.05-.115 1.407-.097.083-2.42 2.029-5.718 2.446-.043.006-.085.009-.127.009zm-1.821-4.767c-.425 0-.819-.273-.954-.701-.165-.527.127-1.088.654-1.254 3.13-.983 4.253-2.692 4.299-2.764.295-.462.911-.605 1.375-.312.465.292.611.899.324 1.366-.06.097-1.506 2.396-5.399 3.619-.099.031-.2.046-.299.046z" fill="#744EAA"/></svg>
|
||||
|
After Width: | Height: | Size: 2.8 KiB |
+68
-30
@@ -2,52 +2,90 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>bug.tv — home</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<meta name="theme-color" content="#09090b">
|
||||
<meta name="description" content="bug tv — stream movies and series.">
|
||||
<!-- API base default; replaced at build time (empty → https://api-tv.bug.tools). -->
|
||||
<meta name="bug-tv-api" content="">
|
||||
<!-- Path the site is served under (history routing); "/" for a domain root. -->
|
||||
<meta name="bug-tv-root" content="/">
|
||||
<title>bug tv</title>
|
||||
<script>
|
||||
/* Router mode + <base> so assets resolve from deep links (/title/tv/1399) and file://. */
|
||||
(function () {
|
||||
var l = location;
|
||||
var m = document.querySelector('meta[name="bug-tv-root"]');
|
||||
var root = m && m.content && !/^@.*@$/.test(m.content) ? m.content : '/';
|
||||
if (root.slice(-1) !== '/') root += '/';
|
||||
var fileish = l.protocol === 'file:' || /\.html?$/i.test(l.pathname);
|
||||
var hash = fileish || /^#\//.test(l.hash);
|
||||
var base = document.createElement('base');
|
||||
base.href = fileish ? l.href.split('#')[0] : l.origin + root;
|
||||
document.head.appendChild(base);
|
||||
window.__BUGTV_ROUTER = { mode: hash ? 'hash' : 'history', root: root };
|
||||
})();
|
||||
</script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link rel="preconnect" href="https://image.tmdb.org">
|
||||
<link rel="preconnect" href="https://api.themoviedb.org">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
|
||||
<link rel="icon" type="image/svg+xml" href="img/bug.svg">
|
||||
<link rel="stylesheet" href="css/tokens.css">
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<link rel="stylesheet" href="css/components.css">
|
||||
<link rel="stylesheet" href="css/pages.css">
|
||||
<link rel="stylesheet" href="css/player.css">
|
||||
<link rel="modulepreload" href="js/router.js">
|
||||
</head>
|
||||
<body class="home-page">
|
||||
<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="brand" href="index.html">bug<span>.tv</span></a>
|
||||
<nav class="site-header__nav" aria-label="Primary">
|
||||
<body>
|
||||
<a class="skip-link" href="#app">Skip to content</a>
|
||||
|
||||
<header class="site-header is-over-hero">
|
||||
<div class="site-header__inner container">
|
||||
<a class="brand" data-href="/" aria-label="bug tv home">
|
||||
<img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span>
|
||||
</a>
|
||||
<nav class="site-nav" aria-label="Primary">
|
||||
<a class="site-nav__link" data-nav data-href="/">Home</a>
|
||||
<a class="site-nav__link" data-nav data-href="/movies">Movies</a>
|
||||
<a class="site-nav__link" data-nav data-href="/tv">Series</a>
|
||||
<a class="site-nav__link" data-nav data-href="/list">My List</a>
|
||||
</nav>
|
||||
<div class="site-header__actions">
|
||||
<a class="icon-btn" href="search.html" aria-label="Search" title="Search">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
|
||||
</a>
|
||||
<a class="icon-btn" href="settings.html" aria-label="Settings" title="Settings">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
|
||||
</a>
|
||||
<form class="header-search" role="search">
|
||||
<button class="header-search__icon" type="button" tabindex="-1" aria-hidden="true"><span data-icon="search"></span></button>
|
||||
<input type="search" name="q" placeholder="Search titles" autocomplete="off" spellcheck="false" aria-label="Search movies and series">
|
||||
<kbd class="header-search__kbd" aria-hidden="true">/</kbd>
|
||||
</form>
|
||||
<a class="icon-btn header-search-link" data-nav data-href="/search" aria-label="Search" title="Search"><span data-icon="search"></span></a>
|
||||
<a class="icon-btn" data-nav data-href="/settings" aria-label="Settings" title="Settings"><span data-icon="settings"></span></a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="page" id="content">
|
||||
<div id="heroSlot"></div>
|
||||
<div class="container">
|
||||
<div id="sections"></div>
|
||||
</div>
|
||||
</main>
|
||||
<main id="app" class="app" aria-live="polite"></main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="container">
|
||||
<span>tv.bug.tools</span>
|
||||
<span>api: <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
|
||||
<span>tv.bug.tools doesn't store files, but provides links to external services.</span>
|
||||
<div class="container site-footer__inner">
|
||||
<span class="brand brand--sm"><img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span></span>
|
||||
<span class="site-footer__note">bug tv doesn't host files — it links to third-party sources. Metadata by TMDB.</span>
|
||||
<span class="site-footer__api">api · <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="js/util.js"></script>
|
||||
<script src="js/config.js"></script>
|
||||
<script src="js/api.js"></script>
|
||||
<script src="js/storage.js"></script>
|
||||
<script src="js/cards.js"></script>
|
||||
<script src="js/app.js"></script>
|
||||
<script src="js/home.js"></script>
|
||||
<nav class="tabbar" aria-label="Primary">
|
||||
<a class="tabbar__link" data-nav data-href="/"><span data-icon="home" data-size="22"></span><span>Home</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/movies"><span data-icon="film" data-size="22"></span><span>Movies</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/tv"><span data-icon="tv" data-size="22"></span><span>Series</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/search"><span data-icon="search" data-size="22"></span><span>Search</span></a>
|
||||
<a class="tabbar__link" data-nav data-href="/list"><span data-icon="bookmark" data-size="22"></span><span>My List</span></a>
|
||||
</nav>
|
||||
|
||||
<div id="toasts" class="toasts" role="status" aria-live="polite"></div>
|
||||
|
||||
<noscript><p style="padding:2rem;color:#fff">bug tv needs JavaScript.</p></noscript>
|
||||
<script type="module" src="js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+169
-166
@@ -1,176 +1,179 @@
|
||||
/*
|
||||
API — two upstreams:
|
||||
1. the bug-tv REST server (SR.config.getBase()): provider catalog,
|
||||
/streams lookup, and the /proxy/media tunnel the player needs (CORS,
|
||||
headers, m3u8 rewrite).
|
||||
2. TMDB, called straight from the browser (it is CORS-enabled): search,
|
||||
trending, details, seasons, episodes. Each returns the same shape the
|
||||
server's endpoints used to, so the pages are unchanged.
|
||||
API — client for the bug-tv server (docs/api.md, "Endpoints").
|
||||
|
||||
Keeping catalog traffic off the server means it only does provider scraping
|
||||
and stream proxying.
|
||||
streams(params, handlers) opens the SSE stream at /v1/streams and calls
|
||||
handlers as events arrive:
|
||||
onMeta({tmdb,type,season,episode,providers,timeoutMs,cached})
|
||||
onStreams({provider, ms, streams:[Stream]})
|
||||
onProvider({name, status, ms, count, error?})
|
||||
onDone({total, ms})
|
||||
onError(Error)
|
||||
Returns { close() }.
|
||||
|
||||
If EventSource fails before any event arrives (old proxy, CORS, a browser
|
||||
without SSE), it falls back to ?format=json and replays the aggregated
|
||||
response through the same handlers.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
import { resolveUrl, getProviders } from './config.js';
|
||||
|
||||
const TMDB_BASE = 'https://api.themoviedb.org/3';
|
||||
const TMDB_IMG = 'https://image.tmdb.org/t/p/';
|
||||
|
||||
async function request(path, params) {
|
||||
const url = new URL(SR.config.getBase() + path);
|
||||
if (params) {
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url.toString());
|
||||
} catch (e) {
|
||||
throw new Error(`cannot reach the API at ${SR.config.getBase()} — check the base URL in Settings`);
|
||||
}
|
||||
let data = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch (e) {
|
||||
/* non-JSON body */
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error((data && data.error) || `API error: HTTP ${res.status}`);
|
||||
}
|
||||
return data;
|
||||
function providerList() {
|
||||
let list;
|
||||
try {
|
||||
list = getProviders();
|
||||
} catch (e) {
|
||||
list = null;
|
||||
}
|
||||
return Array.isArray(list) ? list.filter(Boolean) : [];
|
||||
}
|
||||
|
||||
// Direct TMDB call. `key` overrides the configured key (Settings "Test").
|
||||
async function tmdb(pathname, params, key) {
|
||||
const url = new URL(TMDB_BASE + pathname);
|
||||
url.searchParams.set('api_key', key || SR.config.getTmdbKey());
|
||||
url.searchParams.set('language', 'en-US');
|
||||
if (params) {
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === null || v === '') continue;
|
||||
url.searchParams.set(k, String(v));
|
||||
}
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url.toString());
|
||||
} catch (e) {
|
||||
throw new Error('cannot reach the TMDB API — check your connection or the TMDB API key in Settings');
|
||||
}
|
||||
let data = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch (e) {
|
||||
/* non-JSON body */
|
||||
}
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
throw new Error('TMDB rejected the API key — check "TMDB API key" in Settings');
|
||||
}
|
||||
throw new Error((data && (data.status_message || data.error)) || `TMDB error: HTTP ${res.status}`);
|
||||
}
|
||||
return data;
|
||||
function query(params, extra) {
|
||||
const q = new URLSearchParams();
|
||||
q.set('tmdb', String(params.tmdb ?? params.id));
|
||||
q.set('type', params.type === 'tv' ? 'tv' : 'movie');
|
||||
if (params.type === 'tv') {
|
||||
if (params.season != null) q.set('season', String(params.season));
|
||||
if (params.episode != null) q.set('episode', String(params.episode));
|
||||
}
|
||||
const providers = Array.isArray(params.providers) ? params.providers : providerList();
|
||||
if (providers.length) q.set('providers', providers.join(','));
|
||||
for (const [k, v] of Object.entries(extra || {})) q.set(k, v);
|
||||
return q.toString();
|
||||
}
|
||||
|
||||
// route a media/subtitle URL through the API proxy (CORS, headers, m3u8 rewrite)
|
||||
function proxyUrl(target, headers) {
|
||||
const q = new URLSearchParams();
|
||||
q.set('url', target);
|
||||
q.set('h', JSON.stringify(headers || {}));
|
||||
return SR.config.getBase() + '/proxy/media?' + q.toString();
|
||||
}
|
||||
async function getJson(path) {
|
||||
const res = await fetch(resolveUrl(path), { headers: { Accept: 'application/json' } });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status} for ${path}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// Same shapes the server endpoints used to return.
|
||||
function searchResult(m) {
|
||||
const isTv = m.media_type === 'tv';
|
||||
const date = isTv ? m.first_air_date : m.release_date;
|
||||
return {
|
||||
tmdb_id: m.id,
|
||||
type: isTv ? 'tv' : 'movie',
|
||||
name: m.title || m.name,
|
||||
year: date ? String(date).slice(0, 4) : '',
|
||||
poster: m.poster_path ? `${TMDB_IMG}w342${m.poster_path}` : '',
|
||||
backdrop: m.backdrop_path ? `${TMDB_IMG}w1280${m.backdrop_path}` : '',
|
||||
rating: m.vote_average ? Number(m.vote_average).toFixed(1) : '',
|
||||
overview: m.overview || '',
|
||||
};
|
||||
}
|
||||
|
||||
function fullImage(pathname) {
|
||||
return pathname ? `${TMDB_IMG}original${pathname}` : '';
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.api = {
|
||||
request,
|
||||
tmdb,
|
||||
proxyUrl,
|
||||
|
||||
// — TMDB, straight from the browser —
|
||||
search: (q) =>
|
||||
tmdb('/search/multi', { query: q, include_adult: 'false', page: 1 }).then((r) => {
|
||||
const results = (r.results || [])
|
||||
.filter((m) => m.media_type === 'movie' || m.media_type === 'tv')
|
||||
.slice(0, 15)
|
||||
.map(searchResult);
|
||||
return { query: q, count: results.length, results };
|
||||
}),
|
||||
trending: (type, timeWindow) => {
|
||||
const t = ['movie', 'tv', 'all'].includes(type) ? type : 'all';
|
||||
const w = timeWindow === 'day' ? 'day' : 'week';
|
||||
return tmdb(`/trending/${t}/${w}`).then((r) => {
|
||||
const results = (r.results || []).slice(0, 20).map(searchResult);
|
||||
return { type: t, window: w, count: results.length, results };
|
||||
});
|
||||
},
|
||||
details: (type, id) =>
|
||||
tmdb(`/${type}/${id}`, { append_to_response: 'images' }).then((d) => {
|
||||
d.poster_url = fullImage(d.poster_path);
|
||||
d.backdrop_url = fullImage(d.backdrop_path);
|
||||
if (d.images) {
|
||||
for (const key of Object.keys(d.images)) {
|
||||
d.images[key] = (d.images[key] || []).map((im) => ({ ...im, url: fullImage(im.file_path) }));
|
||||
}
|
||||
}
|
||||
return d;
|
||||
}),
|
||||
seasons: (id) =>
|
||||
tmdb(`/tv/${id}`).then((r) => {
|
||||
const seasons = (r.seasons || [])
|
||||
.filter((s) => s.season_number > 0 && (s.episode_count || 0) > 0)
|
||||
.map((s) => ({
|
||||
season_number: s.season_number,
|
||||
name: s.name,
|
||||
episode_count: s.episode_count,
|
||||
air_date: s.air_date || '',
|
||||
}));
|
||||
return { tmdb_id: id, count: seasons.length, seasons };
|
||||
}),
|
||||
episodes: (id, season) =>
|
||||
tmdb(`/tv/${id}/season/${season}`).then((r) => {
|
||||
const episodes = (r.episodes || [])
|
||||
.slice()
|
||||
.sort((a, b) => a.episode_number - b.episode_number)
|
||||
.map((e) => ({
|
||||
episode_number: e.episode_number,
|
||||
name: e.name,
|
||||
air_date: e.air_date || '',
|
||||
still: e.still_path ? `${TMDB_IMG}w300${e.still_path}` : '',
|
||||
}));
|
||||
return { tmdb_id: id, season: parseInt(season, 10), count: episodes.length, episodes };
|
||||
}),
|
||||
|
||||
// — bug-tv server (providers, streams, proxy) —
|
||||
streams: ({ tmdb, type, season, episode, providers }) =>
|
||||
request('/streams', {
|
||||
tmdb,
|
||||
type,
|
||||
season,
|
||||
episode,
|
||||
providers: Array.isArray(providers) && providers.length ? providers.join(',') : '',
|
||||
}),
|
||||
providers: () => request('/providers'),
|
||||
export function streams(params, handlers = {}) {
|
||||
const h = {
|
||||
onMeta() {},
|
||||
onStreams() {},
|
||||
onProvider() {},
|
||||
onDone() {},
|
||||
onError() {},
|
||||
...handlers,
|
||||
};
|
||||
})();
|
||||
let closed = false;
|
||||
let gotEvent = false;
|
||||
let finished = false;
|
||||
let es = null;
|
||||
let abort = null;
|
||||
|
||||
const call = (fn, data) => {
|
||||
try {
|
||||
fn(data);
|
||||
} catch (e) {
|
||||
console.error('[api.streams] handler failed', e);
|
||||
}
|
||||
};
|
||||
|
||||
const listen = (fn) => (ev) => {
|
||||
if (closed || finished) return;
|
||||
gotEvent = true;
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(ev.data);
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
call(fn, data);
|
||||
};
|
||||
|
||||
function finish(data) {
|
||||
if (finished || closed) return;
|
||||
finished = true;
|
||||
if (es) es.close();
|
||||
call(h.onDone, data || { total: 0, ms: 0 });
|
||||
}
|
||||
|
||||
async function jsonFallback() {
|
||||
if (es) es.close();
|
||||
es = null;
|
||||
abort = typeof AbortController === 'function' ? new AbortController() : null;
|
||||
const started = performance.now();
|
||||
try {
|
||||
const res = await fetch(resolveUrl(`/v1/streams?${query(params, { format: 'json' })}`), {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: abort ? abort.signal : undefined,
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
if (closed) return;
|
||||
const list = Array.isArray(data.streams) ? data.streams : [];
|
||||
const errors = data.providerErrors || {};
|
||||
const byProvider = new Map();
|
||||
for (const s of list) {
|
||||
const p = s.provider || 'unknown';
|
||||
if (!byProvider.has(p)) byProvider.set(p, []);
|
||||
byProvider.get(p).push(s);
|
||||
}
|
||||
const names = [...new Set([...byProvider.keys(), ...Object.keys(errors)])];
|
||||
const ms = Math.round(performance.now() - started);
|
||||
call(h.onMeta, {
|
||||
tmdb: params.tmdb,
|
||||
type: params.type,
|
||||
season: params.season,
|
||||
episode: params.episode,
|
||||
providers: names,
|
||||
timeoutMs: 0,
|
||||
cached: [],
|
||||
});
|
||||
for (const [provider, s] of byProvider) call(h.onStreams, { provider, ms, streams: s });
|
||||
for (const name of names) {
|
||||
const count = (byProvider.get(name) || []).length;
|
||||
call(
|
||||
h.onProvider,
|
||||
errors[name]
|
||||
? { name, status: 'error', ms, count, error: String(errors[name]) }
|
||||
: { name, status: count ? 'ok' : 'empty', ms, count },
|
||||
);
|
||||
}
|
||||
finish({ total: list.length, ms });
|
||||
} catch (e) {
|
||||
if (closed) return;
|
||||
call(h.onError, e);
|
||||
finish({ total: 0, ms: Math.round(performance.now() - started), error: String(e.message || e) });
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof EventSource !== 'function') {
|
||||
jsonFallback();
|
||||
} else {
|
||||
es = new EventSource(resolveUrl(`/v1/streams?${query(params)}`));
|
||||
es.addEventListener('meta', listen(h.onMeta));
|
||||
es.addEventListener('streams', listen(h.onStreams));
|
||||
es.addEventListener('provider', listen(h.onProvider));
|
||||
es.addEventListener('done', listen(finish));
|
||||
es.addEventListener('error', () => {
|
||||
if (closed || finished) return;
|
||||
if (!gotEvent) {
|
||||
jsonFallback();
|
||||
return;
|
||||
}
|
||||
// Connection dropped mid-stream. EventSource would reconnect and replay
|
||||
// the whole scrape; stop and treat what arrived as final.
|
||||
finish({ total: -1, ms: 0, error: 'stream interrupted' });
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (es) es.close();
|
||||
if (abort) abort.abort();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function providers() {
|
||||
return getJson('/v1/providers');
|
||||
}
|
||||
|
||||
export function prefetch(params) {
|
||||
return fetch(resolveUrl(`/v1/prefetch?${query(params)}`), { headers: { Accept: 'application/json' } })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.catch(() => null);
|
||||
}
|
||||
+96
-32
@@ -1,41 +1,105 @@
|
||||
/*
|
||||
APP — shared chrome for every page: footer API label, toast notifications.
|
||||
(Settings moved to its own page: settings.html)
|
||||
app.js — boots the shell: header (glass → solid on scroll, nav state, search box),
|
||||
mobile tab bar, footer label, then starts the router.
|
||||
Exposes window.bugtv = { navigate, href, toast } for non-module callers / debugging.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
import { h, debounce } from './util.js';
|
||||
import { getBase } from './config.js';
|
||||
import { start, navigate, href, onChange, current } from './router.js';
|
||||
import { toast } from './ui/toast.js';
|
||||
import { icon } from './ui/icons.js';
|
||||
|
||||
function initChrome() {
|
||||
const label = document.getElementById('apiBaseLabel');
|
||||
if (label) {
|
||||
const base = SR.config.getBase();
|
||||
label.textContent = base;
|
||||
label.href = base;
|
||||
}
|
||||
const header = document.querySelector('.site-header');
|
||||
const outlet = document.getElementById('app');
|
||||
|
||||
// links declared as data-href="/path" in index.html get mode-aware hrefs
|
||||
function wireLinks(scope = document) {
|
||||
scope.querySelectorAll('[data-href]').forEach((a) => a.setAttribute('href', href(a.dataset.href)));
|
||||
}
|
||||
|
||||
// icons for static markup: <span data-icon="search"></span>
|
||||
document.querySelectorAll('[data-icon]').forEach((el) => el.replaceWith(icon(el.dataset.icon, { size: Number(el.dataset.size) || 20 })));
|
||||
wireLinks();
|
||||
|
||||
// header: transparent over the hero, solid once scrolled
|
||||
const onScroll = () => header.classList.toggle('is-solid', window.scrollY > 24);
|
||||
window.addEventListener('scroll', onScroll, { passive: true });
|
||||
onScroll();
|
||||
|
||||
// search box in the header
|
||||
const searchForm = document.querySelector('.header-search');
|
||||
const searchInput = searchForm.querySelector('input');
|
||||
const searchGo = debounce(() => {
|
||||
const q = searchInput.value.trim();
|
||||
const onSearch = current().name === 'search';
|
||||
if (!q && !onSearch) return;
|
||||
navigate(`/search${q ? `?q=${encodeURIComponent(q)}` : ''}`, { replace: onSearch });
|
||||
}, 300);
|
||||
searchInput.addEventListener('input', searchGo);
|
||||
searchForm.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
searchGo.cancel();
|
||||
const q = searchInput.value.trim();
|
||||
navigate(`/search${q ? `?q=${encodeURIComponent(q)}` : ''}`, { replace: current().name === 'search' });
|
||||
});
|
||||
searchInput.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') {
|
||||
searchInput.value = '';
|
||||
searchInput.blur();
|
||||
}
|
||||
});
|
||||
searchForm.querySelector('.header-search__icon').addEventListener('click', () => searchInput.focus());
|
||||
|
||||
let toastTimer = null;
|
||||
|
||||
function toast(message, isError) {
|
||||
let el = document.getElementById('toast');
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = 'toast';
|
||||
el.className = 'toast';
|
||||
el.setAttribute('role', 'status');
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
el.textContent = message;
|
||||
el.classList.toggle('toast--error', !!isError);
|
||||
el.classList.add('toast--show');
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => el.classList.remove('toast--show'), 4500);
|
||||
// "/" focuses search (like most streaming sites)
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === '/' && !/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName) && !e.metaKey && !e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
if (getComputedStyle(searchForm).display === 'none') navigate('/search');
|
||||
else searchInput.focus();
|
||||
}
|
||||
});
|
||||
|
||||
function showError(err, fallback) {
|
||||
toast(err && err.message ? err.message : fallback || 'Something went wrong', true);
|
||||
// active nav state + keep the header search in sync with the URL
|
||||
const navMap = { home: '/', movies: '/movies', tv: '/tv', list: '/list', search: '/search', settings: '/settings' };
|
||||
onChange((r) => {
|
||||
const active = navMap[r.name] || (r.name === 'browse' ? (r.params.type === 'tv' ? '/tv' : '/movies') : null);
|
||||
document.querySelectorAll('[data-nav]').forEach((a) => {
|
||||
const on = a.dataset.href === active;
|
||||
a.classList.toggle('is-active', on);
|
||||
if (on) a.setAttribute('aria-current', 'page');
|
||||
else a.removeAttribute('aria-current');
|
||||
});
|
||||
if (r.name === 'search') {
|
||||
if (document.activeElement !== searchInput) searchInput.value = r.query.get('q') || '';
|
||||
} else {
|
||||
searchInput.value = '';
|
||||
}
|
||||
header.classList.toggle('is-over-hero', r.name === 'home' || r.name === 'movies' || r.name === 'tv' || r.name === 'title');
|
||||
onScroll();
|
||||
});
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.app = { initChrome, toast, showError };
|
||||
})();
|
||||
// footer API label
|
||||
const apiLabel = document.getElementById('apiBaseLabel');
|
||||
if (apiLabel) {
|
||||
const paint = () => {
|
||||
apiLabel.textContent = getBase().replace(/^https?:\/\//, '');
|
||||
apiLabel.href = getBase();
|
||||
};
|
||||
paint();
|
||||
window.addEventListener('storage', paint);
|
||||
onChange(paint);
|
||||
}
|
||||
|
||||
// skip link (fragment links would navigate because of <base>)
|
||||
const skip = document.querySelector('.skip-link');
|
||||
if (skip) {
|
||||
skip.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
outlet.setAttribute('tabindex', '-1');
|
||||
outlet.focus();
|
||||
});
|
||||
}
|
||||
|
||||
window.bugtv = Object.assign(window.bugtv || {}, { navigate, href, toast, h });
|
||||
|
||||
start(outlet);
|
||||
-249
@@ -1,249 +0,0 @@
|
||||
/*
|
||||
CARDS — renders poster cards, rows (carousels) and grids.
|
||||
Items can come straight from the API ({tmdb_id, type, name, year, poster})
|
||||
or from storage records; normalizeItem() handles both.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const { escapeHtml: esc, tmdbResize, formatSeconds } = SR.util;
|
||||
|
||||
function normalizeItem(r) {
|
||||
return {
|
||||
tmdbId: r.tmdb_id != null ? r.tmdb_id : r.tmdbId,
|
||||
type: r.type,
|
||||
season: r.season,
|
||||
episode: r.episode,
|
||||
name: r.name || r.title || '',
|
||||
year: r.year || '',
|
||||
poster: r.poster || r.poster_url || '',
|
||||
backdrop: r.backdrop || r.backdrop_url || '',
|
||||
rating: r.rating || (r.vote_average ? Number(r.vote_average).toFixed(1) : ''),
|
||||
overview: r.overview || '',
|
||||
};
|
||||
}
|
||||
|
||||
function watchHref(item) {
|
||||
const p = new URLSearchParams();
|
||||
p.set('id', item.tmdbId);
|
||||
p.set('type', item.type);
|
||||
if (item.type === 'tv') {
|
||||
if (item.season != null) p.set('s', item.season);
|
||||
if (item.episode != null) p.set('e', item.episode);
|
||||
}
|
||||
return `watch.html?${p.toString()}`;
|
||||
}
|
||||
|
||||
function card(item, opts = {}) {
|
||||
const el = document.createElement('a');
|
||||
el.className = 'card';
|
||||
el.href = opts.href || watchHref(item);
|
||||
const poster = tmdbResize(item.poster, 'w342');
|
||||
const progress =
|
||||
opts.progress != null
|
||||
? `<span class="card__progress"><i style="width:${Math.round(Math.min(1, opts.progress) * 100)}%"></i></span>`
|
||||
: '';
|
||||
const meta =
|
||||
item.meta ||
|
||||
(item.year
|
||||
? `${item.year} · ${item.type === 'tv' ? 'TV' : 'Movie'}`
|
||||
: item.type === 'tv'
|
||||
? 'TV'
|
||||
: 'Movie');
|
||||
const metaHtml = item.metaHtml || `<span class="card__meta__text">${esc(meta)}</span>`;
|
||||
const title = item.hideTitle
|
||||
? ''
|
||||
: `<span class="card__title">${esc(item.name)}</span>`;
|
||||
el.innerHTML = `
|
||||
<span class="card__poster${poster ? '' : ' card__poster--empty'}">
|
||||
${poster ? `<img src="${poster}" alt="" loading="lazy">` : '?'}
|
||||
${progress}
|
||||
</span>
|
||||
${title}
|
||||
<span class="card__meta">${metaHtml}</span>`;
|
||||
if (item.hideTitle) el.setAttribute('aria-label', `${item.name} — ${meta}`);
|
||||
return el;
|
||||
}
|
||||
|
||||
function row(title, items) {
|
||||
const section = document.createElement('section');
|
||||
section.className = 'row';
|
||||
section.innerHTML = `<div class="row__header"><h2 class="row__title">${esc(title)}</h2></div>`;
|
||||
const scroll = document.createElement('div');
|
||||
scroll.className = 'row__scroll';
|
||||
for (const item of items) scroll.appendChild(card(item));
|
||||
section.appendChild(scroll);
|
||||
return section;
|
||||
}
|
||||
|
||||
function grid(items) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'grid';
|
||||
for (const item of items) el.appendChild(card(item));
|
||||
return el;
|
||||
}
|
||||
|
||||
function emptyState(title, hint) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'empty';
|
||||
el.innerHTML = `<h3>${esc(title)}</h3>${hint ? `<p>${esc(hint)}</p>` : ''}`;
|
||||
return el;
|
||||
}
|
||||
|
||||
// "Continue watching" row: latest record per show, with progress bar
|
||||
function continueRow() {
|
||||
const recs = SR.storage.latestPerShow();
|
||||
if (!recs.length) return null;
|
||||
const items = recs.map((r) => ({
|
||||
tmdbId: r.tmdbId,
|
||||
type: r.type,
|
||||
season: r.season,
|
||||
episode: r.episode,
|
||||
name: r.show || r.title || '',
|
||||
poster: r.poster || '',
|
||||
hideTitle: true,
|
||||
meta:
|
||||
r.type === 'tv'
|
||||
? `S${r.season} · E${r.episode} · ${formatSeconds(Math.max(0, r.d - r.t))} left`
|
||||
: `Movie · ${formatSeconds(Math.max(0, r.d - r.t))} left`,
|
||||
metaHtml:
|
||||
r.type === 'tv'
|
||||
? `<span class="card__ep">S${r.season} <span class="card__ep-dot">·</span> E${r.episode}</span><span class="card__dot">·</span><span class="card__meta__text">${formatSeconds(Math.max(0, r.d - r.t))} left</span>`
|
||||
: `<span class="card__meta__text">Movie · ${formatSeconds(Math.max(0, r.d - r.t))} left</span>`,
|
||||
progress: r.d ? r.t / r.d : 0,
|
||||
}));
|
||||
return row('Continue watching', items);
|
||||
}
|
||||
|
||||
function heroCarousel(items) {
|
||||
const data = (items || []).filter((item) => item && item.backdrop && item.name);
|
||||
if (!data.length) return null;
|
||||
|
||||
const section = document.createElement('section');
|
||||
section.className = 'hero';
|
||||
section.setAttribute('aria-roledescription', 'carousel');
|
||||
section.setAttribute('aria-label', 'Featured titles');
|
||||
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'hero__slides';
|
||||
const slideEls = [];
|
||||
|
||||
for (let i = 0; i < data.length; i += 1) {
|
||||
const item = data[i];
|
||||
const slide = document.createElement('article');
|
||||
slide.className = i === 0 ? 'hero__slide is-active' : 'hero__slide';
|
||||
slide.setAttribute('role', 'group');
|
||||
slide.setAttribute('aria-roledescription', 'slide');
|
||||
slide.setAttribute('aria-label', `${i + 1} of ${data.length}: ${item.name}`);
|
||||
|
||||
const typeLabel = item.type === 'tv' ? 'TV' : 'Movie';
|
||||
const metaBits = [
|
||||
item.rating ? `<span class="hero__rating">★ ${esc(item.rating)}</span>` : '',
|
||||
item.year ? `<span>${esc(item.year)}</span>` : '',
|
||||
`<span class="badge">${esc(typeLabel)}</span>`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('<span class="hero__dot" style="height: 1px;">·</span>');
|
||||
|
||||
slide.innerHTML = `
|
||||
<img class="hero__backdrop" src="${item.backdrop}" alt="" loading="${i === 0 ? 'eager' : 'lazy'}">
|
||||
<div class="hero__scrim"></div>
|
||||
<div class="hero__fade"></div>
|
||||
<div class="container hero__inner">
|
||||
<div class="hero__content">
|
||||
<h1 class="hero__title">${esc(item.name)}</h1>
|
||||
<div class="hero__meta">${metaBits}</div>
|
||||
${item.overview ? `<p class="hero__overview">${esc(item.overview)}</p>` : ''}
|
||||
<div class="hero__actions">
|
||||
<a class="btn btn--primary hero__play" href="${watchHref(item)}">
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"></path></svg>
|
||||
<span>Play</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
wrap.appendChild(slide);
|
||||
slideEls.push(slide);
|
||||
}
|
||||
|
||||
section.appendChild(wrap);
|
||||
|
||||
if (slideEls.length > 1) {
|
||||
const prev = document.createElement('button');
|
||||
prev.type = 'button';
|
||||
prev.className = 'hero__arrow hero__arrow--prev';
|
||||
prev.setAttribute('aria-label', 'Previous slide');
|
||||
prev.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18l-6-6 6-6"></path></svg>';
|
||||
|
||||
const next = document.createElement('button');
|
||||
next.type = 'button';
|
||||
next.className = 'hero__arrow hero__arrow--next';
|
||||
next.setAttribute('aria-label', 'Next slide');
|
||||
next.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"></path></svg>';
|
||||
|
||||
const dots = document.createElement('div');
|
||||
dots.className = 'hero__dots';
|
||||
const dotEls = [];
|
||||
for (let i = 0; i < slideEls.length; i += 1) {
|
||||
const dot = document.createElement('button');
|
||||
dot.type = 'button';
|
||||
dot.className = i === 0 ? 'hero__dot is-active' : 'hero__dot';
|
||||
dot.setAttribute('aria-label', `Go to slide ${i + 1}`);
|
||||
dots.appendChild(dot);
|
||||
dotEls.push(dot);
|
||||
}
|
||||
|
||||
section.append(prev, next, dots);
|
||||
|
||||
let current = 0;
|
||||
let timer = null;
|
||||
|
||||
function goTo(index) {
|
||||
current = (index + slideEls.length) % slideEls.length;
|
||||
slideEls.forEach((slide, i) => slide.classList.toggle('is-active', i === current));
|
||||
dotEls.forEach((dot, i) => dot.classList.toggle('is-active', i === current));
|
||||
}
|
||||
|
||||
function start() {
|
||||
stop();
|
||||
if (!document.hidden) timer = setInterval(() => goTo(current + 1), 7000);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
if (timer) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
prev.addEventListener('click', () => {
|
||||
goTo(current - 1);
|
||||
start();
|
||||
});
|
||||
next.addEventListener('click', () => {
|
||||
goTo(current + 1);
|
||||
start();
|
||||
});
|
||||
dotEls.forEach((dot, i) => dot.addEventListener('click', () => {
|
||||
goTo(i);
|
||||
start();
|
||||
}));
|
||||
section.addEventListener('mouseenter', stop);
|
||||
section.addEventListener('mouseleave', start);
|
||||
section.addEventListener('focusin', stop);
|
||||
section.addEventListener('focusout', (e) => {
|
||||
if (!section.contains(e.relatedTarget)) start();
|
||||
});
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) stop();
|
||||
else start();
|
||||
});
|
||||
start();
|
||||
}
|
||||
|
||||
return section;
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.cards = { normalizeItem, card, row, grid, emptyState, continueRow, watchHref, heroCarousel };
|
||||
})();
|
||||
+96
-171
@@ -1,182 +1,107 @@
|
||||
/*
|
||||
CONFIG — where the API lives + which providers to query.
|
||||
config.js — where the API lives, the TMDB key, and which providers to query.
|
||||
|
||||
API base resolution order:
|
||||
1. ?api=<url> query param on any page (session override)
|
||||
2. localStorage (saved from Settings)
|
||||
3. built-in default
|
||||
1. ?api=<url> query param (session override, also read from a hash route)
|
||||
2. localStorage (saved from Settings) key: bug-tv.apiBase.v1
|
||||
3. <meta name="bug-tv-api" content="…"> in index.html (substituted at build time by nix)
|
||||
4. built-in default https://api-tv.bug.tools
|
||||
|
||||
Providers: until the user toggles anything in Settings, the server's own
|
||||
enabled list is used. Once customized, a {name: bool} map is stored in
|
||||
localStorage; names missing from the map default to enabled.
|
||||
Providers: until the user toggles anything in Settings, getProviders() returns null and
|
||||
the server's defaults apply. Once customized a {id: bool} map is stored (same format as v4,
|
||||
key bug-tv.providers.v1); getProviders() returns the enabled ids.
|
||||
|
||||
TMDB key: search/trending/details/images go straight to TMDB from the
|
||||
browser (the server only serves providers, streams and the media proxy).
|
||||
The key resolves from localStorage (Settings) or the built-in default.
|
||||
TMDB key: catalog calls go straight from the browser to TMDB.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
import { getParam, safe } from './util.js';
|
||||
|
||||
const DEFAULT_BASE = 'https://api-tv.bug.tools';
|
||||
const STORAGE_KEY = 'bug-tv.apiBase.v1';
|
||||
const PROVIDER_KEY = 'bug-tv.providers.v1';
|
||||
export const FALLBACK_BASE = 'https://api-tv.bug.tools';
|
||||
export const STORAGE_KEY = 'bug-tv.apiBase.v1';
|
||||
export const PROVIDER_KEY = 'bug-tv.providers.v1';
|
||||
export const DEFAULT_TMDB_KEY = 'ac014b130a8e6344c91dff4e68b18d47';
|
||||
export const TMDB_KEY_STORAGE_KEY = 'bug-tv.tmdbKey.v1';
|
||||
|
||||
// Search/details/images go straight to TMDB from the browser; this key
|
||||
// only ever reaches api.themoviedb.org.
|
||||
const DEFAULT_TMDB_KEY = 'ac014b130a8e6344c91dff4e68b18d47';
|
||||
const TMDB_KEY_STORAGE_KEY = 'bug-tv.tmdbKey.v1';
|
||||
function normalize(value) {
|
||||
let v = String(value || '').trim();
|
||||
if (!v) return '';
|
||||
if (!/^https?:\/\//i.test(v)) v = `${/^(localhost|127\.|\[::1\])/.test(v) ? 'http' : 'https'}://${v}`;
|
||||
return v.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
function normalize(value) {
|
||||
let v = String(value || '').trim();
|
||||
if (!v) return '';
|
||||
if (!/^https?:\/\//i.test(v)) v = `https://${v}`;
|
||||
return v.replace(/\/+$/, '');
|
||||
function metaBase() {
|
||||
const el = typeof document !== 'undefined' && document.querySelector('meta[name="bug-tv-api"]');
|
||||
const v = el && el.getAttribute('content');
|
||||
// ignore unsubstituted placeholders like "@API_BASE@"
|
||||
return v && !/^@.*@$/.test(v.trim()) ? normalize(v) : '';
|
||||
}
|
||||
|
||||
export const DEFAULT_BASE = metaBase() || FALLBACK_BASE;
|
||||
|
||||
export function getBase() {
|
||||
const fromQuery = getParam('api');
|
||||
if (fromQuery) return normalize(fromQuery);
|
||||
const stored = safe(() => localStorage.getItem(STORAGE_KEY), null);
|
||||
if (stored) return normalize(stored);
|
||||
return DEFAULT_BASE;
|
||||
}
|
||||
|
||||
export function setBase(value) {
|
||||
const v = normalize(value);
|
||||
safe(() => (v ? localStorage.setItem(STORAGE_KEY, v) : localStorage.removeItem(STORAGE_KEY)));
|
||||
return getBase();
|
||||
}
|
||||
|
||||
export function clearBase() {
|
||||
safe(() => localStorage.removeItem(STORAGE_KEY));
|
||||
}
|
||||
|
||||
// Resolves API-relative URLs ("/v1/p/…") against the configured base; absolute URLs pass through.
|
||||
export function resolveUrl(relOrAbs) {
|
||||
const s = String(relOrAbs || '');
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(s)) return s;
|
||||
return getBase() + (s.startsWith('/') ? s : `/${s}`);
|
||||
}
|
||||
|
||||
export function getTmdbKey() {
|
||||
const stored = safe(() => localStorage.getItem(TMDB_KEY_STORAGE_KEY), null);
|
||||
return stored && stored.trim() ? stored.trim() : DEFAULT_TMDB_KEY;
|
||||
}
|
||||
|
||||
export function setTmdbKey(value) {
|
||||
const v = String(value || '').trim();
|
||||
safe(() => (v ? localStorage.setItem(TMDB_KEY_STORAGE_KEY, v) : localStorage.removeItem(TMDB_KEY_STORAGE_KEY)));
|
||||
return getTmdbKey();
|
||||
}
|
||||
|
||||
export function clearTmdbKey() {
|
||||
safe(() => localStorage.removeItem(TMDB_KEY_STORAGE_KEY));
|
||||
}
|
||||
|
||||
// Raw {id: bool} map or null when the user never customized.
|
||||
export function getProviderMap() {
|
||||
const raw = safe(() => localStorage.getItem(PROVIDER_KEY), null);
|
||||
if (!raw) return null;
|
||||
const parsed = safe(() => JSON.parse(raw), null);
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
// Enabled provider ids, or null → use the server's defaults.
|
||||
export function getProviders() {
|
||||
const map = getProviderMap();
|
||||
return map ? Object.keys(map).filter((n) => map[n] !== false) : null;
|
||||
}
|
||||
|
||||
// Accepts a list of enabled ids or an {id: bool} map; null/undefined clears the override.
|
||||
export function setProviders(listOrMap) {
|
||||
if (listOrMap == null) return clearProviders();
|
||||
let map = listOrMap;
|
||||
if (Array.isArray(listOrMap)) {
|
||||
map = {};
|
||||
for (const id of listOrMap) map[id] = true;
|
||||
}
|
||||
safe(() => localStorage.setItem(PROVIDER_KEY, JSON.stringify(map)));
|
||||
}
|
||||
|
||||
function getBase() {
|
||||
const fromQuery = SR.util.getParam('api');
|
||||
if (fromQuery) return normalize(fromQuery);
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) return normalize(stored);
|
||||
} catch (e) {
|
||||
/* private mode etc. */
|
||||
}
|
||||
return DEFAULT_BASE;
|
||||
}
|
||||
|
||||
function setBase(value) {
|
||||
const v = normalize(value);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, v);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function clearBase() {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function getTmdbKey() {
|
||||
try {
|
||||
const stored = localStorage.getItem(TMDB_KEY_STORAGE_KEY);
|
||||
if (stored) return stored.trim();
|
||||
} catch (e) {
|
||||
/* private mode etc. */
|
||||
}
|
||||
return DEFAULT_TMDB_KEY;
|
||||
}
|
||||
|
||||
function setTmdbKey(value) {
|
||||
const v = String(value || '').trim();
|
||||
try {
|
||||
localStorage.setItem(TMDB_KEY_STORAGE_KEY, v);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function clearTmdbKey() {
|
||||
try {
|
||||
localStorage.removeItem(TMDB_KEY_STORAGE_KEY);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
// null → user has not customized; caller should fall back to server defaults
|
||||
function getProviders() {
|
||||
try {
|
||||
const raw = localStorage.getItem(PROVIDER_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function setProviders(map) {
|
||||
try {
|
||||
localStorage.setItem(PROVIDER_KEY, JSON.stringify(map));
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function clearProviders() {
|
||||
try {
|
||||
localStorage.removeItem(PROVIDER_KEY);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
const PREFERRED_PROVIDERS = ['cineby', 'playimdb', 'vidrock'];
|
||||
|
||||
// Merge the server's provider lists with the user's toggles.
|
||||
// Returns the enabled provider names, in the server's `all` order.
|
||||
function enabledProviders(allNames, serverEnabled) {
|
||||
const all = Array.isArray(allNames) ? allNames : [];
|
||||
const overrides = getProviders();
|
||||
if (overrides) {
|
||||
return Object.keys(overrides).filter((n) => overrides[n] !== false);
|
||||
}
|
||||
const server = Array.isArray(serverEnabled) ? serverEnabled : [];
|
||||
const wanted = new Set([...PREFERRED_PROVIDERS, ...server]);
|
||||
return (all.length ? all : PREFERRED_PROVIDERS.slice()).filter((n) =>
|
||||
wanted.has(n)
|
||||
);
|
||||
}
|
||||
|
||||
// Watch-page resolver. Re-reads localStorage on every call so provider
|
||||
// changes made in Settings apply to the next lookup without a reload.
|
||||
function resolveProviders(catalog) {
|
||||
const all = Array.isArray(catalog && catalog.all) ? catalog.all : [];
|
||||
const serverEnabled = Array.isArray(catalog && catalog.enabled) ? catalog.enabled : [];
|
||||
const overrides = getProviders();
|
||||
if (overrides) {
|
||||
return {
|
||||
names: Object.keys(overrides).filter((n) => overrides[n] !== false),
|
||||
customized: true,
|
||||
useServerDefaults: false,
|
||||
};
|
||||
}
|
||||
const wanted = new Set([...PREFERRED_PROVIDERS, ...serverEnabled]);
|
||||
const names = all.length
|
||||
? all.filter((n) => wanted.has(n))
|
||||
: PREFERRED_PROVIDERS.slice();
|
||||
return {
|
||||
names,
|
||||
customized: false,
|
||||
useServerDefaults: !names.length,
|
||||
};
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.config = {
|
||||
DEFAULT_BASE,
|
||||
STORAGE_KEY,
|
||||
PROVIDER_KEY,
|
||||
DEFAULT_TMDB_KEY,
|
||||
TMDB_KEY_STORAGE_KEY,
|
||||
getBase,
|
||||
setBase,
|
||||
clearBase,
|
||||
getTmdbKey,
|
||||
setTmdbKey,
|
||||
clearTmdbKey,
|
||||
getProviders,
|
||||
setProviders,
|
||||
clearProviders,
|
||||
enabledProviders,
|
||||
resolveProviders,
|
||||
};
|
||||
})();
|
||||
export function clearProviders() {
|
||||
safe(() => localStorage.removeItem(PROVIDER_KEY));
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
HOME — continue-watching row + trending rows.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const heroSlot = document.getElementById('heroSlot');
|
||||
const sections = document.getElementById('sections');
|
||||
|
||||
const cont = SR.cards.continueRow();
|
||||
if (cont) sections.appendChild(cont);
|
||||
|
||||
function appendRow(data, title) {
|
||||
if (!data || !data.count) return;
|
||||
sections.appendChild(SR.cards.row(title, data.results.map(SR.cards.normalizeItem)));
|
||||
}
|
||||
|
||||
function itemsFrom(data) {
|
||||
return data && Array.isArray(data.results) ? data.results.map(SR.cards.normalizeItem) : [];
|
||||
}
|
||||
|
||||
function loadHeroLogos(section, items) {
|
||||
const slides = section.querySelectorAll('.hero__slide');
|
||||
items.forEach((item, i) => {
|
||||
const slide = slides[i];
|
||||
if (!slide || !item || item.tmdbId == null) return;
|
||||
const titleEl = slide.querySelector('.hero__title');
|
||||
if (!titleEl) return;
|
||||
const logo = document.createElement('img');
|
||||
logo.className = 'hero__logo';
|
||||
logo.alt = item.name;
|
||||
logo.hidden = true;
|
||||
titleEl.insertAdjacentElement('beforebegin', logo);
|
||||
SR.api.details(item.type, item.tmdbId)
|
||||
.then((details) => {
|
||||
const images = (details && details.images) || {};
|
||||
const logos = images.logos || [];
|
||||
const url = (logos.find((l) => l && l.url && String(l.iso_639_1 || '').toLowerCase() === 'en') || {}).url;
|
||||
if (!url) return;
|
||||
logo.onerror = () => {
|
||||
logo.hidden = true;
|
||||
titleEl.hidden = false;
|
||||
};
|
||||
logo.src = SR.util.tmdbResize(url, 'w500');
|
||||
logo.hidden = false;
|
||||
titleEl.hidden = true;
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const [movieRes, tvRes] = await Promise.allSettled([
|
||||
SR.api.trending('movie', 'day'),
|
||||
SR.api.trending('tv', 'week'),
|
||||
]);
|
||||
|
||||
if (movieRes.status === 'fulfilled') appendRow(movieRes.value, 'Trending movies today');
|
||||
else SR.app.showError(movieRes.reason, 'could not load trending movies');
|
||||
|
||||
if (tvRes.status === 'fulfilled') appendRow(tvRes.value, 'Trending shows this week');
|
||||
else SR.app.showError(tvRes.reason, 'could not load trending shows');
|
||||
|
||||
try {
|
||||
const heroData = [...itemsFrom(tvRes.value), ...itemsFrom(movieRes.value)]
|
||||
.filter((item) => item.backdrop && item.overview && item.name)
|
||||
.slice(0, 6);
|
||||
const hero = SR.cards.heroCarousel(heroData);
|
||||
if (hero) {
|
||||
heroSlot.appendChild(hero);
|
||||
loadHeroLogos(hero, heroData);
|
||||
}
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'could not load featured titles');
|
||||
}
|
||||
})();
|
||||
})();
|
||||
@@ -1,182 +0,0 @@
|
||||
/*
|
||||
PLAYER — plays a stream in a <video> element and supports switching
|
||||
sources mid-watch without losing your place.
|
||||
|
||||
Pipeline per stream:
|
||||
- hls.js for .m3u8 when available
|
||||
- native HLS for Safari (canPlayType check)
|
||||
- direct <video src> for mp4/webm
|
||||
- everything else (DASH, mkv, magnet, …) → friendly error
|
||||
|
||||
Every media + subtitle URL is routed through the API proxy.
|
||||
On source switch we carry over currentTime, playbackRate, volume, muted
|
||||
and the playing state, clamped to the new duration.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function create(video, handlers = {}) {
|
||||
const onStatus = handlers.onStatus || (() => {});
|
||||
const onError = handlers.onError || (() => {});
|
||||
const onReady = handlers.onReady || (() => {});
|
||||
|
||||
let hls = null;
|
||||
let token = 0; // guards against overlapping loads
|
||||
let networkRetry = false;
|
||||
|
||||
function teardown() {
|
||||
token++;
|
||||
if (hls) {
|
||||
try {
|
||||
hls.destroy();
|
||||
} catch (e) {
|
||||
/* already destroyed */
|
||||
}
|
||||
hls = null;
|
||||
}
|
||||
for (const track of video.querySelectorAll('track')) track.remove();
|
||||
video.removeAttribute('src');
|
||||
try {
|
||||
video.load();
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function capture() {
|
||||
const v = video;
|
||||
return {
|
||||
time: isFinite(v.currentTime) && v.currentTime > 0 ? v.currentTime : 0,
|
||||
rate: v.playbackRate || 1,
|
||||
volume: v.volume,
|
||||
muted: v.muted,
|
||||
playing: !v.paused && !v.ended,
|
||||
};
|
||||
}
|
||||
|
||||
function restore(st) {
|
||||
const v = video;
|
||||
v.playbackRate = st.rate;
|
||||
v.volume = st.volume;
|
||||
v.muted = st.muted;
|
||||
const seek = () => {
|
||||
const d = v.duration;
|
||||
let t = st.time;
|
||||
if (isFinite(d) && d > 0) t = Math.min(t, Math.max(0, d - 5));
|
||||
if (t > 10) v.currentTime = t;
|
||||
if (st.playing) v.play().catch(() => {});
|
||||
};
|
||||
if (isFinite(v.duration) && v.duration > 0) seek();
|
||||
else v.addEventListener('loadedmetadata', seek, { once: true });
|
||||
}
|
||||
|
||||
function attachSubtitles(stream) {
|
||||
for (const sub of stream.subtitles || []) {
|
||||
let resolved;
|
||||
try {
|
||||
resolved = new URL(sub.url, stream.url).toString();
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
const track = document.createElement('track');
|
||||
track.kind = 'subtitles';
|
||||
track.srclang = sub.language || 'en';
|
||||
track.label = sub.name || sub.language || 'Subtitles';
|
||||
track.src = SR.api.proxyUrl(resolved, stream.headers);
|
||||
video.appendChild(track);
|
||||
}
|
||||
}
|
||||
|
||||
function load(stream, opts = {}) {
|
||||
const st = capture();
|
||||
const explicitResume = typeof opts.resumeAt === 'number' && opts.resumeAt > 10;
|
||||
if (typeof opts.resumeAt === 'number') st.time = Math.max(0, opts.resumeAt);
|
||||
const readyAt = () => (explicitResume ? st.time : 0);
|
||||
|
||||
teardown();
|
||||
networkRetry = false;
|
||||
const myToken = token;
|
||||
const guarded = (fn) => () => {
|
||||
if (myToken === token) fn();
|
||||
};
|
||||
|
||||
const url = stream.url || '';
|
||||
const isHls = stream.type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
|
||||
const isDash = stream.type === 'dash' || /\.mpd($|\?)/i.test(url);
|
||||
const isDirect =
|
||||
stream.type === 'mp4' ||
|
||||
stream.type === 'webm' ||
|
||||
/\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
|
||||
|
||||
if (isDash) {
|
||||
onError('DASH streams are not supported yet — pick another source.');
|
||||
return;
|
||||
}
|
||||
if (!isHls && !isDirect) {
|
||||
onError(`The browser can't play ${stream.type} files directly — pick an MP4 or HLS source.`);
|
||||
return;
|
||||
}
|
||||
|
||||
attachSubtitles(stream);
|
||||
const proxied = SR.api.proxyUrl(url, stream.headers);
|
||||
|
||||
if (isHls && window.Hls && Hls.isSupported()) {
|
||||
onStatus('Loading stream…');
|
||||
const h = new Hls({ enableWorker: true });
|
||||
hls = h;
|
||||
h.loadSource(proxied);
|
||||
h.attachMedia(video);
|
||||
h.on(Hls.Events.MANIFEST_PARSED, guarded(() => {
|
||||
restore(st);
|
||||
onReady(readyAt());
|
||||
}));
|
||||
h.on(Hls.Events.ERROR, (evt, data) => {
|
||||
if (myToken !== token || !data.fatal) return;
|
||||
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
|
||||
if (!networkRetry) {
|
||||
networkRetry = true;
|
||||
setTimeout(() => {
|
||||
networkRetry = false;
|
||||
if (myToken === token && hls === h) h.startLoad();
|
||||
}, 2000);
|
||||
}
|
||||
} else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
|
||||
h.recoverMediaError();
|
||||
} else {
|
||||
onError('Playback failed: ' + (data.details || 'unknown stream error'));
|
||||
teardown();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// native HLS (Safari) or direct file
|
||||
onStatus('Loading stream…');
|
||||
video.src = proxied;
|
||||
video.addEventListener(
|
||||
'loadedmetadata',
|
||||
guarded(() => {
|
||||
restore(st);
|
||||
onReady(readyAt());
|
||||
}),
|
||||
{ once: true }
|
||||
);
|
||||
video.addEventListener(
|
||||
'error',
|
||||
guarded(() => {
|
||||
onError('Could not load this stream — try another source.');
|
||||
}),
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
teardown();
|
||||
}
|
||||
|
||||
return { load, destroy };
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.player = { create };
|
||||
})();
|
||||
@@ -0,0 +1,305 @@
|
||||
/*
|
||||
router.js — single-page router with clean paths + hash fallback.
|
||||
|
||||
Modes (decided once at boot by the inline script in index.html, recomputed here if absent):
|
||||
history /title/tv/1399 (host rewrites unknown paths to index.html or 404.html)
|
||||
hash /#/title/tv/1399 (file://, /index.html, or a hash route present on load)
|
||||
|
||||
Views: every route lazily imports a module exporting
|
||||
render(root: HTMLElement, params) → cleanup function | void | Promise<cleanup|void>
|
||||
update?(params) → boolean (optional: handle a same-route change in place, e.g. ?q=)
|
||||
params = { ...pathParams (strings), query: URLSearchParams, path, route: name, signal: AbortSignal }
|
||||
The signal aborts when the user navigates away; cleanup is also called then.
|
||||
|
||||
Public API:
|
||||
navigate(path, { replace }), href(path) → string for <a href>, back(fallbackPath),
|
||||
current() → { path, name, params, query }, register(name, pattern, loader),
|
||||
onChange(fn) → unsubscribe, start(outlet), mode, root
|
||||
*/
|
||||
import { h } from './util.js';
|
||||
|
||||
const boot = window.__BUGTV_ROUTER || (() => {
|
||||
const meta = document.querySelector('meta[name="bug-tv-root"]');
|
||||
let root = meta && meta.content && !/^@.*@$/.test(meta.content) ? meta.content : '/';
|
||||
if (!root.endsWith('/')) root += '/';
|
||||
const hash = location.protocol === 'file:' || /\.html?$/i.test(location.pathname) || /^#\//.test(location.hash);
|
||||
return { mode: hash ? 'hash' : 'history', root };
|
||||
})();
|
||||
|
||||
export const mode = boot.mode;
|
||||
export const root = boot.root;
|
||||
|
||||
const routes = [];
|
||||
const listeners = new Set();
|
||||
let outlet = null;
|
||||
let active = null; // { route, mod, cleanup, controller, token }
|
||||
let token = 0;
|
||||
|
||||
function compile(pattern) {
|
||||
const keys = [];
|
||||
const src = pattern
|
||||
.replace(/\/+$/, '')
|
||||
.split('/')
|
||||
.map((seg) => {
|
||||
if (!seg) return '';
|
||||
const m = seg.match(/^:(\w+)(\?)?$/);
|
||||
if (!m) return `/${seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`;
|
||||
keys.push(m[1]);
|
||||
return m[2] ? '(?:/([^/]+))?' : '/([^/]+)';
|
||||
})
|
||||
.join('');
|
||||
return { re: new RegExp(`^${src || ''}/?$`), keys };
|
||||
}
|
||||
|
||||
export function register(name, pattern, loader, defaults = {}) {
|
||||
const { re, keys } = compile(pattern);
|
||||
routes.push({ name, pattern, re, keys, loader, defaults });
|
||||
}
|
||||
|
||||
// Built-in routes. The watch view is owned by the player workstream.
|
||||
register('home', '/', () => import('./views/home.js'));
|
||||
register('movies', '/movies', () => import('./views/home.js'), { kind: 'movie' });
|
||||
register('tv', '/tv', () => import('./views/home.js'), { kind: 'tv' });
|
||||
register('title', '/title/:type/:id', () => import('./views/title.js'));
|
||||
register('watch', '/watch/:type/:id/:season?/:episode?', () => import('./views/watch.js'));
|
||||
register('search', '/search', () => import('./views/search.js'));
|
||||
register('list', '/list', () => import('./views/list.js'));
|
||||
register('browse', '/browse/:type', () => import('./views/browse.js'));
|
||||
register('settings', '/settings', () => import('./views/settings.js'));
|
||||
|
||||
function match(path) {
|
||||
for (const r of routes) {
|
||||
const m = r.re.exec(path);
|
||||
if (!m) continue;
|
||||
const params = { ...r.defaults };
|
||||
r.keys.forEach((k, i) => {
|
||||
if (m[i + 1] !== undefined) params[k] = decodeURIComponent(m[i + 1]);
|
||||
});
|
||||
return { route: r, params };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Current app location → { path, search }
|
||||
function location_() {
|
||||
if (mode === 'hash') {
|
||||
const raw = location.hash.replace(/^#/, '') || '/';
|
||||
const i = raw.indexOf('?');
|
||||
return { path: i >= 0 ? raw.slice(0, i) || '/' : raw, search: i >= 0 ? raw.slice(i) : '' };
|
||||
}
|
||||
let p = location.pathname;
|
||||
if (p.startsWith(root)) p = `/${p.slice(root.length)}`;
|
||||
else if (`${p}/` === root) p = '/';
|
||||
return { path: p || '/', search: location.search };
|
||||
}
|
||||
|
||||
export function href(path) {
|
||||
const p = String(path || '/');
|
||||
if (mode === 'hash') return `#${p.startsWith('/') ? p : `/${p}`}`;
|
||||
return root + p.replace(/^\/+/, '');
|
||||
}
|
||||
|
||||
export function current() {
|
||||
const { path, search } = location_();
|
||||
const m = match(path);
|
||||
return { path, name: m ? m.route.name : null, params: m ? m.params : {}, query: new URLSearchParams(search) };
|
||||
}
|
||||
|
||||
export function onChange(fn) {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
}
|
||||
|
||||
function saveScroll() {
|
||||
try {
|
||||
history.replaceState({ ...(history.state || {}), scrollY: window.scrollY }, '');
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function navigate(path, opts = {}) {
|
||||
const target = String(path || '/');
|
||||
const cur = location_();
|
||||
if (!opts.replace && target === cur.path + cur.search) return;
|
||||
if (!opts.replace) {
|
||||
saveScroll();
|
||||
depth++;
|
||||
}
|
||||
if (mode === 'hash') {
|
||||
const url = `${location.href.split('#')[0]}#${target}`;
|
||||
if (opts.replace) history.replaceState({}, '', url);
|
||||
else history.pushState({}, '', url);
|
||||
} else {
|
||||
const url = href(target);
|
||||
if (opts.replace) history.replaceState({}, '', url);
|
||||
else history.pushState({}, '', url);
|
||||
}
|
||||
resolve({ scroll: opts.replace ? 'keep' : 'top' });
|
||||
}
|
||||
|
||||
let depth = 0; // in-app history entries we pushed (best effort)
|
||||
|
||||
export function back(fallback = '/') {
|
||||
if (depth > 0) history.back();
|
||||
else navigate(fallback, { replace: true });
|
||||
}
|
||||
|
||||
function errorView(title, detail) {
|
||||
return h('section.page.page--center',
|
||||
h('div.empty',
|
||||
h('div.empty__icon', '!'),
|
||||
h('h1.empty__title', title),
|
||||
detail ? h('p.empty__text', detail) : null,
|
||||
h('a.btn.btn--primary', { href: href('/') }, 'Back to home')));
|
||||
}
|
||||
|
||||
async function resolve({ scroll = 'top' } = {}) {
|
||||
if (!outlet) return;
|
||||
const loc = location_();
|
||||
// legacy v4 URLs (watch.html?id=&type=&s=&e=, search.html?q=)
|
||||
const legacy = legacyRedirect(loc);
|
||||
if (legacy) {
|
||||
navigate(legacy, { replace: true });
|
||||
return;
|
||||
}
|
||||
const m = match(loc.path);
|
||||
const query = new URLSearchParams(loc.search);
|
||||
const my = ++token;
|
||||
|
||||
// same route + view supports in-place update (e.g. search ?q= typing)
|
||||
if (m && active && active.route === m.route && active.mod && typeof active.mod.update === 'function') {
|
||||
const handled = active.mod.update({ ...m.params, query, path: loc.path, route: m.route.name, signal: active.controller.signal });
|
||||
if (handled) {
|
||||
emit(m, loc);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (active) {
|
||||
try {
|
||||
active.controller.abort();
|
||||
if (typeof active.cleanup === 'function') active.cleanup();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
active = null;
|
||||
}
|
||||
|
||||
document.body.dataset.route = m ? m.route.name : 'notfound';
|
||||
emit(m, loc);
|
||||
outlet.replaceChildren();
|
||||
outlet.setAttribute('aria-busy', 'true');
|
||||
if (scroll !== 'keep') window.scrollTo(0, 0);
|
||||
|
||||
if (!m) {
|
||||
outlet.replaceChildren(errorView('Page not found', 'That page does not exist.'));
|
||||
outlet.removeAttribute('aria-busy');
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const entry = { route: m.route, mod: null, cleanup: null, controller };
|
||||
active = entry;
|
||||
let mod;
|
||||
try {
|
||||
mod = await m.route.loader();
|
||||
} catch (e) {
|
||||
if (my !== token) return;
|
||||
console.error(e);
|
||||
outlet.replaceChildren(
|
||||
errorView(
|
||||
m.route.name === 'watch' ? 'Player unavailable' : 'Could not load this page',
|
||||
m.route.name === 'watch' ? 'The player module is not installed yet.' : String(e && e.message ? e.message : e),
|
||||
),
|
||||
);
|
||||
outlet.removeAttribute('aria-busy');
|
||||
return;
|
||||
}
|
||||
if (my !== token) return;
|
||||
entry.mod = mod;
|
||||
const params = { ...m.params, query, path: loc.path, route: m.route.name, signal: controller.signal };
|
||||
try {
|
||||
if (typeof mod.render !== 'function') throw new Error('view has no render()');
|
||||
const result = await mod.render(outlet, params);
|
||||
if (my !== token || controller.signal.aborted) {
|
||||
if (typeof result === 'function') result();
|
||||
return;
|
||||
}
|
||||
entry.cleanup = result;
|
||||
} catch (e) {
|
||||
if (my !== token) return;
|
||||
console.error(e);
|
||||
outlet.replaceChildren(errorView('Something went wrong', String(e && e.message ? e.message : e)));
|
||||
}
|
||||
outlet.removeAttribute('aria-busy');
|
||||
if (scroll === 'restore' && history.state && history.state.scrollY) {
|
||||
const y = history.state.scrollY;
|
||||
requestAnimationFrame(() => window.scrollTo(0, y));
|
||||
setTimeout(() => window.scrollTo(0, y), 400);
|
||||
}
|
||||
}
|
||||
|
||||
function emit(m, loc) {
|
||||
const info = { path: loc.path, name: m ? m.route.name : null, params: m ? m.params : {}, query: new URLSearchParams(loc.search) };
|
||||
for (const fn of listeners) {
|
||||
try {
|
||||
fn(info);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function legacyRedirect(loc) {
|
||||
const p = loc.path.replace(/\/+$/, '');
|
||||
if (/\/watch\.html$/.test(p)) {
|
||||
const q = new URLSearchParams(loc.search);
|
||||
const id = q.get('id');
|
||||
const type = q.get('type') === 'tv' ? 'tv' : 'movie';
|
||||
if (!id) return '/';
|
||||
return type === 'tv' ? `/watch/tv/${id}/${q.get('s') || 1}/${q.get('e') || 1}` : `/watch/movie/${id}`;
|
||||
}
|
||||
if (/\/search\.html$/.test(p)) return `/search${loc.search}`;
|
||||
if (/\/settings\.html$/.test(p)) return '/settings';
|
||||
if (/\/(index|404)\.html$/.test(p) && mode === 'history') return `/${loc.search}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
function onClick(e) {
|
||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
const a = e.target.closest && e.target.closest('a[href]');
|
||||
if (!a || a.target === '_blank' || a.hasAttribute('download') || a.dataset.native != null) return;
|
||||
const raw = a.getAttribute('href');
|
||||
if (mode === 'hash') return; // "#/…" links navigate natively via hashchange
|
||||
let url;
|
||||
try {
|
||||
url = new URL(a.href, location.href);
|
||||
} catch (err) {
|
||||
return;
|
||||
}
|
||||
if (url.origin !== location.origin || !url.pathname.startsWith(root) || raw.startsWith('#')) return;
|
||||
if (/\.[a-z0-9]{2,5}$/i.test(url.pathname) && !/\/(index|404)\.html$/.test(url.pathname)) return;
|
||||
e.preventDefault();
|
||||
navigate(`/${url.pathname.slice(root.length)}${url.search}`);
|
||||
}
|
||||
|
||||
export function start(el) {
|
||||
outlet = el;
|
||||
if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
|
||||
document.addEventListener('click', onClick);
|
||||
if (mode === 'hash') {
|
||||
// covers <a href="#/…"> clicks and back/forward (pushState itself fires nothing)
|
||||
window.addEventListener('hashchange', () => {
|
||||
if (history.state && history.state.scrollY != null) depth = Math.max(0, depth - 1);
|
||||
else depth++;
|
||||
resolve({ scroll: 'restore' });
|
||||
});
|
||||
} else {
|
||||
window.addEventListener('popstate', () => {
|
||||
depth = Math.max(0, depth - 1);
|
||||
resolve({ scroll: 'restore' });
|
||||
});
|
||||
}
|
||||
resolve({ scroll: 'keep' });
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
SEARCH — debounced live search with client-side type filter.
|
||||
URL ?q= is kept in sync so results are shareable/bookmarkable.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const input = document.getElementById('searchInput');
|
||||
const chipsEl = document.getElementById('typeChips');
|
||||
const resultsEl = document.getElementById('results');
|
||||
const countEl = document.getElementById('searchCount');
|
||||
|
||||
const state = { type: 'all', results: [] };
|
||||
|
||||
function render() {
|
||||
resultsEl.replaceChildren();
|
||||
const filtered = state.type === 'all' ? state.results : state.results.filter((i) => i.type === state.type);
|
||||
if (!state.results.length) {
|
||||
countEl.textContent = '';
|
||||
resultsEl.appendChild(
|
||||
SR.cards.emptyState('Nothing found', 'Check the spelling or try a different name.')
|
||||
);
|
||||
return;
|
||||
}
|
||||
countEl.textContent = `${filtered.length} of ${state.results.length} result${state.results.length === 1 ? '' : 's'}`;
|
||||
if (!filtered.length) {
|
||||
resultsEl.appendChild(SR.cards.emptyState('No matches for this filter', 'Try the All filter, or a different search.'));
|
||||
return;
|
||||
}
|
||||
resultsEl.appendChild(SR.cards.grid(filtered));
|
||||
}
|
||||
|
||||
async function runSearch(q) {
|
||||
q = (q || '').trim();
|
||||
if (!q) {
|
||||
state.results = [];
|
||||
countEl.textContent = '';
|
||||
resultsEl.replaceChildren(SR.cards.emptyState('Search the catalog', 'Type a movie or show name above.'));
|
||||
return;
|
||||
}
|
||||
countEl.textContent = 'Searching…';
|
||||
try {
|
||||
const data = await SR.api.search(q);
|
||||
state.results = data.results.map(SR.cards.normalizeItem);
|
||||
render();
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'search failed');
|
||||
countEl.textContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
const LABELS = { all: 'All', movie: 'Movies', tv: 'TV' };
|
||||
for (const t of ['all', 'movie', 'tv']) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = t === 'all' ? 'chip chip--active' : 'chip';
|
||||
b.textContent = LABELS[t];
|
||||
b.addEventListener('click', () => {
|
||||
state.type = t;
|
||||
for (const c of chipsEl.querySelectorAll('.chip')) c.classList.remove('chip--active');
|
||||
b.classList.add('chip--active');
|
||||
render();
|
||||
});
|
||||
chipsEl.appendChild(b);
|
||||
}
|
||||
|
||||
input.addEventListener(
|
||||
'input',
|
||||
SR.util.debounce(() => {
|
||||
const q = input.value.trim();
|
||||
history.replaceState(null, '', q ? `?q=${encodeURIComponent(q)}` : 'search.html');
|
||||
runSearch(q);
|
||||
}, 450)
|
||||
);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
runSearch(input.value.trim());
|
||||
}
|
||||
});
|
||||
|
||||
const initialQ = SR.util.getParam('q') || '';
|
||||
input.value = initialQ;
|
||||
if (initialQ) runSearch(initialQ);
|
||||
else input.focus();
|
||||
})();
|
||||
@@ -1,187 +0,0 @@
|
||||
/*
|
||||
SETTINGS — source provider toggles, API server base URL, TMDB key, local data.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const providerList = document.getElementById('providerList');
|
||||
const providersStatus = document.getElementById('providersStatus');
|
||||
const apiBaseInput = document.getElementById('apiBaseInput');
|
||||
const connStatus = document.getElementById('connStatus');
|
||||
const tmdbKeyInput = document.getElementById('tmdbKeyInput');
|
||||
const tmdbStatus = document.getElementById('tmdbStatus');
|
||||
const dataStatus = document.getElementById('dataStatus');
|
||||
|
||||
/* ---- nav --------------------------------------------------------------------- */
|
||||
|
||||
const navlinks = Array.from(document.querySelectorAll('.settings__navlink'));
|
||||
navlinks.forEach((link) => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const target = document.querySelector(link.getAttribute('href'));
|
||||
if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
navlinks.forEach((l) => l.classList.toggle('is-active', l === link));
|
||||
history.replaceState(null, '', link.getAttribute('href'));
|
||||
});
|
||||
});
|
||||
|
||||
/* ---- sources ------------------------------------------------------------------- */
|
||||
|
||||
let allProviders = [];
|
||||
let serverEnabled = [];
|
||||
const boxes = new Map(); // provider name -> checkbox
|
||||
|
||||
function setStatus(el, message, kind) {
|
||||
el.textContent = message || '';
|
||||
el.className =
|
||||
kind === 'ok' ? 'settings__status settings__status--ok'
|
||||
: kind === 'err' ? 'settings__status settings__status--err'
|
||||
: 'settings__status';
|
||||
}
|
||||
|
||||
function currentMap() {
|
||||
const map = {};
|
||||
for (const [name, box] of boxes) map[name] = box.checked;
|
||||
return map;
|
||||
}
|
||||
|
||||
function persist(map, message) {
|
||||
SR.config.setProviders(map);
|
||||
if (message) setStatus(providersStatus, message);
|
||||
}
|
||||
|
||||
function renderProviders() {
|
||||
providerList.replaceChildren();
|
||||
boxes.clear();
|
||||
const overrides = SR.config.getProviders();
|
||||
const enabled = SR.config.enabledProviders(allProviders, serverEnabled);
|
||||
for (const name of allProviders) {
|
||||
const checked = enabled.includes(name);
|
||||
const label = document.createElement('label');
|
||||
label.className = 'provider';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'checkbox';
|
||||
input.checked = !!checked;
|
||||
const nameEl = document.createElement('span');
|
||||
nameEl.className = 'provider__name';
|
||||
nameEl.textContent = name;
|
||||
label.append(input, nameEl);
|
||||
input.addEventListener('change', () =>
|
||||
persist(currentMap(), input.checked ? `${name} enabled` : `${name} disabled`));
|
||||
boxes.set(name, input);
|
||||
providerList.appendChild(label);
|
||||
}
|
||||
const on = boxes.size ? Array.from(boxes.values()).filter((b) => b.checked).length : 0;
|
||||
const source = overrides ? 'your selection' : 'default sources';
|
||||
let host;
|
||||
try { host = new URL(SR.config.getBase()).host; } catch (e) { host = SR.config.getBase(); }
|
||||
setStatus(providersStatus, `${on} of ${allProviders.length} enabled — ${source} · ${host}`);
|
||||
}
|
||||
|
||||
function resetProviders(message) {
|
||||
SR.config.clearProviders();
|
||||
renderProviders();
|
||||
if (message) setStatus(providersStatus, message);
|
||||
}
|
||||
|
||||
document.getElementById('allOn').addEventListener('click', () => {
|
||||
if (!boxes.size) return;
|
||||
for (const box of boxes.values()) box.checked = true;
|
||||
persist(currentMap(), 'All sources enabled');
|
||||
});
|
||||
|
||||
document.getElementById('allOff').addEventListener('click', () => {
|
||||
if (!boxes.size) return;
|
||||
for (const box of boxes.values()) box.checked = false;
|
||||
persist(currentMap(), 'All sources disabled');
|
||||
});
|
||||
|
||||
document.getElementById('providersReset').addEventListener('click', () =>
|
||||
resetProviders('Using default sources'));
|
||||
|
||||
async function initSources() {
|
||||
try {
|
||||
const data = await SR.api.providers();
|
||||
allProviders = data.all || [];
|
||||
serverEnabled = data.enabled || [];
|
||||
renderProviders();
|
||||
} catch (e) {
|
||||
setStatus(providersStatus, `Could not load the provider list: ${e.message}`, 'err');
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- server ----------------------------------------------------------------------- */
|
||||
|
||||
apiBaseInput.value = SR.config.getBase();
|
||||
|
||||
async function testConnection() {
|
||||
try {
|
||||
const data = await SR.api.providers();
|
||||
setStatus(connStatus, `Connected — ${data.all ? data.all.length : 0} provider(s) known.`, 'ok');
|
||||
return true;
|
||||
} catch (e) {
|
||||
setStatus(connStatus, `Not reachable: ${e.message}`, 'err');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('apiBaseSave').addEventListener('click', async () => {
|
||||
SR.config.setBase(apiBaseInput.value);
|
||||
apiBaseInput.value = SR.config.getBase();
|
||||
SR.app.initChrome(); // refresh the footer label
|
||||
if (await testConnection()) SR.app.toast('API base URL saved');
|
||||
});
|
||||
|
||||
document.getElementById('apiBaseReset').addEventListener('click', async () => {
|
||||
SR.config.clearBase();
|
||||
apiBaseInput.value = SR.config.getBase();
|
||||
SR.app.initChrome();
|
||||
await testConnection();
|
||||
});
|
||||
|
||||
/* ---- TMDB key ------------------------------------------------------------------- */
|
||||
|
||||
tmdbKeyInput.value = SR.config.getTmdbKey();
|
||||
|
||||
async function testTmdbKey(key) {
|
||||
setStatus(tmdbStatus, 'Testing TMDB key…');
|
||||
try {
|
||||
await SR.api.tmdb('/search/movie', { query: 'The Matrix', page: 1 }, key);
|
||||
setStatus(tmdbStatus, 'TMDB key works — search, details and images load directly from TMDB.', 'ok');
|
||||
} catch (e) {
|
||||
setStatus(tmdbStatus, e.message, 'err');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('tmdbKeySave').addEventListener('click', async () => {
|
||||
SR.config.setTmdbKey(tmdbKeyInput.value);
|
||||
tmdbKeyInput.value = SR.config.getTmdbKey();
|
||||
await testTmdbKey(SR.config.getTmdbKey());
|
||||
});
|
||||
|
||||
document.getElementById('tmdbKeyTest').addEventListener('click', async () => {
|
||||
await testTmdbKey(tmdbKeyInput.value.trim());
|
||||
});
|
||||
|
||||
document.getElementById('tmdbKeyReset').addEventListener('click', async () => {
|
||||
SR.config.clearTmdbKey();
|
||||
tmdbKeyInput.value = SR.config.getTmdbKey();
|
||||
await testTmdbKey(SR.config.getTmdbKey());
|
||||
});
|
||||
|
||||
/* ---- data ---------------------------------------------------------------------------- */
|
||||
|
||||
document.getElementById('clearHistory').addEventListener('click', () => {
|
||||
SR.storage.clear();
|
||||
setStatus(dataStatus, 'Continue-watching history cleared.');
|
||||
});
|
||||
|
||||
document.getElementById('resetProviders').addEventListener('click', () => {
|
||||
resetProviders('');
|
||||
setStatus(dataStatus, 'Source toggles reset to default sources.');
|
||||
});
|
||||
|
||||
initSources();
|
||||
})();
|
||||
+150
-71
@@ -1,91 +1,170 @@
|
||||
/*
|
||||
STORAGE — resume points, kept in localStorage (survives restarts, no size
|
||||
worries like cookies, no per-request overhead).
|
||||
storage.js — resume points, My List and preferences in localStorage.
|
||||
|
||||
A "record" looks like:
|
||||
{
|
||||
key: "m:603" | "t:1396:s1:e2",
|
||||
type: "movie" | "tv",
|
||||
tmdbId: 1396,
|
||||
season: 1, // tv only
|
||||
episode: 2, // tv only
|
||||
show: "Show name",
|
||||
title: "Episode name", // tv only
|
||||
poster: "https://…/w342/…",
|
||||
t: 934.2, // seconds played
|
||||
d: 2710.5, // duration seconds
|
||||
at: 1712345678901,
|
||||
provider: "cineby"
|
||||
}
|
||||
Resume record (key bug-tv.resume.v1, unchanged from v4):
|
||||
{ key: "m:603" | "t:1396:s1:e2", type: "movie"|"tv", tmdbId, season?, episode?,
|
||||
show: "Show name", title?: "Episode name", poster: "https://…/w342/…",
|
||||
backdrop?: "https://…/w780/…", still?: "https://…/w300/…",
|
||||
t: seconds played, d: duration seconds, at: epoch ms, provider? }
|
||||
|
||||
One record per (movie) or (show, season, episode). The home page collapses
|
||||
to the most recent record per show.
|
||||
My List item (key bug-tv.mylist.v1):
|
||||
{ type, id, title, poster_path, backdrop_path, year, rating, addedAt }
|
||||
|
||||
Prefs (key bug-tv.prefs.v1): free-form { name: value }. Names used by the UI:
|
||||
subtitleLang ("" = off, "en", …), autoplayNext (bool, default true), volume (0..1), muted.
|
||||
|
||||
Every mutation dispatches a window event so views can refresh:
|
||||
"bugtv:resume", "bugtv:mylist", "bugtv:prefs" (detail = { key? / item? / name? })
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
import { safe } from './util.js';
|
||||
|
||||
const KEY = 'bug-tv.resume.v1';
|
||||
const MAX_RECORDS = 200;
|
||||
const RESUME_KEY = 'bug-tv.resume.v1';
|
||||
const LIST_KEY = 'bug-tv.mylist.v1';
|
||||
const PREFS_KEY = 'bug-tv.prefs.v1';
|
||||
const MAX_RECORDS = 200;
|
||||
|
||||
function readAll() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(KEY) || '{}');
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function readObj(key) {
|
||||
const parsed = safe(() => JSON.parse(localStorage.getItem(key) || '{}'), {});
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
}
|
||||
|
||||
function writeAll(all) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(all));
|
||||
} catch (e) {
|
||||
/* storage full/blocked — resume just won't persist */
|
||||
}
|
||||
}
|
||||
function writeObj(key, obj) {
|
||||
safe(() => localStorage.setItem(key, JSON.stringify(obj)));
|
||||
}
|
||||
|
||||
function keyFor({ type, tmdbId, season, episode }) {
|
||||
return type === 'tv' ? `t:${tmdbId}:s${season}:e${episode}` : `m:${tmdbId}`;
|
||||
}
|
||||
function emit(name, detail) {
|
||||
safe(() => window.dispatchEvent(new CustomEvent(name, { detail })));
|
||||
}
|
||||
|
||||
function get(key) {
|
||||
return readAll()[key] || null;
|
||||
}
|
||||
export function keyFor({ type, tmdbId, season, episode }) {
|
||||
return type === 'tv' ? `t:${tmdbId}:s${season}:e${episode}` : `m:${tmdbId}`;
|
||||
}
|
||||
|
||||
function save(record) {
|
||||
const all = readAll();
|
||||
all[record.key] = record;
|
||||
export const resume = {
|
||||
KEY: RESUME_KEY,
|
||||
keyFor,
|
||||
get(key) {
|
||||
return readObj(RESUME_KEY)[key] || null;
|
||||
},
|
||||
save(record) {
|
||||
if (!record || !record.key) return;
|
||||
const all = readObj(RESUME_KEY);
|
||||
all[record.key] = { ...record, at: record.at || Date.now() };
|
||||
const keys = Object.keys(all).sort((a, b) => (all[a].at || 0) - (all[b].at || 0));
|
||||
while (keys.length > MAX_RECORDS) delete all[keys.shift()];
|
||||
writeAll(all);
|
||||
}
|
||||
|
||||
function remove(key) {
|
||||
const all = readAll();
|
||||
writeObj(RESUME_KEY, all);
|
||||
emit('bugtv:resume', { key: record.key });
|
||||
},
|
||||
remove(key) {
|
||||
const all = readObj(RESUME_KEY);
|
||||
if (all[key]) {
|
||||
delete all[key];
|
||||
writeAll(all);
|
||||
writeObj(RESUME_KEY, all);
|
||||
emit('bugtv:resume', { key });
|
||||
}
|
||||
}
|
||||
|
||||
function clear() {
|
||||
writeAll({});
|
||||
}
|
||||
|
||||
function list() {
|
||||
return Object.values(readAll());
|
||||
}
|
||||
|
||||
},
|
||||
// remove every record of a movie/show
|
||||
removeShow(type, tmdbId) {
|
||||
const all = readObj(RESUME_KEY);
|
||||
let changed = false;
|
||||
for (const [k, r] of Object.entries(all)) {
|
||||
if (r && r.type === type && String(r.tmdbId) === String(tmdbId)) {
|
||||
delete all[k];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
writeObj(RESUME_KEY, all);
|
||||
emit('bugtv:resume', {});
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
writeObj(RESUME_KEY, {});
|
||||
emit('bugtv:resume', {});
|
||||
},
|
||||
list() {
|
||||
return Object.values(readObj(RESUME_KEY)).filter((r) => r && r.key);
|
||||
},
|
||||
// records of one movie/show, newest first
|
||||
forShow(type, tmdbId) {
|
||||
return resume
|
||||
.list()
|
||||
.filter((r) => r.type === type && String(r.tmdbId) === String(tmdbId))
|
||||
.sort((a, b) => (b.at || 0) - (a.at || 0));
|
||||
},
|
||||
// one entry per movie/show: the most recently watched record wins
|
||||
function latestPerShow() {
|
||||
latestPerShow() {
|
||||
const byShow = new Map();
|
||||
for (const rec of list().sort((a, b) => (a.at || 0) - (b.at || 0))) {
|
||||
const showKey = rec.type === 'tv' ? `t:${rec.tmdbId}` : `m:${rec.tmdbId}`;
|
||||
byShow.set(showKey, rec);
|
||||
for (const rec of resume.list().sort((a, b) => (a.at || 0) - (b.at || 0))) {
|
||||
byShow.set(`${rec.type === 'tv' ? 't' : 'm'}:${rec.tmdbId}`, rec);
|
||||
}
|
||||
return [...byShow.values()].sort((a, b) => (b.at || 0) - (a.at || 0));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.storage = { KEY, keyFor, get, save, remove, clear, list, latestPerShow };
|
||||
})();
|
||||
// fraction watched 0..1 for a record (0 when unknown)
|
||||
export function progressOf(rec) {
|
||||
return rec && rec.d > 0 ? Math.min(1, Math.max(0, rec.t / rec.d)) : 0;
|
||||
}
|
||||
|
||||
export const myList = {
|
||||
KEY: LIST_KEY,
|
||||
_all() {
|
||||
return readObj(LIST_KEY);
|
||||
},
|
||||
has(type, id) {
|
||||
return !!myList._all()[`${type}:${id}`];
|
||||
},
|
||||
// item: { type, id, title, poster_path?, backdrop_path?, year?, rating? } → returns new state
|
||||
toggle(item) {
|
||||
const all = myList._all();
|
||||
const k = `${item.type}:${item.id}`;
|
||||
let state;
|
||||
if (all[k]) {
|
||||
delete all[k];
|
||||
state = false;
|
||||
} else {
|
||||
all[k] = {
|
||||
type: item.type,
|
||||
id: item.id,
|
||||
title: item.title || item.name || '',
|
||||
poster_path: item.poster_path || null,
|
||||
backdrop_path: item.backdrop_path || null,
|
||||
year: item.year || '',
|
||||
rating: item.rating || item.vote_average || 0,
|
||||
addedAt: Date.now(),
|
||||
};
|
||||
state = true;
|
||||
}
|
||||
writeObj(LIST_KEY, all);
|
||||
emit('bugtv:mylist', { type: item.type, id: item.id, state });
|
||||
return state;
|
||||
},
|
||||
remove(type, id) {
|
||||
const all = myList._all();
|
||||
if (all[`${type}:${id}`]) {
|
||||
delete all[`${type}:${id}`];
|
||||
writeObj(LIST_KEY, all);
|
||||
emit('bugtv:mylist', { type, id, state: false });
|
||||
}
|
||||
},
|
||||
// newest first
|
||||
all() {
|
||||
return Object.values(myList._all()).sort((a, b) => (b.addedAt || 0) - (a.addedAt || 0));
|
||||
},
|
||||
};
|
||||
|
||||
export const prefs = {
|
||||
KEY: PREFS_KEY,
|
||||
get(name, fallback) {
|
||||
const all = readObj(PREFS_KEY);
|
||||
return Object.prototype.hasOwnProperty.call(all, name) ? all[name] : fallback;
|
||||
},
|
||||
set(name, value) {
|
||||
const all = readObj(PREFS_KEY);
|
||||
if (value === undefined) delete all[name];
|
||||
else all[name] = value;
|
||||
writeObj(PREFS_KEY, all);
|
||||
emit('bugtv:prefs', { name, value });
|
||||
},
|
||||
};
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
tmdb.js — direct browser → TMDB client (CORS-enabled API), cached.
|
||||
|
||||
- In-memory promise cache for every request (dedupes concurrent callers).
|
||||
- sessionStorage cache (30 min) for list endpoints (trending/popular/discover/search/seasons…),
|
||||
so navigating back and forth is instant. Details stay memory-only (large payloads).
|
||||
|
||||
All functions resolve to raw TMDB JSON. List results get `media_type` filled in when the
|
||||
endpoint is type-specific, so cards always know whether an item is a movie or tv show.
|
||||
*/
|
||||
import { getTmdbKey } from './config.js';
|
||||
import { safe } from './util.js';
|
||||
|
||||
const API = 'https://api.themoviedb.org/3';
|
||||
export const IMG_BASE = 'https://image.tmdb.org/t/p/';
|
||||
const SESSION_PREFIX = 'bug-tv.tmdb.';
|
||||
const SESSION_TTL = 30 * 60 * 1000;
|
||||
|
||||
const mem = new Map();
|
||||
|
||||
function buildUrl(path, params) {
|
||||
const url = new URL(API + path);
|
||||
url.searchParams.set('api_key', getTmdbKey());
|
||||
if (!params || params.language === undefined) url.searchParams.set('language', 'en-US');
|
||||
for (const [k, v] of Object.entries(params || {})) {
|
||||
if (v === undefined || v === null || v === '') continue;
|
||||
url.searchParams.set(k, String(v));
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function cacheKey(path, params) {
|
||||
const p = new URLSearchParams();
|
||||
for (const k of Object.keys(params || {}).sort()) {
|
||||
const v = params[k];
|
||||
if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
|
||||
}
|
||||
return `${path}?${p}`;
|
||||
}
|
||||
|
||||
async function fetchJson(path, params, key) {
|
||||
const url = buildUrl(path, params);
|
||||
if (key) url.searchParams.set('api_key', key);
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url.toString());
|
||||
} catch (e) {
|
||||
throw new Error('Cannot reach TMDB — check your connection');
|
||||
}
|
||||
let data = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch (e) {
|
||||
/* non-JSON */
|
||||
}
|
||||
if (!res.ok) {
|
||||
const msg = (data && data.status_message) || `TMDB error: HTTP ${res.status}`;
|
||||
const err = new Error(res.status === 401 ? `TMDB key rejected: ${msg}` : msg);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// get(path, params, { session: bool })
|
||||
export function get(path, params = {}, opts = {}) {
|
||||
const ck = cacheKey(path, params);
|
||||
if (mem.has(ck)) return mem.get(ck);
|
||||
if (opts.session) {
|
||||
const hit = safe(() => JSON.parse(sessionStorage.getItem(SESSION_PREFIX + ck)), null);
|
||||
if (hit && hit.at && Date.now() - hit.at < SESSION_TTL && hit.data) {
|
||||
const p = Promise.resolve(hit.data);
|
||||
mem.set(ck, p);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
const p = fetchJson(path, params).then((data) => {
|
||||
if (opts.session) {
|
||||
safe(() => sessionStorage.setItem(SESSION_PREFIX + ck, JSON.stringify({ at: Date.now(), data })));
|
||||
}
|
||||
return data;
|
||||
});
|
||||
mem.set(ck, p);
|
||||
p.catch(() => mem.delete(ck));
|
||||
return p;
|
||||
}
|
||||
|
||||
// Validate a key without touching the cache (Settings "Test").
|
||||
export function testKey(key) {
|
||||
return fetchJson('/configuration', {}, key);
|
||||
}
|
||||
|
||||
function tag(type) {
|
||||
return (data) => {
|
||||
if (data && Array.isArray(data.results) && type && type !== 'all') {
|
||||
data.results.forEach((r) => {
|
||||
if (r && !r.media_type) r.media_type = type;
|
||||
});
|
||||
}
|
||||
return data;
|
||||
};
|
||||
}
|
||||
|
||||
const t = (type) => (type === 'tv' ? 'tv' : 'movie');
|
||||
|
||||
export function trending(type = 'all', window = 'day', page = 1) {
|
||||
const ty = type === 'all' ? 'all' : t(type);
|
||||
return get(`/trending/${ty}/${window === 'week' ? 'week' : 'day'}`, { page }, { session: true }).then(tag(ty));
|
||||
}
|
||||
|
||||
export function popular(type, page = 1) {
|
||||
return get(`/${t(type)}/popular`, { page }, { session: true }).then(tag(t(type)));
|
||||
}
|
||||
|
||||
export function topRated(type, page = 1) {
|
||||
return get(`/${t(type)}/top_rated`, { page }, { session: true }).then(tag(t(type)));
|
||||
}
|
||||
|
||||
export function discover(type, params = {}) {
|
||||
return get(`/discover/${t(type)}`, { sort_by: 'popularity.desc', ...params }, { session: true }).then(tag(t(type)));
|
||||
}
|
||||
|
||||
export function details(type, id) {
|
||||
const ty = t(type);
|
||||
const extra = ty === 'tv' ? 'content_ratings' : 'release_dates';
|
||||
return get(`/${ty}/${id}`, {
|
||||
append_to_response: `images,credits,similar,recommendations,external_ids,videos,${extra}`,
|
||||
include_image_language: 'en,null',
|
||||
}).then((d) => {
|
||||
if (d) {
|
||||
d.media_type = ty;
|
||||
if (d.similar) tag(ty)(d.similar);
|
||||
if (d.recommendations) tag(ty)(d.recommendations);
|
||||
}
|
||||
return d;
|
||||
});
|
||||
}
|
||||
|
||||
export function season(tvId, n) {
|
||||
return get(`/tv/${tvId}/season/${n}`, {}, { session: true });
|
||||
}
|
||||
|
||||
export function search(q, page = 1) {
|
||||
const query = String(q || '').trim();
|
||||
if (!query) return Promise.resolve({ results: [], total_results: 0, page: 1, total_pages: 0 });
|
||||
return get('/search/multi', { query, page, include_adult: 'false' }, { session: true }).then((d) => {
|
||||
d.results = (d.results || []).filter((r) => r.media_type === 'movie' || r.media_type === 'tv');
|
||||
return d;
|
||||
});
|
||||
}
|
||||
|
||||
export function genres(type) {
|
||||
return get(`/genre/${t(type)}/list`, {}, { session: true }).then((d) => {
|
||||
const map = {};
|
||||
for (const g of (d && d.genres) || []) map[g.id] = g.name;
|
||||
return map;
|
||||
});
|
||||
}
|
||||
|
||||
export function network(id) {
|
||||
return get(`/network/${id}`, {}, { session: true });
|
||||
}
|
||||
|
||||
export function company(id) {
|
||||
return get(`/company/${id}`, {}, { session: true });
|
||||
}
|
||||
|
||||
// Image URL helper: img('/abc.jpg', 'w342'); returns '' for missing paths.
|
||||
export function img(path, size = 'original') {
|
||||
if (!path) return '';
|
||||
if (/^https?:/i.test(path)) return path;
|
||||
return `${IMG_BASE}${size}${path}`;
|
||||
}
|
||||
|
||||
// srcset for responsive images: srcset('/abc.jpg', ['w300','w780','w1280'])
|
||||
export function srcset(path, sizes) {
|
||||
if (!path) return '';
|
||||
return sizes
|
||||
.map((s) => `${img(path, s)} ${s.replace(/^w/, '')}w`)
|
||||
.filter((s) => !/original/.test(s))
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/* ---- details helpers ---------------------------------------------------------------- */
|
||||
|
||||
// Best logo: English png first, then English, then language-neutral; null if none.
|
||||
export function logoFor(d) {
|
||||
const logos = (d && d.images && d.images.logos) || [];
|
||||
if (!logos.length) return null;
|
||||
const score = (l) =>
|
||||
(l.iso_639_1 === 'en' ? 4 : l.iso_639_1 == null ? 1 : 0) +
|
||||
(/\.png$/i.test(l.file_path) ? 2 : 0) +
|
||||
(l.vote_average || 0) / 20;
|
||||
const best = [...logos].sort((a, b) => score(b) - score(a))[0];
|
||||
return best && (best.iso_639_1 === 'en' || best.iso_639_1 == null) ? best : null;
|
||||
}
|
||||
|
||||
export function trailerFor(d) {
|
||||
const vids = ((d && d.videos && d.videos.results) || []).filter((v) => v.site === 'YouTube');
|
||||
const score = (v) =>
|
||||
(v.type === 'Trailer' ? 4 : v.type === 'Teaser' ? 2 : 0) + (v.official ? 1 : 0) + (v.iso_639_1 === 'en' ? 1 : 0);
|
||||
return vids.sort((a, b) => score(b) - score(a))[0] || null;
|
||||
}
|
||||
|
||||
export function certificationFor(d) {
|
||||
if (!d) return '';
|
||||
if (d.content_ratings) {
|
||||
const us = (d.content_ratings.results || []).find((r) => r.iso_3166_1 === 'US');
|
||||
return (us && us.rating) || '';
|
||||
}
|
||||
if (d.release_dates) {
|
||||
const us = (d.release_dates.results || []).find((r) => r.iso_3166_1 === 'US');
|
||||
const c = us && (us.release_dates || []).map((r) => r.certification).find(Boolean);
|
||||
return c || '';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// normalize any TMDB list result / details / my-list item into a card model
|
||||
export function toItem(r, typeHint) {
|
||||
if (!r) return null;
|
||||
const type = r.media_type === 'tv' || r.media_type === 'movie' ? r.media_type : r.type || typeHint || (r.first_air_date !== undefined ? 'tv' : 'movie');
|
||||
return {
|
||||
type: type === 'tv' ? 'tv' : 'movie',
|
||||
id: r.id,
|
||||
title: r.title || r.name || r.original_title || r.original_name || '',
|
||||
year: r.year || String(r.release_date || r.first_air_date || '').slice(0, 4),
|
||||
rating: Number(r.vote_average || r.rating || 0),
|
||||
poster_path: r.poster_path || null,
|
||||
backdrop_path: r.backdrop_path || null,
|
||||
overview: r.overview || '',
|
||||
genre_ids: r.genre_ids || (r.genres ? r.genres.map((g) => g.id) : []),
|
||||
};
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
+171
-58
@@ -1,70 +1,183 @@
|
||||
/*
|
||||
UTIL — small shared helpers. No dependencies.
|
||||
util.js — small shared helpers (no dependencies).
|
||||
|
||||
h(tag, attrs, ...children) builds DOM without innerHTML:
|
||||
h('a.card.card--wide', { href: '/x', onclick: fn, dataset: { id: 1 } }, 'text', node)
|
||||
- tag may carry .class and #id suffixes
|
||||
- attrs: class (string|array), style (string|object, supports --custom-props),
|
||||
dataset, on<event> functions, booleans (true → present, false/null → omitted),
|
||||
anything else → setAttribute. `attrs` may be omitted.
|
||||
- children: strings (text nodes — never parsed as HTML), nodes, arrays, null/false (skipped)
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? '' : value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
export function escapeHtml(value) {
|
||||
return String(value == null ? '' : value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
const SVG_TAGS = new Set(['svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'g']);
|
||||
|
||||
export function h(tag, attrs, ...children) {
|
||||
let name = 'div';
|
||||
const classes = [];
|
||||
let id = '';
|
||||
const m = String(tag).match(/^([a-z0-9-]*)((?:[.#][\w-]+)*)$/i);
|
||||
if (m) {
|
||||
name = m[1] || 'div';
|
||||
(m[2].match(/[.#][\w-]+/g) || []).forEach((p) => {
|
||||
if (p[0] === '.') classes.push(p.slice(1));
|
||||
else id = p.slice(1);
|
||||
});
|
||||
} else {
|
||||
name = tag;
|
||||
}
|
||||
|
||||
function getParam(name) {
|
||||
return new URLSearchParams(location.search).get(name);
|
||||
const isSvg = SVG_TAGS.has(name);
|
||||
const el = isSvg ? document.createElementNS(SVG_NS, name) : document.createElement(name);
|
||||
if (classes.length) el.setAttribute('class', classes.join(' '));
|
||||
if (id) el.id = id;
|
||||
if (attrs != null && (typeof attrs !== 'object' || attrs instanceof Node || Array.isArray(attrs))) {
|
||||
children.unshift(attrs);
|
||||
attrs = null;
|
||||
}
|
||||
|
||||
// 95 -> "1:35", 3675 -> "1:01:15"
|
||||
function formatSeconds(sec) {
|
||||
sec = Math.max(0, Math.floor(sec || 0));
|
||||
const h = Math.floor(sec / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
const s = sec % 60;
|
||||
const mm = h ? String(m).padStart(2, '0') : String(m);
|
||||
const ss = String(s).padStart(2, '0');
|
||||
return h ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
|
||||
if (attrs) {
|
||||
for (const [k, v] of Object.entries(attrs)) {
|
||||
if (v == null || v === false) continue;
|
||||
if (k === 'class' || k === 'className') {
|
||||
const extra = Array.isArray(v) ? v.filter(Boolean).join(' ') : String(v);
|
||||
if (extra) el.setAttribute('class', [el.getAttribute('class'), extra].filter(Boolean).join(' '));
|
||||
} else if (k === 'style') {
|
||||
if (typeof v === 'string') el.setAttribute('style', v);
|
||||
else {
|
||||
for (const [sk, sv] of Object.entries(v)) {
|
||||
if (sv == null) continue;
|
||||
if (sk.startsWith('--')) el.style.setProperty(sk, sv);
|
||||
else el.style[sk] = sv;
|
||||
}
|
||||
}
|
||||
} else if (k === 'dataset') {
|
||||
for (const [dk, dv] of Object.entries(v)) if (dv != null) el.dataset[dk] = dv;
|
||||
} else if (k.startsWith('on') && typeof v === 'function') {
|
||||
el.addEventListener(k.slice(2).toLowerCase(), v);
|
||||
} else if (k === 'text') {
|
||||
el.textContent = v;
|
||||
} else if (!isSvg && (k === 'value' || k === 'checked' || k === 'selected')) {
|
||||
el[k] = v;
|
||||
} else if (v === true) {
|
||||
el.setAttribute(k, '');
|
||||
} else {
|
||||
el.setAttribute(k, String(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
appendChildren(el, children);
|
||||
return el;
|
||||
}
|
||||
|
||||
// 141 -> "2h 21m"
|
||||
function runtimeLabel(mins) {
|
||||
if (!mins || mins <= 0) return '';
|
||||
const h = Math.floor(mins / 60);
|
||||
const m = mins % 60;
|
||||
return h ? (m ? `${h}h ${m}m` : `${h}h`) : `${m}m`;
|
||||
function appendChildren(el, children) {
|
||||
for (const c of children) {
|
||||
if (c == null || c === false || c === true) continue;
|
||||
if (Array.isArray(c)) appendChildren(el, c);
|
||||
else if (c instanceof Node) el.appendChild(c);
|
||||
else el.appendChild(document.createTextNode(String(c)));
|
||||
}
|
||||
}
|
||||
|
||||
function debounce(fn, wait) {
|
||||
let timer = null;
|
||||
return function (...args) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn.apply(this, args), wait);
|
||||
};
|
||||
export function clear(el) {
|
||||
if (el) el.replaceChildren();
|
||||
return el;
|
||||
}
|
||||
|
||||
// Reads a query param from the real query string or from a hash route (#/search?q=x).
|
||||
export function getParam(name) {
|
||||
const q = new URLSearchParams(location.search).get(name);
|
||||
if (q != null) return q;
|
||||
const hash = location.hash || '';
|
||||
const i = hash.indexOf('?');
|
||||
return i >= 0 ? new URLSearchParams(hash.slice(i + 1)).get(name) : null;
|
||||
}
|
||||
|
||||
// 95 -> "1:35", 3675 -> "1:01:15"
|
||||
export function formatSeconds(sec) {
|
||||
sec = Math.max(0, Math.floor(sec || 0));
|
||||
const hh = Math.floor(sec / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
const s = sec % 60;
|
||||
const mm = hh ? String(m).padStart(2, '0') : String(m);
|
||||
const ss = String(s).padStart(2, '0');
|
||||
return hh ? `${hh}:${mm}:${ss}` : `${mm}:${ss}`;
|
||||
}
|
||||
|
||||
// 141 -> "2h 21m"
|
||||
export function runtimeLabel(mins) {
|
||||
if (!mins || mins <= 0) return '';
|
||||
const hh = Math.floor(mins / 60);
|
||||
const m = Math.round(mins % 60);
|
||||
return hh ? (m ? `${hh}h ${m}m` : `${hh}h`) : `${m}m`;
|
||||
}
|
||||
|
||||
// seconds → "23m" / "1h 4m"
|
||||
export function durationLabel(sec) {
|
||||
return runtimeLabel(Math.max(1, Math.round((sec || 0) / 60)));
|
||||
}
|
||||
|
||||
export function yearOf(date) {
|
||||
return date ? String(date).slice(0, 4) : '';
|
||||
}
|
||||
|
||||
export function debounce(fn, wait) {
|
||||
let timer = null;
|
||||
const d = function (...args) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn.apply(this, args), wait);
|
||||
};
|
||||
d.cancel = () => clearTimeout(timer);
|
||||
return d;
|
||||
}
|
||||
|
||||
// resize a full TMDB image URL (…/t/p/<size>/path) to another size
|
||||
export function tmdbResize(url, size) {
|
||||
if (!url) return '';
|
||||
return String(url).replace(/\/t\/p\/[A-Za-z0-9._-]+/, `/t/p/${size}`);
|
||||
}
|
||||
|
||||
export function clamp(n, lo, hi) {
|
||||
return Math.min(hi, Math.max(lo, n));
|
||||
}
|
||||
|
||||
export function plural(n, word, pluralWord) {
|
||||
return `${n} ${n === 1 ? word : pluralWord || `${word}s`}`;
|
||||
}
|
||||
|
||||
// Kept from v4 for the player workstream.
|
||||
export function webPlayable(stream) {
|
||||
const s = stream || {};
|
||||
const url = String(s.url || '');
|
||||
if (!/^https?:\/\//i.test(url)) return false;
|
||||
const type = String(s.type || '').toLowerCase();
|
||||
if (['magnet', 'torrent', 'dash', 'mkv', 'avi'].includes(type)) return false;
|
||||
const isHls = type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
|
||||
const isDirect = type === 'mp4' || type === 'webm' || /\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
|
||||
return isHls || isDirect;
|
||||
}
|
||||
|
||||
export function reducedMotion() {
|
||||
try {
|
||||
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// resize a full TMDB image URL (…/t/p/<size>/path) to another size
|
||||
function tmdbResize(url, size) {
|
||||
if (!url) return '';
|
||||
return url.replace(/\/t\/p\/[A-Za-z0-9._-]+/, `/t/p/${size}`);
|
||||
// Swallow errors from storage access in private mode etc.
|
||||
export function safe(fn, fallback) {
|
||||
try {
|
||||
return fn();
|
||||
} catch (e) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// True when the in-browser player can load the stream through the proxy.
|
||||
function webPlayable(stream) {
|
||||
const s = stream || {};
|
||||
const url = String(s.url || '');
|
||||
if (!/^https?:\/\//i.test(url)) return false;
|
||||
const type = String(s.type || '').toLowerCase();
|
||||
if (['magnet', 'torrent', 'dash', 'mkv', 'avi'].includes(type)) return false;
|
||||
const isHls = type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
|
||||
const isDirect =
|
||||
type === 'mp4' ||
|
||||
type === 'webm' ||
|
||||
/\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
|
||||
return isHls || isDirect;
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.util = { escapeHtml, getParam, formatSeconds, runtimeLabel, debounce, tmdbResize, webPlayable };
|
||||
})();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
views/browse.js — /browse/:type?with_genres=&with_networks=&title= discover grid with infinite scroll.
|
||||
Without filters it lists popular titles of that type.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import * as tmdb from '../tmdb.js';
|
||||
import { posterCard, skeletonCard } from '../ui/card.js';
|
||||
|
||||
const PASS = ['with_genres', 'with_networks', 'with_companies', 'with_original_language', 'sort_by', 'with_keywords', 'first_air_date_year', 'primary_release_year'];
|
||||
|
||||
export function render(root, params) {
|
||||
const type = params.type === 'tv' ? 'tv' : 'movie';
|
||||
const q = params.query;
|
||||
const filters = {};
|
||||
PASS.forEach((k) => q.get(k) && (filters[k] = q.get(k)));
|
||||
const title = q.get('title') || (type === 'tv' ? 'Series' : 'Movies');
|
||||
document.title = `${title} · bug tv`;
|
||||
|
||||
const gridEl = h('div.grid', { role: 'list' });
|
||||
const sentinel = h('div.load-more');
|
||||
const status = h('p.muted.center');
|
||||
root.append(h('div.page.page--padded.container',
|
||||
h('div.page__head', h('div', h('p.page__eyebrow', type === 'tv' ? 'Series' : 'Movies'), h('h1.page__title', title))),
|
||||
gridEl, status, sentinel));
|
||||
|
||||
let page = 0;
|
||||
let total = 1;
|
||||
let loading = false;
|
||||
const seen = new Set();
|
||||
|
||||
async function more() {
|
||||
if (loading || page >= total || page >= 20) return;
|
||||
loading = true;
|
||||
const skels = Array.from({ length: 12 }, () => skeletonCard('poster'));
|
||||
gridEl.append(...skels);
|
||||
try {
|
||||
const next = page + 1;
|
||||
const d = Object.keys(filters).length
|
||||
? await tmdb.discover(type, { ...filters, page: next, 'vote_count.gte': filters.with_networks ? 20 : 50 })
|
||||
: await tmdb.popular(type, next);
|
||||
if (params.signal.aborted) return;
|
||||
page = next;
|
||||
total = d.total_pages || 1;
|
||||
skels.forEach((s) => s.remove());
|
||||
const items = (d.results || []).map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path && !seen.has(x.id) && seen.add(x.id));
|
||||
gridEl.append(...items.map((it) => posterCard(it)));
|
||||
if (!gridEl.children.length) status.textContent = 'Nothing found.';
|
||||
} catch (e) {
|
||||
skels.forEach((s) => s.remove());
|
||||
status.textContent = e.message;
|
||||
total = 0;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
// keep filling while the sentinel is still visible
|
||||
if (sentinel.getBoundingClientRect().top < window.innerHeight + 600) more();
|
||||
}
|
||||
|
||||
const io = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && more(), { rootMargin: '800px 0px' });
|
||||
io.observe(sentinel);
|
||||
more();
|
||||
return () => io.disconnect();
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
views/home.js — home (/), Movies (/movies) and TV (/tv) browse pages.
|
||||
params.kind: undefined | 'movie' | 'tv'
|
||||
*/
|
||||
import { h, durationLabel } from '../util.js';
|
||||
import * as tmdb from '../tmdb.js';
|
||||
import { href } from '../router.js';
|
||||
import { resume, myList, progressOf } from '../storage.js';
|
||||
import { billboard } from '../ui/hero.js';
|
||||
import { row } from '../ui/row.js';
|
||||
import { posterCard, wideCard, logoCard } from '../ui/card.js';
|
||||
import { watchHref } from '../ui/actions.js';
|
||||
import { toast } from '../ui/toast.js';
|
||||
|
||||
const NETWORKS = [
|
||||
{ id: 213, name: 'Netflix' },
|
||||
{ id: 49, name: 'HBO' },
|
||||
{ id: 2739, name: 'Disney+' },
|
||||
{ id: 2552, name: 'Apple TV+' },
|
||||
{ id: 1024, name: 'Prime Video' },
|
||||
{ id: 453, name: 'Hulu' },
|
||||
{ id: 4330, name: 'Paramount+' },
|
||||
{ id: 3186, name: 'HBO Max' },
|
||||
];
|
||||
|
||||
const GENRES = {
|
||||
all: [
|
||||
{ type: 'movie', id: 28, name: 'Action Movies' },
|
||||
{ type: 'tv', id: 10765, name: 'Sci-Fi & Fantasy Series' },
|
||||
{ type: 'movie', id: 35, name: 'Comedy Movies' },
|
||||
{ type: 'tv', id: 80, name: 'Crime Series' },
|
||||
{ type: 'movie', id: 16, name: 'Animation' },
|
||||
{ type: 'movie', id: 27, name: 'Horror' },
|
||||
],
|
||||
movie: [
|
||||
{ type: 'movie', id: 28, name: 'Action' },
|
||||
{ type: 'movie', id: 878, name: 'Science Fiction' },
|
||||
{ type: 'movie', id: 35, name: 'Comedy' },
|
||||
{ type: 'movie', id: 53, name: 'Thrillers' },
|
||||
{ type: 'movie', id: 16, name: 'Animation' },
|
||||
{ type: 'movie', id: 27, name: 'Horror' },
|
||||
{ type: 'movie', id: 10749, name: 'Romance' },
|
||||
{ type: 'movie', id: 99, name: 'Documentaries' },
|
||||
],
|
||||
tv: [
|
||||
{ type: 'tv', id: 18, name: 'Drama' },
|
||||
{ type: 'tv', id: 10765, name: 'Sci-Fi & Fantasy' },
|
||||
{ type: 'tv', id: 80, name: 'Crime' },
|
||||
{ type: 'tv', id: 35, name: 'Comedy' },
|
||||
{ type: 'tv', id: 16, name: 'Animation' },
|
||||
{ type: 'tv', id: 10759, name: 'Action & Adventure' },
|
||||
{ type: 'tv', id: 9648, name: 'Mystery' },
|
||||
{ type: 'tv', id: 99, name: 'Documentary' },
|
||||
],
|
||||
};
|
||||
|
||||
const items = (type) => (d) => ((d && d.results) || []).map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path || x.backdrop_path);
|
||||
const poster = (it) => posterCard(it);
|
||||
|
||||
// Continue Watching record → wide card, backdrop looked up lazily when the record has none
|
||||
function continueCard(rec, onRemoved) {
|
||||
const item = { type: rec.type, id: rec.tmdbId, title: rec.show || rec.title || '', backdrop_path: null, rating: 0 };
|
||||
const left = rec.d ? Math.max(0, rec.d - rec.t) : 0;
|
||||
const leftText = left ? `${durationLabel(left)} left` : '';
|
||||
const meta = rec.type === 'tv' ? [`S${rec.season} E${rec.episode}`, leftText].filter(Boolean).join(' · ') : leftText || 'Movie';
|
||||
const image = rec.backdrop || rec.still || null;
|
||||
const card = wideCard(item, {
|
||||
href: watchHref(rec.type, rec.tmdbId, rec.season, rec.episode),
|
||||
image: image || null,
|
||||
meta,
|
||||
kicker: rec.type === 'tv' && rec.title && rec.title !== rec.show ? rec.title : null,
|
||||
progress: progressOf(rec),
|
||||
onRemove: (el) => {
|
||||
resume.removeShow(rec.type, rec.tmdbId);
|
||||
el.remove();
|
||||
onRemoved();
|
||||
toast(`Removed “${item.title}” from Continue Watching`);
|
||||
},
|
||||
});
|
||||
if (!image) {
|
||||
tmdb.details(rec.type, rec.tmdbId).then((d) => {
|
||||
const path = d.backdrop_path || d.poster_path;
|
||||
if (!path) return;
|
||||
const media = card.querySelector('.card__media');
|
||||
const im = h('img.card__img', { src: tmdb.img(path, 'w780'), alt: '', loading: 'lazy', decoding: 'async', onload: (e) => e.target.classList.add('is-loaded') });
|
||||
media.insertBefore(im, media.querySelector('.card__shade'));
|
||||
}).catch(() => {});
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
export async function render(root, params) {
|
||||
const kind = params.kind === 'movie' || params.kind === 'tv' ? params.kind : null;
|
||||
document.title = kind === 'movie' ? 'Movies · bug tv' : kind === 'tv' ? 'Series · bug tv' : 'bug tv';
|
||||
|
||||
const heroSlot = h('div.hero-slot', h('div.hero.hero--loading', h('div.hero__skeleton.skeleton')));
|
||||
const rows = h('div.rows');
|
||||
root.append(h('div.page.page--home', heroSlot, rows));
|
||||
|
||||
let hero = null;
|
||||
const listeners = [];
|
||||
|
||||
// hero: top trending
|
||||
tmdb.trending(kind || 'all', 'day').then((d) => {
|
||||
if (params.signal.aborted) return;
|
||||
const list = items(kind)(d).filter((x) => x.backdrop_path && x.overview).slice(0, 5);
|
||||
const label = kind === 'movie' ? 'Movies' : kind === 'tv' ? 'TV Shows' : null;
|
||||
hero = billboard(list, {
|
||||
eyebrow: (i, it) => `#${i + 1} in ${label || (it.type === 'tv' ? 'TV Shows' : 'Movies')} Today`,
|
||||
});
|
||||
heroSlot.replaceChildren(hero.el);
|
||||
}).catch((e) => {
|
||||
heroSlot.replaceChildren();
|
||||
toast(e.message, { error: true });
|
||||
});
|
||||
|
||||
// Continue Watching
|
||||
const contRecords = () => resume.latestPerShow().filter((r) => !kind || r.type === kind).filter((r) => progressOf(r) < 0.97 || r.type === 'tv');
|
||||
const cont = row({
|
||||
title: 'Continue Watching',
|
||||
variant: 'wide',
|
||||
items: contRecords(),
|
||||
render: (rec) => continueCard(rec, () => { if (!cont.querySelector('.card')) cont.hidden = true; }),
|
||||
});
|
||||
rows.appendChild(cont);
|
||||
const onResume = () => cont.setItems(contRecords());
|
||||
window.addEventListener('bugtv:resume', onResume);
|
||||
listeners.push(['bugtv:resume', onResume]);
|
||||
|
||||
// My List
|
||||
const listItems = () => myList.all().filter((x) => !kind || x.type === kind).map((x) => tmdb.toItem(x, x.type));
|
||||
const mine = row({ title: 'My List', moreHref: href('/list'), items: listItems(), render: poster });
|
||||
rows.appendChild(mine);
|
||||
const onList = () => mine.setItems(listItems());
|
||||
window.addEventListener('bugtv:mylist', onList);
|
||||
listeners.push(['bugtv:mylist', onList]);
|
||||
|
||||
const add = (opts) => rows.appendChild(row(opts));
|
||||
|
||||
if (!kind) {
|
||||
add({ title: 'Trending Today', load: () => tmdb.trending('all', 'day').then(items()), render: (it, i) => posterCard(it, { rank: i < 10 ? i + 1 : null }) });
|
||||
add({ title: 'Popular on Streaming', variant: 'logo', items: NETWORKS.slice(0, 6), render: networkCard, lazy: true });
|
||||
add({ title: 'Popular Movies', moreHref: href('/browse/movie?title=Popular%20Movies'), load: () => tmdb.popular('movie').then(items('movie')), render: poster });
|
||||
add({ title: 'Popular Series', variant: 'wide', moreHref: href('/browse/tv?title=Popular%20Series'), load: () => tmdb.popular('tv').then(items('tv')), render: (it) => wideCard(it) });
|
||||
add({ title: 'Top Rated Movies', load: () => tmdb.topRated('movie').then(items('movie')), render: poster });
|
||||
add({ title: 'Top Rated Series', load: () => tmdb.topRated('tv').then(items('tv')), render: poster });
|
||||
} else {
|
||||
const label = kind === 'movie' ? 'Movies' : 'Series';
|
||||
add({ title: `Trending ${label}`, load: () => tmdb.trending(kind, 'day').then(items(kind)), render: (it, i) => posterCard(it, { rank: i < 10 ? i + 1 : null }) });
|
||||
if (kind === 'tv') add({ title: 'Networks', variant: 'logo', items: NETWORKS, render: networkCard, lazy: true });
|
||||
add({ title: `Popular ${label}`, variant: 'wide', moreHref: href(`/browse/${kind}?title=${encodeURIComponent(`Popular ${label}`)}`), load: () => tmdb.popular(kind).then(items(kind)), render: (it) => wideCard(it) });
|
||||
add({ title: `Top Rated ${label}`, load: () => tmdb.topRated(kind).then(items(kind)), render: poster });
|
||||
if (kind === 'movie') {
|
||||
add({ title: 'Now in Theaters', load: () => tmdb.get('/movie/now_playing', { page: 1 }, { session: true }).then(items('movie')), render: poster });
|
||||
} else {
|
||||
add({ title: 'Airing This Week', load: () => tmdb.get('/tv/on_the_air', { page: 1 }, { session: true }).then(items('tv')), render: poster });
|
||||
}
|
||||
}
|
||||
|
||||
(GENRES[kind || 'all']).forEach((g, i) => {
|
||||
const more = href(`/browse/${g.type}?with_genres=${g.id}&title=${encodeURIComponent(g.name)}`);
|
||||
add({
|
||||
title: g.name,
|
||||
moreHref: more,
|
||||
variant: i % 3 === 1 ? 'wide' : 'poster',
|
||||
load: () => tmdb.discover(g.type, { with_genres: g.id, 'vote_count.gte': 200 }).then(items(g.type)),
|
||||
render: i % 3 === 1 ? (it) => wideCard(it) : poster,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (hero) hero.destroy();
|
||||
listeners.forEach(([n, fn]) => window.removeEventListener(n, fn));
|
||||
};
|
||||
}
|
||||
|
||||
function networkCard(n) {
|
||||
const card = logoCard({ name: n.name, logo: null, href: href(`/browse/tv?with_networks=${n.id}&title=${encodeURIComponent(n.name)}`) });
|
||||
tmdb.network(n.id).then((d) => {
|
||||
if (!d || !d.logo_path) return;
|
||||
const media = card.querySelector('.card__media');
|
||||
const im = h('img.card__logo', { src: tmdb.img(d.logo_path, 'w300'), alt: n.name, decoding: 'async' });
|
||||
im.addEventListener('load', () => media.replaceChildren(im), { once: true });
|
||||
}).catch(() => {});
|
||||
return card;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
views/list.js — /list My List (+ Continue Watching shortcut).
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import * as tmdb from '../tmdb.js';
|
||||
import { href } from '../router.js';
|
||||
import { myList } from '../storage.js';
|
||||
import { grid, posterCard } from '../ui/card.js';
|
||||
import { icon } from '../ui/icons.js';
|
||||
|
||||
export function render(root) {
|
||||
document.title = 'My List · bug tv';
|
||||
const body = h('div');
|
||||
const filters = h('div.tabs.tabs--pills', { role: 'tablist', 'aria-label': 'Filter' });
|
||||
let filter = 'all';
|
||||
const opts = [['all', 'All'], ['movie', 'Movies'], ['tv', 'Series']];
|
||||
const tabs = opts.map(([k, label]) => h('button.tab', { type: 'button', role: 'tab', onclick: () => { filter = k; paint(); } }, label));
|
||||
filters.append(...tabs);
|
||||
|
||||
function paint() {
|
||||
tabs.forEach((t, i) => {
|
||||
t.classList.toggle('is-active', opts[i][0] === filter);
|
||||
t.setAttribute('aria-selected', opts[i][0] === filter ? 'true' : 'false');
|
||||
});
|
||||
const all = myList.all();
|
||||
const items = all.filter((x) => filter === 'all' || x.type === filter).map((x) => tmdb.toItem(x, x.type));
|
||||
filters.hidden = !all.length;
|
||||
if (!items.length) {
|
||||
body.replaceChildren(h('div.empty',
|
||||
h('div.empty__icon', icon('bookmark', { size: 28 })),
|
||||
h('h2.empty__title', all.length ? 'Nothing here' : 'Your list is empty'),
|
||||
h('p.empty__text', 'Add movies and series with the + My List button and they will show up here.'),
|
||||
h('a.btn.btn--primary', { href: href('/') }, 'Browse titles')));
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(grid(items, (it) => posterCard(it)));
|
||||
}
|
||||
|
||||
root.append(h('div.page.page--padded.container',
|
||||
h('div.page__head', h('h1.page__title', 'My List'), filters),
|
||||
body));
|
||||
paint();
|
||||
window.addEventListener('bugtv:mylist', paint);
|
||||
return () => window.removeEventListener('bugtv:mylist', paint);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
views/search.js — /search?q= live TMDB multi-search (movies + tv), URL-synced.
|
||||
*/
|
||||
import { h, debounce } from '../util.js';
|
||||
import * as tmdb from '../tmdb.js';
|
||||
import { navigate } from '../router.js';
|
||||
import { grid, posterCard, skeletonCard } from '../ui/card.js';
|
||||
import { icon } from '../ui/icons.js';
|
||||
|
||||
let state = null;
|
||||
|
||||
function skeletonGrid(n = 12) {
|
||||
return h('div.grid', Array.from({ length: n }, () => skeletonCard('poster')));
|
||||
}
|
||||
|
||||
async function run(q) {
|
||||
const s = state;
|
||||
if (!s) return;
|
||||
const my = ++s.req;
|
||||
s.input.value !== q && document.activeElement !== s.input && (s.input.value = q);
|
||||
document.title = q ? `“${q}” · Search · bug tv` : 'Search · bug tv';
|
||||
if (!q.trim()) {
|
||||
s.heading.textContent = 'Popular right now';
|
||||
s.results.replaceChildren(skeletonGrid());
|
||||
try {
|
||||
const d = await tmdb.trending('all', 'week');
|
||||
if (my !== s.req) return;
|
||||
s.results.replaceChildren(grid((d.results || []).map((r) => tmdb.toItem(r)).filter((x) => x.poster_path)));
|
||||
} catch (e) {
|
||||
if (my === s.req) s.results.replaceChildren(h('p.muted', e.message));
|
||||
}
|
||||
return;
|
||||
}
|
||||
s.heading.textContent = `Results for “${q}”`;
|
||||
s.results.replaceChildren(skeletonGrid());
|
||||
try {
|
||||
const [p1, p2] = await Promise.all([tmdb.search(q, 1), tmdb.search(q, 2).catch(() => ({ results: [] }))]);
|
||||
if (my !== s.req) return;
|
||||
const seen = new Set();
|
||||
const list = [...p1.results, ...(p1.total_pages > 1 ? p2.results : [])]
|
||||
.map((r) => tmdb.toItem(r))
|
||||
.filter((x) => !seen.has(`${x.type}:${x.id}`) && seen.add(`${x.type}:${x.id}`));
|
||||
list.sort((a, b) => (b.poster_path ? 1 : 0) - (a.poster_path ? 1 : 0));
|
||||
if (!list.length) {
|
||||
s.results.replaceChildren(h('div.empty',
|
||||
h('div.empty__icon', icon('search', { size: 28 })),
|
||||
h('h2.empty__title', 'No matches'),
|
||||
h('p.empty__text', 'Try a different title, or check the spelling.')));
|
||||
return;
|
||||
}
|
||||
s.heading.textContent = `${list.length}${p1.total_results > list.length ? '+' : ''} results for “${q}”`;
|
||||
s.results.replaceChildren(grid(list, (it) => posterCard(it)));
|
||||
} catch (e) {
|
||||
if (my === s.req) s.results.replaceChildren(h('div.empty', h('h2.empty__title', 'Search failed'), h('p.empty__text', e.message)));
|
||||
}
|
||||
}
|
||||
|
||||
export function render(root, params) {
|
||||
const q = params.query.get('q') || '';
|
||||
const input = h('input.search-field__input', {
|
||||
type: 'search', placeholder: 'Search movies and series', value: q, autocomplete: 'off', spellcheck: 'false', enterkeyhint: 'search', 'aria-label': 'Search',
|
||||
});
|
||||
const go = debounce(() => navigate(`/search${input.value.trim() ? `?q=${encodeURIComponent(input.value.trim())}` : ''}`, { replace: true }), 300);
|
||||
input.addEventListener('input', go);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
go.cancel();
|
||||
navigate(`/search?q=${encodeURIComponent(input.value.trim())}`, { replace: true });
|
||||
input.blur();
|
||||
}
|
||||
});
|
||||
const heading = h('h1.page__title');
|
||||
const results = h('div.search-results', { 'aria-live': 'polite' });
|
||||
root.append(h('div.page.page--padded.container',
|
||||
h('label.search-field.search-field--page', icon('search', { size: 22 }), input),
|
||||
heading,
|
||||
results));
|
||||
state = { input, heading, results, req: 0 };
|
||||
run(q);
|
||||
// focus the page input on mobile (header search is hidden there)
|
||||
if (!q && window.matchMedia('(max-width: 720px)').matches) setTimeout(() => input.focus(), 50);
|
||||
return () => {
|
||||
go.cancel();
|
||||
state = null;
|
||||
};
|
||||
}
|
||||
|
||||
export function update(params) {
|
||||
if (!state) return false;
|
||||
run(params.query.get('q') || '');
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
views/settings.js — playback prefs, source providers, API server, TMDB key, local data.
|
||||
*/
|
||||
import { h } from '../util.js';
|
||||
import * as config from '../config.js';
|
||||
import { resume, myList, prefs } from '../storage.js';
|
||||
import { testKey } from '../tmdb.js';
|
||||
import { toast } from '../ui/toast.js';
|
||||
import { icon } from '../ui/icons.js';
|
||||
|
||||
const LANGS = [
|
||||
['', 'Off'], ['en', 'English'], ['es', 'Spanish'], ['fr', 'French'], ['de', 'German'], ['it', 'Italian'],
|
||||
['pt', 'Portuguese'], ['nl', 'Dutch'], ['pl', 'Polish'], ['ru', 'Russian'], ['tr', 'Turkish'], ['ar', 'Arabic'],
|
||||
['hi', 'Hindi'], ['ja', 'Japanese'], ['ko', 'Korean'], ['zh', 'Chinese'], ['sv', 'Swedish'], ['no', 'Norwegian'],
|
||||
['da', 'Danish'], ['fi', 'Finnish'], ['el', 'Greek'], ['he', 'Hebrew'], ['id', 'Indonesian'], ['vi', 'Vietnamese'],
|
||||
];
|
||||
|
||||
function status() {
|
||||
const el = h('p.status', { role: 'status' });
|
||||
el.set = (msg, kind) => {
|
||||
el.textContent = msg || '';
|
||||
el.className = `status${kind ? ` status--${kind}` : ''}`;
|
||||
};
|
||||
return el;
|
||||
}
|
||||
|
||||
function card(id, title, desc, ...children) {
|
||||
return h('section.settings-card', { id },
|
||||
h('header.settings-card__head', h('h2.settings-card__title', title), desc ? h('p.settings-card__desc', desc) : null),
|
||||
...children);
|
||||
}
|
||||
|
||||
function toggle(label, checked, onchange, hint) {
|
||||
const input = h('input', { type: 'checkbox', role: 'switch', checked, onchange: (e) => onchange(e.target.checked) });
|
||||
return h('label.switch-row', h('span.switch-row__text', h('span', label), hint ? h('small', hint) : null), h('span.switch', input, h('span.switch__track')));
|
||||
}
|
||||
|
||||
async function fetchProviders(signal) {
|
||||
const base = config.getBase();
|
||||
let res = await fetch(`${base}/v1/providers`, { signal, headers: { Accept: 'application/json' } }).catch((e) => {
|
||||
throw new Error(`cannot reach ${base}`);
|
||||
});
|
||||
if (res.status === 404) {
|
||||
// v4 server compatibility: { all, enabled }
|
||||
res = await fetch(`${base}/providers`, { signal });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const old = await res.json();
|
||||
return {
|
||||
defaults: old.enabled || [],
|
||||
providers: (old.all || []).map((n) => ({ id: n, name: n, enabled: (old.enabled || []).includes(n) })),
|
||||
};
|
||||
}
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
return { defaults: data.defaults || [], providers: data.providers || [] };
|
||||
}
|
||||
|
||||
function healthText(hl) {
|
||||
if (!hl) return '';
|
||||
const total = (hl.ok || 0) + (hl.fail || 0) + (hl.timeouts || 0);
|
||||
if (!total) return 'no data yet';
|
||||
const pct = Math.round(((hl.ok || 0) / total) * 100);
|
||||
return `${pct}% ok${hl.avgMs ? ` · ${(hl.avgMs / 1000).toFixed(1)}s avg` : ''}`;
|
||||
}
|
||||
|
||||
function healthLevel(hl) {
|
||||
if (!hl) return 'none';
|
||||
const total = (hl.ok || 0) + (hl.fail || 0) + (hl.timeouts || 0);
|
||||
if (!total) return 'none';
|
||||
const r = (hl.ok || 0) / total;
|
||||
return r > 0.7 ? 'good' : r > 0.35 ? 'fair' : 'bad';
|
||||
}
|
||||
|
||||
export function render(root, params) {
|
||||
document.title = 'Settings · bug tv';
|
||||
|
||||
/* ---- playback ---- */
|
||||
const subSel = h('select.select', { 'aria-label': 'Preferred subtitle language', onchange: (e) => { prefs.set('subtitleLang', e.target.value); toast('Subtitle preference saved'); } },
|
||||
LANGS.map(([v, l]) => h('option', { value: v, selected: prefs.get('subtitleLang', '') === v }, l)));
|
||||
const playback = card('playback', 'Playback', 'Applied by the player on every title.',
|
||||
h('div.field-row', h('label.field-row__label', 'Subtitles'), h('div.select-wrap', subSel, icon('down', { size: 18 }))),
|
||||
toggle('Autoplay next episode', prefs.get('autoplayNext', true) !== false, (v) => prefs.set('autoplayNext', v), 'Counts down at the end of an episode, then plays the next one.'));
|
||||
|
||||
/* ---- sources ---- */
|
||||
const provStatus = status();
|
||||
const provList = h('div.provider-grid');
|
||||
const provFilter = h('input.input.input--sm', { type: 'search', placeholder: 'Filter sources', 'aria-label': 'Filter sources' });
|
||||
let providers = [];
|
||||
let defaults = [];
|
||||
const boxes = new Map();
|
||||
|
||||
function effectiveEnabled() {
|
||||
const custom = config.getProviders();
|
||||
if (custom) return new Set(custom);
|
||||
return new Set(defaults.length ? defaults : providers.filter((p) => p.enabled).map((p) => p.id));
|
||||
}
|
||||
function persist(msg) {
|
||||
const map = {};
|
||||
for (const [id, box] of boxes) map[id] = box.checked;
|
||||
config.setProviders(map);
|
||||
summary();
|
||||
if (msg) toast(msg);
|
||||
}
|
||||
function summary() {
|
||||
const on = [...boxes.values()].filter((b) => b.checked).length;
|
||||
provStatus.set(`${on} of ${providers.length} enabled — ${config.getProviders() ? 'your selection' : 'server defaults'}`);
|
||||
}
|
||||
function paintProviders() {
|
||||
const enabled = effectiveEnabled();
|
||||
boxes.clear();
|
||||
provList.replaceChildren(...providers.map((p) => {
|
||||
const box = h('input', { type: 'checkbox', checked: enabled.has(p.id), onchange: () => persist(`${p.name || p.id} ${box.checked ? 'enabled' : 'disabled'}`) });
|
||||
boxes.set(p.id, box);
|
||||
const tags = [...(p.types || []), p.language].filter(Boolean).slice(0, 3);
|
||||
return h('label.provider', { dataset: { name: `${p.id} ${p.name || ''}`.toLowerCase() } },
|
||||
box,
|
||||
h('span.provider__check', icon('check', { size: 14, stroke: 3 })),
|
||||
h('span.provider__text',
|
||||
h('span.provider__name', p.name || p.id),
|
||||
h('span.provider__meta',
|
||||
h('i.health', { class: `health--${healthLevel(p.health)}`, title: healthText(p.health) || 'no health data' }),
|
||||
[healthText(p.health), ...tags].filter(Boolean).join(' · '))));
|
||||
}));
|
||||
summary();
|
||||
}
|
||||
provFilter.addEventListener('input', () => {
|
||||
const q = provFilter.value.trim().toLowerCase();
|
||||
provList.querySelectorAll('.provider').forEach((el) => { el.hidden = q && !el.dataset.name.includes(q); });
|
||||
});
|
||||
async function loadProviders() {
|
||||
provStatus.set('Loading sources…');
|
||||
try {
|
||||
const data = await fetchProviders(params.signal);
|
||||
providers = data.providers;
|
||||
defaults = data.defaults;
|
||||
paintProviders();
|
||||
} catch (e) {
|
||||
if (params.signal.aborted) return;
|
||||
provList.replaceChildren();
|
||||
provStatus.set(`Could not load the provider list: ${e.message}`, 'err');
|
||||
}
|
||||
}
|
||||
const sources = card('sources', 'Sources', 'Which providers the server scrapes for streams. Health comes from the server’s recent results.',
|
||||
h('div.toolbar',
|
||||
provFilter,
|
||||
h('div.toolbar__actions',
|
||||
h('button.btn.btn--ghost.btn--sm', { type: 'button', onclick: () => { boxes.forEach((b) => { b.checked = true; }); persist('All sources enabled'); } }, 'Enable all'),
|
||||
h('button.btn.btn--ghost.btn--sm', { type: 'button', onclick: () => { boxes.forEach((b) => { b.checked = false; }); persist('All sources disabled'); } }, 'Disable all'),
|
||||
h('button.btn.btn--ghost.btn--sm', { type: 'button', onclick: () => { config.clearProviders(); paintProviders(); toast('Using server defaults'); } }, 'Server defaults'))),
|
||||
provStatus,
|
||||
provList);
|
||||
|
||||
/* ---- server ---- */
|
||||
const baseInput = h('input.input', { type: 'url', value: config.getBase(), spellcheck: 'false', autocomplete: 'off', placeholder: config.DEFAULT_BASE, 'aria-label': 'API base URL' });
|
||||
const connStatus = status();
|
||||
async function testConn() {
|
||||
connStatus.set('Testing…');
|
||||
try {
|
||||
const res = await fetch(`${config.getBase()}/healthz`);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
connStatus.set(`Connected to ${config.getBase()}`, 'ok');
|
||||
return true;
|
||||
} catch (e) {
|
||||
connStatus.set(`Not reachable: ${e.message}`, 'err');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const server = card('server', 'Server', 'The bug tv API that finds and proxies streams.',
|
||||
h('div.input-row', baseInput,
|
||||
h('button.btn.btn--primary', { type: 'button', onclick: async () => { config.setBase(baseInput.value); baseInput.value = config.getBase(); if (await testConn()) toast('API server saved'); loadProviders(); } }, 'Save'),
|
||||
h('button.btn.btn--ghost', { type: 'button', onclick: async () => { config.clearBase(); baseInput.value = config.getBase(); await testConn(); loadProviders(); } }, 'Reset')),
|
||||
h('p.hint', `Default: ${config.DEFAULT_BASE}. Add ?api=<url> to any link for a one-off override.`),
|
||||
connStatus);
|
||||
|
||||
/* ---- TMDB ---- */
|
||||
const keyInput = h('input.input', { type: 'text', value: config.getTmdbKey(), spellcheck: 'false', autocomplete: 'off', placeholder: '32-character TMDB API key', 'aria-label': 'TMDB API key' });
|
||||
const keyStatus = status();
|
||||
async function testTmdb(key) {
|
||||
keyStatus.set('Testing TMDB key…');
|
||||
try {
|
||||
await testKey(key);
|
||||
keyStatus.set('TMDB key works.', 'ok');
|
||||
} catch (e) {
|
||||
keyStatus.set(e.message, 'err');
|
||||
}
|
||||
}
|
||||
const tmdbCard = card('tmdb', 'TMDB', 'Catalog, artwork and search come straight from TMDB using this key.',
|
||||
h('div.input-row', keyInput,
|
||||
h('button.btn.btn--primary', { type: 'button', onclick: () => { config.setTmdbKey(keyInput.value); keyInput.value = config.getTmdbKey(); testTmdb(config.getTmdbKey()); } }, 'Save'),
|
||||
h('button.btn.btn--ghost', { type: 'button', onclick: () => testTmdb(keyInput.value.trim()) }, 'Test'),
|
||||
h('button.btn.btn--ghost', { type: 'button', onclick: () => { config.clearTmdbKey(); keyInput.value = config.getTmdbKey(); testTmdb(config.getTmdbKey()); } }, 'Reset')),
|
||||
keyStatus);
|
||||
|
||||
/* ---- data ---- */
|
||||
const dataStatus = status();
|
||||
const data = card('data', 'Your data', 'Stored only in this browser.',
|
||||
h('div.toolbar__actions',
|
||||
h('button.btn.btn--ghost', { type: 'button', onclick: () => { if (confirm('Clear all Continue Watching progress?')) { resume.clear(); dataStatus.set('Continue Watching cleared.', 'ok'); } } }, icon('trash', { size: 18 }), 'Clear watch progress'),
|
||||
h('button.btn.btn--ghost', { type: 'button', onclick: () => { if (confirm('Remove everything from My List?')) { myList.all().forEach((x) => myList.remove(x.type, x.id)); dataStatus.set('My List cleared.', 'ok'); } } }, icon('trash', { size: 18 }), 'Clear My List'),
|
||||
h('button.btn.btn--ghost', { type: 'button', onclick: () => { config.clearProviders(); paintProviders(); dataStatus.set('Source toggles reset.', 'ok'); } }, 'Reset source toggles')),
|
||||
dataStatus);
|
||||
|
||||
const nav = h('nav.settings-nav', { 'aria-label': 'Settings sections' },
|
||||
[['playback', 'Playback'], ['sources', 'Sources'], ['server', 'Server'], ['tmdb', 'TMDB'], ['data', 'Your data']].map(([id, label]) =>
|
||||
h('button.settings-nav__link', { type: 'button', onclick: () => document.getElementById(id).scrollIntoView({ behavior: 'smooth', block: 'start' }) }, label)));
|
||||
|
||||
root.append(h('div.page.page--padded.container.settings',
|
||||
h('div.page__head', h('h1.page__title', 'Settings')),
|
||||
h('div.settings__layout', nav, h('div.settings__cards', playback, sources, server, tmdbCard, data))));
|
||||
|
||||
loadProviders();
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
views/title.js — /title/:type/:id detail page.
|
||||
*/
|
||||
import { h, runtimeLabel, plural, yearOf } from '../util.js';
|
||||
import * as tmdb from '../tmdb.js';
|
||||
import { href } from '../router.js';
|
||||
import { resume } from '../storage.js';
|
||||
import { icon } from '../ui/icons.js';
|
||||
import { row } from '../ui/row.js';
|
||||
import { posterCard } from '../ui/card.js';
|
||||
import { castRow } from '../ui/cast.js';
|
||||
import { episodesSection } from '../ui/episodes.js';
|
||||
import { trailerModal } from '../ui/modal.js';
|
||||
import { playTarget, myListButton, shareTitle, titlePath } from '../ui/actions.js';
|
||||
|
||||
const DAY = 86400000;
|
||||
|
||||
function badgeFor(d, type) {
|
||||
const now = Date.now();
|
||||
if (type === 'tv') {
|
||||
if (d.next_episode_to_air) {
|
||||
const n = d.next_episode_to_air;
|
||||
return n.episode_number === 1 ? `Season ${n.season_number} coming soon` : 'New episodes weekly';
|
||||
}
|
||||
const last = d.last_episode_to_air;
|
||||
if (last && last.air_date && now - new Date(last.air_date) < 45 * DAY) return `Season ${last.season_number} out now`;
|
||||
if (d.status === 'Ended') return 'Complete series';
|
||||
return null;
|
||||
}
|
||||
if (d.release_date) {
|
||||
const age = now - new Date(d.release_date);
|
||||
if (age < 0) return 'Coming soon';
|
||||
if (age < 90 * DAY) return 'New release';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function skeleton() {
|
||||
return h('div.page.page--title',
|
||||
h('section.title-hero.title-hero--loading',
|
||||
h('div.title-hero__content.container',
|
||||
h('div.skeleton.skeleton--block', { style: { width: '40%', height: '64px' } }),
|
||||
h('div.skeleton.skeleton--line', { style: { width: '30%' } }),
|
||||
h('div.skeleton.skeleton--line', { style: { width: '55%' } }))));
|
||||
}
|
||||
|
||||
function infoList(d, type) {
|
||||
const rows = [];
|
||||
const add = (k, v) => v && rows.push(h('div.facts__row', h('dt', k), h('dd', v)));
|
||||
if (type === 'tv') {
|
||||
add('Status', d.status);
|
||||
add('First aired', d.first_air_date && new Date(d.first_air_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }));
|
||||
add('Seasons', d.number_of_seasons && `${plural(d.number_of_seasons, 'season')} · ${plural(d.number_of_episodes || 0, 'episode')}`);
|
||||
add('Network', (d.networks || []).map((n) => n.name).join(', '));
|
||||
add('Created by', (d.created_by || []).map((c) => c.name).join(', '));
|
||||
} else {
|
||||
add('Released', d.release_date && new Date(d.release_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }));
|
||||
add('Runtime', runtimeLabel(d.runtime));
|
||||
const directors = ((d.credits && d.credits.crew) || []).filter((c) => c.job === 'Director').map((c) => c.name);
|
||||
add('Director', directors.join(', '));
|
||||
add('Studio', (d.production_companies || []).slice(0, 2).map((c) => c.name).join(', '));
|
||||
}
|
||||
add('Language', (d.spoken_languages || []).slice(0, 3).map((l) => l.english_name || l.name).join(', '));
|
||||
return rows.length ? h('dl.facts', rows) : null;
|
||||
}
|
||||
|
||||
export async function render(root, params) {
|
||||
const type = params.type === 'tv' ? 'tv' : 'movie';
|
||||
const id = params.id;
|
||||
root.append(skeleton());
|
||||
|
||||
let d;
|
||||
try {
|
||||
d = await tmdb.details(type, id);
|
||||
} catch (e) {
|
||||
if (params.signal.aborted) return;
|
||||
root.replaceChildren(h('section.page.page--center', h('div.empty',
|
||||
h('h1.empty__title', 'Could not load this title'),
|
||||
h('p.empty__text', e.message),
|
||||
h('a.btn.btn--primary', { href: href('/') }, 'Back to home'))));
|
||||
return;
|
||||
}
|
||||
if (params.signal.aborted) return;
|
||||
|
||||
const item = tmdb.toItem(d, type);
|
||||
document.title = `${item.title} · bug tv`;
|
||||
const logo = tmdb.logoFor(d);
|
||||
const cert = tmdb.certificationFor(d);
|
||||
const badge = badgeFor(d, type);
|
||||
const trailer = tmdb.trailerFor(d);
|
||||
const target = playTarget(type, id, d);
|
||||
|
||||
const titleText = h('h1.title-hero__title', item.title);
|
||||
const titleBox = h('div.hero__titlebox.title-hero__titlebox', titleText);
|
||||
if (logo) {
|
||||
const im = h('img.hero__logo', { src: tmdb.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, 4).map((g) =>
|
||||
h('a.meta-link', { href: href(`/browse/${type}?with_genres=${g.id}&title=${encodeURIComponent(g.name)}`) }, g.name));
|
||||
const extra = type === 'tv' ? (d.number_of_seasons ? plural(d.number_of_seasons, 'Season') : '') : runtimeLabel(d.runtime);
|
||||
const meta = h('div.hero__meta',
|
||||
item.rating > 0 ? h('span.rating.rating--lg', icon('star', { size: 16 }), item.rating.toFixed(1)) : null,
|
||||
yearOf(d.release_date || d.first_air_date) ? h('span', yearOf(d.release_date || d.first_air_date)) : null,
|
||||
extra ? h('span', extra) : null,
|
||||
cert ? h('span.chip.chip--outline', cert) : null,
|
||||
genres.length ? h('span.hero__genres', genres.flatMap((g, i) => (i ? [h('span.dot', '•'), g] : [g]))) : null,
|
||||
);
|
||||
|
||||
const playBtn = h('a.btn.btn--primary.btn--lg', { href: href(target.path) },
|
||||
icon('play'), h('span', target.label),
|
||||
target.progress > 0 ? h('span.btn__progress', h('i', { style: { width: `${Math.round(target.progress * 100)}%` } })) : null);
|
||||
|
||||
const actions = h('div.hero__actions',
|
||||
playBtn,
|
||||
myListButton(item, { className: 'btn btn--glass btn--lg' }),
|
||||
trailer ? h('button.btn.btn--glass.btn--lg', { type: 'button', onclick: () => trailerModal(trailer.key, item.title) }, icon('trailer'), h('span', 'Trailer')) : null,
|
||||
h('button.btn.btn--glass.btn--lg.btn--icon', { type: 'button', 'aria-label': 'Share', title: 'Share', onclick: () => shareTitle(item.title, titlePath(type, id)) }, icon('share')),
|
||||
);
|
||||
|
||||
const backdropPath = d.backdrop_path || (d.images && d.images.backdrops && d.images.backdrops[0] && d.images.backdrops[0].file_path);
|
||||
const hero = h('section.title-hero',
|
||||
backdropPath ? h('div.hero__media', h('img.hero__img.is-loaded', {
|
||||
src: tmdb.img(backdropPath, 'w1280'),
|
||||
srcset: `${tmdb.img(backdropPath, 'w780')} 780w, ${tmdb.img(backdropPath, 'w1280')} 1280w, ${tmdb.img(backdropPath, 'original')} 1920w`,
|
||||
sizes: '100vw', alt: '', decoding: 'async', fetchpriority: 'high',
|
||||
})) : null,
|
||||
h('div.hero__scrim'),
|
||||
h('div.title-hero__content.container',
|
||||
badge ? h('span.badge', badge) : null,
|
||||
titleBox,
|
||||
meta,
|
||||
d.tagline ? h('p.title-hero__tagline', d.tagline) : null,
|
||||
actions,
|
||||
),
|
||||
);
|
||||
|
||||
const story = h('section.section.story.container',
|
||||
h('div.story__main',
|
||||
h('h2.section__title', 'Storyline'),
|
||||
h('p.story__text', d.overview || 'No synopsis available.')),
|
||||
infoList(d, type));
|
||||
|
||||
const body = h('div.title-body');
|
||||
const cast = castRow(d.credits);
|
||||
if (cast) body.appendChild(h('div.container-row', cast));
|
||||
|
||||
let eps = null;
|
||||
if (type === 'tv') {
|
||||
const last = resume.forShow('tv', id)[0];
|
||||
const season = params.query.get('season') || (last && last.season);
|
||||
eps = episodesSection(d, { season });
|
||||
if (eps) body.appendChild(h('div.container', eps));
|
||||
}
|
||||
|
||||
const similar = ((d.recommendations && d.recommendations.results && d.recommendations.results.length ? d.recommendations : d.similar) || {}).results || [];
|
||||
const similarItems = similar.map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path);
|
||||
if (similarItems.length) body.appendChild(h('div.container-row', row({ title: 'More Like This', items: similarItems, render: (it) => posterCard(it), lazy: false })));
|
||||
|
||||
root.replaceChildren(h('div.page.page--title', hero, story, body));
|
||||
|
||||
// keep Continue / progress fresh when the player writes resume data (e.g. returning from /watch)
|
||||
const onResume = () => {
|
||||
const t = playTarget(type, id, d);
|
||||
playBtn.href = href(t.path);
|
||||
playBtn.querySelector('span').textContent = t.label;
|
||||
if (eps) eps.refresh();
|
||||
};
|
||||
window.addEventListener('bugtv:resume', onResume);
|
||||
return () => window.removeEventListener('bugtv:resume', onResume);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
-890
@@ -1,890 +0,0 @@
|
||||
/*
|
||||
WATCH — hero, player, source list (switch mid-watch), episodes.
|
||||
|
||||
URL params: ?id=<tmdb id>&type=<movie|tv>
|
||||
TV adds &s=<season>&e=<episode> as playback progresses.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const params = new URLSearchParams(location.search);
|
||||
const id = (params.get('id') || '').trim();
|
||||
const type = params.get('type') === 'tv' ? 'tv' : 'movie';
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const content = document.getElementById('content');
|
||||
if (!id || !/^\d+$/.test(id)) {
|
||||
content.replaceChildren(SR.cards.emptyState('Missing ?id=', 'This page needs a TMDB id, e.g. watch.html?id=1396&type=tv'));
|
||||
return;
|
||||
}
|
||||
|
||||
const heroEl = document.getElementById('hero');
|
||||
const heroBackdrop = document.getElementById('heroBackdrop');
|
||||
const heroTitleCard = document.getElementById('heroTitleCard');
|
||||
const heroTitle = document.getElementById('heroTitle');
|
||||
const heroMeta = document.getElementById('heroMeta');
|
||||
const heroGenres = document.getElementById('heroGenres');
|
||||
const heroOverview = document.getElementById('heroOverview');
|
||||
const playButton = document.getElementById('playButton');
|
||||
const playLabel = document.getElementById('playLabel');
|
||||
const episodeSection = document.getElementById('episodeSection');
|
||||
const seasonTabs = document.getElementById('seasonTabs');
|
||||
const episodeShelf = document.getElementById('episodeShelf');
|
||||
const playerOverlay = document.getElementById('playerOverlay');
|
||||
const playerClose = document.getElementById('playerClose');
|
||||
|
||||
// custom player controls
|
||||
const video = document.getElementById('video');
|
||||
const statusEl = document.getElementById('playerStatus');
|
||||
const sourceLabel = document.getElementById('sourceLabel');
|
||||
const resumeNote = document.getElementById('resumeNote');
|
||||
const sourcesPanel = document.getElementById('sourcesPanel');
|
||||
const sourcesClose = document.getElementById('sourcesClose');
|
||||
|
||||
const playerWrap = document.getElementById('playerWrap');
|
||||
const bigPlay = document.getElementById('bigPlay');
|
||||
const pcSeek = document.getElementById('pcSeek');
|
||||
const pcPlay = document.getElementById('pcPlay');
|
||||
const pcMute = document.getElementById('pcMute');
|
||||
const pcVol = document.getElementById('pcVol');
|
||||
const pcTime = document.getElementById('pcTime');
|
||||
const pcCc = document.getElementById('pcCc');
|
||||
const pcQuality = document.getElementById('pcQuality');
|
||||
const pcGear = document.getElementById('pcGear');
|
||||
const pcPip = document.getElementById('pcPip');
|
||||
const pcFull = document.getElementById('pcFull');
|
||||
|
||||
const state = {
|
||||
details: null,
|
||||
seasons: [],
|
||||
episodes: [],
|
||||
streams: [],
|
||||
unsupported: [],
|
||||
providerErrors: {},
|
||||
loadErrors: {},
|
||||
sourceIndex: -1,
|
||||
season: null,
|
||||
episode: null,
|
||||
loadedKey: null,
|
||||
loadToken: 0,
|
||||
overlayOpen: false,
|
||||
lastFocusedElement: null,
|
||||
pendingClose: false,
|
||||
};
|
||||
|
||||
|
||||
/* ---- status overlay ------------------------------------------------------ */
|
||||
|
||||
function closeSources() {
|
||||
sourcesPanel.hidden = true;
|
||||
pcGear.classList.remove('is-on');
|
||||
}
|
||||
|
||||
function showStatus(msg, isError) {
|
||||
closeSources();
|
||||
statusEl.hidden = false;
|
||||
playerWrap.classList.remove('player-wrap--controls', 'player-wrap--paused');
|
||||
statusEl.innerHTML = isError
|
||||
? `<h3>Playback problem</h3><p>${SR.util.escapeHtml(msg)}</p>`
|
||||
: `<div class="spinner"></div><p>${SR.util.escapeHtml(msg)}</p>`;
|
||||
}
|
||||
|
||||
function hideStatus() {
|
||||
statusEl.hidden = true;
|
||||
syncPaused();
|
||||
}
|
||||
|
||||
/* ---- player --------------------------------------------------------------- */
|
||||
|
||||
const player = SR.player.create(video, {
|
||||
onStatus: (msg) => showStatus(msg),
|
||||
onReady: (resumeAt) => {
|
||||
hideStatus();
|
||||
if (resumeAt > 10) resumeNote.textContent = `Resuming at ${SR.util.formatSeconds(resumeAt)}`;
|
||||
},
|
||||
onError: (msg) => {
|
||||
showStatus(msg, true);
|
||||
SR.app.toast(msg, true);
|
||||
},
|
||||
});
|
||||
|
||||
/* ---- custom player controls -------------------------------------------------- */
|
||||
|
||||
const ICON_PLAY =
|
||||
'<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"></path></svg>';
|
||||
const ICON_PAUSE =
|
||||
'<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 4h4v16H6zm8 0h4v16h-4z"></path></svg>';
|
||||
const ICON_VOL =
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path><path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path></svg>';
|
||||
const ICON_VOL_X =
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><line x1="23" y1="9" x2="17" y2="15"></line><line x1="17" y1="9" x2="23" y2="15"></line></svg>';
|
||||
|
||||
let hideTimer = null;
|
||||
let scrubbing = false;
|
||||
|
||||
function paintProgress(el, ratio) {
|
||||
const pct = Math.max(0, Math.min(1, ratio)) * 100;
|
||||
el.style.setProperty('--pc-progress', pct + '%');
|
||||
}
|
||||
|
||||
function timeLabel() {
|
||||
const d = video.duration;
|
||||
const ds = d && isFinite(d) ? SR.util.formatSeconds(d) : '0:00';
|
||||
return `${SR.util.formatSeconds(video.currentTime)} / ${ds}`;
|
||||
}
|
||||
|
||||
function syncPlayIcon() {
|
||||
const playing = !video.paused && !video.ended;
|
||||
pcPlay.innerHTML = playing ? ICON_PAUSE : ICON_PLAY;
|
||||
pcPlay.setAttribute('aria-label', playing ? 'Pause' : 'Play');
|
||||
}
|
||||
|
||||
function syncVolIcon() {
|
||||
const muted = video.muted || video.volume === 0;
|
||||
pcMute.innerHTML = muted ? ICON_VOL_X : ICON_VOL;
|
||||
pcMute.setAttribute('aria-label', muted ? 'Unmute' : 'Mute');
|
||||
pcMute.classList.toggle('is-on', muted);
|
||||
pcVol.value = String(video.muted ? 0 : video.volume);
|
||||
paintProgress(pcVol, video.muted ? 0 : video.volume);
|
||||
}
|
||||
|
||||
function syncTimeUI() {
|
||||
if (scrubbing) return;
|
||||
const d = video.duration;
|
||||
if (d && isFinite(d) && d > 0) {
|
||||
pcSeek.value = String(Math.round((video.currentTime / d) * 1000));
|
||||
paintProgress(pcSeek, video.currentTime / d);
|
||||
}
|
||||
pcTime.textContent = timeLabel();
|
||||
}
|
||||
|
||||
function syncPaused() {
|
||||
playerWrap.classList.toggle('player-wrap--paused', video.paused);
|
||||
}
|
||||
|
||||
function togglePlay() {
|
||||
if (!video.src && !video.currentSrc) return;
|
||||
if (video.paused || video.ended) {
|
||||
video.play().catch(() => {});
|
||||
} else {
|
||||
video.pause();
|
||||
}
|
||||
}
|
||||
|
||||
function showControls() {
|
||||
playerWrap.classList.add('player-wrap--controls');
|
||||
clearTimeout(hideTimer);
|
||||
hideTimer = setTimeout(() => {
|
||||
if (!video.paused && !video.ended && !scrubbing && sourcesPanel.hidden) {
|
||||
playerWrap.classList.remove('player-wrap--controls');
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function toggleFullscreen() {
|
||||
const el = playerWrap;
|
||||
const doc = document;
|
||||
if (doc.fullscreenElement || doc.webkitFullscreenElement) {
|
||||
(doc.exitFullscreen || doc.webkitExitFullscreen).call(doc);
|
||||
} else {
|
||||
(el.requestFullscreen || el.webkitRequestFullscreen).call(el);
|
||||
}
|
||||
}
|
||||
|
||||
function togglePip() {
|
||||
if (!document.pictureInPictureEnabled) {
|
||||
SR.app.toast('Picture-in-picture is not supported in this browser', true);
|
||||
return;
|
||||
}
|
||||
if (document.pictureInPictureElement) {
|
||||
document.exitPictureInPicture().catch(() => {});
|
||||
} else {
|
||||
video.requestPictureInPicture().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function toggleCc() {
|
||||
const tracks = video.textTracks;
|
||||
let target = null;
|
||||
for (let i = 0; i < tracks.length; i++) {
|
||||
if (tracks[i].kind === 'subtitles') {
|
||||
target = tracks[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!target) {
|
||||
SR.app.toast('This source has no subtitles', true);
|
||||
return;
|
||||
}
|
||||
target.mode = target.mode === 'showing' ? 'hidden' : 'showing';
|
||||
pcCc.classList.toggle('is-on', target.mode === 'showing');
|
||||
pcCc.setAttribute('aria-pressed', String(target.mode === 'showing'));
|
||||
}
|
||||
|
||||
// video events
|
||||
video.addEventListener('click', () => {
|
||||
if (!sourcesPanel.hidden) {
|
||||
closeSources();
|
||||
return;
|
||||
}
|
||||
togglePlay();
|
||||
});
|
||||
video.addEventListener('dblclick', toggleFullscreen);
|
||||
video.addEventListener('play', () => {
|
||||
syncPlayIcon();
|
||||
syncPaused();
|
||||
showControls();
|
||||
});
|
||||
video.addEventListener('pause', () => {
|
||||
syncPlayIcon();
|
||||
syncPaused();
|
||||
showControls();
|
||||
});
|
||||
video.addEventListener('loadedmetadata', () => {
|
||||
syncPlayIcon();
|
||||
syncPaused();
|
||||
syncTimeUI();
|
||||
});
|
||||
video.addEventListener('timeupdate', syncTimeUI);
|
||||
video.addEventListener('volumechange', syncVolIcon);
|
||||
|
||||
// buttons
|
||||
bigPlay.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
togglePlay();
|
||||
});
|
||||
pcPlay.addEventListener('click', togglePlay);
|
||||
pcMute.addEventListener('click', () => {
|
||||
video.muted = !video.muted;
|
||||
});
|
||||
pcCc.addEventListener('click', toggleCc);
|
||||
pcGear.addEventListener('click', () => {
|
||||
if (sourcesPanel.hidden) {
|
||||
sourcesPanel.hidden = false;
|
||||
pcGear.classList.add('is-on');
|
||||
showControls();
|
||||
} else {
|
||||
closeSources();
|
||||
}
|
||||
});
|
||||
sourcesClose.addEventListener('click', closeSources);
|
||||
pcPip.addEventListener('click', togglePip);
|
||||
pcFull.addEventListener('click', toggleFullscreen);
|
||||
|
||||
// seek + volume scrubbing
|
||||
pcSeek.addEventListener('pointerdown', () => {
|
||||
scrubbing = true;
|
||||
showControls();
|
||||
});
|
||||
pcSeek.addEventListener('input', () => {
|
||||
const d = video.duration;
|
||||
if (d && isFinite(d) && d > 0) {
|
||||
paintProgress(pcSeek, pcSeek.value / 1000);
|
||||
pcTime.textContent = `${SR.util.formatSeconds((pcSeek.value / 1000) * d)} / ${SR.util.formatSeconds(d)}`;
|
||||
}
|
||||
});
|
||||
pcSeek.addEventListener('change', () => {
|
||||
const d = video.duration;
|
||||
if (d && isFinite(d) && d > 0) {
|
||||
video.currentTime = (pcSeek.value / 1000) * d;
|
||||
}
|
||||
scrubbing = false;
|
||||
syncTimeUI();
|
||||
});
|
||||
pcVol.addEventListener('input', () => {
|
||||
video.volume = Number(pcVol.value);
|
||||
video.muted = video.volume === 0;
|
||||
});
|
||||
|
||||
// reveal controls on hover/interaction
|
||||
playerWrap.addEventListener('pointermove', showControls);
|
||||
playerWrap.addEventListener('pointerdown', showControls);
|
||||
|
||||
// keyboard shortcuts
|
||||
document.addEventListener('keydown', (e) => {
|
||||
const tag = (e.target.tagName || '').toLowerCase();
|
||||
if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
|
||||
const d = video.duration;
|
||||
switch (e.key) {
|
||||
case ' ':
|
||||
case 'k':
|
||||
e.preventDefault();
|
||||
togglePlay();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
if (d && isFinite(d)) video.currentTime = Math.min(d, video.currentTime + 10);
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
if (d && isFinite(d)) video.currentTime = Math.max(0, video.currentTime - 10);
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
video.volume = Math.min(1, video.volume + 0.05);
|
||||
video.muted = false;
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
video.volume = Math.max(0, video.volume - 0.05);
|
||||
break;
|
||||
case 'm':
|
||||
video.muted = !video.muted;
|
||||
break;
|
||||
case 'f':
|
||||
toggleFullscreen();
|
||||
break;
|
||||
case 'c':
|
||||
toggleCc();
|
||||
break;
|
||||
case 'Escape':
|
||||
if (!sourcesPanel.hidden) closeSources();
|
||||
else if (state.overlayOpen) {
|
||||
if (document.fullscreenElement) {
|
||||
state.pendingClose = true;
|
||||
document.exitFullscreen().catch(() => {});
|
||||
} else {
|
||||
closePlayer();
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
if (video.src || video.currentSrc) showControls();
|
||||
});
|
||||
|
||||
// initial icon state
|
||||
syncPlayIcon();
|
||||
syncVolIcon();
|
||||
|
||||
/* ---- hero ------------------------------------------------------------------ */
|
||||
|
||||
function openPlayer() {
|
||||
if (state.overlayOpen) return;
|
||||
state.overlayOpen = true;
|
||||
state.lastFocusedElement = document.activeElement;
|
||||
playerOverlay.hidden = false;
|
||||
document.body.classList.add('player-open');
|
||||
playerClose.focus();
|
||||
}
|
||||
|
||||
function closePlayer() {
|
||||
if (!state.overlayOpen) return;
|
||||
state.overlayOpen = false;
|
||||
state.pendingClose = false;
|
||||
video.pause();
|
||||
playerOverlay.hidden = true;
|
||||
document.body.classList.remove('player-open');
|
||||
if (state.lastFocusedElement && typeof state.lastFocusedElement.focus === 'function') {
|
||||
state.lastFocusedElement.focus();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('fullscreenchange', () => {
|
||||
if (!document.fullscreenElement && state.pendingClose && state.overlayOpen) closePlayer();
|
||||
});
|
||||
|
||||
function syncHeader() {
|
||||
document.body.classList.toggle('is-scrolled', window.scrollY > 8);
|
||||
}
|
||||
window.addEventListener('scroll', syncHeader, { passive: true });
|
||||
syncHeader();
|
||||
|
||||
function setPlayLabel() {
|
||||
if (type === 'tv' && state.season != null && state.episode != null) {
|
||||
playLabel.textContent = `Play S${state.season} E${state.episode}`;
|
||||
} else {
|
||||
playLabel.textContent = 'Play';
|
||||
}
|
||||
}
|
||||
|
||||
function renderHero(d) {
|
||||
document.title = `${d.name || d.title} — bug.tv`;
|
||||
const isTv = type === 'tv';
|
||||
const year = String((isTv ? d.first_air_date : d.release_date) || '').slice(0, 4);
|
||||
const facts = [];
|
||||
if (isTv) {
|
||||
if (d.number_of_seasons) {
|
||||
facts.push(`${d.number_of_seasons} season${d.number_of_seasons === 1 ? '' : 's'}`);
|
||||
}
|
||||
} else {
|
||||
const runtime = SR.util.runtimeLabel(d.runtime);
|
||||
if (runtime) facts.push(runtime);
|
||||
}
|
||||
if (year) facts.push(year);
|
||||
|
||||
const vote = Number(d.vote_average || 0);
|
||||
const filled = Math.max(0, Math.min(5, Math.round(vote / 2)));
|
||||
const rating = vote
|
||||
? `<span class="watch-hero__rating" role="img" aria-label="${vote.toFixed(1)} out of 10">${'★'.repeat(filled)}${'☆'.repeat(5 - filled)} ${vote.toFixed(1)}</span>`
|
||||
: '';
|
||||
|
||||
const title = d.name || d.title || '';
|
||||
heroTitle.textContent = title;
|
||||
heroMeta.innerHTML = [rating, ...facts.map((fact) => `<span>${SR.util.escapeHtml(fact)}</span>`)]
|
||||
.filter(Boolean)
|
||||
.join('<span class="watch-hero__dot" aria-hidden="true">·</span>');
|
||||
|
||||
heroGenres.replaceChildren();
|
||||
for (const genre of d.genres || []) {
|
||||
const tag = document.createElement('span');
|
||||
tag.className = 'tag';
|
||||
tag.textContent = genre.name;
|
||||
heroGenres.appendChild(tag);
|
||||
}
|
||||
|
||||
heroOverview.textContent = d.overview || '';
|
||||
heroOverview.hidden = !d.overview;
|
||||
|
||||
const images = d.images || {};
|
||||
const backdrop = d.backdrop_url || (images.backdrops && images.backdrops[0] && images.backdrops[0].url);
|
||||
heroBackdrop.style.backgroundImage = backdrop
|
||||
? `url("${SR.util.escapeHtml(SR.util.tmdbResize(backdrop, 'w1280'))}")`
|
||||
: '';
|
||||
|
||||
const logos = images.logos || [];
|
||||
const logo = (logos.find((l) => l && l.url && String(l.iso_639_1 || '').toLowerCase() === 'en') || {}).url;
|
||||
if (logo) {
|
||||
heroTitleCard.alt = title;
|
||||
heroTitleCard.src = SR.util.tmdbResize(logo, 'w500');
|
||||
heroTitleCard.hidden = false;
|
||||
heroTitle.hidden = true;
|
||||
heroTitleCard.onerror = () => {
|
||||
heroTitleCard.hidden = true;
|
||||
heroTitle.hidden = false;
|
||||
};
|
||||
} else {
|
||||
heroTitleCard.hidden = true;
|
||||
heroTitle.hidden = false;
|
||||
}
|
||||
|
||||
playButton.hidden = false;
|
||||
setPlayLabel();
|
||||
}
|
||||
|
||||
function renderHeroError(message) {
|
||||
heroTitle.textContent = 'Unavailable';
|
||||
heroTitle.hidden = false;
|
||||
heroMeta.textContent = message;
|
||||
heroOverview.textContent = '';
|
||||
heroBackdrop.style.backgroundImage = '';
|
||||
heroTitleCard.hidden = true;
|
||||
playButton.hidden = true;
|
||||
episodeSection.hidden = true;
|
||||
}
|
||||
|
||||
|
||||
/* ---- url -------------------------------------------------------------------- */
|
||||
|
||||
function syncUrl() {
|
||||
const p = new URLSearchParams();
|
||||
p.set('id', id);
|
||||
p.set('type', type);
|
||||
if (type === 'tv') {
|
||||
if (state.season != null) p.set('s', state.season);
|
||||
if (state.episode != null) p.set('e', state.episode);
|
||||
}
|
||||
history.replaceState(null, '', `?${p.toString()}`);
|
||||
}
|
||||
|
||||
/* ---- streams ------------------------------------------------------------------ */
|
||||
|
||||
function keyFor() {
|
||||
return SR.storage.keyFor({ type, tmdbId: Number(id), season: state.season, episode: state.episode });
|
||||
}
|
||||
|
||||
let providerCatalog = null; // cached per page load; enabled names are re-read from localStorage every lookup
|
||||
|
||||
async function getProviderCatalog() {
|
||||
if (providerCatalog) return providerCatalog;
|
||||
try {
|
||||
const data = await SR.api.providers();
|
||||
providerCatalog = { all: data.all || [], enabled: data.enabled || [] };
|
||||
} catch (e) {
|
||||
return { all: [], enabled: [] };
|
||||
}
|
||||
return providerCatalog;
|
||||
}
|
||||
|
||||
async function getProviderInfo() {
|
||||
if (SR.config.getProviders()) return SR.config.resolveProviders(null);
|
||||
return SR.config.resolveProviders(await getProviderCatalog());
|
||||
}
|
||||
|
||||
async function loadStreams() {
|
||||
const token = ++state.loadToken;
|
||||
const providerInfo = await getProviderInfo();
|
||||
if (token !== state.loadToken) return;
|
||||
|
||||
if (!providerInfo.useServerDefaults && providerInfo.names.length === 0) {
|
||||
closeSources();
|
||||
pcQuality.textContent = '';
|
||||
sourceLabel.textContent = '';
|
||||
resumeNote.textContent = '';
|
||||
showStatus('No sources are enabled. Open Settings → Sources and enable at least one provider.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const query = {
|
||||
tmdb: id,
|
||||
type,
|
||||
providers: providerInfo.useServerDefaults ? null : providerInfo.names,
|
||||
};
|
||||
if (type === 'tv') {
|
||||
if (state.season == null || state.episode == null) return;
|
||||
query.season = state.season;
|
||||
query.episode = state.episode;
|
||||
}
|
||||
|
||||
closeSources();
|
||||
pcQuality.textContent = '';
|
||||
showStatus('Finding streams…');
|
||||
sourceLabel.textContent = '';
|
||||
resumeNote.textContent = '';
|
||||
|
||||
try {
|
||||
const data = await SR.api.streams(query);
|
||||
if (token !== state.loadToken) return;
|
||||
|
||||
const allStreams = data.streams || [];
|
||||
state.streams = allStreams.filter(SR.util.webPlayable);
|
||||
state.unsupported = allStreams.filter((s) => !SR.util.webPlayable(s));
|
||||
state.providerErrors = data.providerErrors || {};
|
||||
state.loadErrors = data.loadErrors || {};
|
||||
renderSources();
|
||||
pcGear.hidden = state.streams.length === 0;
|
||||
if (state.streams.length) playSource(0);
|
||||
else {
|
||||
const failed = Object.keys({ ...state.loadErrors, ...state.providerErrors });
|
||||
const hidden = state.unsupported.length;
|
||||
if (failed.length || hidden) {
|
||||
const parts = ['No web-playable streams found.'];
|
||||
if (failed.length) parts.push(`Provider failures: ${failed.join(', ')}.`);
|
||||
if (hidden) parts.push(`Hidden ${hidden} unsupported source(s).`);
|
||||
showStatus(parts.join(' '), true);
|
||||
} else {
|
||||
showStatus('No streams found for this title.', true);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (token !== state.loadToken) return;
|
||||
SR.app.showError(e, 'stream lookup failed');
|
||||
showStatus('Stream lookup failed.', true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Sort the popup by provider: provider name is the primary key (A→Z),
|
||||
// original rank is the tie-breaker so order inside a provider is stable.
|
||||
function sortedStreams() {
|
||||
return state.streams
|
||||
.map((s, i) => ({ s, i }))
|
||||
.sort((a, b) => {
|
||||
const pa = String(a.s.provider || '').toLowerCase();
|
||||
const pb = String(b.s.provider || '').toLowerCase();
|
||||
if (pa !== pb) return pa < pb ? -1 : 1;
|
||||
return a.i - b.i;
|
||||
});
|
||||
}
|
||||
|
||||
function renderSources() {
|
||||
const list = document.getElementById('sourceList');
|
||||
list.replaceChildren();
|
||||
let lastProvider = null;
|
||||
for (const { s, i } of sortedStreams()) {
|
||||
if (s.provider !== lastProvider) {
|
||||
lastProvider = s.provider;
|
||||
const h = document.createElement('div');
|
||||
h.className = 'player-sources__group';
|
||||
h.textContent = s.provider || 'Other';
|
||||
list.appendChild(h);
|
||||
}
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = i === state.sourceIndex ? 'source-item source-item--active' : 'source-item';
|
||||
const meta = [s.quality, s.audio].filter(Boolean).join(' · ');
|
||||
b.innerHTML = `
|
||||
<span class="source-item__rank">${i + 1}</span>
|
||||
<span class="source-item__name">${SR.util.escapeHtml(s.name)}</span>
|
||||
${meta ? `<span class="source-item__meta">${SR.util.escapeHtml(meta)}</span>` : ''}`;
|
||||
b.addEventListener('click', () => playSource(i));
|
||||
list.appendChild(b);
|
||||
}
|
||||
const failures = { ...state.loadErrors, ...state.providerErrors };
|
||||
const failed = Object.keys(failures);
|
||||
if (failed.length) {
|
||||
const note = document.createElement('div');
|
||||
note.className = 'player-sources__group player-sources__group--error';
|
||||
note.textContent = `Failed: ${failed.join(', ')}`;
|
||||
note.title = failed.map((name) => `${name}: ${failures[name] || 'no streams'}`).join('\n');
|
||||
list.appendChild(note);
|
||||
}
|
||||
if (state.unsupported.length) {
|
||||
const types = [
|
||||
...new Set(state.unsupported.map((s) => String(s.type || 'unknown').toLowerCase())),
|
||||
];
|
||||
const note = document.createElement('div');
|
||||
note.className = 'player-sources__group player-sources__group--error';
|
||||
note.textContent = `Hidden unsupported: ${state.unsupported.length} (${types.join(', ')})`;
|
||||
note.title = state.unsupported
|
||||
.map((s) => `${s.provider || 'Other'}: ${s.name || 'stream'} (${s.type || 'unknown'})`)
|
||||
.join('\n');
|
||||
list.appendChild(note);
|
||||
}
|
||||
const count = `${state.streams.length} source${state.streams.length === 1 ? '' : 's'}`;
|
||||
document.getElementById('sourcesCount').textContent = state.unsupported.length
|
||||
? `${count} · ${state.unsupported.length} hidden`
|
||||
: count;
|
||||
}
|
||||
|
||||
function playSource(i) {
|
||||
const s = state.streams[i];
|
||||
if (!s) return;
|
||||
const key = keyFor();
|
||||
// Same episode as the one currently loaded → source switch: carry the
|
||||
// playhead over (resumeAt: null). A different episode → fresh resume:
|
||||
// pick up its own saved record, or start from the top.
|
||||
const resumeAt = state.loadedKey === key ? null : (() => {
|
||||
const rec = SR.storage.get(key);
|
||||
return rec && rec.t > 10 ? rec.t : 0;
|
||||
})();
|
||||
state.sourceIndex = i;
|
||||
state.loadedKey = key;
|
||||
closeSources();
|
||||
renderSources();
|
||||
sourceLabel.textContent = `${s.name} — ${[s.quality, s.provider].filter(Boolean).join(', ')}`;
|
||||
pcQuality.textContent = s.quality || '';
|
||||
player.load(s, { resumeAt });
|
||||
}
|
||||
|
||||
/* ---- resume persistence ---------------------------------------------------------- */
|
||||
|
||||
let lastPersist = 0;
|
||||
|
||||
function persistProgress(force) {
|
||||
const d = video.duration;
|
||||
if (!d || !isFinite(d)) return;
|
||||
const t = video.currentTime;
|
||||
if (t < 10) return;
|
||||
const key = keyFor();
|
||||
if (t >= d - 15 || t / d >= 0.95) {
|
||||
SR.storage.remove(key);
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (!force && now - lastPersist < 3000) return;
|
||||
lastPersist = now;
|
||||
const ep = state.episodes.find((e) => e.episode_number === state.episode);
|
||||
SR.storage.save({
|
||||
key,
|
||||
type,
|
||||
tmdbId: Number(id),
|
||||
season: state.season,
|
||||
episode: state.episode,
|
||||
show: state.details ? state.details.name || state.details.title : '',
|
||||
title: ep ? ep.name || '' : '',
|
||||
poster: state.details ? SR.util.tmdbResize(state.details.poster_url, 'w342') : '',
|
||||
t,
|
||||
d,
|
||||
at: now,
|
||||
provider: state.streams[state.sourceIndex] ? state.streams[state.sourceIndex].provider : '',
|
||||
});
|
||||
}
|
||||
|
||||
video.addEventListener('timeupdate', () => persistProgress(false));
|
||||
video.addEventListener('pause', () => persistProgress(true));
|
||||
video.addEventListener('seeked', () => persistProgress(true));
|
||||
video.addEventListener('ended', () => SR.storage.remove(keyFor()));
|
||||
window.addEventListener('pagehide', () => persistProgress(true));
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) persistProgress(true);
|
||||
});
|
||||
|
||||
/* ---- episodes ------------------------------------------------------------------------ */
|
||||
|
||||
async function loadSeasons() {
|
||||
const data = await SR.api.seasons(id);
|
||||
state.seasons = (data.seasons || []).slice().sort((a, b) => a.season_number - b.season_number);
|
||||
renderSeasonTabs();
|
||||
}
|
||||
|
||||
function renderSeasonTabs() {
|
||||
seasonTabs.replaceChildren();
|
||||
for (const s of state.seasons) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.role = 'tab';
|
||||
b.className = s.season_number === state.season ? 'chip chip--active' : 'chip';
|
||||
b.textContent = `Season ${s.season_number}`;
|
||||
b.title = `${s.name || `Season ${s.season_number}`} (${s.episode_count || 0})`;
|
||||
b.addEventListener('click', () => {
|
||||
if (s.season_number !== state.season) loadEpisodes(s.season_number, null);
|
||||
});
|
||||
seasonTabs.appendChild(b);
|
||||
}
|
||||
}
|
||||
|
||||
function showShelfSpinner() {
|
||||
episodeShelf.replaceChildren();
|
||||
const cell = document.createElement('div');
|
||||
cell.className = 'episode-shelf__loading';
|
||||
cell.innerHTML = '<div class="spinner"></div>';
|
||||
episodeShelf.appendChild(cell);
|
||||
}
|
||||
|
||||
function progressFor(season, episode) {
|
||||
const key = SR.storage.keyFor({ type, tmdbId: Number(id), season, episode });
|
||||
const rec = SR.storage.get(key);
|
||||
if (!rec || !rec.t || !rec.d) return 0;
|
||||
return Math.max(0, Math.min(1, rec.t / rec.d));
|
||||
}
|
||||
|
||||
function renderEpisodes() {
|
||||
episodeShelf.replaceChildren();
|
||||
if (!state.episodes.length) {
|
||||
const empty = SR.cards.emptyState('No episodes listed');
|
||||
empty.className = `${empty.className} episode-shelf__empty`;
|
||||
episodeShelf.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const ep of state.episodes) {
|
||||
const current = ep.episode_number === state.episode;
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = current ? 'episode-card episode-card--current' : 'episode-card';
|
||||
const date = ep.air_date ? ` · ${SR.util.escapeHtml(ep.air_date)}` : '';
|
||||
const still = ep.still || (ep.still_path ? SR.util.tmdbResize(ep.still_path, 'w300') : '');
|
||||
const progress = progressFor(state.season, ep.episode_number);
|
||||
|
||||
b.innerHTML = `
|
||||
<span class="episode-card__thumb${still ? '' : ' episode-card__thumb--empty'}">
|
||||
${still ? `<img src="${still}" alt="" loading="lazy">` : `<span aria-hidden="true">${ep.episode_number}</span>`}
|
||||
${progress > 0 ? `<span class="episode-card__progress" style="width:${Math.round(progress * 100)}%"></span>` : ''}
|
||||
</span>
|
||||
<span class="episode-card__body">
|
||||
<span class="episode-card__num">S${state.season} · E${ep.episode_number}${date}</span>
|
||||
<span class="episode-card__title">${SR.util.escapeHtml(ep.name || `Episode ${ep.episode_number}`)}</span>
|
||||
<span class="episode-card__meta">${SR.util.escapeHtml(SR.util.runtimeLabel(ep.runtime) || '')}</span>
|
||||
</span>`;
|
||||
|
||||
const img = b.querySelector('.episode-card__thumb img');
|
||||
if (img) {
|
||||
img.addEventListener('error', () => {
|
||||
const thumb = img.closest('.episode-card__thumb');
|
||||
img.remove();
|
||||
thumb.classList.add('episode-card__thumb--empty');
|
||||
const num = document.createElement('span');
|
||||
num.setAttribute('aria-hidden', 'true');
|
||||
num.textContent = ep.episode_number;
|
||||
thumb.prepend(num);
|
||||
});
|
||||
}
|
||||
|
||||
b.addEventListener('click', () => playEpisode(ep.episode_number));
|
||||
episodeShelf.appendChild(b);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEpisodes(season, autoplayEpisode) {
|
||||
const token = ++state.loadToken;
|
||||
state.season = season;
|
||||
state.episode = autoplayEpisode != null ? autoplayEpisode : null;
|
||||
renderSeasonTabs();
|
||||
showShelfSpinner();
|
||||
|
||||
const data = await SR.api.episodes(id, season);
|
||||
if (token !== state.loadToken) return;
|
||||
|
||||
state.episodes = data.episodes || [];
|
||||
if (autoplayEpisode != null && state.episodes.some((e) => e.episode_number === autoplayEpisode)) {
|
||||
playEpisode(autoplayEpisode);
|
||||
return;
|
||||
}
|
||||
state.episode = state.episodes.length ? state.episodes[0].episode_number : null;
|
||||
renderEpisodes();
|
||||
syncUrl();
|
||||
setPlayLabel();
|
||||
}
|
||||
|
||||
function playEpisode(n) {
|
||||
state.episode = n;
|
||||
syncUrl();
|
||||
renderEpisodes();
|
||||
setPlayLabel();
|
||||
openPlayer();
|
||||
loadStreams();
|
||||
}
|
||||
|
||||
playButton.addEventListener('click', () => {
|
||||
if (type === 'tv' && state.episode == null) {
|
||||
if (state.episodes.length) playEpisode(state.episodes[0].episode_number);
|
||||
return;
|
||||
}
|
||||
if (state.loadedKey === keyFor() && state.streams.length) {
|
||||
openPlayer();
|
||||
video.play().catch(() => {});
|
||||
return;
|
||||
}
|
||||
openPlayer();
|
||||
loadStreams();
|
||||
});
|
||||
|
||||
playerClose.addEventListener('click', closePlayer);
|
||||
|
||||
(async function init() {
|
||||
let details;
|
||||
try {
|
||||
details = await SR.api.details(type, id);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load this title');
|
||||
renderHeroError('Could not load this title.');
|
||||
return;
|
||||
}
|
||||
|
||||
state.details = details;
|
||||
renderHero(details);
|
||||
|
||||
if (type !== 'tv') {
|
||||
setPlayLabel();
|
||||
return;
|
||||
}
|
||||
|
||||
episodeSection.hidden = false;
|
||||
showStatus('Loading episodes…');
|
||||
|
||||
try {
|
||||
await loadSeasons();
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load seasons');
|
||||
renderHeroError('Could not load seasons.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.seasons.length) {
|
||||
renderHeroError('No seasons found for this show.');
|
||||
return;
|
||||
}
|
||||
|
||||
const sParam = parseInt(params.get('s'), 10);
|
||||
const eParam = parseInt(params.get('e'), 10);
|
||||
const hasSeason = (n) => state.seasons.some((s) => s.season_number === n);
|
||||
const season = hasSeason(sParam) ? sParam : hasSeason(1) ? 1 : state.seasons[0].season_number;
|
||||
|
||||
try {
|
||||
await loadEpisodes(season, null);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load episodes');
|
||||
renderHeroError('Could not load episodes.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.episodes.length) {
|
||||
renderHeroError('No episodes found for this show.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (season === sParam && state.episodes.some((e) => e.episode_number === eParam)) {
|
||||
playEpisode(eParam);
|
||||
}
|
||||
})();
|
||||
})();
|
||||
@@ -1,61 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>bug.tv — search</title>
|
||||
<link rel="stylesheet" href="css/tokens.css">
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<link rel="stylesheet" href="css/components.css">
|
||||
<link rel="stylesheet" href="css/pages.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="brand" href="index.html">bug<span>.tv</span></a>
|
||||
<nav class="site-header__nav" aria-label="Primary">
|
||||
|
||||
</nav>
|
||||
<div class="site-header__actions">
|
||||
<a class="icon-btn is-active" href="search.html" aria-label="Search" title="Search">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
|
||||
</a>
|
||||
<a class="icon-btn" href="settings.html" aria-label="Settings" title="Settings">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container page" id="content">
|
||||
<div class="search-bar">
|
||||
<form class="search-bar__form" role="search" onsubmit="return false">
|
||||
<input class="field search-bar__input" id="searchInput" type="search" placeholder="Search movies and shows…" autocomplete="off" spellcheck="false">
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="search-toolbar">
|
||||
<div class="chips" id="typeChips"></div>
|
||||
<span class="search-count" id="searchCount"></span>
|
||||
</div>
|
||||
|
||||
<div id="results"></div>
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="container">
|
||||
<span>tv.bug.tools</span>
|
||||
<span>api: <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
|
||||
<span>tv.bug.tools doesn't store files, but provides links to external services.</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="js/util.js"></script>
|
||||
<script src="js/config.js"></script>
|
||||
<script src="js/api.js"></script>
|
||||
<script src="js/storage.js"></script>
|
||||
<script src="js/cards.js"></script>
|
||||
<script src="js/app.js"></script>
|
||||
<script src="js/search.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,101 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>bug.tv — settings</title>
|
||||
<link rel="stylesheet" href="css/tokens.css">
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<link rel="stylesheet" href="css/components.css">
|
||||
<link rel="stylesheet" href="css/pages.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="brand" href="index.html">bug<span>.tv</span></a>
|
||||
<nav class="site-header__nav" aria-label="Primary">
|
||||
|
||||
</nav>
|
||||
<div class="site-header__actions">
|
||||
<a class="icon-btn" href="search.html" aria-label="Search" title="Search">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
|
||||
</a>
|
||||
<a class="icon-btn is-active" href="settings.html" aria-label="Settings" title="Settings" aria-current="page">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="page container">
|
||||
<div class="settings">
|
||||
<nav class="settings__nav" aria-label="Settings sections">
|
||||
<a class="settings__navlink is-active" href="#sources">Sources</a>
|
||||
<a class="settings__navlink" href="#server">Server</a>
|
||||
<a class="settings__navlink" href="#data">Data</a>
|
||||
</nav>
|
||||
|
||||
<div class="settings__content">
|
||||
<section class="settings__card" id="sources">
|
||||
<h2>Sources</h2>
|
||||
<p class="settings__hint">Choose which providers to search for streams. Saved in this browser; applies from the next stream lookup.</p>
|
||||
<div class="settings__actions">
|
||||
<button class="btn btn--ghost" id="allOn" type="button">Enable all</button>
|
||||
<button class="btn btn--ghost" id="allOff" type="button">Disable all</button>
|
||||
<button class="btn btn--ghost" id="providersReset" type="button">Server defaults</button>
|
||||
</div>
|
||||
<p class="settings__status" id="providersStatus"></p>
|
||||
<div class="provider-list" id="providerList"></div>
|
||||
</section>
|
||||
|
||||
<section class="settings__card" id="server">
|
||||
<h2>Server</h2>
|
||||
<p class="settings__hint">The REST API that bug.tv uses for providers, stream lookups and the media proxy. Change this only if you run your own instance.</p>
|
||||
<label class="field-label" for="apiBaseInput">API base URL</label>
|
||||
<input class="field" id="apiBaseInput" type="text" spellcheck="false" autocomplete="off" placeholder="https://api-tv.bug.tools">
|
||||
<div class="settings__actions">
|
||||
<button class="btn btn--primary" id="apiBaseSave" type="button">Save</button>
|
||||
<button class="btn btn--ghost" id="apiBaseReset" type="button">Reset to default</button>
|
||||
</div>
|
||||
<p class="settings__status" id="connStatus"></p>
|
||||
<p class="settings__hint">Search, details and images go straight to TMDB from your browser, using the key below — your server is not involved.</p>
|
||||
<label class="field-label" for="tmdbKeyInput">TMDB API key</label>
|
||||
<input class="field" id="tmdbKeyInput" type="text" spellcheck="false" autocomplete="off" placeholder="32-character TMDB API key">
|
||||
<div class="settings__actions">
|
||||
<button class="btn btn--primary" id="tmdbKeySave" type="button">Save</button>
|
||||
<button class="btn btn--ghost" id="tmdbKeyTest" type="button">Test</button>
|
||||
<button class="btn btn--ghost" id="tmdbKeyReset" type="button">Reset to default</button>
|
||||
</div>
|
||||
<p class="settings__status" id="tmdbStatus"></p>
|
||||
</section>
|
||||
|
||||
<section class="settings__card" id="data">
|
||||
<h2>Data</h2>
|
||||
<p class="settings__hint">Everything bug.tv stores lives in this browser — no accounts, nothing on a server.</p>
|
||||
<div class="settings__actions">
|
||||
<button class="btn btn--ghost" id="clearHistory" type="button">Clear continue-watching</button>
|
||||
<button class="btn btn--ghost" id="resetProviders" type="button">Reset source toggles</button>
|
||||
</div>
|
||||
<p class="settings__status" id="dataStatus"></p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="container">
|
||||
<span>tv.bug.tools</span>
|
||||
<span>api: <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
|
||||
<span>tv.bug.tools doesn't store files, but provides links to external services.</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="js/util.js"></script>
|
||||
<script src="js/config.js"></script>
|
||||
<script src="js/api.js"></script>
|
||||
<script src="js/storage.js"></script>
|
||||
<script src="js/cards.js"></script>
|
||||
<script src="js/app.js"></script>
|
||||
<script src="js/settings.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>bug.tv — watch</title>
|
||||
<link rel="stylesheet" href="css/tokens.css">
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<link rel="stylesheet" href="css/components.css">
|
||||
<link rel="stylesheet" href="css/pages.css">
|
||||
</head>
|
||||
<body class="watch-page">
|
||||
<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="brand" href="index.html">bug<span>.tv</span></a>
|
||||
<nav class="site-header__nav" aria-label="Primary">
|
||||
|
||||
</nav>
|
||||
<div class="site-header__actions">
|
||||
<a class="icon-btn" href="search.html" aria-label="Search" title="Search">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
|
||||
</a>
|
||||
<a class="icon-btn" href="settings.html" aria-label="Settings" title="Settings">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="page page--watch" id="content">
|
||||
<section id="hero" class="watch-hero" aria-labelledby="heroTitle">
|
||||
<div id="heroBackdrop" class="watch-hero__backdrop" aria-hidden="true"></div>
|
||||
<div class="watch-hero__scrim" aria-hidden="true"></div>
|
||||
<div class="watch-hero__inner">
|
||||
<img id="heroTitleCard" class="watch-hero__logo" hidden alt="">
|
||||
<h1 id="heroTitle" class="watch-hero__title">Loading…</h1>
|
||||
<div id="heroMeta" class="watch-hero__meta"></div>
|
||||
<div id="heroGenres" class="watch-hero__genres"></div>
|
||||
<p id="heroOverview" class="watch-hero__overview"></p>
|
||||
<div class="watch-hero__actions">
|
||||
<button id="playButton" class="btn btn--primary" type="button">
|
||||
<span id="playLabel">Play</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="episodeSection" class="watch-episodes" hidden>
|
||||
<div class="container">
|
||||
<h2 class="watch-episodes__title">Episodes</h2>
|
||||
<div id="seasonTabs" class="season-tabs" role="tablist" aria-label="Seasons"></div>
|
||||
<div id="episodeShelf" class="episode-shelf" role="list"></div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div id="playerOverlay" class="player-overlay" hidden>
|
||||
<button id="playerClose" class="icon-btn player-overlay__close" type="button" aria-label="Close player">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
||||
</button>
|
||||
<div class="player-wrap" id="playerWrap">
|
||||
<video id="video" playsinline preload="metadata"></video>
|
||||
|
||||
<button class="player-bigplay" id="bigPlay" type="button" aria-label="Play">
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"></path></svg>
|
||||
</button>
|
||||
|
||||
<div class="player-controls" id="playerControls">
|
||||
<input class="pc-seek" id="pcSeek" type="range" min="0" max="1000" step="1" value="0" aria-label="Seek position">
|
||||
<div class="player-controls__bar">
|
||||
<button class="pc-btn" id="pcPlay" type="button" aria-label="Play or pause">
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"></path></svg>
|
||||
</button>
|
||||
<button class="pc-btn" id="pcMute" type="button" aria-label="Mute or unmute">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path><path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path></svg>
|
||||
</button>
|
||||
<input class="pc-vol" id="pcVol" type="range" min="0" max="1" step="0.05" value="1" aria-label="Volume">
|
||||
<span class="pc-time" id="pcTime">0:00 / 0:00</span>
|
||||
<span class="player-controls__spacer"></span>
|
||||
<button class="pc-btn pc-btn--text" id="pcCc" type="button" aria-pressed="false" aria-label="Toggle captions">CC</button>
|
||||
<span class="pc-quality" id="pcQuality"></span>
|
||||
<button class="pc-btn" id="pcGear" type="button" aria-label="Source settings">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
|
||||
</button>
|
||||
<button class="pc-btn" id="pcPip" type="button" aria-label="Picture in picture">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="4" width="20" height="14" rx="2"></rect><rect x="12" y="9" width="7" height="5" rx="1" fill="currentColor" stroke="none"></rect></svg>
|
||||
</button>
|
||||
<button class="pc-btn" id="pcFull" type="button" aria-label="Toggle fullscreen">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="player-status" id="playerStatus" hidden>
|
||||
<div class="spinner"></div>
|
||||
<p>Warming up…</p>
|
||||
</div>
|
||||
|
||||
<div class="player-sources" id="sourcesPanel" hidden>
|
||||
<div class="player-sources__head">
|
||||
<span>Sources · <span id="sourcesCount"></span></span>
|
||||
<button class="player-sources__close" id="sourcesClose" type="button" aria-label="Close sources">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="player-sources__list" id="sourceList"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="watch-toolbar">
|
||||
<span class="watch-toolbar__source" id="sourceLabel"></span>
|
||||
<span id="resumeNote"></span>
|
||||
<span class="watch-toolbar__spacer"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="container">
|
||||
<span>tv.bug.tools</span>
|
||||
<span>api: <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
|
||||
<span>tv.bug.tools doesn't store files, but provides links to external services.</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="vendor/hls.min.js"></script>
|
||||
<script src="js/util.js"></script>
|
||||
<script src="js/config.js"></script>
|
||||
<script src="js/api.js"></script>
|
||||
<script src="js/storage.js"></script>
|
||||
<script src="js/cards.js"></script>
|
||||
<script src="js/app.js"></script>
|
||||
<script src="js/player.js"></script>
|
||||
<script src="js/watch.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user