Rebuild the web UI in React and Tailwind #279

Merged
naps62-yolo merged 4 commits from 278-react-tailwind-ui into main 2026-11-11 16:34:48 +00:00
31 changed files with 11435 additions and 10503 deletions
+4 -3
View File
@@ -12,9 +12,10 @@ web
## Stack
Vite + TypeScript SPA, no framework *(fixed by DESIGN.md §11: `web/` is a
Vite + TypeScript SPA embedded in the Rust binary via `include_dir`; the
reference project `~/tea/maestro` is framework-free vanilla TS)*.
Vite + TypeScript SPA embedded in the Rust binary via `include_dir`
(DESIGN.md §11), built with React and Tailwind v4 (#278). Tailwind's theme is
reset to the design tokens, so utilities only ever produce token values; the
board's own component styles live in `web/src/components.css`.
## Users
+11 -1
View File
@@ -1,7 +1,12 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.8/schema.json",
"files": {
"includes": ["web/**", "!web/src/api/**", "!web/dist/**", "!web/node_modules/**"]
"includes": [
"web/**",
"!web/src/api/**",
"!web/dist/**",
"!web/node_modules/**"
]
},
"formatter": {
"enabled": true,
@@ -21,5 +26,10 @@
"organizeImports": "on"
}
}
},
"css": {
"parser": {
"tailwindDirectives": true
}
}
}
+2 -471
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark" />
<title>arr</title>
<script type="module" src="/src/main.ts"></script>
<script type="module" src="/src/main.tsx"></script>
</head>
<body>
<!--
@@ -78,191 +78,6 @@
panels; every slot reserves its final size before data arrives. Detail
pages open with a back control and the title, then one action bar.
-->
<header class="rail" id="rail">
<div class="rail-inner">
<div class="rail-id">
<span class="lamp" id="master-lamp" data-state="probing" aria-hidden="true"></span>
<a class="wordmark" id="wordmark" href="/">arr</a>
</div>
<nav class="rail-nav" aria-label="destinations">
<a class="nav-link" href="/" data-dest="library">library</a>
<a class="nav-link" href="/queues" data-dest="queues"
>queues<span class="nav-count readout" data-role="queues-count" hidden></span
></a>
<a class="nav-link" href="/settings" data-dest="settings">settings</a>
</nav>
<div class="rail-search" id="rail-search">
<span class="rail-search-glyph" data-glyph="search" aria-hidden="true"></span>
<input
id="search"
class="search-input readout"
type="text"
spellcheck="false"
autocomplete="off"
enterkeyhint="search"
placeholder="title, tmdb id, tt…, magnet"
aria-label="unified search — titles, TMDB or IMDb ids, magnets and .torrent links"
/>
<span class="search-hint readout" id="search-hint" aria-hidden="true">/</span>
<button
type="button"
class="control control-icon rail-search-close"
id="search-close"
aria-label="close search"
data-glyph="close"
></button>
</div>
<button
type="button"
class="control control-icon rail-search-open"
id="search-open"
aria-label="search"
data-glyph="search"
></button>
<span class="readout dim rail-version" id="version" data-testid="version">v —</span>
</div>
</header>
<nav class="tabbar" id="tabbar" aria-label="destinations">
<a class="tab" href="/" data-dest="library"
><span data-glyph="library" aria-hidden="true"></span><span class="tab-label">library</span></a
>
<a class="tab" href="/search" data-dest="search"
><span data-glyph="search" aria-hidden="true"></span><span class="tab-label">search</span></a
>
<a class="tab" href="/queues" data-dest="queues"
><span data-glyph="warning" aria-hidden="true"></span><span class="tab-label">queues</span
><span class="tab-badge readout" data-role="queues-count" hidden></span
></a>
<a class="tab" href="/settings" data-dest="settings"
><span data-glyph="cog" aria-hidden="true"></span><span class="tab-label">settings</span></a
>
</nav>
<main class="deck" id="deck" hidden aria-label="search results">
<header class="page-bar">
<h2 class="page-title">search</h2>
<p class="head-status readout" id="deck-status" role="status" data-empty="true"></p>
</header>
<div class="segmented deck-filter" id="deck-filter" role="toolbar" aria-label="show only one kind" hidden>
<button type="button" class="seg" data-kind="all" aria-pressed="true">
all<span class="filter-count" data-role="count"></span>
</button>
<button type="button" class="seg" data-kind="movie" aria-pressed="false">
movies<span class="filter-count" data-role="count"></span>
</button>
<button type="button" class="seg" data-kind="series" aria-pressed="false">
series<span class="filter-count" data-role="count"></span>
</button>
</div>
<section class="deck-group" id="group-library" hidden aria-labelledby="label-library">
<header class="deck-head">
<h3 class="deck-label" id="label-library">in library</h3>
<span class="deck-count readout" id="count-library"></span>
</header>
<ul class="deck-rows" id="rows-library"></ul>
</section>
<section class="deck-group" id="group-tmdb" hidden aria-labelledby="label-tmdb">
<header class="deck-head">
<h3 class="deck-label" id="label-tmdb">on tmdb</h3>
<span class="deck-count readout" id="count-tmdb"></span>
</header>
<ul class="deck-rows" id="rows-tmdb"></ul>
</section>
<section class="deck-group" id="group-manual" hidden aria-labelledby="label-manual">
<header class="deck-head">
<h3 class="deck-label" id="label-manual">manual grab</h3>
</header>
<article class="module intake" id="manual-intake"></article>
</section>
</main>
<main class="deck" id="library" hidden aria-label="library">
<header class="page-bar">
<h2 class="page-title">library</h2>
<span class="deck-count readout" id="library-summary"></span>
<p class="head-status readout" id="library-status" role="status" data-empty="true"></p>
<fieldset class="segmented" aria-label="layout">
<button type="button" class="seg seg-icon" id="library-view-grid" aria-pressed="true" aria-label="poster grid" data-glyph="grid"></button>
<button type="button" class="seg seg-icon" id="library-view-list" aria-pressed="false" aria-label="list" data-glyph="list"></button>
</fieldset>
</header>
<div id="library-libraries"></div>
<section class="deck-group" id="library-series" hidden aria-labelledby="label-lib-series">
<header class="deck-head">
<h3 class="deck-label" id="label-lib-series">series</h3>
<span class="deck-count readout" id="count-lib-series"></span>
</header>
<ul class="deck-rows" id="rows-lib-series"></ul>
</section>
<section class="deck-group" id="library-movies" hidden aria-labelledby="label-lib-movies">
<header class="deck-head">
<h3 class="deck-label" id="label-lib-movies">movies</h3>
<span class="deck-count readout" id="count-lib-movies"></span>
</header>
<ul class="deck-rows" id="rows-lib-movies"></ul>
</section>
</main>
<main class="deck" id="queues" hidden aria-label="attention queues">
<header class="page-bar">
<h2 class="page-title">queues</h2>
<span class="deck-count readout" id="queues-summary"></span>
<p class="head-status readout" id="queues-status" role="status" data-empty="true"></p>
</header>
<section class="deck-group" id="queue-no-pt" hidden aria-labelledby="label-no-pt">
<header class="deck-head">
<h3 class="deck-label" id="label-no-pt">no pt source</h3>
<span class="deck-count readout" id="count-no-pt"></span>
</header>
<div class="group-note" data-explain-group>
<p>Kids titles with no Portuguese release yet.</p>
<p class="group-note-more" hidden>
They can sit here for months, by design. Allow English writes the movie's override
and its search goes ahead. A series waits for its own page.
</p>
</div>
<ul class="deck-rows" id="rows-no-pt"></ul>
</section>
<section class="deck-group" id="queue-decision" hidden aria-labelledby="label-decision">
<header class="deck-head">
<h3 class="deck-label" id="label-decision">needs decision</h3>
<span class="deck-count readout" id="count-decision"></span>
</header>
<div class="group-note" data-explain-group>
<p>Titles where two different releases failed.</p>
<p class="group-note-more" hidden>
Open the movie and pick a release by hand. Series entries are display-only for now.
</p>
</div>
<ul class="deck-rows" id="rows-decision"></ul>
</section>
<section class="deck-group" id="queue-subtitles" hidden aria-labelledby="label-subtitles">
<header class="deck-head">
<h3 class="deck-label" id="label-subtitles">missing subtitles</h3>
<span class="deck-count readout" id="count-subtitles"></span>
</header>
<div class="group-note" data-explain-group>
<p>A wanted subtitle language is missing.</p>
<p class="group-note-more" hidden>
Each chip says why: no candidate, a translation or provider failure, the daily budget,
or a timing sync that looked wrong. Open the title to search, translate or retry.
</p>
</div>
<ul class="deck-rows" id="rows-subtitles"></ul>
</section>
</main>
<!--
MOVIE PAGE (§9.6, issue 149): a library row opens /movies/{id} — one
machined module carries what the film IS: backdrop hotlinked from TMDB
@@ -278,195 +93,6 @@
rejection rules untouched; /movies/{id}/releases lands here with the
deck section in view.
-->
<main class="deck detail" id="movie" hidden aria-label="movie detail">
<section class="hero" id="movie-hero" aria-label="title metadata">
<header class="page-head">
<button type="button" class="control control-icon" id="movie-back" aria-label="back" data-glyph="back"></button>
<h2 class="page-title" id="movie-title" tabindex="-1">&nbsp;</h2>
<span class="page-year readout" id="movie-year"></span>
</header>
<div class="hero-body">
<div class="hero-poster"><img class="movie-poster" id="movie-poster" alt="" /></div>
<div class="hero-info">
<span class="hero-chips" id="movie-chips"></span>
<p class="hero-rating readout" id="movie-rating"></p>
<p class="hero-meta readout" id="movie-meta"></p>
<p class="hero-tagline" id="movie-tagline"></p>
<p class="hero-overview" id="movie-overview"></p>
</div>
</div>
<p class="r-note hero-note readout" id="movie-note" role="status" hidden></p>
</section>
<div class="actionbar">
<button type="button" class="control" id="movie-sweep">search indexers</button>
<span class="actionbar-links" id="movie-actions"></span>
<button
type="button"
class="control control-icon"
id="movie-more"
aria-label="library settings for this title"
aria-expanded="false"
aria-controls="movie-more-panel"
data-glyph="more"
></button>
</div>
<div class="more-panel" id="movie-more-panel" hidden>
<div class="more-links" id="movie-links"></div>
<div class="more-toggles" id="movie-toggles"></div>
<p class="control-note readout" id="movie-blocked-note" hidden>
Targeted search is off. RSS still matches this title, so a release can still arrive.
</p>
<label class="field more-field">
<span class="field-label" id="movie-root-label">root</span>
<select class="form-input" id="movie-root" aria-labelledby="movie-root-label"></select>
</label>
<button
type="button"
class="control control-quiet"
data-kind="delete"
id="movie-remove"
aria-expanded="false"
aria-controls="remove-panel"
>
remove from library
</button>
<div class="remove-panel" id="remove-panel" hidden></div>
</div>
<p class="deck-status readout" id="movie-status" role="status" data-empty="true"></p>
<section class="deck-group" id="movie-files" aria-labelledby="label-disk">
<header class="deck-head">
<h3 class="section-title" id="label-disk">on disk</h3>
<span class="deck-count readout" id="count-disk"></span>
</header>
<ul class="deck-rows" id="rows-disk"></ul>
</section>
<section class="deck-group" id="movie-releases" aria-labelledby="label-releases">
<header class="deck-head">
<h3 class="section-title" id="label-releases">releases</h3>
</header>
<p class="deck-status readout" id="releases-status" role="status" data-empty="true"></p>
<div class="buckets" id="movie-buckets"></div>
</section>
</main>
<main class="deck" id="settings" hidden aria-label="settings">
<header class="page-bar">
<h2 class="page-title">settings</h2>
<span class="deck-count readout" id="settings-summary"></span>
<p class="head-status readout" id="settings-status" role="status" data-empty="true"></p>
</header>
<section class="deck-group" id="group-chain" aria-labelledby="label-chain">
<header class="deck-head">
<h3 class="section-title" id="label-chain">signal chain</h3>
</header>
<section class="chain-wrap" aria-label="signal chain">
<div class="chain">
<article class="module area-tmdb" data-check="tmdb">
<header class="module-head">
<span class="lamp" data-state="probing" aria-hidden="true"></span>
<h4 class="module-name">tmdb</h4>
<span class="module-status readout" data-role="status">probing</span>
</header>
<p class="module-role">metadata in</p>
<p class="module-detail readout" data-role="detail">titles, languages, release dates</p>
</article>
<div class="bus area-t1" aria-hidden="true">
<svg viewBox="0 0 40 8" preserveAspectRatio="none" class="bus-trace" data-trace="tmdb" aria-hidden="true">
<line x1="0" y1="4" x2="32" y2="4" />
<path d="M32 0.5 39 4 32 7.5 Z" class="bus-arrow" />
</svg>
</div>
<article class="module area-prowlarr" data-check="prowlarr">
<header class="module-head">
<span class="lamp" data-state="probing" aria-hidden="true"></span>
<h4 class="module-name">prowlarr</h4>
<span class="module-status readout" data-role="status">probing</span>
</header>
<p class="module-role">indexers in</p>
<p class="module-detail readout" data-role="detail">torznab search and rss</p>
</article>
<div class="bus area-t2" aria-hidden="true">
<svg viewBox="0 0 40 8" preserveAspectRatio="none" class="bus-trace" data-trace="prowlarr" aria-hidden="true">
<line x1="0" y1="4" x2="32" y2="4" />
<path d="M32 0.5 39 4 32 7.5 Z" class="bus-arrow" />
</svg>
</div>
<article class="module module-master area-master" data-check="master">
<header class="module-head">
<span class="lamp lamp-big" data-state="probing" aria-hidden="true"></span>
<h4 class="module-name">arr</h4>
<span class="module-status readout" data-role="status">probing</span>
</header>
<p class="module-role">reconcile core</p>
<p class="module-detail readout" data-role="detail">decide · find · fetch · import</p>
</article>
<div class="bus area-out" aria-hidden="true">
<svg viewBox="0 0 40 8" preserveAspectRatio="none" class="bus-trace" data-trace="master" aria-hidden="true">
<line x1="0" y1="4" x2="32" y2="4" />
<path d="M32 0.5 39 4 32 7.5 Z" class="bus-arrow" />
</svg>
</div>
<article class="module area-qbittorrent" data-check="qbit">
<header class="module-head">
<span class="lamp" data-state="probing" aria-hidden="true"></span>
<h4 class="module-name">qbittorrent</h4>
<span class="module-status readout" data-role="status">probing</span>
</header>
<p class="module-role">torrents out</p>
<p class="module-detail readout" data-role="detail">webui · grab and seed</p>
</article>
</div>
</section>
<section class="chain-lane" id="chain-subs" aria-label="subtitle lane" hidden></section>
</section>
<section class="deck-group" id="group-roots" hidden aria-labelledby="label-roots">
<header class="deck-head">
<h3 class="section-title" id="label-roots">roots</h3>
<button type="button" class="control control-quiet head-action" id="root-add">add root</button>
</header>
<ul class="deck-rows" id="rows-roots"></ul>
</section>
<section class="deck-group" id="group-policies" hidden aria-labelledby="label-policies">
<header class="deck-head">
<h3 class="section-title" id="label-policies">policies</h3>
<button type="button" class="control control-quiet head-action" id="policy-add">add policy</button>
</header>
<div class="group-note">
<p>Editing a policy rescores every title's releases straight away.</p>
</div>
<ul class="deck-rows" id="rows-policies"></ul>
</section>
<section class="deck-group" id="group-subtitles" hidden aria-labelledby="label-settings-subtitles">
<header class="deck-head">
<h3 class="section-title" id="label-settings-subtitles">subtitles</h3>
</header>
<div class="group-note" data-explain-group>
<p>Provider logins and translator keys are not shown here.</p>
<p class="group-note-more" hidden>
They live in the daemon's config and environment (§10), along with the remote-command
template.
</p>
</div>
<div id="subtitles-body"></div>
</section>
</main>
<!--
SERIES DETAIL (§4.1 + §4.2 + §9.3, issue 129): a series row anywhere
opens /series/{id} — the title line carries the audience chip, the
@@ -478,101 +104,6 @@
not name claims — with want/search/deck only where they can do
something: an unaired episode offers no search button at all.
-->
<main class="deck detail" id="series" hidden aria-label="series detail">
<section class="hero" id="series-hero" aria-label="title metadata">
<header class="page-head">
<button type="button" class="control control-icon" id="series-back" aria-label="back" data-glyph="back"></button>
<h2 class="page-title" id="series-title" tabindex="-1">&nbsp;</h2>
<span class="page-year readout" id="series-year"></span>
</header>
<div class="hero-body">
<div class="hero-poster"><img class="movie-poster" id="series-poster" alt="" /></div>
<div class="hero-info">
<!-- audience, episode counts and §4.2 status: operational state,
outranking the artwork, folded into this one header (issue 150) -->
<span class="hero-chips" id="series-chips"></span>
<p class="hero-rating readout" id="series-rating"></p>
<p class="hero-meta readout" id="series-meta"></p>
<p class="hero-tagline" id="series-tagline"></p>
<p class="hero-overview" id="series-overview"></p>
</div>
</div>
<p class="r-note hero-note readout" id="series-note" role="status" hidden></p>
</section>
<div class="actionbar">
<span class="actionbar-links" id="series-actions"></span>
<button
type="button"
class="control control-icon"
id="series-more"
aria-label="library settings for this title"
aria-expanded="false"
aria-controls="series-more-panel"
data-glyph="more"
></button>
</div>
<div class="more-panel" id="series-more-panel" hidden>
<div class="more-links" id="series-links"></div>
<label class="field more-field">
<span class="field-label" id="series-root-label">root</span>
<select
class="form-input"
id="series-root"
data-focus-id="series-root"
aria-labelledby="series-root-label"
></select>
</label>
<button
type="button"
class="control control-quiet"
data-kind="delete"
id="series-remove"
aria-expanded="false"
aria-controls="series-remove-panel"
>
remove from library
</button>
<div class="remove-panel" id="series-remove-panel" hidden></div>
</div>
<p class="deck-status readout" id="series-status" role="status" data-empty="true"></p>
<section class="deck-group" aria-labelledby="label-seasons">
<header class="deck-head">
<h3 class="section-title" id="label-seasons">seasons</h3>
</header>
<ul class="deck-rows seasons" id="rows-seasons"></ul>
</section>
</main>
<main class="deck detail" id="tv-releases" hidden aria-label="season and episode releases">
<header class="page-head">
<button type="button" class="control control-icon" id="tv-releases-back" aria-label="back" data-glyph="back"></button>
<div class="page-id">
<h2 class="page-title" id="tv-releases-title">&nbsp;</h2>
<span class="page-sub readout" id="tv-releases-sub"></span>
</div>
</header>
<div class="actionbar">
<button type="button" class="control" id="tv-releases-sweep">search indexers</button>
</div>
<p class="deck-status readout" id="tv-releases-status" role="status" data-empty="true"></p>
<!-- issue 227: a pack that downloaded in full and was condemned at
import (§5.7). It outlives the status line because it is a fact
about the season, not about the request in flight. -->
<section class="deck-notice" id="tv-releases-failure" hidden aria-labelledby="tv-failure-label">
<h3 class="deck-label" id="tv-failure-label">pack abandoned at import</h3>
<p class="notice-release readout" id="tv-failure-release"></p>
<p class="notice-line" id="tv-failure-what"></p>
<p class="notice-line" id="tv-failure-next"></p>
<p class="notice-line dim">
Nothing was imported, and the torrent was left where it is: nothing is deleted early to
satisfy the library (§7.3).
</p>
</section>
<div class="buckets" id="tv-buckets"></div>
</main>
<div id="app"></div>
</body>
</html>
+9
View File
@@ -14,8 +14,17 @@
},
"devDependencies": {
"@biomejs/biome": "^2.5.8",
"@tailwindcss/vite": "^4.3.5",
"@types/node": "^24.0.0",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^5.2.0",
"tailwindcss": "^4.3.5",
"typescript": "^5.9.3",
"vite": "^7.1.0"
},
"dependencies": {
"react": "^19.3.1",
"react-dom": "^19.3.1"
}
}
+808 -2
View File
@@ -7,22 +7,127 @@ settings:
importers:
.:
dependencies:
react:
specifier: ^19.3.1
version: 19.3.1
react-dom:
specifier: ^19.3.1
version: 19.3.1(react@19.3.1)
devDependencies:
'@biomejs/biome':
specifier: ^2.5.8
version: 2.5.10
'@tailwindcss/vite':
specifier: ^4.3.5
version: 4.3.5(vite@7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0))
'@types/node':
specifier: ^24.0.0
version: 24.13.3
'@types/react':
specifier: ^19.3.0
version: 19.3.0
'@types/react-dom':
specifier: ^19.3.0
version: 19.3.0(@types/react@19.3.0)
'@vitejs/plugin-react':
specifier: ^5.2.0
version: 5.2.0(vite@7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0))
tailwindcss:
specifier: ^4.3.5
version: 4.3.5
typescript:
specifier: ^5.9.3
version: 5.9.3
vite:
specifier: ^7.1.0
version: 7.3.6(@types/node@24.13.3)
version: 7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)
packages:
'@babel/code-frame@7.29.7':
resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}
engines: {node: '>=6.9.0'}
'@babel/compat-data@7.29.7':
resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==}
engines: {node: '>=6.9.0'}
'@babel/core@7.29.13':
resolution: {integrity: sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==}
engines: {node: '>=6.9.0'}
'@babel/generator@7.29.13':
resolution: {integrity: sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw==}
engines: {node: '>=6.9.0'}
'@babel/helper-compilation-targets@7.29.13':
resolution: {integrity: sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==}
engines: {node: '>=6.9.0'}
'@babel/helper-globals@7.29.7':
resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}
engines: {node: '>=6.9.0'}
'@babel/helper-module-imports@7.29.7':
resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==}
engines: {node: '>=6.9.0'}
'@babel/helper-module-transforms@7.29.13':
resolution: {integrity: sha512-/U96wOz+SCoZ7Da/8kjDGltcNY280JPQcRNPK0Hk3PTbdpaiBDQImtC6JsbVwb1HGMr3usZQU2WsWVjhYNmRzw==}
engines: {node: '>=6.9.0'}
peerDependencies:
'@babel/core': ^7.0.0
'@babel/helper-plugin-utils@7.29.7':
resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==}
engines: {node: '>=6.9.0'}
'@babel/helper-string-parser@7.29.13':
resolution: {integrity: sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==}
engines: {node: '>=6.9.0'}
'@babel/helper-validator-identifier@7.29.7':
resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}
engines: {node: '>=6.9.0'}
'@babel/helper-validator-option@7.29.7':
resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}
engines: {node: '>=6.9.0'}
'@babel/helpers@7.29.13':
resolution: {integrity: sha512-laoRpD/kO/iA4CDlgJbixHekg7oPvWALK0PQyK3Ob2I2njZRvVAD77RfWCIImtqWCq6KijoBoZK7bp/HlTWASQ==}
engines: {node: '>=6.9.0'}
'@babel/parser@7.29.13':
resolution: {integrity: sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==}
engines: {node: '>=6.0.0'}
hasBin: true
'@babel/plugin-transform-react-jsx-self@7.29.7':
resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==}
engines: {node: '>=6.9.0'}
peerDependencies:
'@babel/core': ^7.0.0-0
'@babel/plugin-transform-react-jsx-source@7.29.7':
resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==}
engines: {node: '>=6.9.0'}
peerDependencies:
'@babel/core': ^7.0.0-0
'@babel/template@7.29.7':
resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}
engines: {node: '>=6.9.0'}
'@babel/traverse@7.29.13':
resolution: {integrity: sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q==}
engines: {node: '>=6.9.0'}
'@babel/types@7.29.11':
resolution: {integrity: sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==}
engines: {node: '>=6.9.0'}
'@biomejs/biome@2.5.10':
resolution: {integrity: sha512-WRKXARA3kTuiV5sxqTpobJ/I0MVd4vk3pOL6wnp5az4LntFIhWTj1RWZq3DI9PCEN3lXcqy7p5aqUHzvq8AXyQ==}
engines: {node: '>=14.21.3'}
@@ -236,6 +341,22 @@ packages:
cpu: [x64]
os: [win32]
'@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
'@jridgewell/remapping@2.3.5':
resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}
'@jridgewell/resolve-uri@3.1.2':
resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
engines: {node: '>=6.0.0'}
'@jridgewell/sourcemap-codec@1.6.0':
resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
'@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
engines: {node: ^22.20 || ^24.12 || >=25}
@@ -243,6 +364,9 @@ packages:
os: [linux]
libc: [glibc]
'@rolldown/pluginutils@1.0.0-rc.3':
resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==}
'@rollup/rollup-android-arm-eabi@4.62.5':
resolution: {integrity: sha512-jfkGfTwhQpsiSckPF8r9bU3pn3vyd72NlWaO+TgEO6WPSDnUhXzrNYCHBMOYj0ACaUgjm6eERLF+XV9a6RstoA==}
cpu: [arm]
@@ -381,17 +505,179 @@ packages:
cpu: [x64]
os: [win32]
'@tailwindcss/node@4.3.5':
resolution: {integrity: sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==}
'@tailwindcss/oxide-android-arm64@4.3.5':
resolution: {integrity: sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [android]
'@tailwindcss/oxide-darwin-arm64@4.3.5':
resolution: {integrity: sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [darwin]
'@tailwindcss/oxide-darwin-x64@4.3.5':
resolution: {integrity: sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==}
engines: {node: '>= 20'}
cpu: [x64]
os: [darwin]
'@tailwindcss/oxide-freebsd-x64@4.3.5':
resolution: {integrity: sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [freebsd]
'@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5':
resolution: {integrity: sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==}
engines: {node: '>= 20'}
cpu: [arm]
os: [linux]
'@tailwindcss/oxide-linux-arm64-gnu@4.3.5':
resolution: {integrity: sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tailwindcss/oxide-linux-arm64-musl@4.3.5':
resolution: {integrity: sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tailwindcss/oxide-linux-x64-gnu@4.3.5':
resolution: {integrity: sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tailwindcss/oxide-linux-x64-musl@4.3.5':
resolution: {integrity: sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tailwindcss/oxide-wasm32-wasi@4.3.5':
resolution: {integrity: sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==}
engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
bundledDependencies:
- '@napi-rs/wasm-runtime'
- '@emnapi/core'
- '@emnapi/runtime'
- '@tybys/wasm-util'
- '@emnapi/wasi-threads'
- tslib
'@tailwindcss/oxide-win32-arm64-msvc@4.3.5':
resolution: {integrity: sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [win32]
'@tailwindcss/oxide-win32-x64-msvc@4.3.5':
resolution: {integrity: sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [win32]
'@tailwindcss/oxide@4.3.5':
resolution: {integrity: sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==}
engines: {node: '>= 20'}
'@tailwindcss/vite@4.3.5':
resolution: {integrity: sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==}
peerDependencies:
vite: ^5.2.0 || ^6 || ^7 || ^8
'@types/babel__core@7.20.5':
resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}
'@types/babel__generator@7.27.0':
resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}
'@types/babel__template@7.4.4':
resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}
'@types/babel__traverse@7.28.0':
resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}
'@types/estree@1.0.9':
resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
'@types/node@24.13.3':
resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}
'@types/react-dom@19.3.0':
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
peerDependencies:
'@types/react': ^19.3.0
'@types/react@19.3.0':
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
'@vitejs/plugin-react@5.2.0':
resolution: {integrity: sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==}
engines: {node: ^20.19.0 || >=22.12.0}
peerDependencies:
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
baseline-browser-mapping@2.11.35:
resolution: {integrity: sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ==}
engines: {node: '>=6.0.0'}
hasBin: true
browserslist@4.29.5:
resolution: {integrity: sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
hasBin: true
caniuse-lite@1.0.30001823:
resolution: {integrity: sha512-TQ5s/djDjNk1axreUW+4rULH+BmdCMLiJkhaXnO5wqivG7tITkSUj4ItIdzqdZHKaXcHAV8dhH3JxOM7/7bwqw==}
convert-source-map@2.0.0:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
debug@4.4.3:
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
detect-libc@2.1.2:
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
electron-to-chromium@1.5.478:
resolution: {integrity: sha512-pftG+ma5Lm8O6/p45bhYT6StBN5ziQymaRzmCZwFl8DwWHKPPD93FdOmP1aqftcepolQYvrcyTLa17kE8Yf+jg==}
enhanced-resolve@5.26.1:
resolution: {integrity: sha512-PPnnSJq3azKOIewXR/uppBV/6h98dprBJ/WaQ9Qgj10xX1lJLNfg+XShpbsrSqcDSy2yYYyhfXM1wWhftqgyzw==}
engines: {node: '>=10.13.0'}
esbuild@0.28.2:
resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
engines: {node: '>=18'}
hasBin: true
escalade@3.2.0:
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'}
fdir@6.5.0:
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
engines: {node: '>=12.0.0'}
@@ -406,11 +692,122 @@ packages:
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
gensync@1.0.0-beta.2:
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
engines: {node: '>=6.9.0'}
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
jiti@2.7.0:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
jsesc@3.1.0:
resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
engines: {node: '>=6'}
hasBin: true
json5@2.2.3:
resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
engines: {node: '>=6'}
hasBin: true
lightningcss-android-arm64@1.33.0:
resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [android]
lightningcss-darwin-arm64@1.33.0:
resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [darwin]
lightningcss-darwin-x64@1.33.0:
resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [darwin]
lightningcss-freebsd-x64@1.33.0:
resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [freebsd]
lightningcss-linux-arm-gnueabihf@1.33.0:
resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm]
os: [linux]
lightningcss-linux-arm64-gnu@1.33.0:
resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
lightningcss-linux-arm64-musl@1.33.0:
resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
lightningcss-linux-x64-gnu@1.33.0:
resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
lightningcss-linux-x64-musl@1.33.0:
resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
lightningcss-win32-arm64-msvc@1.33.0:
resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [win32]
lightningcss-win32-x64-msvc@1.33.0:
resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [win32]
lightningcss@1.33.0:
resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
engines: {node: '>= 12.0.0'}
lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
magic-string@1.4.5:
resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==}
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
nanoid@3.3.18:
resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
node-releases@2.0.63:
resolution: {integrity: sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==}
engines: {node: '>=18'}
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -422,15 +819,42 @@ packages:
resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}
engines: {node: ^10 || ^12 || >=14}
react-dom@19.3.1:
resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==}
peerDependencies:
react: ^19.3.1
react-refresh@0.18.0:
resolution: {integrity: sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==}
engines: {node: '>=0.10.0'}
react@19.3.1:
resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==}
engines: {node: '>=0.10.0'}
rollup@4.62.5:
resolution: {integrity: sha512-/tqMfgP7GPA3PHhCmuiS4vIjrSVhHLgY++i+dhbG462euyAj7FpM4D9uq1X3BgjlqRdpcOrYhcQtfiQLNc8tqw==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
scheduler@0.28.0:
resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}
semver@6.3.2:
resolution: {integrity: sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==}
hasBin: true
source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
tailwindcss@4.3.5:
resolution: {integrity: sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==}
tapable@2.3.3:
resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
engines: {node: '>=6'}
tinyglobby@0.2.17:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
@@ -443,6 +867,12 @@ packages:
undici-types@7.18.2:
resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}
update-browserslist-db@1.3.4:
resolution: {integrity: sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==}
hasBin: true
peerDependencies:
browserslist: '>= 4.21.0'
vite@7.3.6:
resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -483,8 +913,123 @@ packages:
yaml:
optional: true
yallist@3.1.1:
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
snapshots:
'@babel/code-frame@7.29.7':
dependencies:
'@babel/helper-validator-identifier': 7.29.7
js-tokens: 4.0.0
picocolors: 1.1.1
'@babel/compat-data@7.29.7': {}
'@babel/core@7.29.13':
dependencies:
'@babel/code-frame': 7.29.7
'@babel/generator': 7.29.13
'@babel/helper-compilation-targets': 7.29.13
'@babel/helper-module-transforms': 7.29.13(@babel/core@7.29.13)
'@babel/helpers': 7.29.13
'@babel/parser': 7.29.13
'@babel/template': 7.29.7
'@babel/traverse': 7.29.13
'@babel/types': 7.29.11
'@jridgewell/remapping': 2.3.5
convert-source-map: 2.0.0
debug: 4.4.3
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 6.3.2
transitivePeerDependencies:
- supports-color
'@babel/generator@7.29.13':
dependencies:
'@babel/parser': 7.29.13
'@babel/types': 7.29.11
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
jsesc: 3.1.0
'@babel/helper-compilation-targets@7.29.13':
dependencies:
'@babel/compat-data': 7.29.7
'@babel/helper-validator-option': 7.29.7
browserslist: 4.29.5
lru-cache: 5.1.1
semver: 6.3.2
'@babel/helper-globals@7.29.7': {}
'@babel/helper-module-imports@7.29.7':
dependencies:
'@babel/traverse': 7.29.13
'@babel/types': 7.29.11
transitivePeerDependencies:
- supports-color
'@babel/helper-module-transforms@7.29.13(@babel/core@7.29.13)':
dependencies:
'@babel/core': 7.29.13
'@babel/helper-module-imports': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
'@babel/traverse': 7.29.13
transitivePeerDependencies:
- supports-color
'@babel/helper-plugin-utils@7.29.7': {}
'@babel/helper-string-parser@7.29.13': {}
'@babel/helper-validator-identifier@7.29.7': {}
'@babel/helper-validator-option@7.29.7': {}
'@babel/helpers@7.29.13':
dependencies:
'@babel/template': 7.29.7
'@babel/types': 7.29.11
'@babel/parser@7.29.13':
dependencies:
'@babel/types': 7.29.11
'@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.13)':
dependencies:
'@babel/core': 7.29.13
'@babel/helper-plugin-utils': 7.29.7
'@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.13)':
dependencies:
'@babel/core': 7.29.13
'@babel/helper-plugin-utils': 7.29.7
'@babel/template@7.29.7':
dependencies:
'@babel/code-frame': 7.29.7
'@babel/parser': 7.29.13
'@babel/types': 7.29.11
'@babel/traverse@7.29.13':
dependencies:
'@babel/code-frame': 7.29.7
'@babel/generator': 7.29.13
'@babel/helper-globals': 7.29.7
'@babel/parser': 7.29.13
'@babel/template': 7.29.7
'@babel/types': 7.29.11
debug: 4.4.3
transitivePeerDependencies:
- supports-color
'@babel/types@7.29.11':
dependencies:
'@babel/helper-string-parser': 7.29.13
'@babel/helper-validator-identifier': 7.29.7
'@biomejs/biome@2.5.10':
optionalDependencies:
'@biomejs/cli-darwin-arm64': 2.5.10
@@ -598,9 +1143,30 @@ snapshots:
'@esbuild/win32-x64@0.28.2':
optional: true
'@jridgewell/gen-mapping@0.3.13':
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
'@jridgewell/trace-mapping': 0.3.31
'@jridgewell/remapping@2.3.5':
dependencies:
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
'@jridgewell/resolve-uri@3.1.2': {}
'@jridgewell/sourcemap-codec@1.6.0': {}
'@jridgewell/trace-mapping@0.3.31':
dependencies:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
optional: true
'@rolldown/pluginutils@1.0.0-rc.3': {}
'@rollup/rollup-android-arm-eabi@4.62.5':
optional: true
@@ -676,12 +1242,150 @@ snapshots:
'@rollup/rollup-win32-x64-msvc@4.62.5':
optional: true
'@tailwindcss/node@4.3.5':
dependencies:
'@jridgewell/remapping': 2.3.5
enhanced-resolve: 5.26.1
jiti: 2.7.0
lightningcss: 1.33.0
magic-string: 1.4.5
source-map-js: 1.2.1
tailwindcss: 4.3.5
'@tailwindcss/oxide-android-arm64@4.3.5':
optional: true
'@tailwindcss/oxide-darwin-arm64@4.3.5':
optional: true
'@tailwindcss/oxide-darwin-x64@4.3.5':
optional: true
'@tailwindcss/oxide-freebsd-x64@4.3.5':
optional: true
'@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5':
optional: true
'@tailwindcss/oxide-linux-arm64-gnu@4.3.5':
optional: true
'@tailwindcss/oxide-linux-arm64-musl@4.3.5':
optional: true
'@tailwindcss/oxide-linux-x64-gnu@4.3.5':
optional: true
'@tailwindcss/oxide-linux-x64-musl@4.3.5':
optional: true
'@tailwindcss/oxide-wasm32-wasi@4.3.5':
optional: true
'@tailwindcss/oxide-win32-arm64-msvc@4.3.5':
optional: true
'@tailwindcss/oxide-win32-x64-msvc@4.3.5':
optional: true
'@tailwindcss/oxide@4.3.5':
optionalDependencies:
'@tailwindcss/oxide-android-arm64': 4.3.5
'@tailwindcss/oxide-darwin-arm64': 4.3.5
'@tailwindcss/oxide-darwin-x64': 4.3.5
'@tailwindcss/oxide-freebsd-x64': 4.3.5
'@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.5
'@tailwindcss/oxide-linux-arm64-gnu': 4.3.5
'@tailwindcss/oxide-linux-arm64-musl': 4.3.5
'@tailwindcss/oxide-linux-x64-gnu': 4.3.5
'@tailwindcss/oxide-linux-x64-musl': 4.3.5
'@tailwindcss/oxide-wasm32-wasi': 4.3.5
'@tailwindcss/oxide-win32-arm64-msvc': 4.3.5
'@tailwindcss/oxide-win32-x64-msvc': 4.3.5
'@tailwindcss/vite@4.3.5(vite@7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0))':
dependencies:
'@tailwindcss/node': 4.3.5
'@tailwindcss/oxide': 4.3.5
tailwindcss: 4.3.5
vite: 7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)
'@types/babel__core@7.20.5':
dependencies:
'@babel/parser': 7.29.13
'@babel/types': 7.29.11
'@types/babel__generator': 7.27.0
'@types/babel__template': 7.4.4
'@types/babel__traverse': 7.28.0
'@types/babel__generator@7.27.0':
dependencies:
'@babel/types': 7.29.11
'@types/babel__template@7.4.4':
dependencies:
'@babel/parser': 7.29.13
'@babel/types': 7.29.11
'@types/babel__traverse@7.28.0':
dependencies:
'@babel/types': 7.29.11
'@types/estree@1.0.9': {}
'@types/node@24.13.3':
dependencies:
undici-types: 7.18.2
'@types/react-dom@19.3.0(@types/react@19.3.0)':
dependencies:
'@types/react': 19.3.0
'@types/react@19.3.0':
dependencies:
csstype: 3.2.3
'@vitejs/plugin-react@5.2.0(vite@7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0))':
dependencies:
'@babel/core': 7.29.13
'@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.13)
'@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.13)
'@rolldown/pluginutils': 1.0.0-rc.3
'@types/babel__core': 7.20.5
react-refresh: 0.18.0
vite: 7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)
transitivePeerDependencies:
- supports-color
baseline-browser-mapping@2.11.35: {}
browserslist@4.29.5:
dependencies:
baseline-browser-mapping: 2.11.35
caniuse-lite: 1.0.30001823
electron-to-chromium: 1.5.478
node-releases: 2.0.63
update-browserslist-db: 1.3.4(browserslist@4.29.5)
caniuse-lite@1.0.30001823: {}
convert-source-map@2.0.0: {}
csstype@3.2.3: {}
debug@4.4.3:
dependencies:
ms: 2.1.3
detect-libc@2.1.2: {}
electron-to-chromium@1.5.478: {}
enhanced-resolve@5.26.1:
dependencies:
graceful-fs: 4.2.11
tapable: 2.3.3
esbuild@0.28.2:
optionalDependencies:
'@esbuild/aix-ppc64': 0.28.2
@@ -711,6 +1415,8 @@ snapshots:
'@esbuild/win32-ia32': 0.28.2
'@esbuild/win32-x64': 0.28.2
escalade@3.2.0: {}
fdir@6.5.0(picomatch@4.0.5):
optionalDependencies:
picomatch: 4.0.5
@@ -718,8 +1424,81 @@ snapshots:
fsevents@2.3.3:
optional: true
gensync@1.0.0-beta.2: {}
graceful-fs@4.2.11: {}
jiti@2.7.0: {}
js-tokens@4.0.0: {}
jsesc@3.1.0: {}
json5@2.2.3: {}
lightningcss-android-arm64@1.33.0:
optional: true
lightningcss-darwin-arm64@1.33.0:
optional: true
lightningcss-darwin-x64@1.33.0:
optional: true
lightningcss-freebsd-x64@1.33.0:
optional: true
lightningcss-linux-arm-gnueabihf@1.33.0:
optional: true
lightningcss-linux-arm64-gnu@1.33.0:
optional: true
lightningcss-linux-arm64-musl@1.33.0:
optional: true
lightningcss-linux-x64-gnu@1.33.0:
optional: true
lightningcss-linux-x64-musl@1.33.0:
optional: true
lightningcss-win32-arm64-msvc@1.33.0:
optional: true
lightningcss-win32-x64-msvc@1.33.0:
optional: true
lightningcss@1.33.0:
dependencies:
detect-libc: 2.1.2
optionalDependencies:
lightningcss-android-arm64: 1.33.0
lightningcss-darwin-arm64: 1.33.0
lightningcss-darwin-x64: 1.33.0
lightningcss-freebsd-x64: 1.33.0
lightningcss-linux-arm-gnueabihf: 1.33.0
lightningcss-linux-arm64-gnu: 1.33.0
lightningcss-linux-arm64-musl: 1.33.0
lightningcss-linux-x64-gnu: 1.33.0
lightningcss-linux-x64-musl: 1.33.0
lightningcss-win32-arm64-msvc: 1.33.0
lightningcss-win32-x64-msvc: 1.33.0
lru-cache@5.1.1:
dependencies:
yallist: 3.1.1
magic-string@1.4.5:
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
ms@2.1.3: {}
nanoid@3.3.18: {}
node-releases@2.0.63: {}
picocolors@1.1.1: {}
picomatch@4.0.5: {}
@@ -730,6 +1509,15 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.1
react-dom@19.3.1(react@19.3.1):
dependencies:
react: 19.3.1
scheduler: 0.28.0
react-refresh@0.18.0: {}
react@19.3.1: {}
rollup@4.62.5:
dependencies:
'@types/estree': 1.0.9
@@ -762,8 +1550,16 @@ snapshots:
'@rollup/rollup-win32-x64-msvc': 4.62.5
fsevents: 2.3.3
scheduler@0.28.0: {}
semver@6.3.2: {}
source-map-js@1.2.1: {}
tailwindcss@4.3.5: {}
tapable@2.3.3: {}
tinyglobby@0.2.17:
dependencies:
fdir: 6.5.0(picomatch@4.0.5)
@@ -773,7 +1569,13 @@ snapshots:
undici-types@7.18.2: {}
vite@7.3.6(@types/node@24.13.3):
update-browserslist-db@1.3.4(browserslist@4.29.5):
dependencies:
browserslist: 4.29.5
escalade: 3.2.0
picocolors: 1.1.1
vite@7.3.6(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0):
dependencies:
esbuild: 0.28.2
fdir: 6.5.0(picomatch@4.0.5)
@@ -784,3 +1586,7 @@ snapshots:
optionalDependencies:
'@types/node': 24.13.3
fsevents: 2.3.3
jiti: 2.7.0
lightningcss: 1.33.0
yallist@3.1.1: {}
+18 -3
View File
@@ -4,8 +4,13 @@
//
// Every `var(--x)` must name a custom property something defines — a token in
// `:root`, a component-local one in the CSS, or one the TS sets with
// `setProperty` — so a mistyped or deleted token fails here rather than
// silently falling back to the browser default.
// `setProperty` or a React `style` key — so a mistyped or deleted token fails
// here rather than silently falling back to the browser default.
//
// Tailwind's theme is reset to the tokens alone (style.css), so a utility can
// only produce a token value. The one way around that is an arbitrary value
// — `p-[3px]`, `bg-[#fff]` — and those are allowed only when they name a
// token: `p-[var(--space-2)]` or the `p-(--space-2)` shorthand.
//
// Allowed colour literals: inside a `:root` block (token definitions) and
// inside `@font-face`. Relative colour derived from a token —
@@ -27,7 +32,7 @@ function walk(dir, out = []) {
if (!SKIP_DIRS.has(name)) {
walk(path, out);
}
} else if (/\.(css|ts|html)$/.test(name)) {
} else if (/\.(css|tsx?|html)$/.test(name)) {
out.push(path);
}
}
@@ -103,6 +108,8 @@ function checkCss(source, rel) {
}
}
const ARBITRARY = /(?:^|[\s"'`:])!?-?[a-z][\w-]*-\[([^\]\s]+)\]/g;
function checkPlain(source, rel) {
// Comments are prose, not styling — `checkCss` already ignores them, and
// without the same treatment here an issue reference like `#140` reads as a
@@ -115,6 +122,11 @@ function checkPlain(source, rel) {
if (COLOR_LITERAL.test(neutral)) {
errors.push(`${rel}:${index + 1}: literal colour outside the token block`);
}
for (const match of rawLine.matchAll(ARBITRARY)) {
if (!/^var\(--[\w-]+\)$/.test(match[1])) {
errors.push(`${rel}:${index + 1}: arbitrary utility value "[${match[1]}]" — use a token`);
}
}
});
}
@@ -139,6 +151,9 @@ for (const { source } of sources) {
for (const match of source.matchAll(/setProperty\(\s*["'](--[\w-]+)["']/g)) {
defined.add(match[1]);
}
for (const match of source.matchAll(/["'](--[\w-]+)["']\s*:/g)) {
defined.add(match[1]);
}
}
for (const { rel, source } of sources) {
source.split("\n").forEach((line, index) => {
+669
View File
@@ -0,0 +1,669 @@
// The shell (§9.7): one sticky rail and, below 40rem, a bottom tab bar, both
// carrying the four destinations; under them one surface, with the detail
// pages and the tv deck layered over it.
import {
type MouseEvent,
type ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { flushSync } from "react-dom";
import { LAYER, LiveContext, type Nav, NavContext, type TvDeckRequest, useEscape } from "./context";
import { type Download, fetchDownloads } from "./downloads";
import { type Probe, probeHealth } from "./health";
import { Icon, type IconName } from "./icons";
import { two } from "./parts";
import {
currentRoute,
type Destination,
destinationOf,
navigate,
ROUTE_EVENT,
type Route,
} from "./router";
import { fetchMovie } from "./search";
import { episodeTarget, fetchEpisode, fetchSeries, seasonTarget } from "./series";
import { flag } from "./ui";
import { LibraryView } from "./views/Library";
import { MovieView } from "./views/Movie";
import { QueuesView, queueBadgeTotal } from "./views/Queues";
import { SearchView } from "./views/Search";
import { SeriesView } from "./views/Series";
import { SettingsView } from "./views/Settings";
import { TvDeckView } from "./views/TvDeck";
const POLL_MS = 15_000;
const DEBOUNCE_MS = 250;
type BaseRoute = Extract<Route, { kind: "library" | "queues" | "settings" | "search" }>;
type Overlay =
| { kind: "movie"; movieId: number; toReleases: boolean }
| { kind: "series"; seriesId: number };
interface Layers {
base: BaseRoute;
/** Bumped to remount the surface underneath, so it repaints from the API. */
baseKey: number;
/** Bumped for every search the deck should run, even of the same query. */
searchRun: number;
overlay: Overlay | null;
tv: TvDeckRequest | null;
}
const LIBRARY: BaseRoute = { kind: "library" };
function isBase(route: Route): route is BaseRoute {
return (
route.kind === "library" ||
route.kind === "queues" ||
route.kind === "settings" ||
route.kind === "search"
);
}
/** The route the shell is on, for lighting the right destination. */
function useRoute(): Route {
const [route, setRoute] = useState(currentRoute);
useEffect(() => {
const update = () => setRoute(currentRoute());
window.addEventListener(ROUTE_EVENT, update);
window.addEventListener("popstate", update);
return () => {
window.removeEventListener(ROUTE_EVENT, update);
window.removeEventListener("popstate", update);
};
}, []);
return route;
}
/** §9.8: the app's one poll — health, downloads and the queue count on one cadence. */
function usePoll() {
const [probe, setProbe] = useState<Probe | null>(null);
const [downloads, setDownloads] = useState<Download[]>([]);
const [badge, setBadge] = useState(0);
useEffect(() => {
let inFlight = false;
let live = true;
const run = async () => {
if (inFlight) {
return;
}
inFlight = true;
const next = await probeHealth();
if (live) {
setProbe(next);
}
const fetched = await fetchDownloads();
if (live) {
setDownloads(fetched);
}
inFlight = false;
const total = await queueBadgeTotal();
if (live && total !== null) {
setBadge(total);
}
};
void run();
const timer = window.setInterval(() => void run(), POLL_MS);
return () => {
live = false;
window.clearInterval(timer);
};
}, []);
return useMemo(() => ({ probe, downloads, badge, setBadge }), [probe, downloads, badge]);
}
function NavLink({
destination,
current,
className,
href,
onGo,
children,
}: {
destination: Destination;
current: Destination;
className: string;
href: string;
onGo: (destination: Destination) => void;
children: ReactNode;
}) {
return (
<a
className={className}
href={href}
data-dest={destination}
aria-current={destination === current ? "page" : undefined}
onClick={(event: MouseEvent) => {
event.preventDefault();
onGo(destination);
}}
>
{children}
</a>
);
}
/** Gives focus back to the control a layer opened from, once the layer is gone. */
function restoreFocus(target: HTMLElement | null) {
window.requestAnimationFrame(() => {
if (target?.isConnected) {
target.focus();
}
});
}
function TabGlyph({ name }: { name: IconName }) {
return (
<span aria-hidden="true">
<Icon name={name} />
</span>
);
}
export function App() {
const live = usePoll();
const route = useRoute();
const destination = destinationOf(route);
const [layers, setLayers] = useState<Layers>(() => ({
base: LIBRARY,
baseKey: 0,
searchRun: 0,
overlay: null,
tv: null,
}));
// the layers as of the last render, for handlers that act on them
const layersRef = useRef(layers);
layersRef.current = layers;
const [input, setInput] = useState("");
const [searching, setSearching] = useState(false);
const [inputFocused, setInputFocused] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const wordmark = useRef<HTMLAnchorElement>(null);
const debounce = useRef<number | undefined>(undefined);
const routeTicket = useRef(0);
// where back and Esc land, and which control gets focus back
const overlayParent = useRef<Route>(LIBRARY);
const overlayOrigin = useRef<HTMLElement | null>(null);
const tvOrigin = useRef<HTMLElement | null>(null);
const showBase = useCallback((base: BaseRoute) => {
setLayers((current) => ({
...current,
base,
searchRun: base.kind === "search" ? current.searchRun + 1 : current.searchRun,
overlay: null,
tv: null,
}));
}, []);
// popstate and the initial load both dispatch through here, so refresh
// and back/forward reach the same view a click would have.
const applyRoute = useCallback(
async (next: Route) => {
window.clearTimeout(debounce.current);
// a later route, or a click, outranks a deep-link fetch still out
routeTicket.current += 1;
const ticket = routeTicket.current;
const stale = () => ticket !== routeTicket.current;
if (isBase(next)) {
// §9.7: "/" is the library — clear any stale query so the rail input
// matches the route on a cold load or back-navigation
setInput(next.kind === "search" ? next.query : "");
showBase(next);
return;
}
const home = () => {
navigate(LIBRARY, { replace: true });
setInput("");
showBase(LIBRARY);
};
// a deep link has no origin click to restore focus to — the wordmark is
// the closest stand-in, and the surface underneath is the library
overlayParent.current = LIBRARY;
overlayOrigin.current = wordmark.current;
setInput("");
if (next.kind === "movie" || next.kind === "releases") {
const found = await fetchMovie(next.movieId);
if (stale()) {
return;
}
if (found === null) {
home();
return;
}
setLayers((current) => ({
...current,
base: LIBRARY,
overlay: { kind: "movie", movieId: next.movieId, toReleases: next.kind === "releases" },
tv: null,
}));
return;
}
if (next.kind === "series") {
const found = await fetchSeries(next.seriesId);
if (stale()) {
return;
}
if (found === null) {
home();
return;
}
setLayers((current) => ({
...current,
base: LIBRARY,
overlay: { kind: "series", seriesId: next.seriesId },
tv: null,
}));
return;
}
// both deck routes live over the series page, exactly as a click on a
// deck button does; resolve what that click would have
let tv: TvDeckRequest;
if (next.kind === "seasonReleases") {
const title = (await fetchSeries(next.seriesId))?.title ?? "";
if (stale()) {
return;
}
if (title === "") {
home();
return;
}
tv = {
title,
sub: `season ${two(next.seasonNumber)} · packs`,
seriesId: next.seriesId,
target: seasonTarget(next.seriesId, next.seasonNumber),
route: next,
};
} else {
const episode = await fetchEpisode(next.episodeId);
const title = episode === null ? "" : ((await fetchSeries(episode.series_id))?.title ?? "");
if (stale()) {
return;
}
if (episode === null || title === "") {
home();
return;
}
tv = {
title,
sub: `S${two(episode.season_number)}E${two(episode.number)} · ${episode.title}`,
seriesId: episode.series_id,
target: episodeTarget(episode.id),
route: next,
};
}
tvOrigin.current = wordmark.current;
setLayers((current) => ({
...current,
base: LIBRARY,
overlay: { kind: "series", seriesId: tv.seriesId },
tv,
}));
},
[showBase],
);
useEffect(() => {
const onPop = () => {
void applyRoute(currentRoute());
};
window.addEventListener("popstate", onPop);
void applyRoute(currentRoute());
return () => window.removeEventListener("popstate", onPop);
}, [applyRoute]);
const goHome = useCallback(() => {
window.clearTimeout(debounce.current);
navigate(LIBRARY);
setInput("");
showBase(LIBRARY);
}, [showBase]);
const nav = useMemo<Nav>(() => {
const openOverlay = (overlay: Overlay, path: Route, origin: HTMLElement | null) => {
routeTicket.current += 1;
overlayParent.current = layersRef.current.base;
overlayOrigin.current = origin;
navigate(path);
setLayers((current) => ({ ...current, overlay, tv: null }));
};
return {
openMovie: (movieId, origin) =>
openOverlay(
{ kind: "movie", movieId, toReleases: false },
{ kind: "movie", movieId },
origin,
),
openSeries: (seriesId, origin) =>
openOverlay({ kind: "series", seriesId }, { kind: "series", seriesId }, origin),
openTvDeck: (request, origin) => {
tvOrigin.current = origin;
navigate(request.route);
setLayers((current) => ({ ...current, tv: request }));
},
close: () => {
const { tv, overlay } = layersRef.current;
if (tv !== null) {
navigate({ kind: "series", seriesId: tv.seriesId });
setLayers((current) => ({ ...current, tv: null }));
restoreFocus(tvOrigin.current);
} else if (overlay !== null) {
navigate(overlayParent.current);
setLayers((current) => ({ ...current, overlay: null }));
restoreFocus(overlayOrigin.current);
}
},
// a removed title must not survive on the surface the page opened over
removed: () => {
navigate(overlayParent.current);
setLayers((current) => ({
...current,
overlay: null,
tv: null,
baseKey: current.baseKey + 1,
}));
},
goHome,
};
}, [goHome]);
const covered = layers.overlay !== null;
/* ---- the rail's search box ---- */
/** Opens the rail's search box and puts the caret in it. Below 40rem the box
* only exists once the rail is searching, so that paints first. */
const openSearch = () => {
flushSync(() => setSearching(true));
inputRef.current?.focus();
inputRef.current?.select();
};
const clearSearch = () => {
window.clearTimeout(debounce.current);
if (input !== "") {
goHome();
}
};
// one Escape on the search deck clears it and lands on the library
useEscape(LAYER.base, layers.base.kind === "search" && !covered, () => {
goHome();
inputRef.current?.focus();
});
// "/" focuses the box from anywhere
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
const active = document.activeElement;
if (
event.key === "/" &&
!(active instanceof HTMLInputElement) &&
!(active instanceof HTMLTextAreaElement)
) {
event.preventDefault();
inputRef.current?.focus();
inputRef.current?.select();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
const search = (query: string, replace = true) => {
navigate({ kind: "search", query }, { replace });
showBase({ kind: "search", query });
};
const onInput = (value: string) => {
setInput(value);
window.clearTimeout(debounce.current);
const query = value.trim();
if (query === "") {
navigate(LIBRARY);
showBase(LIBRARY);
return;
}
debounce.current = window.setTimeout(() => search(query), DEBOUNCE_MS);
};
const go = (target: Destination) => {
if (target === "search") {
openSearch();
return;
}
setSearching(false);
clearSearch();
const next: BaseRoute =
target === "queues"
? { kind: "queues" }
: target === "settings"
? { kind: "settings" }
: LIBRARY;
navigate(next);
showBase(next);
};
const railSearching = searching || inputFocused || destination === "search";
const masterState =
live.probe === null
? "probing"
: live.probe.kind === "unreachable"
? "unreachable"
: live.probe.report.status === "degraded"
? "degraded"
: "ok";
const version = live.probe?.kind === "report" ? `v${live.probe.report.version}` : "v —";
const badge = live.badge === 0 ? null : String(live.badge);
return (
<LiveContext.Provider value={live}>
<NavContext.Provider value={nav}>
<header className="rail" data-searching={flag(railSearching)}>
<div className="rail-inner">
<div className="rail-id">
<span className="lamp" data-state={masterState} aria-hidden="true" />
{/* §9.7: the wordmark is a link home — intercepted so it navigates
the SPA instead of reloading, but still a real anchor */}
<a
className="wordmark"
href="/"
id="wordmark"
ref={wordmark}
onClick={(event) => {
event.preventDefault();
goHome();
}}
>
arr
</a>
</div>
<nav className="rail-nav" aria-label="destinations">
<NavLink
destination="library"
current={destination}
className="nav-link"
href="/"
onGo={go}
>
library
</NavLink>
<NavLink
destination="queues"
current={destination}
className="nav-link"
href="/queues"
onGo={go}
>
queues
<span
className="nav-count readout"
data-role="queues-count"
hidden={badge === null}
>
{badge ?? ""}
</span>
</NavLink>
<NavLink
destination="settings"
current={destination}
className="nav-link"
href="/settings"
onGo={go}
>
settings
</NavLink>
</nav>
<div className="rail-search">
<span className="rail-search-glyph" aria-hidden="true">
<Icon name="search" />
</span>
<input
ref={inputRef}
id="search"
className="search-input readout"
type="text"
spellCheck={false}
autoComplete="off"
enterKeyHint="search"
placeholder="title, tmdb id, tt…, magnet"
aria-label="unified search — titles, TMDB or IMDb ids, magnets and .torrent links"
value={input}
onChange={(event) => onInput(event.target.value)}
onFocus={() => setInputFocused(true)}
onBlur={() => {
setInputFocused(false);
if (input === "") {
setSearching(false);
}
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
window.clearTimeout(debounce.current);
const query = input.trim();
if (query !== "") {
search(query);
}
} else if (event.key === "ArrowDown") {
const first = document.querySelector<HTMLElement>("#deck .r-link");
if (first) {
event.preventDefault();
first.focus();
}
} else if (event.key === "Escape") {
goHome();
}
}}
/>
<span className="search-hint readout" aria-hidden="true" hidden={inputFocused}>
/
</span>
<button
type="button"
className="control control-icon rail-search-close"
aria-label="close search"
onClick={() => {
setSearching(false);
clearSearch();
}}
>
<Icon name="close" />
</button>
</div>
<button
type="button"
className="control control-icon rail-search-open"
aria-label="search"
onClick={openSearch}
>
<Icon name="search" />
</button>
<span className="readout dim rail-version" data-testid="version">
{version}
</span>
</div>
</header>
<nav className="tabbar" aria-label="destinations">
<NavLink destination="library" current={destination} className="tab" href="/" onGo={go}>
<TabGlyph name="library" />
<span className="tab-label">library</span>
</NavLink>
<NavLink
destination="search"
current={destination}
className="tab"
href="/search"
onGo={go}
>
<TabGlyph name="search" />
<span className="tab-label">search</span>
</NavLink>
<NavLink
destination="queues"
current={destination}
className="tab"
href="/queues"
onGo={go}
>
<TabGlyph name="warning" />
<span className="tab-label">queues</span>
<span className="tab-badge readout" data-role="queues-count" hidden={badge === null}>
{badge ?? ""}
</span>
</NavLink>
<NavLink
destination="settings"
current={destination}
className="tab"
href="/settings"
onGo={go}
>
<TabGlyph name="cog" />
<span className="tab-label">settings</span>
</NavLink>
</nav>
{layers.base.kind === "library" && <LibraryView key={layers.baseKey} hidden={covered} />}
{layers.base.kind === "queues" && <QueuesView key={layers.baseKey} hidden={covered} />}
{layers.base.kind === "settings" && <SettingsView key={layers.baseKey} hidden={covered} />}
{layers.base.kind === "search" && (
<SearchView
key={layers.baseKey}
query={layers.base.query}
run={layers.searchRun}
hidden={covered}
onExitUp={() => inputRef.current?.focus()}
/>
)}
{layers.overlay?.kind === "movie" && (
<MovieView
key={layers.overlay.movieId}
movieId={layers.overlay.movieId}
toReleases={layers.overlay.toReleases}
/>
)}
{layers.overlay?.kind === "series" && (
<SeriesView
key={layers.overlay.seriesId}
seriesId={layers.overlay.seriesId}
covered={layers.tv !== null}
/>
)}
{layers.tv !== null && (
<TvDeckView
key={`${layers.tv.route.kind}:${JSON.stringify(layers.tv.route)}`}
request={layers.tv}
/>
)}
</NavContext.Provider>
</LiveContext.Provider>
);
}
+447
View File
@@ -0,0 +1,447 @@
// The §9.3 release deck: three buckets, eligible always open, below-policy
// and rejected collapsed to counts. Shared by the movie page and the tv deck.
import { Fragment, type ReactNode, useEffect, useRef, useState } from "react";
import {
blacklistAdvice,
blacklistClass,
blacklistReasonLabel,
bucketOf,
formatAudio,
formatHdr,
formatResolution,
formatScore,
formatSeeders,
formatSize,
formatSource,
type MovieRelease,
overridable,
ruleLabel,
type WaiveOutcome,
} from "./releases";
import { Chip, Control, DeckHead, Disclosure, EmptyRow, Row, SkeletonRows, useNote } from "./ui";
export type Bucket = "eligible" | "waived" | "rejected";
export interface ReleaseActions {
reload: () => Promise<void>;
notify: (text: string, tone?: "fault") => void;
/** One click on grab — a plain grab, or waive-then-grab where the rule
* that failed has an override (§9.3). */
grab: (release: MovieRelease, bucket: Bucket) => Promise<WaiveOutcome>;
}
/**
* What the deck shows: placeholders while the first read is out, nothing,
* or a set of verdicts. `paint` changes on every repaint, so a repaint
* collapses the buckets and resets the rows the way a fresh list does.
*/
export type DeckState =
| { kind: "skeleton" }
| { kind: "none" }
| { kind: "releases"; releases: MovieRelease[]; paint: number };
/** Stops in the score heat scale — keep in step with the --score-* tokens. */
const SCORE_STOPS = 6;
type ScoreStopper = (score: number | null) => number | null;
/**
* Score colour is relative to one list (issue 111): highest green, lowest
* red, seven interpolated stops between.
*/
function scoreStopper(releases: MovieRelease[]): ScoreStopper {
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const release of releases) {
if (release.score !== null) {
if (release.score < min) {
min = release.score;
}
if (release.score > max) {
max = release.score;
}
}
}
return (score: number | null): number | null => {
if (score === null || min > max) {
return null;
}
// all-equal scores are jointly the best the list offers
return max === min ? SCORE_STOPS : Math.round(((score - min) / (max - min)) * SCORE_STOPS);
};
}
/** Long lists are paged: the first rows render, the rest wait behind one control. */
const PAGE_ROWS = 25;
function Paged<T>({
items,
keyOf,
render,
}: {
items: T[];
keyOf: (item: T) => string | number;
render: (item: T) => ReactNode;
}) {
const [all, setAll] = useState(false);
const shown = all ? items : items.slice(0, PAGE_ROWS);
const rest = items.length - shown.length;
return (
<>
{shown.map((item) => (
<Fragment key={keyOf(item)}>{render(item)}</Fragment>
))}
{rest > 0 && (
<li className="bucket-more">
<Control
text={`show ${rest} more`}
quiet
glyph="chevronDown"
onClick={() => setAll(true)}
/>
</li>
)}
</>
);
}
/** The column header the release cells line up under, from 46rem. */
function Colhead() {
return (
<div className="colhead" aria-hidden="true">
<span className="colhead-score">score</span>
<span className="colhead-cells">
<span>res</span>
<span>source</span>
<span className="num">size</span>
<span>hdr</span>
<span>audio</span>
<span className="num">seed</span>
</span>
</div>
);
}
function CollapsedBucket({
label,
releases,
bucket,
scoreStop,
actions,
}: {
label: string;
releases: MovieRelease[];
bucket: Bucket;
scoreStop: ScoreStopper;
actions: ReleaseActions;
}) {
const [open, setOpen] = useState(false);
return (
<section className="deck-group" hidden={releases.length === 0}>
<DeckHead as="h4" label={label} count={releases.length === 0 ? "" : releases.length}>
<Disclosure count={releases.length} open={open} onToggle={() => setOpen(!open)} />
</DeckHead>
<div hidden={!open}>
<Colhead />
<ul className="deck-rows">
<Paged
items={releases}
keyOf={(release) => release.id}
render={(release) => (
<ReleaseRow
release={release}
bucket={bucket}
scoreStop={scoreStop}
actions={actions}
/>
)}
/>
</ul>
</div>
</section>
);
}
/**
* Splits classified releases into the three buckets and paints them. The
* API pre-sorts by bucket then score; splitting preserves order.
*/
export function Buckets({ state, actions }: { state: DeckState; actions: ReleaseActions }) {
if (state.kind !== "releases") {
return (
<div className="buckets">
<section className="deck-group" hidden={state.kind === "none"}>
<DeckHead as="h4" label="eligible" count="" />
<Colhead />
<ul className="deck-rows">{state.kind === "skeleton" && <SkeletonRows count={4} />}</ul>
</section>
<section className="deck-group" hidden>
<DeckHead as="h4" label="below policy" count="" />
</section>
<section className="deck-group" hidden>
<DeckHead as="h4" label="rejected" count="" />
</section>
</div>
);
}
return <PaintedBuckets key={state.paint} releases={state.releases} actions={actions} />;
}
function PaintedBuckets({
releases,
actions,
}: {
releases: MovieRelease[];
actions: ReleaseActions;
}) {
const scoreStop = scoreStopper(releases);
const eligible = releases.filter((release) => bucketOf(release) === "eligible");
const waived = releases.filter((release) => bucketOf(release) === "waived");
const rejected = releases.filter((release) => bucketOf(release) === "rejected");
// §9.3: over-strict filters must be visible, not silently absent — and
// where a rule can be waived, the count says so rather than leaving the
// way out folded inside a collapsed bucket. Only a rejected row needs
// forcing; a row below policy is offered already.
const forceable = rejected.filter(overridable).length;
return (
<div className="buckets">
<section className="deck-group">
<DeckHead as="h4" label="eligible" count={eligible.length} />
<Colhead />
<ul className="deck-rows">
{eligible.length === 0 ? (
<EmptyRow
text={
forceable > 0
? `none — every candidate is below policy or rejected; ${forceable} can be forced`
: "none — every candidate is below policy or rejected"
}
/>
) : (
<Paged
items={eligible}
keyOf={(release) => release.id}
render={(release) => (
<ReleaseRow
release={release}
bucket="eligible"
scoreStop={scoreStop}
actions={actions}
/>
)}
/>
)}
</ul>
</section>
<CollapsedBucket
label="below policy"
releases={waived}
bucket="waived"
scoreStop={scoreStop}
actions={actions}
/>
<CollapsedBucket
label="rejected"
releases={rejected}
bucket="rejected"
scoreStop={scoreStop}
actions={actions}
/>
</div>
);
}
type GrabState = "idle" | "busy" | "done" | "failed";
/** How long "sent" holds before the control is ready again. */
const SENT_MS = 4000;
/**
* One classified release: the score leads, the deciding attributes follow,
* the name is secondary and opens to its full string on a tap (§9.3). Grab is
* the one word control a row may carry, at a fixed width, and its outcome
* changes its label rather than adding a line.
*/
function ReleaseRow({
release,
bucket,
scoreStop,
actions,
}: {
release: MovieRelease;
bucket: Bucket;
scoreStop: ScoreStopper;
actions: ReleaseActions;
}) {
const [note, say] = useNote();
const [grab, setGrab] = useState<GrabState>("idle");
const timer = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
const stop = scoreStop(release.score);
const values = {
res: formatResolution(release.parsed),
src: formatSource(release.parsed),
size: formatSize(release.size),
hdr: formatHdr(release.parsed),
aud: formatAudio(release.parsed),
seed: formatSeeders(release.seeders),
};
const attribute = (label: string, value: string, secondary: boolean) => (
<Chip
className={value === "—" ? "dim" : undefined}
data-cell=""
data-pri={secondary ? "2" : undefined}
aria-label={value === "—" ? `${label} unclaimed` : `${label} ${value}`}
>
{value}
</Chip>
);
// #227: a blacklisted release was grabbed, downloaded and condemned at
// import. Which of the two things happened decides what the operator does
// next, and `blacklisted` alone reads the same for both.
const blacklisted =
bucket === "rejected" && release.rejected_rule === "blacklisted"
? blacklistClass(release.blacklist_reason)
: null;
// §9.3: every row that is not eligible names the rule behind it
const verdictText =
bucket === "eligible"
? null
: bucket === "waived"
? release.rejected_rule
? `below policy · ${ruleLabel(release.rejected_rule)}`
: "below policy"
: blacklisted
? `blacklisted · ${blacklistReasonLabel(release.blacklist_reason)}`
: release.rejected_rule
? `rejected · ${ruleLabel(release.rejected_rule)}`
: "rejected";
// A rejected row is normally inert, but §9.3's one click is exactly for
// the rule the operator disagrees with: where an override exists, the row
// offers it and the grab that follows stays a waiver.
const writesOverride = bucket !== "eligible" && overridable(release);
const offersGrab = bucket !== "rejected" || writesOverride;
const label = writesOverride ? "force" : "grab";
const grabText =
grab === "busy" ? "sending" : grab === "failed" ? "retry" : grab === "done" ? "sent" : label;
const run = () => {
setGrab("busy");
say(null);
void actions.grab(release, bucket).then((outcome) => {
const written = outcome.overrideWritten ? "override written · " : "";
if (outcome.kind === "error") {
setGrab("failed");
say(`${written}grab failed — ${outcome.detail}`, "fault");
} else {
setGrab("done");
timer.current = window.setTimeout(() => setGrab("idle"), SENT_MS);
}
if (outcome.overrideWritten) {
// the override changed classification; reread the verdicts and
// keep the outcome visible past the re-render
const text =
outcome.kind === "error"
? `${written}grab failed — ${outcome.detail}`
: `${written}grab sent`;
void actions.reload().then(() => {
actions.notify(text, outcome.kind === "error" ? "fault" : undefined);
});
}
});
};
return (
<Row
kind="release"
lead={
// biome-ignore lint/a11y/useAriaPropsSupportedByRole: the score's name is read with its row, not as a control
<span
className="score"
data-score={stop === null ? undefined : String(stop)}
aria-label={`score ${formatScore(release.score)}`}
>
{formatScore(release.score)}
</span>
}
meta={
<>
{verdictText !== null && (
<Chip data-verdict={bucket} data-blacklist={blacklisted ?? undefined}>
{verdictText}
</Chip>
)}
{attribute("resolution", values.res, false)}
{attribute("size", values.size, false)}
{attribute("source", values.src, true)}
{attribute("seeders", values.seed, true)}
{attribute("hdr", values.hdr, true)}
{attribute("audio", values.aud, true)}
</>
}
beforeSub={
<div className="r-cells" aria-hidden="true">
{(
[
[values.res, false],
[values.src, false],
[values.size, true],
[values.hdr, false],
[values.aud, false],
[values.seed, true],
] as const
).map(([value, numeric], index) => (
<span
// fixed columns: the position is the identity
// biome-ignore lint/suspicious/noArrayIndexKey: see above
key={index}
title={value}
className={
[numeric ? "num" : "", value === "—" ? "unclaimed" : ""]
.filter(Boolean)
.join(" ") || undefined
}
>
{value}
</span>
))}
</div>
}
sub={<span>{release.name}</span>}
subExpands
afterSub={
blacklisted && (
<span className="r-why readout" data-blacklist={blacklisted}>
{blacklistAdvice(release.blacklist_reason)}
</span>
)
}
actions={[
{
node: offersGrab ? (
<Control
text={grabText}
fixed
busy={grab === "busy"}
done={grab === "done"}
failed={grab === "failed"}
disabled={grab === "busy" || grab === "done"}
aria-label={
writesOverride
? `force grab — relaxes ${ruleLabel(release.rejected_rule)} for this title and grabs anyway`
: undefined
}
onClick={run}
/>
) : null,
width: "word",
},
]}
note={note}
/>
);
}
File diff suppressed because it is too large Load Diff
+111
View File
@@ -0,0 +1,111 @@
import { createContext, useContext, useEffect, useRef } from "react";
import type { Download } from "./downloads";
import type { Probe } from "./health";
import type { Route } from "./router";
import type { TvTarget } from "./series";
/** What the app's one poll keeps current (§9.8): health, downloads, the queue count. */
export interface Live {
probe: Probe | null;
downloads: Download[];
/** The amber count on the queues destination. */
badge: number;
setBadge: (total: number) => void;
}
export const LiveContext = createContext<Live>({
probe: null,
downloads: [],
badge: 0,
setBadge: () => {},
});
export function useLive(): Live {
return useContext(LiveContext);
}
/** A season or episode release deck, opened over the series page. */
export interface TvDeckRequest {
title: string;
sub: string | null;
seriesId: number;
target: TvTarget;
/** The deck's own URL: a season's packs or one episode. */
route: Route;
}
/**
* How a view opens another layer. `origin` is the control the click came
* from: closing the layer gives it focus back.
*/
export interface Nav {
openMovie: (movieId: number, origin: HTMLElement | null) => void;
openSeries: (seriesId: number, origin: HTMLElement | null) => void;
openTvDeck: (request: TvDeckRequest, origin: HTMLElement | null) => void;
/** Back from the innermost layer. */
close: () => void;
/** The open title is gone: close it and repaint the surface underneath. */
removed: () => void;
/** The library — the "/" route. */
goHome: () => void;
}
export const NavContext = createContext<Nav | null>(null);
export function useNav(): Nav {
const nav = useContext(NavContext);
if (nav === null) {
throw new Error("useNav outside the app shell");
}
return nav;
}
/*
* One Escape steps back one layer. Every open layer registers here with its
* depth, and a single capturing listener hands the key to the deepest one —
* the order components happen to mount in never decides it.
*/
export const LAYER = {
base: 10,
detail: 20,
tvDeck: 30,
confirm: 40,
} as const;
const layers = new Map<symbol, { depth: number; run: () => void }>();
window.addEventListener(
"keydown",
(event) => {
if (event.key !== "Escape") {
return;
}
let top: { depth: number; run: () => void } | null = null;
for (const layer of layers.values()) {
if (top === null || layer.depth >= top.depth) {
top = layer;
}
}
if (top !== null) {
event.preventDefault();
event.stopImmediatePropagation();
top.run();
}
},
true,
);
export function useEscape(depth: number, active: boolean, run: () => void) {
const latest = useRef(run);
latest.current = run;
useEffect(() => {
if (!active) {
return;
}
const key = Symbol("layer");
layers.set(key, { depth, run: () => latest.current() });
return () => {
layers.delete(key);
};
}, [depth, active]);
}
+275
View File
@@ -0,0 +1,275 @@
// What both §9.6 detail pages share: the hero, the action bar's links, and
// the removal confirmation.
import { type CSSProperties, type ReactNode, useEffect, useRef, useState } from "react";
import { Icon, ProviderMark, Star } from "./icons";
import { formatMetaLine, formatRating, formatVoteCount, tmdbImage } from "./movie";
import { type ActionOutcome, formatSize, totalSize } from "./releases";
import { cx, flag, IconControl, IconLink, type Note, NoteLine } from "./ui";
/** What both detail heroes paint from TMDB (§9.6). */
export interface HeroDetail {
poster_path: string | null;
backdrop_path: string | null;
vote_average: number | null;
vote_count: number;
runtime: number | null;
genres: string[];
tagline: string | null;
overview: string | null;
}
/**
* The detail hero is a fixed grid: the poster's box, the chip line, one line
* each for rating and meta, and three reserved lines of overview. Data fills
* the slots; it never adds them, so the page does not grow in steps.
*/
export function Hero({
title,
year,
detail,
chips,
note,
onBack,
}: {
title: string;
year: number | null;
detail: HeroDetail | null;
chips: ReactNode;
note: Note | null;
onBack: () => void;
}) {
const heading = useRef<HTMLHeadingElement>(null);
const [posterLoaded, setPosterLoaded] = useState(false);
const [posterBroken, setPosterBroken] = useState(false);
const [overviewFull, setOverviewFull] = useState(false);
useEffect(() => {
heading.current?.focus({ preventScroll: true });
window.scrollTo({ top: 0 });
}, []);
const posterUrl = detail === null ? null : tmdbImage(detail.poster_path, "w342");
const backdropUrl = detail === null ? null : tmdbImage(detail.backdrop_path, "w1280");
const tagline = detail?.tagline;
return (
<section
className={cx("hero", backdropUrl !== null && "has-backdrop")}
style={
backdropUrl === null
? undefined
: ({ "--backdrop": `url("${backdropUrl}")` } as CSSProperties)
}
aria-label="title metadata"
>
<header className="page-head">
<IconControl glyph="back" label="back" onClick={onBack} />
<h2 className="page-title" tabIndex={-1} ref={heading}>
{title === "" ? " " : title}
</h2>
<span className="page-year readout">{year === null ? "" : year}</span>
</header>
<div className="hero-body">
<div className="hero-poster">
<img
className="movie-poster"
alt={posterUrl === null || posterBroken ? "" : `${title} poster`}
src={posterUrl === null || posterBroken ? undefined : posterUrl}
data-loaded={flag(posterLoaded && !posterBroken)}
onLoad={() => setPosterLoaded(true)}
onError={() => setPosterBroken(true)}
/>
</div>
<div className="hero-info">
<span className="hero-chips">{chips}</span>
<p className="hero-rating readout">
{detail !== null && detail.vote_average !== null && (
<>
<Star />
{`${formatRating(detail.vote_average)} `}
<span className="dim">{`(${formatVoteCount(detail.vote_count)})`}</span>
</>
)}
</p>
<p className="hero-meta readout">
{detail === null ? "" : formatMetaLine(detail.runtime, detail.genres)}
</p>
<p className="hero-tagline">
{tagline !== null && tagline !== undefined && tagline !== "" ? `“${tagline}”` : ""}
</p>
{/* biome-ignore lint/a11y/useKeyWithClickEvents: a reading aid; the full text is in the DOM either way */}
<p
className="hero-overview"
data-full={flag(overviewFull)}
onClick={() => setOverviewFull(!overviewFull)}
>
{detail?.overview ?? ""}
</p>
</div>
</div>
<NoteLine note={note} className="r-note hero-note readout" />
</section>
);
}
/** The trailer: the play glyph, and the word wherever there is room for it. */
export function TrailerLink({ href, title }: { href: string; title: string }) {
return (
<IconLink className="trailer-link" label={`watch the ${title} trailer`} href={href}>
<Icon name="play" />
<span className="control-word">trailer</span>
</IconLink>
);
}
export function ProviderLink({
mark,
label,
href,
}: {
mark: "tmdb" | "tvdb" | "imdb" | "rt";
label: string;
href: string;
}) {
return (
<IconLink label={label} href={href}>
<ProviderMark name={mark} />
</IconLink>
);
}
/** The slice of a file the removal panel reads: evidence, nothing else. */
export interface RemoveFile {
path: string;
size: number;
}
/**
* What the panel needs to know about a title (issue 175): a movie and a
* series differ only in which endpoints they call, how their files roll up
* to one folder, and how many torrents the §7.3 warning speaks of.
*/
export interface RemoveSubject {
title: string;
files: () => Promise<{ kind: "files"; files: RemoveFile[] } | { kind: "error"; detail: string }>;
/** The one folder the delete takes, when the files agree on it. */
folder: (files: RemoveFile[]) => string | null;
remove: () => Promise<ActionOutcome>;
/** What does not happen: seeding continues under its own rule (§7.3). */
seedLine: string;
}
/**
* The removal confirmation (issue 104, simplified by 110): removing a title
* always unlinks its §7.4 folder, so there is one decision, not two.
*
* It names the §7.4 folder it would unlink rather than promising in the
* abstract — the service knows only what it wrote (§2), so the file list is
* the whole truth about what disappears. And it says what does not happen:
* seeding continues under its own rule (§7.3).
*/
export function RemovePanel({
subject,
onCancel,
onRemoved,
}: {
subject: RemoveSubject;
onCancel: () => void;
onRemoved: () => void;
}) {
const [evidence, setEvidence] = useState("reading files…");
const [path, setPath] = useState<string | null>(null);
const [files, setFiles] = useState<RemoveFile[] | null>(null);
const [folderNamed, setFolderNamed] = useState(false);
const [working, setWorking] = useState<{ text: string; tone?: "fault" } | null>(null);
const [busy, setBusy] = useState(false);
const keep = useRef<HTMLButtonElement>(null);
// cancel takes focus, not the destructive action: no toggle is left to arm first
useEffect(() => {
keep.current?.focus();
}, []);
useEffect(() => {
let live = true;
void subject.files().then((outcome) => {
if (!live) {
return;
}
if (outcome.kind === "error") {
setEvidence(`files unreadable — ${outcome.detail}`);
return;
}
setFiles(outcome.files);
if (outcome.files.length === 0) {
setEvidence("nothing on disk");
return;
}
const count = `${outcome.files.length} ${outcome.files.length === 1 ? "file" : "files"}`;
setEvidence(`${count} · ${formatSize(totalSize(outcome.files))}`);
const folder = subject.folder(outcome.files);
setFolderNamed(folder !== null);
setPath(folder ?? outcome.files.map((file) => file.path).join("\n"));
});
return () => {
live = false;
};
}, [subject]);
const hasFiles = files !== null && files.length > 0;
const note =
working ??
(hasFiles
? {
text: `${folderNamed ? "deletes the folder above." : "deletes the files above."} ${subject.seedLine}`,
tone: "warn" as const,
}
: { text: "the library entry goes. nothing was imported for this title." });
const confirm = () => {
setBusy(true);
setWorking({ text: "removing title and files…" });
void subject.remove().then((outcome) => {
if (outcome.kind === "done") {
onRemoved();
return;
}
setBusy(false);
// the row is still there on a failed unlink, so retrying is the fix
setWorking({ text: `remove failed — ${outcome.detail}`, tone: "fault" });
});
};
// evidence, then what removing it costs
return (
// biome-ignore lint/a11y/useSemanticElements: a fieldset brings its own border, padding and min-width, which this group does not want
<div
className="remove-body"
role="group"
aria-label={`remove ${subject.title}`}
data-armed={String(hasFiles)}
>
<p className="remove-evidence readout dim">{evidence}</p>
<p className="remove-path readout" hidden={path === null}>
{path ?? ""}
</p>
<p className="remove-note readout" id="remove-note" role="status" data-tone={note.tone}>
{note.text}
</p>
<div className="remove-actions">
<button
type="button"
className="control"
aria-describedby="remove-note"
disabled={busy}
onClick={confirm}
>
remove and delete files
</button>
<button type="button" className="control" ref={keep} disabled={busy} onClick={onCancel}>
keep
</button>
</div>
</div>
);
}
-145
View File
@@ -1,145 +0,0 @@
// The shared icon-only control block (#230), consumed by the title pages,
// decks and readouts in main.ts, the settings rows (#231) and the subtitle
// chips and provider list (#251). One glyph set, one arm-then-confirm idiom —
// never a second implementation per view. A view that cannot fit the shared
// control grows a variant of it here; it does not keep a private copy.
export const SVG_NS = "http://www.w3.org/2000/svg";
const ICON_PATHS = {
trash: [
"M2.8 4.3h10.4",
"M5.7 4.3V3.1c0-.5.4-.9.9-.9h2.8c.5 0 .9.4.9.9v1.2",
"M4.2 4.3l.5 8.5c0 .8.7 1.4 1.5 1.4h3.6c.8 0 1.5-.6 1.5-1.4l.5-8.5",
"M6.6 7v4.2",
"M9.4 7v4.2",
],
search: ["M7.2 2.6a4.4 4.4 0 1 1 0 8.8 4.4 4.4 0 0 1 0-8.8Z", "M10.4 10.4l3.2 3.2"],
disk: [
"M2.5 9.8l1.6-5c.2-.7.8-1.2 1.5-1.2h4.8c.7 0 1.3.5 1.5 1.2l1.6 5",
"M2.5 9.8h11v2.5c0 .7-.5 1.2-1.2 1.2H3.7c-.7 0-1.2-.5-1.2-1.2z",
"M10.9 11.6h.01",
],
pencil: [
"M11.2 2.4a1.5 1.5 0 0 1 2.1 0l.3.3a1.5 1.5 0 0 1 0 2.1L5.9 12.5l-3.2.8.8-3.2z",
"M10.1 3.5l2.4 2.4",
],
cog: [
"M6.81 3.56 L7.00 1.68 L9.00 1.68 L9.19 3.56 L11.25 4.75 L12.97 3.97 L13.97 5.71 L12.44 6.81 L12.44 9.19 L13.97 10.29 L12.97 12.03 L11.25 11.25 L9.19 12.44 L9.00 14.32 L7.00 14.32 L6.81 12.44 L4.75 11.25 L3.03 12.03 L2.03 10.29 L3.56 9.19 L3.56 6.81 L2.03 5.71 L3.03 3.97 L4.75 4.75Z",
"M8 5.6a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8Z",
],
warning: ["M8 1.8l6.2 11H1.8z", "M8 5.3v3.4M8 11.2h.01"],
check: ["M3.2 8.4l3 3 6.6-6.8"],
// the caption frame the rest of the world draws for subtitles: a screen
// with two lines of text sitting low in it
captions: [
"M2 3.4h12c.4 0 .7.3.7.7v7.8c0 .4-.3.7-.7.7H2c-.4 0-.7-.3-.7-.7V4.1c0-.4.3-.7.7-.7Z",
"M4.1 8.2h3.1",
"M8.8 8.2h3.1",
"M4.1 10.5h7.8",
],
chevronUp: ["M3 10.2l5-4.6 5 4.6"],
chevronDown: ["M3 5.8l5 4.6 5-4.6"],
chevronRight: ["M6 3l4.6 5L6 13"],
back: ["M13 8H3.4", "M7.4 3.8L3.2 8l4.2 4.2"],
play: ["M4.6 2.9v10.2c0 .4.4.6.7.4l7.8-5.1c.3-.2.3-.6 0-.8L5.3 2.5c-.3-.2-.7 0-.7.4Z"],
more: [
"M3.2 7.3a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4Z",
"M8 7.3a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4Z",
"M12.8 7.3a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4Z",
],
plus: ["M8 3v10", "M3 8h10"],
grid: [
"M2.5 2.5h4.4v4.4H2.5z",
"M9.1 2.5h4.4v4.4H9.1z",
"M2.5 9.1h4.4v4.4H2.5z",
"M9.1 9.1h4.4v4.4H9.1z",
],
list: ["M5.6 4h8", "M5.6 8h8", "M5.6 12h8", "M2.4 4h.01", "M2.4 8h.01", "M2.4 12h.01"],
library: ["M2.5 2.5h3v11h-3z", "M6.5 2.5h3v11h-3z", "M10.3 3.1l2.9-.8 2.3 10.6-2.9.7z"],
close: ["M3.6 3.6l8.8 8.8", "M12.4 3.6l-8.8 8.8"],
info: ["M8 1.8a6.2 6.2 0 1 1 0 12.4A6.2 6.2 0 0 1 8 1.8Z", "M8 7.2v4", "M8 4.8h.01"],
} as const;
export type IconName = keyof typeof ICON_PATHS;
/** Stroke glyph on the shared 16-grid; the control's aria-label carries the meaning. */
export function icon(name: IconName): SVGSVGElement {
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", "0 0 16 16");
svg.setAttribute("class", "icon");
svg.setAttribute("aria-hidden", "true");
svg.dataset.icon = name;
for (const d of ICON_PATHS[name]) {
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", d);
svg.append(path);
}
return svg;
}
/**
* How much room the control has, and where the armed state explains itself.
*/
export interface ArmedDeleteOptions {
/**
* Chip scale: the control plate comes off (§9.6 keeps a chip to one row).
* The two clicks, the amber armed state and the 4-second disarm are the
* same control either way.
*/
compact?: boolean;
/**
* The row's status slot. Arming writes "tap again to …" here and disarming
* clears it, so the button itself never changes size — the explanation
* lives beside it, not inside it.
*/
explain?: (text: string | null) => void;
}
/**
* The arm-then-confirm, icon-only: a trash glyph resting, an amber check
* while armed, in the same square either way, so an accidental hit never
* destroys and arming never moves its neighbours.
*/
export function armedDeleteIcon(
label: string,
execute: () => void,
options: ArmedDeleteOptions = {},
): HTMLButtonElement {
const button = document.createElement("button");
button.type = "button";
button.className = options.compact ? "control-micro" : "control control-icon";
button.dataset.kind = "delete";
button.setAttribute("aria-label", label);
button.replaceChildren(icon("trash"));
let armed = false;
let resetTimer: number | undefined;
const disarm = () => {
armed = false;
window.clearTimeout(resetTimer);
delete button.dataset.armed;
button.setAttribute("aria-label", label);
button.replaceChildren(icon("trash"));
options.explain?.(null);
};
button.addEventListener("click", () => {
if (armed) {
disarm();
button.disabled = true;
execute();
return;
}
armed = true;
button.dataset.armed = "true";
button.replaceChildren(icon("check"));
button.setAttribute("aria-label", `confirm — ${label}`);
options.explain?.(`tap again to ${label}`);
resetTimer = window.setTimeout(disarm, 4000);
});
button.addEventListener("blur", () => {
if (armed) {
disarm();
}
});
return button;
}
+208
View File
@@ -0,0 +1,208 @@
import { useEffect, useRef, useState } from "react";
// The shared icon-only control block (#230), consumed by the title pages,
// decks and readouts, the settings rows (#231) and the subtitle chips and
// provider list (#251). One glyph set, one arm-then-confirm idiom —
// never a second implementation per view. A view that cannot fit the shared
// control grows a variant of it here; it does not keep a private copy.
const ICON_PATHS = {
trash: [
"M2.8 4.3h10.4",
"M5.7 4.3V3.1c0-.5.4-.9.9-.9h2.8c.5 0 .9.4.9.9v1.2",
"M4.2 4.3l.5 8.5c0 .8.7 1.4 1.5 1.4h3.6c.8 0 1.5-.6 1.5-1.4l.5-8.5",
"M6.6 7v4.2",
"M9.4 7v4.2",
],
search: ["M7.2 2.6a4.4 4.4 0 1 1 0 8.8 4.4 4.4 0 0 1 0-8.8Z", "M10.4 10.4l3.2 3.2"],
disk: [
"M2.5 9.8l1.6-5c.2-.7.8-1.2 1.5-1.2h4.8c.7 0 1.3.5 1.5 1.2l1.6 5",
"M2.5 9.8h11v2.5c0 .7-.5 1.2-1.2 1.2H3.7c-.7 0-1.2-.5-1.2-1.2z",
"M10.9 11.6h.01",
],
pencil: [
"M11.2 2.4a1.5 1.5 0 0 1 2.1 0l.3.3a1.5 1.5 0 0 1 0 2.1L5.9 12.5l-3.2.8.8-3.2z",
"M10.1 3.5l2.4 2.4",
],
cog: [
"M6.81 3.56 L7.00 1.68 L9.00 1.68 L9.19 3.56 L11.25 4.75 L12.97 3.97 L13.97 5.71 L12.44 6.81 L12.44 9.19 L13.97 10.29 L12.97 12.03 L11.25 11.25 L9.19 12.44 L9.00 14.32 L7.00 14.32 L6.81 12.44 L4.75 11.25 L3.03 12.03 L2.03 10.29 L3.56 9.19 L3.56 6.81 L2.03 5.71 L3.03 3.97 L4.75 4.75Z",
"M8 5.6a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8Z",
],
warning: ["M8 1.8l6.2 11H1.8z", "M8 5.3v3.4M8 11.2h.01"],
check: ["M3.2 8.4l3 3 6.6-6.8"],
// the caption frame the rest of the world draws for subtitles: a screen
// with two lines of text sitting low in it
captions: [
"M2 3.4h12c.4 0 .7.3.7.7v7.8c0 .4-.3.7-.7.7H2c-.4 0-.7-.3-.7-.7V4.1c0-.4.3-.7.7-.7Z",
"M4.1 8.2h3.1",
"M8.8 8.2h3.1",
"M4.1 10.5h7.8",
],
chevronUp: ["M3 10.2l5-4.6 5 4.6"],
chevronDown: ["M3 5.8l5 4.6 5-4.6"],
chevronRight: ["M6 3l4.6 5L6 13"],
back: ["M13 8H3.4", "M7.4 3.8L3.2 8l4.2 4.2"],
play: ["M4.6 2.9v10.2c0 .4.4.6.7.4l7.8-5.1c.3-.2.3-.6 0-.8L5.3 2.5c-.3-.2-.7 0-.7.4Z"],
more: [
"M3.2 7.3a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4Z",
"M8 7.3a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4Z",
"M12.8 7.3a.7.7 0 1 1 0 1.4.7.7 0 0 1 0-1.4Z",
],
plus: ["M8 3v10", "M3 8h10"],
grid: [
"M2.5 2.5h4.4v4.4H2.5z",
"M9.1 2.5h4.4v4.4H9.1z",
"M2.5 9.1h4.4v4.4H2.5z",
"M9.1 9.1h4.4v4.4H9.1z",
],
list: ["M5.6 4h8", "M5.6 8h8", "M5.6 12h8", "M2.4 4h.01", "M2.4 8h.01", "M2.4 12h.01"],
library: ["M2.5 2.5h3v11h-3z", "M6.5 2.5h3v11h-3z", "M10.3 3.1l2.9-.8 2.3 10.6-2.9.7z"],
close: ["M3.6 3.6l8.8 8.8", "M12.4 3.6l-8.8 8.8"],
info: ["M8 1.8a6.2 6.2 0 1 1 0 12.4A6.2 6.2 0 0 1 8 1.8Z", "M8 7.2v4", "M8 4.8h.01"],
} as const;
export type IconName = keyof typeof ICON_PATHS;
/** Stroke glyph on the shared 16-grid; the control's aria-label carries the meaning. */
export function Icon({ name }: { name: IconName }) {
return (
<svg viewBox="0 0 16 16" className="icon" aria-hidden="true" data-icon={name}>
{ICON_PATHS[name].map((d) => (
<path key={d} d={d} />
))}
</svg>
);
}
/** §9.6 provider marks, drawn and shipped inline — never a remote image. */
export function ProviderMark({ name }: { name: "tmdb" | "tvdb" | "imdb" | "rt" }) {
if (name === "rt") {
return (
<svg className="icon icon-mark" aria-hidden="true" viewBox="0 0 20 20">
<path d="M10 6.6c4.1 0 6.8 2.1 6.8 5.2 0 3.3-3 5.7-6.8 5.7s-6.8-2.4-6.8-5.7c0-3.1 2.7-5.2 6.8-5.2Z" />
<path d="M10 6.6C8.6 7.1 7 6.8 5.9 5.8" />
<path d="M10 6.6c1.4.5 3 .2 4.1-.8" />
<path d="M10 6.6c-.3-1.2 0-2.3.9-3.2" />
</svg>
);
}
return (
<svg className="icon icon-mark" aria-hidden="true" viewBox="0 0 44 20">
<rect x="1" y="1.5" width="42" height="17" rx="4" />
<text x="22" y="13.2" textAnchor="middle" fontSize="9">
{{ tmdb: "TMDB", tvdb: "TVDB", imdb: "IMDb" }[name]}
</text>
</svg>
);
}
/** The drawn star before a TMDB rating — no glyph standing in for an icon. */
export function Star() {
return (
<svg viewBox="0 0 12 12" className="star" aria-hidden="true">
<path d="M6 0.8 L7.5 4.2 L11.2 4.6 L8.4 7.1 L9.2 10.8 L6 8.9 L2.8 10.8 L3.6 7.1 L0.8 4.6 L4.5 4.2 Z" />
</svg>
);
}
/** How long an armed delete waits for its second tap before it disarms. */
const ARMED_MS = 4000;
/**
* The shared arm-then-confirm state: the first tap arms, the second runs,
* blur or four seconds disarm. `execute` resolving to `false` re-enables the
* control so the operator can retry; anything else leaves it spent, because
* the caller is about to repaint the row away.
*/
export function useArmed(execute: () => Promise<boolean | undefined> | undefined) {
const [armed, setArmed] = useState(false);
const [spent, setSpent] = useState(false);
const timer = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
const disarm = () => {
window.clearTimeout(timer.current);
setArmed(false);
};
const click = () => {
if (armed) {
disarm();
setSpent(true);
void execute()?.then((ok) => {
if (ok === false) {
setSpent(false);
}
});
return true;
}
setArmed(true);
timer.current = window.setTimeout(() => setArmed(false), ARMED_MS);
return false;
};
return { armed, spent, click, disarm };
}
/**
* How much room the control has, and where the armed state explains itself.
*/
export interface ArmedDeleteOptions {
/**
* Chip scale: the control plate comes off (§9.6 keeps a chip to one row).
* The two clicks, the amber armed state and the 4-second disarm are the
* same control either way.
*/
compact?: boolean;
/**
* The row's status slot. Arming writes "tap again to …" here and disarming
* clears it, so the button itself never changes size — the explanation
* lives beside it, not inside it.
*/
explain?: (text: string | null) => void;
}
/**
* The arm-then-confirm, icon-only: a trash glyph resting, an amber check
* while armed, in the same square either way, so an accidental hit never
* destroys and arming never moves its neighbours.
*/
export function ArmedDeleteIcon({
label,
execute,
compact = false,
explain,
}: ArmedDeleteOptions & {
label: string;
execute: () => Promise<boolean | undefined> | undefined;
}) {
const { armed, spent, click, disarm } = useArmed(execute);
const wasArmed = useRef(false);
useEffect(() => {
if (armed) {
explain?.(`tap again to ${label}`);
} else if (wasArmed.current) {
explain?.(null);
}
wasArmed.current = armed;
}, [armed, explain, label]);
return (
<button
type="button"
className={compact ? "control-micro" : "control control-icon"}
data-kind="delete"
data-armed={armed ? "true" : undefined}
aria-label={armed ? `confirm — ${label}` : label}
disabled={spent}
onClick={(event) => {
// a chip may one day carry its own click; the delete never bubbles into it
event.stopPropagation();
click();
}}
onBlur={() => {
if (armed) {
disarm();
}
}}
>
<Icon name={armed ? "check" : "trash"} />
</button>
);
}
-5874
View File
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
import "./style.css";
const root = document.getElementById("app");
if (root === null) {
throw new Error("index.html is missing #app");
}
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);
+229
View File
@@ -0,0 +1,229 @@
// The chips and row parts several views share: media state, waivers, live
// downloads, counts, ratings and the row poster.
import { useState } from "react";
import { useLive } from "./context";
import { downloadChipDetail, downloadChipLabel, findDownload } from "./downloads";
import { Icon, Star } from "./icons";
import { waiverLabel } from "./library";
import { formatRating, formatVoteCount, tmdbImage } from "./movie";
import { Chip, type Say } from "./ui";
/**
* What the operator reads for the stored `blocked` flag. §6.3 gives it one
* effect — it stops the targeted-search lane and leaves RSS matching on —
* and "blocked" reads as "block this title outright", which is the wrong
* promise. The flag, the column and the API keep their name; only the words
* on screen say what it does. [`BLOCKED_EFFECT`] carries the RSS half.
*/
export const NO_TARGETED_SEARCH = "no targeted search";
/** The half a three-word label cannot hold, for titles and accessible names. */
export const BLOCKED_EFFECT = "arr stops searching for this title; RSS still matches it";
export function two(value: number): string {
return value < 10 ? `0${value}` : String(value);
}
export function seasonTag(seasonNumber: number): string {
return `S${two(seasonNumber)}`;
}
export function episodeTag(seasonNumber: number, episodeNumber: number): string {
return `${seasonTag(seasonNumber)}E${two(episodeNumber)}`;
}
/** A row's title: the name, then the year in the readout face. */
export function TitleText({ title, year }: { title: string; year: number | null }) {
return (
<span>
{title}
{year !== null && <span className="yr">{year}</span>}
</span>
);
}
/**
* §4.2 state ramp on a media-state chip. `available` is a drawn check glyph —
* a shape, not only a hue, so it still reads greyscale — with the word kept
* as the chip's aria-label; every other state keeps the word on the chip.
*/
export function MediaStateChip({ state, wanted }: { state: string; wanted: boolean }) {
if (state === "available") {
// a bare span's aria-label is not reliably exposed; role="img" is what
// makes the word reachable once the glyph replaced it
return (
<Chip role="img" aria-label={state} data-movie-state={state} data-wanted={String(wanted)}>
<Icon name="check" />
</Chip>
);
}
return (
<Chip data-movie-state={state} data-wanted={String(wanted)}>
{state}
</Chip>
);
}
/**
* §5.7 honesty: a waived import is never presented as a clean match. The
* rule that was relaxed is a sentence, not a word, so the chip draws the
* warning glyph (§4.2's drawn-glyph exemption) and the sentence is a tap
* away in the row's status slot — never only in a tooltip.
*/
export function WaiverChip({ waiver, say }: { waiver: unknown; say?: Say }) {
const label = waiverLabel(waiver);
if (label === null) {
return null;
}
return (
<Chip
base="chip chip-glyph"
data-verdict="waived"
aria-label={label}
role={say ? undefined : "img"}
explain={say ? { text: `imported below policy — ${label}`, say, tone: "warn" } : undefined}
>
<Icon name="warning" />
</Chip>
);
}
/**
* §9.8: live download state on the row that owns the item. Absent unless
* arr itself grabbed this exact target — a season pack shows on the season
* row only, because the API only ever returns a row for the
* `target_kind`/`target_id` actually grabbed. Fixed width, and it sits last
* on its line, so the poll adding or dropping it never moves another chip.
* Its detail (rate, ETA) is a tap away rather than a hover away.
*/
export function DownloadChip({
targetKind,
targetId,
say,
}: {
targetKind: string;
targetId: number;
say?: Say;
}) {
const { downloads } = useLive();
const download = findDownload(downloads, targetKind, targetId);
return (
<span className="dl-slot" data-dl-kind={targetKind} data-dl-id={targetId}>
{download !== null && (
<Chip
className="dl-chip"
data-dl-phase={download.phase}
aria-label={`download ${downloadChipDetail(download)}`}
explain={say ? { text: `download ${downloadChipDetail(download)}`, say } : undefined}
>
{downloadChipLabel(download)}
</Chip>
)}
</span>
);
}
/** The ramp read off N/M itself: green when full, amber while a gap remains. */
function countsTone(available: number, total: number): "complete" | "partial" | undefined {
if (total === 0) {
return undefined;
}
return available >= total ? "complete" : "partial";
}
export function CountsChip({
label,
available,
total,
ariaLabel,
glyph = false,
}: {
label: string;
available: number;
total: number;
ariaLabel: string;
/** Season rows lead the count with the disk glyph. */
glyph?: boolean;
}) {
return (
<Chip data-counts={countsTone(available, total)} aria-label={ariaLabel}>
{glyph && <Icon name="disk" />}
{label}
</Chip>
);
}
/** Episode counts for a title, hidden rather than shown as `0/0`. */
export function EpisodeCountsChip({ available, total }: { available: number; total: number }) {
if (total === 0) {
return null;
}
return (
<CountsChip
label={`${available}/${total} eps`}
available={available}
total={total}
ariaLabel={`${available} of ${total} episodes on disk`}
/>
);
}
/**
* TMDB's rating as a chip (#148). No votes means no chip — never a 0.0.
*/
export function RatingChip({
voteAverage,
voteCount,
secondary = false,
}: {
voteAverage: number | null;
voteCount?: number;
secondary?: boolean;
}) {
if (voteAverage === null) {
return null;
}
const votes = voteCount === undefined ? "" : ` from ${formatVoteCount(voteCount)} votes`;
return (
<Chip
aria-label={`rated ${formatRating(voteAverage)}${votes}`}
data-pri={secondary ? "2" : undefined}
>
<Star />
{formatRating(voteAverage)}
</Chip>
);
}
/** A search row's poster at w92, or a same-size blank so the edge never jitters. */
export function RowPoster({ posterPath, title }: { posterPath: string | null; title: string }) {
const [broken, setBroken] = useState(false);
if (posterPath === null || broken) {
return <span className="row-poster-blank" aria-hidden="true" />;
}
return (
<img
className="row-poster"
loading="lazy"
src={tmdbImage(posterPath, "w92") ?? ""}
alt={`${title} poster`}
// hotlinked art can 404; fall back to the blank rather than alt-text spill
onError={() => setBroken(true)}
/>
);
}
/** The amber lamp that leads every attention-queue row. */
export function AttentionLamp() {
return (
<span className="lead-lamp">
<span className="lamp" data-state="warn" aria-hidden="true" />
</span>
);
}
/** The audience of a root, or its id when the roots list does not carry it. */
export function audienceOf(roots: { id: number; audience: string }[], rootId: number): string {
return roots.find((root) => root.id === rootId)?.audience ?? `root ${rootId}`;
}
+205
View File
@@ -0,0 +1,205 @@
// Title rows and cards shared by search, the library and the queues.
import { type ReactNode, useState } from "react";
import type { LibrarySeries } from "./library";
import { seriesStatusChipRedundant } from "./library";
import { tmdbImage } from "./movie";
import {
audienceOf,
DownloadChip,
EpisodeCountsChip,
MediaStateChip,
NO_TARGETED_SEARCH,
RatingChip,
RowPoster,
TitleText,
WaiverChip,
} from "./parts";
import type { LibraryMovie, LibrarySeriesHit, Root } from "./search";
import { Chip, Row, useNote } from "./ui";
export type OpenTitle = (id: number, origin: HTMLElement) => void;
/** One movie the library holds, as search, the library list and the queues show it. */
export function MovieRow({
movie,
roots,
open,
}: {
movie: LibraryMovie;
roots: Root[];
open: OpenTitle;
}) {
const [note, say] = useNote();
return (
<Row
kind="title"
lead={<RowPoster posterPath={movie.poster_path} title={movie.title} />}
title={<TitleText title={movie.title} year={movie.year} />}
meta={
<>
<MediaStateChip state={movie.state} wanted={movie.wanted} />
<WaiverChip waiver={movie.waiver} say={say} />
{!movie.wanted && <Chip>not wanted</Chip>}
{movie.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
<Chip data-pri="2">{audienceOf(roots, movie.root_id)}</Chip>
<RatingChip voteAverage={movie.vote_average} secondary />
<DownloadChip targetKind="movie" targetId={movie.id} say={say} />
</>
}
note={note}
open={{ label: `open ${movie.title}`, run: (origin) => open(movie.id, origin) }}
/>
);
}
/**
* An in-library series hit: the whole row opens the series detail view,
* which is where its seasons, episodes and decks live (issue 129).
*/
export function SeriesHitRow({
series,
roots,
open,
}: {
series: LibrarySeriesHit;
roots: Root[];
open: OpenTitle;
}) {
return (
<Row
kind="title"
lead={<RowPoster posterPath={series.poster_path} title={series.title} />}
title={<TitleText title={series.title} year={series.year} />}
meta={
<>
<Chip>{audienceOf(roots, series.root_id)}</Chip>
{series.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
<RatingChip voteAverage={series.vote_average} secondary />
</>
}
open={{ label: `open ${series.title}`, run: (origin) => open(series.id, origin) }}
/>
);
}
/** The §4.2 derived status, unless the counts already say it. */
function SeriesStatusChip({ series }: { series: LibrarySeries }) {
if (seriesStatusChipRedundant(series)) {
return null;
}
return <Chip data-status={series.status}>{series.status}</Chip>;
}
/**
* One series with its §4.2 derived status: displayed, never editable. The
* row opens the detail view — seasons, episodes and their decks (issue 129).
*/
export function SeriesRow({
series,
roots,
open,
}: {
series: LibrarySeries;
roots: Root[];
open: OpenTitle;
}) {
return (
<Row
kind="title"
lead={<RowPoster posterPath={series.poster_path} title={series.title} />}
title={<TitleText title={series.title} year={series.year} />}
meta={
<>
<SeriesStatusChip series={series} />
<EpisodeCountsChip available={series.available_episodes} total={series.total_episodes} />
{series.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
<Chip data-pri="2">{audienceOf(roots, series.root_id)}</Chip>
</>
}
open={{ label: `open ${series.title}`, run: (origin) => open(series.id, origin) }}
/>
);
}
/**
* One §9.6 grid tile (#151): poster, title and operational chips. The grid
* supplies the library context, so cards do not repeat it.
* A missing poster becomes a same-ratio placeholder carrying its title,
* so the grid never reflows and never has a hole in it.
*/
function LibraryCard({
posterPath,
title,
chips,
open,
}: {
posterPath: string | null;
title: string;
chips: ReactNode;
open: (origin: HTMLElement) => void;
}) {
const [broken, setBroken] = useState(false);
return (
<li>
<button type="button" className="card" onClick={(event) => open(event.currentTarget)}>
<span className="card-art">
{posterPath === null || broken ? (
<span className="card-blank">
<span className="card-blank-title">{title}</span>
</span>
) : (
<img
className="card-poster"
loading="lazy"
src={tmdbImage(posterPath, "w342") ?? ""}
alt={`${title} poster`}
// hotlinked art can 404; fall back to the titled blank rather than a hole
onError={() => setBroken(true)}
/>
)}
</span>
<span className="card-body">
<span className="card-name">{title}</span>
<span className="card-chips">{chips}</span>
</span>
</button>
</li>
);
}
export function SeriesCard({ series, open }: { series: LibrarySeries; open: OpenTitle }) {
return (
<LibraryCard
posterPath={series.poster_path}
title={series.title}
chips={
<>
<EpisodeCountsChip available={series.available_episodes} total={series.total_episodes} />
{series.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
<SeriesStatusChip series={series} />
</>
}
open={(origin) => open(series.id, origin)}
/>
);
}
export function MovieCard({ movie, open }: { movie: LibraryMovie; open: OpenTitle }) {
return (
<LibraryCard
posterPath={movie.poster_path}
title={movie.title}
chips={
<>
<MediaStateChip state={movie.state} wanted={movie.wanted} />
<DownloadChip targetKind="movie" targetId={movie.id} />
<WaiverChip waiver={movie.waiver} />
{!movie.wanted && <Chip>not wanted</Chip>}
{movie.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
</>
}
open={(origin) => open(movie.id, origin)}
/>
);
}
+13 -854
View File
@@ -1,12 +1,8 @@
// Hand-written mirror of arr-api's /api/policies and /api/roots schemas,
// plus the settings view over them — same reasoning as search.ts: the
// Hand-written mirror of arr-api's /api/policies, /api/roots and
// /api/settings/subtitles schemas — same reasoning as search.ts: the
// generated client (src/api/) is uncommitted, so CI's tsc cannot see it.
import { armedDeleteIcon, icon } from "./icons";
import { navigate } from "./router";
import type { Root } from "./search";
import { forgetSubtitleOptions } from "./subtitles";
import { control, type RowDom, row, setSlot, chip as uiChip } from "./ui";
/** One policy row: the JSON columns as the API returns them. */
export interface PolicyDoc {
@@ -41,10 +37,10 @@ export interface RootInput {
policy_id: number;
}
const RESOLUTIONS = ["2160p", "1080p", "720p"] as const;
const SOURCES = ["Remux", "BluRay", "WEB-DL", "WEBRip", "HDTV"] as const;
export const RESOLUTIONS = ["2160p", "1080p", "720p"] as const;
export const SOURCES = ["Remux", "BluRay", "WEB-DL", "WEBRip", "HDTV"] as const;
/** DESIGN.md §15: OpenSubtitles is the available subtitle provider. */
const PROVIDERS = ["opensubtitles"] as const;
export const PROVIDERS = ["opensubtitles"] as const;
/** The runtime-editable half of subtitle config (§15) — issue #198's shape. */
export interface SubtitleSettings {
@@ -78,7 +74,7 @@ async function errorDetail(response: Response): Promise<string> {
}
}
async function fetchPolicies(): Promise<PolicyDoc[]> {
export async function fetchPolicies(): Promise<PolicyDoc[]> {
const response = await fetch("/api/policies");
if (!response.ok) {
throw new Error(await errorDetail(response));
@@ -86,7 +82,7 @@ async function fetchPolicies(): Promise<PolicyDoc[]> {
return (await response.json()) as PolicyDoc[];
}
async function fetchRoots(): Promise<Root[]> {
export async function fetchRoots(): Promise<Root[]> {
const response = await fetch("/api/roots");
if (!response.ok) {
throw new Error(await errorDetail(response));
@@ -94,7 +90,7 @@ async function fetchRoots(): Promise<Root[]> {
return (await response.json()) as Root[];
}
async function fetchSubtitleSettings(): Promise<SubtitleSettings> {
export async function fetchSubtitleSettings(): Promise<SubtitleSettings> {
const response = await fetch("/api/settings/subtitles");
if (!response.ok) {
throw new Error(await errorDetail(response));
@@ -102,11 +98,11 @@ async function fetchSubtitleSettings(): Promise<SubtitleSettings> {
return (await response.json()) as SubtitleSettings;
}
function saveSubtitleSettings(input: SubtitleSettingsInput): Promise<SaveOutcome> {
export function saveSubtitleSettings(input: SubtitleSettingsInput): Promise<SaveOutcome> {
return sendJson("/api/settings/subtitles", "PUT", input);
}
type SaveOutcome = { ok: true; json: unknown } | { ok: false; detail: string };
export type SaveOutcome = { ok: true; json: unknown } | { ok: false; detail: string };
async function sendJson(url: string, method: string, body: unknown): Promise<SaveOutcome> {
try {
@@ -124,19 +120,19 @@ async function sendJson(url: string, method: string, body: unknown): Promise<Sav
}
}
function savePolicy(id: number | null, policy: Omit<PolicyDoc, "id">): Promise<SaveOutcome> {
export function savePolicy(id: number | null, policy: Omit<PolicyDoc, "id">): Promise<SaveOutcome> {
return id === null
? sendJson("/api/policies", "POST", policy)
: sendJson(`/api/policies/${id}`, "PUT", policy);
}
function saveRoot(id: number | null, root: RootInput): Promise<SaveOutcome> {
export function saveRoot(id: number | null, root: RootInput): Promise<SaveOutcome> {
return id === null
? sendJson("/api/roots", "POST", root)
: sendJson(`/api/roots/${id}`, "PUT", root);
}
async function deleteRow(kind: "policies" | "roots", id: number): Promise<string | null> {
export async function deleteRow(kind: "policies" | "roots", id: number): Promise<string | null> {
try {
const response = await fetch(`/api/${kind}/${id}`, { method: "DELETE" });
if (!response.ok) {
@@ -147,840 +143,3 @@ async function deleteRow(kind: "policies" | "roots", id: number): Promise<string
return "daemon unreachable";
}
}
/* ---- form primitives ---------------------------------------------------- */
function must<T extends Element>(selector: string): T {
const element = document.querySelector<T>(selector);
if (!element) {
throw new Error(`settings markup is missing ${selector}`);
}
return element;
}
function el<K extends keyof HTMLElementTagNameMap>(
tag: K,
className: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
node.className = className;
if (text !== undefined) {
node.textContent = text;
}
return node;
}
function chip(text: string): HTMLSpanElement {
return uiChip(text);
}
function field(labelText: string, control: HTMLElement): HTMLDivElement {
const wrap = el("div", "field");
wrap.append(el("span", "field-label readout dim", labelText), control);
return wrap;
}
function textControl(value: string, placeholder = ""): HTMLInputElement {
const input = document.createElement("input");
input.type = "text";
input.className = "form-input readout";
input.value = value;
input.placeholder = placeholder;
input.spellcheck = false;
input.autocomplete = "off";
return input;
}
function numberControl(value: number): HTMLInputElement {
const input = document.createElement("input");
input.type = "number";
input.className = "form-input readout form-num";
input.value = String(value);
return input;
}
function selectControl(options: readonly string[], value: string): HTMLSelectElement {
const select = document.createElement("select");
select.className = "form-input readout";
for (const option of options) {
const item = document.createElement("option");
item.value = option;
item.textContent = option;
if (option === value) {
item.selected = true;
}
select.append(item);
}
select.value = value;
return select;
}
/** `a, b, c` ⇄ parts. Empty entries dropped; validation happens at save. */
function listValue(input: HTMLInputElement): string[] {
return input.value
.split(",")
.map((part) => part.trim())
.filter((part) => part !== "");
}
/** Icon-only edit toggle for one row; the label names the row it opens. */
function editIcon(label: string): HTMLButtonElement {
const button = el("button", "control control-icon");
button.type = "button";
button.setAttribute("aria-label", label);
button.setAttribute("aria-expanded", "false");
button.append(icon("pencil"));
return button;
}
interface SettingsView {
hide: () => void;
open: () => void;
}
export function settingsMain(views: { hide: () => void }[], goHome: () => void): SettingsView {
const view = must<HTMLElement>("#settings");
const deck = must<HTMLElement>("#deck");
const summary = must<HTMLElement>("#settings-summary");
const status = must<HTMLElement>("#settings-status");
const rootsSection = must<HTMLElement>("#group-roots");
const rootsRows = must<HTMLUListElement>("#rows-roots");
const policiesSection = must<HTMLElement>("#group-policies");
const policiesRows = must<HTMLUListElement>("#rows-policies");
const subtitlesSection = must<HTMLElement>("#group-subtitles");
const subtitlesBody = must<HTMLElement>("#subtitles-body");
let roots: Root[] = [];
let policies: PolicyDoc[] = [];
let subtitleSettings: SubtitleSettings | null = null;
// guards a stale fetch from painting over a newer view
let sequence = 0;
function setStatus(text: string | null, tone?: "fault") {
setSlot(status, text, tone);
}
function clearGroups() {
for (const section of [rootsSection, policiesSection, subtitlesSection]) {
section.hidden = true;
}
rootsRows.replaceChildren();
policiesRows.replaceChildren();
subtitlesBody.replaceChildren();
summary.textContent = "";
}
async function load() {
sequence += 1;
const ticket = sequence;
setStatus("reading settings…");
try {
const [fetchedRoots, fetchedPolicies, fetchedSubtitleSettings] = await Promise.all([
fetchRoots(),
fetchPolicies(),
fetchSubtitleSettings(),
]);
if (ticket !== sequence) {
return;
}
roots = fetchedRoots;
policies = fetchedPolicies;
subtitleSettings = fetchedSubtitleSettings;
} catch (error) {
if (ticket !== sequence) {
return;
}
clearGroups();
setStatus(`settings unavailable — ${(error as Error).message}`, "fault");
return;
}
render();
}
function render() {
clearGroups();
setStatus(null);
rootsSection.hidden = false;
policiesSection.hidden = false;
summary.textContent = `${roots.length} roots · ${policies.length} policies`;
for (const root of roots) {
rootsRows.append(rootRow(root));
}
for (const policy of policies) {
policiesRows.append(policyRow(policy));
}
if (subtitleSettings) {
subtitlesSection.hidden = false;
subtitlesBody.append(subtitlesPanel(subtitleSettings));
}
}
/* -- roots -------------------------------------------------------------- */
/**
* One settings row: identity, chips, then the edit and delete pair in the
* row's fixed action column. The edit panel opens in the row's tray.
*/
function settingsRow(
title: string,
chips: HTMLSpanElement[],
label: string,
remove: () => Promise<string | null>,
panel: () => HTMLElement,
): HTMLLIElement {
let say: RowDom["say"] = () => {};
const del = armedDeleteIcon(
`delete ${label}`,
() => {
void remove().then((detail) => {
if (detail !== null) {
del.disabled = false;
say(detail, "fault");
return;
}
void load();
});
},
{ explain: (text) => say(text, "warn") },
);
const edit = editIcon(`edit ${label}`);
const parts = row({
kind: "setting",
title,
meta: chips,
actions: [
{ node: edit, width: "icon" },
{ node: del, width: "icon" },
],
});
say = parts.say;
parts.body.querySelector(".r-title")?.classList.add("readout");
edit.addEventListener("click", () => {
const existing = parts.tray.querySelector(".edit-panel");
if (existing) {
existing.remove();
edit.setAttribute("aria-expanded", "false");
return;
}
parts.tray.append(panel());
edit.setAttribute("aria-expanded", "true");
});
return parts.item;
}
function rootRow(root: Root): HTMLLIElement {
return settingsRow(
root.path,
[chip(root.kind), chip(root.audience), chip(root.policy_name)],
`root ${root.path}`,
() => deleteRow("roots", root.id),
() => rootPanel(root),
);
}
function rootPanel(root: Root | null): HTMLElement {
const panel = el("div", "edit-panel add-panel");
const grid = el("div", "form-grid");
const kind = selectControl(["movie", "tv"], root?.kind ?? "movie");
const audience = selectControl(["main", "kids"], root?.audience ?? "main");
const path = textControl(root?.path ?? "", "/mnt/media/…");
const policyId = selectControl(
policies.map((policy) => String(policy.id)),
String(root?.policy_id ?? policies[0]?.id ?? ""),
);
// readable option labels without coupling value → name lookups
for (const [index, policy] of policies.entries()) {
const option = policyId.options[index];
if (option) {
option.textContent = policy.name;
}
}
grid.append(
field("kind", kind),
field("audience", audience),
field("path", path),
field("policy", policyId),
);
const note = el("p", "add-note readout");
note.setAttribute("role", "status");
note.hidden = true;
const save = control(root === null ? "create root" : "save root");
save.addEventListener("click", () => {
save.disabled = true;
note.hidden = false;
delete note.dataset.tone;
note.textContent = "saving…";
const input: RootInput = {
kind: kind.value,
audience: audience.value,
path: path.value.trim(),
policy_id: Number(policyId.value),
};
void saveRoot(root?.id ?? null, input).then((outcome) => {
if (outcome.ok) {
void load();
return;
}
save.disabled = false;
note.hidden = false;
note.dataset.tone = "fault";
note.textContent = outcome.detail;
});
});
const cancel = control("cancel", { quiet: true });
cancel.addEventListener("click", () => {
panel.remove();
});
const actions = el("div", "add-actions");
actions.append(save, cancel, note);
panel.append(grid, actions);
queueMicrotask(() => (root === null ? kind : path).focus());
return panel;
}
/* -- policies ------------------------------------------------------------ */
function requiredAudioLabel(policy: PolicyDoc): string {
return policy.required_audio.require === "original_language"
? "original language"
: `any of ${policy.required_audio.langs.join(", ")}`;
}
function policyRow(policy: PolicyDoc): HTMLLIElement {
const bandCount = Object.keys(policy.size_bands).length;
return settingsRow(
policy.name,
[
chip(policy.resolution_pref.join(" › ") || "no resolutions"),
chip(requiredAudioLabel(policy)),
chip(`${bandCount} band${bandCount === 1 ? "" : "s"}`),
],
`policy ${policy.name}`,
() => deleteRow("policies", policy.id),
() => policyPanel(policy),
);
}
/**
* Comma-list editor that checks its vocabulary while typing, so an unknown
* resolution or profile is named before a round trip.
*/
function knownList(
labelText: string,
values: string[],
known: readonly string[],
invalid: (message: string | null) => void,
): HTMLDivElement {
const input = textControl(values.join(", "), known.join(", "));
input.addEventListener("input", () => {
const unknown = listValue(input).find((part) => !known.includes(part));
if (unknown !== undefined) {
input.dataset.invalid = "true";
invalid(`${labelText}: unknown value '${unknown}'`);
} else if (input.dataset.invalid !== undefined) {
delete input.dataset.invalid;
invalid(null);
}
});
return field(labelText, input);
}
function newPolicyDoc(): Omit<PolicyDoc, "id"> {
return {
name: "",
required_audio: { require: "original_language" },
dub_blacklist: ["pt-BR"],
hdr_rules: { dv_profile_reject: ["5", "7"] },
size_bands: {},
resolution_pref: ["2160p", "1080p"],
source_weights: {},
score_weights: {
size_at_target: 1000,
source_tier: 25,
seeder_doubling: 8,
resolution_step: 10000,
},
};
}
function policyPanel(policy: PolicyDoc | null): HTMLElement {
const current: Omit<PolicyDoc, "id"> = policy ?? newPolicyDoc();
const panel = el("div", "edit-panel add-panel");
const grid = el("div", "form-grid");
const invalidate = (message: string | null) => {
note.hidden = message === null || note.textContent === "";
if (message !== null) {
note.dataset.tone = "fault";
note.textContent = message;
} else if (note.dataset.tone === "fault") {
note.hidden = true;
}
};
const note = el("p", "add-note readout");
note.setAttribute("role", "status");
note.hidden = true;
const name = textControl(current.name, "policy name");
grid.append(field("name", name));
const audioMode = selectControl(
["original_language", "any_of"],
current.required_audio.require,
);
const audioLangs = textControl(
current.required_audio.require === "any_of" ? current.required_audio.langs.join(", ") : "",
"pt-PT, …",
);
audioMode.addEventListener("change", () => {
audioLangs.disabled = audioMode.value === "original_language";
});
audioLangs.disabled = audioMode.value === "original_language";
const blacklist = textControl(current.dub_blacklist.join(", "), "pt-BR");
grid.append(field("required audio", audioMode), field("required langs", audioLangs));
grid.append(field("dub blacklist", blacklist));
let profilesInput: HTMLInputElement;
const profiles = knownList(
"rejected dv profiles",
current.hdr_rules.dv_profile_reject,
["5", "7", "8"],
invalidate,
);
profilesInput = profiles.querySelector("input") ?? document.createElement("input");
grid.append(profiles);
// one line per resolution: floor, target, penalty, ceiling — numbers stay
// numbers, and an empty ceiling is no ceiling
for (const resolution of RESOLUTIONS) {
const band = current.size_bands[resolution];
const line = el("div", "band-line");
line.dataset.resolution = resolution;
line.append(el("span", "field-label readout dim", resolution));
const floor = numberControl(band?.floor_gib ?? 0);
const target = numberControl(band?.target_gib ?? 0);
const penalty = numberControl(band?.penalty_points_per_gib_over ?? 0);
const ceiling = numberControl(band?.ceiling_gib ?? 0);
if (band?.ceiling_gib === undefined) {
ceiling.value = "";
}
ceiling.placeholder = "∞";
floor.setAttribute("aria-label", `${resolution} floor GiB`);
target.setAttribute("aria-label", `${resolution} target GiB`);
penalty.setAttribute("aria-label", `${resolution} penalty points per GiB over`);
ceiling.setAttribute("aria-label", `${resolution} ceiling GiB, empty for none`);
for (const input of [floor, target, penalty, ceiling]) {
input.classList.add("band-num");
line.append(input);
}
grid.append(line);
}
let prefInput: HTMLInputElement;
const pref = knownList(
"resolution preference (first wins)",
current.resolution_pref,
RESOLUTIONS,
invalidate,
);
prefInput = pref.querySelector("input") ?? document.createElement("input");
grid.append(pref);
const WEIGHT_KEYS = [
"size_at_target",
"source_tier",
"seeder_doubling",
"resolution_step",
] as const;
type SourceKey = (typeof SOURCES)[number];
type WeightKey = (typeof WEIGHT_KEYS)[number];
const sourceInputs = {} as Record<SourceKey, HTMLInputElement>;
for (const source of SOURCES) {
const weight = numberControl(current.source_weights[source] ?? 0);
weight.setAttribute("aria-label", `${source} source weight`);
grid.append(field(`source · ${source.toLowerCase()}`, weight));
sourceInputs[source] = weight;
}
const scoreInputs = {} as Record<WeightKey, HTMLInputElement>;
for (const key of WEIGHT_KEYS) {
const input = numberControl(current.score_weights[key]);
input.setAttribute("aria-label", key.replaceAll("_", " "));
grid.append(field(key.replaceAll("_", " "), input));
scoreInputs[key] = input;
}
const save = control(policy === null ? "create policy" : "save policy");
save.addEventListener("click", () => {
const bad = panel.querySelector<HTMLElement>("[data-invalid]");
if (bad !== null) {
note.hidden = false;
note.dataset.tone = "fault";
note.textContent = "fix the highlighted fields first";
return;
}
const emptyWeight = [...Object.values(sourceInputs), ...Object.values(scoreInputs)].find(
(input) => input.value === "",
);
if (name.value.trim() === "" || emptyWeight !== undefined) {
note.hidden = false;
note.dataset.tone = "fault";
note.textContent = "name and every scoring weight are required";
return;
}
const sizeBands: PolicyDoc["size_bands"] = {};
for (const line of panel.querySelectorAll<HTMLDivElement>(".band-line")) {
const [floor, target, penalty, ceiling] = [
...line.querySelectorAll<HTMLInputElement>("input"),
];
if (!floor || !target || !penalty || !ceiling) {
continue;
}
sizeBands[line.dataset.resolution ?? ""] = {
floor_gib: Number(floor.value),
target_gib: Number(target.value),
penalty_points_per_gib_over: Number(penalty.value),
...(ceiling.value === "" ? {} : { ceiling_gib: Number(ceiling.value) }),
};
}
save.disabled = true;
note.hidden = false;
delete note.dataset.tone;
note.textContent = "saving…";
const payload: Omit<PolicyDoc, "id"> = {
name: name.value.trim(),
required_audio:
audioMode.value === "any_of"
? { require: "any_of", langs: listValue(audioLangs) }
: { require: "original_language" },
dub_blacklist: listValue(blacklist),
hdr_rules: { dv_profile_reject: listValue(profilesInput) },
size_bands: sizeBands,
resolution_pref: listValue(prefInput),
source_weights: Object.fromEntries(
SOURCES.filter((source) => sourceInputs[source].value !== "").map((source) => [
source,
Number(sourceInputs[source].value),
]),
),
score_weights: Object.fromEntries(
WEIGHT_KEYS.map((key) => [key, Number(scoreInputs[key].value)]),
) as PolicyDoc["score_weights"],
};
void savePolicy(policy?.id ?? null, payload).then((outcome) => {
if (outcome.ok) {
void load();
return;
}
save.disabled = false;
note.hidden = false;
note.dataset.tone = "fault";
note.textContent = outcome.detail;
});
});
const cancel = control("cancel", { quiet: true });
cancel.addEventListener("click", () => {
panel.remove();
});
const actions = el("div", "add-actions");
actions.append(save, cancel, note);
panel.append(grid, actions);
queueMicrotask(() => name.focus());
return panel;
}
/* -- subtitles ------------------------------------------------------------ */
/**
* A reorder control: the same `control control-quiet control-icon` the
* sibling rows in this view use (#231), with a chevron off the shared
* glyph set (#251) rather than the words "up" and "down".
*
* `data-move` is how `refreshProviderEdges` finds it (#255). Position in
* the row is not a contract — the day a third button joins the row, an
* ordinal selector would quietly disable the wrong control.
*/
function moveButton(direction: "up" | "down", label: string): HTMLButtonElement {
const button = el("button", "control control-icon provider-move");
button.type = "button";
button.dataset.move = direction;
button.setAttribute("aria-label", label);
button.append(icon(direction === "up" ? "chevronUp" : "chevronDown"));
return button;
}
/**
* One row per known provider, checkbox to enable, a daily-budget number,
* and up/down controls — list order is the priority order the API stores
* in `providers_enabled`. Disabled providers stay in the list, at
* whatever position they were left, so re-enabling one keeps its spot.
*/
function providerRow(
provider: string,
enabled: boolean,
budget: number,
): { item: HTMLLIElement; enabledInput: HTMLInputElement; budgetInput: HTMLInputElement } {
const enabledInput = document.createElement("input");
enabledInput.type = "checkbox";
enabledInput.className = "provider-toggle";
enabledInput.checked = enabled;
enabledInput.setAttribute("aria-label", `enable ${provider}`);
const budgetInput = numberControl(budget);
budgetInput.classList.add("provider-budget");
budgetInput.setAttribute("aria-label", `${provider} daily budget`);
const up = moveButton("up", `move ${provider} up`);
const down = moveButton("down", `move ${provider} down`);
const toggleWrap = el("label", "provider-check");
toggleWrap.append(enabledInput);
const { item } = row({
kind: "provider",
lead: toggleWrap,
title: provider,
actions: [
{ node: budgetInput, width: "word" },
{ node: up, width: "icon" },
{ node: down, width: "icon" },
],
});
item.dataset.provider = provider;
up.addEventListener("click", () => {
const previous = item.previousElementSibling;
if (previous) {
previous.before(item);
refreshProviderEdges();
}
});
down.addEventListener("click", () => {
const next = item.nextElementSibling;
if (next) {
next.after(item);
refreshProviderEdges();
}
});
return { item, enabledInput, budgetInput };
}
let refreshProviderEdges: () => void = () => {};
function subtitlesPanel(settings: SubtitleSettings): HTMLElement {
const panel = el("div", "add-panel subtitle-panel");
const grid = el("div", "form-grid");
const wanted = textControl(settings.wanted_languages.join(", "), "pt-PT, en");
grid.append(field("wanted languages", wanted));
const hasEngines = settings.available_engines.length > 0;
const engineSelect = selectControl(
["none", ...settings.available_engines],
settings.translation_engine ?? "none",
);
engineSelect.disabled = !hasEngines;
grid.append(field("translation engine", engineSelect));
const timeout = numberControl(settings.remote_command_timeout_seconds);
grid.append(field("remote command timeout (s)", timeout));
const hasOpenAi = settings.available_engines.includes("openai");
const openAiBaseUrl = textControl(
settings.openai_base_url ?? "",
"optional — e.g. http://127.0.0.1:8080/v1",
);
const openAiModel = textControl(settings.openai_model ?? "", "optional — e.g. gpt-4o-mini");
openAiBaseUrl.setAttribute("aria-label", "openai base url");
openAiModel.setAttribute("aria-label", "openai model");
panel.append(grid);
if (!hasEngines) {
panel.append(
el(
"p",
"add-note readout dim",
"no translation engine is compiled into this binary — pick is unavailable",
),
);
}
// Their own labelled row rather than two more cells in the grid above:
// paired, they belong to one engine, and a base URL needs the width.
if (hasOpenAi) {
panel.append(
el("p", "field-label readout dim", "openai-compatible endpoint — blank means its default"),
);
const openAiGrid = el("div", "form-grid");
openAiGrid.append(field("base url", openAiBaseUrl), field("model", openAiModel));
panel.append(openAiGrid);
}
const translatorInputs: Record<string, HTMLInputElement> = {};
if (hasEngines) {
panel.append(el("p", "field-label readout dim", "translator daily budgets"));
const translatorGrid = el("div", "form-grid");
for (const engine of settings.available_engines) {
const input = numberControl(settings.translator_daily_budgets[engine] ?? 0);
input.setAttribute("aria-label", `${engine} daily budget`);
translatorInputs[engine] = input;
translatorGrid.append(field(engine, input));
}
panel.append(translatorGrid);
}
panel.append(el("p", "field-label readout dim", "providers — enabled, and in priority order"));
const enabledProviders = new Set(settings.providers_enabled);
const order = [
...settings.providers_enabled,
...PROVIDERS.filter((provider) => !enabledProviders.has(provider)),
];
const list = el("ul", "provider-list");
const rows: Record<string, { enabledInput: HTMLInputElement; budgetInput: HTMLInputElement }> =
{};
for (const provider of order) {
const { item, enabledInput, budgetInput } = providerRow(
provider,
enabledProviders.has(provider),
settings.provider_daily_budgets[provider] ?? 0,
);
rows[provider] = { enabledInput, budgetInput };
list.append(item);
}
refreshProviderEdges = () => {
const items = [...list.children];
items.forEach((item, index) => {
const up = item.querySelector<HTMLButtonElement>('[data-move="up"]');
const down = item.querySelector<HTMLButtonElement>('[data-move="down"]');
if (up) up.disabled = index === 0;
if (down) down.disabled = index === items.length - 1;
});
};
refreshProviderEdges();
panel.append(list);
const note = el("p", "add-note readout");
note.setAttribute("role", "status");
note.hidden = true;
const save = control("save subtitles");
save.addEventListener("click", () => {
const providerOrder = [...list.children].map(
(item) => (item as HTMLElement).dataset.provider ?? "",
);
const providersEnabled = providerOrder.filter(
(provider) => rows[provider]?.enabledInput.checked,
);
const providerBudgets: Record<string, number> = {};
for (const provider of providerOrder) {
const value = Number(rows[provider]?.budgetInput.value ?? 0);
if (value > 0) {
providerBudgets[provider] = value;
}
}
const translatorBudgets: Record<string, number> = {};
for (const [engine, input] of Object.entries(translatorInputs)) {
const value = Number(input.value);
if (value > 0) {
translatorBudgets[engine] = value;
}
}
save.disabled = true;
note.hidden = false;
delete note.dataset.tone;
note.textContent = "saving…";
const input: SubtitleSettingsInput = {
wanted_languages: listValue(wanted),
providers_enabled: providersEnabled,
translation_engine: engineSelect.value === "none" ? null : engineSelect.value,
provider_daily_budgets: providerBudgets,
translator_daily_budgets: translatorBudgets,
remote_command_timeout_seconds: Number(timeout.value),
// An emptied field is "use the backend's default", which the API
// stores as NULL.
openai_base_url: hasOpenAi ? openAiBaseUrl.value.trim() || null : settings.openai_base_url,
openai_model: hasOpenAi ? openAiModel.value.trim() || null : settings.openai_model,
};
void saveSubtitleSettings(input).then((outcome) => {
if (outcome.ok) {
// the wanted set decides which languages a title page's subtitle
// chip may name, and that page caches it — this is where it goes
// stale, so this is where it is dropped
forgetSubtitleOptions();
void load();
return;
}
save.disabled = false;
note.hidden = false;
note.dataset.tone = "fault";
note.textContent = outcome.detail;
});
});
const actions = el("div", "add-actions");
actions.append(save, note);
panel.append(actions);
return panel;
}
/* -- shell ---------------------------------------------------------------- */
function open() {
for (const sibling of views) {
sibling.hide();
}
deck.hidden = true;
view.hidden = false;
void load();
}
function hide() {
view.hidden = true;
sequence += 1;
}
function close() {
hide();
goHome();
}
must<HTMLButtonElement>("#root-add").addEventListener("click", () => {
rootsSection.append(rootPanel(null));
});
must<HTMLButtonElement>("#policy-add").addEventListener("click", () => {
policiesSection.append(policyPanel(null));
});
// capture, like the other decks: one Esc steps back one layer
window.addEventListener(
"keydown",
(event) => {
if (event.key === "Escape" && !view.hidden) {
event.stopImmediatePropagation();
navigate({ kind: "library" });
close();
}
},
true,
);
return { hide, open };
}
+85 -2716
View File
File diff suppressed because it is too large Load Diff
+880
View File
@@ -0,0 +1,880 @@
// The manual subtitle surface for one media file (§9.3, §15, issue #203): a
// chip in the file's row, and the inline panel it opens with a fetch lane over
// the providers and a translate lane over what is already on the file.
import { type ReactNode, useEffect, useRef, useState } from "react";
import { ArmedDeleteIcon, Icon } from "./icons";
import { fileName } from "./movie";
import {
cachedSubtitleOptions,
deleteSubtitle,
type EmbeddedTrack,
embeddedTrackLabel,
extractableTracks,
extractTrack,
formatCandidateFlags,
formatDownloads,
formatHashMatch,
formatReleaseMatch,
formatUploaderRating,
grabSubtitle,
languageChoices,
type MissingSubtitle,
missingChipLabel,
type Subtitle,
type SubtitleCandidate,
type SubtitleSearchResults,
type SubtitleStatus,
searchSubtitles,
subtitleChipLabel,
subtitleRuleLabel,
subtitleSummary,
subtitleSummaryLabel,
summaryWidth,
type Translation,
translateSubtitle,
translationSources,
wantedSubtitles,
} from "./subtitles";
import {
Chip,
Control,
DeckHead,
Disclosure,
EmptyRow,
type Note,
NoteLine,
Row,
type Say,
useNote,
} from "./ui";
/** How often an open title re-reads a running translation's status. */
const TRANSLATION_POLL_MS = 5000;
/**
* One present-subtitle chip. Green like an eligible release (the want is
* met); a forced track never satisfies a want (§15) so it stays neutral
* instead, and so does a language nobody asked for — green here means the
* wanted set moved, not merely that a track exists. `data-mt` marks a
* machine translation with the same dashed border a waived release already
* carries — a translation is a relaxed case of "has a subtitle", not the
* clean one, and §15 wants it readable at a glance rather than by hovering
* for the origin word.
*/
function SubtitleChip({
subtitle,
wanted,
onDeleted,
say,
}: {
subtitle: Subtitle;
wanted: string[] | null;
onDeleted: () => void;
say: Say;
}) {
const [failed, setFailed] = useState(false);
const path = subtitle.path;
return (
<Chip
data-verdict={
!subtitle.forced && (wanted === null || wanted.includes(subtitle.language))
? "eligible"
: undefined
}
data-mt={subtitle.origin === "translated" ? "true" : undefined}
data-tone={failed ? "fault" : undefined}
>
{subtitleChipLabel(subtitle)}
{/* An embedded track has no sidecar (§15) — nothing on disk to name or delete.
A chip is too narrow to spell out a filename, so the lane's note names
the sidecar while armed and says why a delete failed. */}
{path !== null && (
<ArmedDeleteIcon
label={`delete ${fileName(path)}`}
compact
explain={(text) => say(text, "warn")}
execute={() => {
setFailed(false);
return deleteSubtitle(subtitle.id).then((outcome) => {
if (outcome.kind === "error") {
setFailed(true);
say(`delete failed — ${outcome.detail}`, "fault");
return false;
}
onDeleted();
return undefined;
});
}}
/>
)}
</Chip>
);
}
/** One missing-language chip; a failure's detail is a tap away in the lane's note. */
export function MissingSubtitleChip({ missing, say }: { missing: MissingSubtitle; say?: Say }) {
return (
<Chip
data-movie-state="missing"
data-wanted="true"
explain={
say && missing.reason === "failed" && missing.detail !== null
? { text: missing.detail, say, tone: "fault" }
: undefined
}
>
{missingChipLabel(missing)}
</Chip>
);
}
/**
* A language picker as pressed controls rather than a select: three or four
* options, all worth seeing at once, and the same affordance the root picker
* and the library view toggles already use.
*/
function LanguagePicker({
label,
languages,
choice,
barred,
onPick,
}: {
label: string;
languages: string[];
choice: string | null;
/** Bars one language — the translate lane cannot target its own source. */
barred?: string | null;
onPick: (language: string) => void;
}) {
return (
// biome-ignore lint/a11y/useSemanticElements: a fieldset brings its own border, padding and min-width, which this group does not want
<div className="segmented subs-langs" role="group" aria-label={label}>
{languages.map((language) => (
<button
key={language}
type="button"
className="seg"
data-language={language}
aria-pressed={language === choice}
disabled={language === barred}
onClick={() => onPick(language)}
>
{language}
</button>
))}
</div>
);
}
/** The picker's effective choice: the one picked, unless it is barred or gone. */
function effectiveChoice(
languages: string[],
picked: string | null,
barred: string | null = null,
): string | null {
if (picked !== null && picked !== barred && languages.includes(picked)) {
return picked;
}
return languages.find((language) => language !== barred) ?? null;
}
/** A labelled select, the same field vocabulary `/settings` already uses. */
function SubtitleField({
label,
narrow = false,
children,
}: {
label: string;
narrow?: boolean;
children: ReactNode;
}) {
return (
// biome-ignore lint/a11y/noLabelWithoutControl: the select is the child
<label className={narrow ? "field subs-field subs-field-narrow" : "field subs-field"}>
<span className="field-label readout dim">{label}</span>
{children}
</label>
);
}
type GrabState = "idle" | "busy" | "done" | "failed";
/**
* One subtitle candidate. Its facts ride as chips in §15's ranking order: a
* `moviehash` match wins outright and is the only chip that earns the
* eligible green; the release name, then rating and download count, only
* order what is left — so on a phone the tiebreakers are the first to go.
*/
function CandidateRow({
candidate,
bucket,
fetchCandidate,
}: {
candidate: SubtitleCandidate;
bucket: "eligible" | "rejected";
fetchCandidate: (candidate: SubtitleCandidate, say: Say) => Promise<boolean>;
}) {
const [note, say] = useNote();
const [grab, setGrab] = useState<GrabState>("idle");
const fact = (value: string, description: string, secondary: boolean, eligible = false) => (
<Chip
className={value === "—" ? "dim" : undefined}
aria-label={description}
data-pri={secondary ? "2" : undefined}
data-verdict={eligible ? "eligible" : undefined}
>
{value}
</Chip>
);
const flags = formatCandidateFlags(candidate);
return (
<Row
kind="candidate"
title={candidate.provider}
meta={
<>
{bucket === "rejected" && (
<Chip data-verdict="rejected">{`rejected · ${subtitleRuleLabel(candidate.rejected_rule)}`}</Chip>
)}
{fact(
formatHashMatch(candidate),
candidate.hash_match
? "matched to this exact file by moviehash"
: "no moviehash match against this file",
false,
candidate.hash_match,
)}
{fact(
formatReleaseMatch(candidate),
candidate.release_match
? "same release name as the file on disk"
: "a different release name from the file on disk",
false,
)}
{fact(
formatUploaderRating(candidate.rating),
candidate.rating === null
? "no uploader rating from this provider"
: `uploader rating ${formatUploaderRating(candidate.rating)} out of 10`,
true,
)}
{fact(
formatDownloads(candidate.download_count),
candidate.download_count === null
? "no download count from this provider"
: `downloaded ${candidate.download_count} times`,
true,
)}
{fact(
flags,
flags === "—" ? "a plain subtitle, neither SDH nor forced" : `flagged ${flags}`,
true,
)}
</>
}
sub={candidate.release_name ?? "no release name given"}
subExpands
actions={[
{
node:
bucket === "eligible" ? (
<Control
text={
grab === "busy"
? "fetching"
: grab === "done"
? "written"
: grab === "failed"
? "retry"
: "grab"
}
fixed
busy={grab === "busy"}
done={grab === "done"}
failed={grab === "failed"}
disabled={grab === "busy" || grab === "done"}
onClick={() => {
setGrab("busy");
void fetchCandidate(candidate, say).then((ok) => setGrab(ok ? "done" : "failed"));
}}
/>
) : null,
width: "word",
},
]}
note={note}
/>
);
}
/**
* §9.3's bucket structure with the middle bucket left out: `arr_core::subs`
* has no `waived` verdict, because nothing about a subtitle is worth
* overriding by hand.
*/
function CandidateBuckets({
results,
fetchCandidate,
}: {
results: SubtitleSearchResults;
fetchCandidate: (candidate: SubtitleCandidate, say: Say) => Promise<boolean>;
}) {
const [open, setOpen] = useState(false);
const eligible = results.candidates.filter((c) => c.verdict === "eligible");
const rejected = results.candidates.filter((c) => c.verdict !== "eligible");
return (
<div className="subs-buckets">
<section className="deck-group">
<DeckHead as="h4" label="eligible" count={eligible.length} />
<ul className="deck-rows">
{eligible.length === 0 && (
<EmptyRow text="none — every candidate names the rule that rejected it below" />
)}
{eligible.map((candidate) => (
<CandidateRow
key={`${candidate.provider}:${candidate.candidate_id}`}
candidate={candidate}
bucket="eligible"
fetchCandidate={fetchCandidate}
/>
))}
</ul>
</section>
<section className="deck-group" hidden={rejected.length === 0}>
<DeckHead as="h4" label="rejected" count={rejected.length}>
<Disclosure count={rejected.length} open={open} onToggle={() => setOpen(!open)} />
</DeckHead>
<div hidden={!open}>
<ul className="deck-rows">
{rejected.map((candidate) => (
<CandidateRow
key={`${candidate.provider}:${candidate.candidate_id}`}
candidate={candidate}
bucket="rejected"
fetchCandidate={fetchCandidate}
/>
))}
</ul>
</div>
</section>
</div>
);
}
/** Providers that could not answer are named, so "no candidates" and
* "nobody could be asked" never read the same. */
function searchSummary(results: SubtitleSearchResults, language: string): string {
const failures = results.provider_errors
.map((failure) => `${failure.provider} could not answer — ${failure.error}`)
.join(" · ");
if (results.candidates.length === 0) {
const nothing = `no ${language} candidate from any provider that answered`;
return failures === "" ? nothing : `${nothing} · ${failures}`;
}
return failures === "" ? "" : failures;
}
interface LoadedOptions {
languages: string[];
engines: string[];
}
/**
* One media file's subtitle chip and the manual panel it opens. The chip
* rides in the file's own row (§9.6 keeps a file to one line), so the caller
* places it among that row's other chips rather than on a line of its own,
* and the panel in the row's tray. A new `status` after a manual fetch or
* translation repaints both without resetting the panel underneath — an
* operator mid-search does not lose the search.
*/
export function useSubtitleSection(
status: SubtitleStatus | undefined,
refresh: () => void,
): { chip: ReactNode; panel: ReactNode } {
const [subtitles, setSubtitles] = useState<Subtitle[]>(status?.subtitles ?? []);
const missing = status?.missing ?? [];
const tracks = status?.embedded_tracks ?? [];
const runs = status?.translations ?? [];
const [localRuns, setLocalRuns] = useState<Translation[] | null>(null);
const shownRuns = localRuns ?? runs;
useEffect(() => {
setSubtitles(status?.subtitles ?? []);
setLocalRuns(null);
}, [status]);
const [open, setOpen] = useState(false);
/** Null until the settings request lands; see `wantedSubtitles`. */
const [wanted, setWanted] = useState<string[] | null>(null);
const [options, setOptions] = useState<LoadedOptions | null>(null);
const [engine, setEngine] = useState("");
const [hintFault, setHintFault] = useState<string | null>(null);
const [presentNote, presentSay] = useNote();
const [searchLanguage, setSearchLanguage] = useState<string | null>(null);
const [targetLanguage, setTargetLanguage] = useState<string | null>(null);
const [searching, setSearching] = useState(false);
const [searchNote, setSearchNote] = useState<(Note & { hidden?: boolean }) | null>({
text: "nothing is asked of a provider until you search.",
});
const [fetchCount, setFetchCount] = useState("");
const [results, setResults] = useState<{ results: SubtitleSearchResults; paint: number } | null>(
null,
);
const [sourceValue, setSourceValue] = useState("");
const [extracting, setExtracting] = useState(false);
const [starting, setStarting] = useState(false);
const [translateNote, setTranslateNote] = useState<Note | null>(null);
const previousRuns = useRef<Translation[]>([]);
// the wanted set decides which languages the chip may name at all, so it
// is asked for on sight rather than when the panel opens; the request is
// shared by every row on the page
useEffect(() => {
let live = true;
void cachedSubtitleOptions().then((outcome) => {
if (live) {
setWanted(outcome.kind === "options" ? outcome.options.wanted_languages : []);
}
});
return () => {
live = false;
};
}, []);
const mediaFileId = status?.media_file_id ?? 0;
/**
* Say where the file's translations stand, from the status rather than
* from the click, so a run started before the page was left still shows.
* The previous runs tell a landed language from one that never ran.
*/
useEffect(() => {
const before = previousRuns.current;
previousRuns.current = shownRuns;
const now = shownRuns.filter((run) => run.state === "running");
const failed = shownRuns.find((run) => run.state === "failed");
const landed = before.find(
(run) =>
run.state === "running" &&
!shownRuns.some((next) => next.language === run.language) &&
subtitles.some((subtitle) => subtitle.language === run.language),
);
if (now.length > 0) {
setTranslateNote({ text: `translating into ${now.map((run) => run.language).join(", ")}…` });
} else if (failed !== undefined) {
setTranslateNote({
text: `translation into ${failed.language} failed — ${failed.detail ?? "no reason given"}`,
tone: "fault",
});
} else if (landed !== undefined) {
setTranslateNote({
text: `written next to the video as a machine translation into ${landed.language}`,
});
}
// a run takes minutes; re-read on a slow beat until it settles, and stop
// once the panel has left the page
if (now.length === 0) {
return;
}
const timer = window.setTimeout(refresh, TRANSLATION_POLL_MS);
return () => window.clearTimeout(timer);
}, [shownRuns, subtitles, refresh]);
if (status === undefined) {
return { chip: null, panel: null };
}
const loadOptions = () => {
if (options !== null) {
return;
}
setOptions({ languages: [], engines: [] });
void cachedSubtitleOptions().then((outcome) => {
const loaded =
outcome.kind === "options"
? outcome.options
: { wanted_languages: [], translation_engine: null, available_engines: [] };
setOptions({
languages: languageChoices(loaded.wanted_languages),
engines: loaded.available_engines,
});
if (
loaded.translation_engine !== null &&
loaded.available_engines.includes(loaded.translation_engine)
) {
setEngine(loaded.translation_engine);
} else {
setEngine(loaded.available_engines[0] ?? "");
}
if (outcome.kind === "error") {
setHintFault(
`subtitle settings unreadable — ${outcome.detail}. The language choices fall back to Portuguese and English.`,
);
} else if (loaded.available_engines.length === 0) {
setHintFault(
"no translation engine is compiled into this binary — each backend is its own cargo feature.",
);
}
});
};
/* ---- the chip ---- */
const summary = subtitleSummary(
{
media_file_id: mediaFileId,
subtitles,
missing,
embedded_tracks: tracks,
translations: shownRuns,
},
wanted,
);
const panelId = `subs-panel-${mediaFileId}`;
const chip = (
<button
type="button"
className="chip subs-chip"
aria-expanded={open}
aria-controls={panelId}
data-verdict={summary.satisfied ? "eligible" : "wanted"}
aria-label={subtitleSummaryLabel(summary)}
onClick={() => {
setOpen(!open);
if (!open) {
loadOptions();
}
}}
>
<Icon name="captions" />
{/* the codes read as one string — the chip's own flex gap would otherwise
open a space in front of every comma. The run is as wide as the wanted
set can ever need, so the chips after it stay in column. */}
<span className="subs-chip-langs" style={{ width: `${summaryWidth(wanted)}ch` }}>
{summary.languages.length === 0 && <span className="dim">none</span>}
{summary.languages.map((entry, index) => (
<span key={entry.language} data-mt={entry.translated ? "true" : undefined}>
{index === 0 ? entry.language : `,${entry.language}`}
</span>
))}
{summary.overflow > 0 && <span>{`+${summary.overflow}`}</span>}
</span>
{/* §4.2's one glyph exemption: everything wanted is on disk, drawn as a
check. The slot is there either way, so a check appearing never
moves the row's other chips. */}
<span className="subs-chip-mark">{summary.satisfied && <Icon name="check" />}</span>
</button>
);
/* ---- sources: what is on the file, and what is still inside it ---- */
const sources = translationSources(subtitles);
const offered = extractableTracks(tracks, subtitles);
const empty = sources.length === 0 && offered.length === 0;
const sourceOptions: string[] = [
// nothing on disk to fall back on, and a browser selects the first
// option on sight — which would leave a track reading as picked
// without having been written out. The operator picks it themselves.
...(sources.length === 0 && offered.length > 0 ? [""] : []),
...sources.map((subtitle) => `subtitle:${subtitle.id}`),
...offered.map((track) => `track:${track.index}`),
];
const source = sourceOptions.includes(sourceValue) ? sourceValue : (sourceOptions[0] ?? "");
/**
* What the picker currently names, and which of the two kinds it is: a
* subtitle already on disk, or a track still inside the video. Only the
* second carries an `index`.
*/
const pickedFrom = (value: string): Subtitle | EmbeddedTrack | null => {
const [kind, rest] = value.split(":");
if (kind === "subtitle") {
return sources.find((subtitle) => String(subtitle.id) === rest) ?? null;
}
if (kind === "track") {
return offered.find((track) => String(track.index) === rest) ?? null;
}
return null;
};
const picked = pickedFrom(source);
const languages = options?.languages ?? [];
const searchChoice = effectiveChoice(languages, searchLanguage);
// the target picker never offers the source's own language, whichever
// kind of source it is — the API refuses it and it is never what was meant
const barred = picked?.language ?? null;
const targetChoice = effectiveChoice(languages, targetLanguage, barred);
const engines = options?.engines ?? [];
const engineDisabled = engines.length === 0;
const running = shownRuns.filter((run) => run.state === "running");
// a track is a source only once it has been written out, so until then
// the button has nothing to translate from
const translateDisabled =
engineDisabled ||
picked === null ||
"index" in picked ||
running.length > 0 ||
extracting ||
starting;
const hint = empty
? "no subtitle with text on this file, and no text track inside it either — fetch one above. An image-based track carries bitmaps, not text, and is never a source."
: (hintFault ??
(offered.length > 0
? "any subtitle already on the file is a legal source, and so is a text track inside the video — picking one writes it out beside the video first."
: "any subtitle already on the file is a legal source — a fetched one, an extracted embedded track, even another machine translation."));
/**
* §15's extraction, on demand: the sidecar lands beside the video and
* becomes an ordinary source. The row repaints from the answer before the
* refresh returns, so the lane is usable immediately. The reconcile loop
* only ever extracts while closing a gap, so on a file where nothing is
* missing this is the only way a sidecar is ever written.
*/
const extractPicked = (track: EmbeddedTrack) => {
setExtracting(true);
setTranslateNote({ text: `writing the ${track.language} ${track.codec} track out…` });
void extractTrack(mediaFileId, track.index).then((outcome) => {
setExtracting(false);
if (outcome.kind === "error") {
setTranslateNote({ text: `extraction failed — ${outcome.detail}`, tone: "fault" });
return;
}
setTranslateNote({
text: `written beside the video — ${outcome.subtitle.language} is now a source`,
});
setSubtitles((current) => [...current, outcome.subtitle]);
setSourceValue(`subtitle:${outcome.subtitle.id}`);
refresh();
});
};
/** One click grabs, syncs and writes (§15) — then the chips repaint. */
const fetchCandidate = async (candidate: SubtitleCandidate, note: Say): Promise<boolean> => {
note(null);
const outcome = await grabSubtitle(mediaFileId, candidate);
if (outcome.kind === "error") {
const stale =
outcome.code === "candidate_expired"
? " — search again, a candidate id does not outlive its search"
: "";
note(`grab failed — ${outcome.detail}${stale}`, "fault");
return false;
}
note(
outcome.subtitle.sync === "rejected"
? "written — alass was implausible, so the unsynced original was kept and the file is flagged"
: "fetched, synced and written",
);
refresh();
return true;
};
const search = () => {
const language = searchChoice;
if (language === null) {
return;
}
setSearching(true);
setFetchCount("");
setSearchNote({ text: `searching providers for ${language}…` });
void searchSubtitles(mediaFileId, language).then((outcome) => {
setSearching(false);
if (outcome.kind === "error") {
setResults(null);
setSearchNote({ text: `search failed — ${outcome.detail}`, tone: "fault" });
return;
}
setResults((current) => ({ results: outcome.results, paint: (current?.paint ?? 0) + 1 }));
setFetchCount(String(outcome.results.candidates.length));
const text = searchSummary(outcome.results, language);
setSearchNote({
text,
tone: outcome.results.provider_errors.length > 0 ? "fault" : undefined,
hidden: text === "",
});
});
};
const translate = () => {
const target = targetChoice;
// a track that has not been written out carries no text; the change
// handler extracts on pick, so this only guards the moment in between
if (target === null || picked === null || "index" in picked || extracting) {
return;
}
setStarting(true);
setTranslateNote({ text: `starting a translation into ${target}…` });
void translateSubtitle(mediaFileId, {
source_subtitle_id: picked.id,
target_language: target,
engine,
}).then((outcome) => {
setStarting(false);
if (outcome.kind === "error") {
setTranslateNote({ text: `translation failed — ${outcome.detail}`, tone: "fault" });
return;
}
setLocalRuns([
...shownRuns.filter((run) => run.language !== outcome.run.language),
outcome.run,
]);
});
};
// the wanted set first, then its gaps, then everything nobody asked for:
// the lane reads as the answer to "am I done here", with the stray
// languages as the footnote they are
const asked = wantedSubtitles(subtitles, wanted);
const rest = subtitles.filter((subtitle) => !asked.includes(subtitle));
const panel = (
<div className="subs-panel" id={panelId} hidden={!open}>
<section className="deck-group subs-lane">
<DeckHead label="on this file" />
<div className="subs-present">
{asked.map((subtitle) => (
<SubtitleChip
key={subtitle.id}
subtitle={subtitle}
wanted={wanted}
onDeleted={refresh}
say={presentSay}
/>
))}
{missing.map((gap) => (
<MissingSubtitleChip key={gap.language} missing={gap} say={presentSay} />
))}
{rest.map((subtitle) => (
<SubtitleChip
key={subtitle.id}
subtitle={subtitle}
wanted={wanted}
onDeleted={refresh}
say={presentSay}
/>
))}
{subtitles.length === 0 && missing.length === 0 && (
<p className="readout dim">no subtitles on this file yet.</p>
)}
</div>
<NoteLine note={presentNote} className="subs-note readout" />
</section>
<section className="deck-group subs-lane">
<DeckHead label="fetch" count={fetchCount} />
<div className="subs-controls">
<LanguagePicker
label="language to search for"
languages={languages}
choice={searchChoice}
onPick={setSearchLanguage}
/>
<button type="button" className="control" disabled={searching} onClick={search}>
search
</button>
</div>
<p
className="subs-note readout"
role="status"
data-tone={searchNote?.tone}
hidden={searchNote?.hidden}
>
{searchNote?.text ?? ""}
</p>
{results !== null && (
<CandidateBuckets
key={results.paint}
results={results.results}
fetchCandidate={fetchCandidate}
/>
)}
</section>
<section className="deck-group subs-lane">
<DeckHead label="translate" />
<div className="subs-controls">
<SubtitleField label="source">
<select
className="form-input"
value={source}
disabled={empty || extracting}
onChange={(event) => {
const value = event.target.value;
setSourceValue(value);
const next = pickedFrom(value);
if (next !== null && "index" in next) {
extractPicked(next);
}
}}
>
{sources.length === 0 && offered.length > 0 && (
<option value="">pick a track to write out</option>
)}
{sources.length > 0 && (
<optgroup label="on this file">
{sources.map((subtitle) => (
<option key={subtitle.id} value={`subtitle:${subtitle.id}`}>
{subtitleChipLabel(subtitle)}
</option>
))}
</optgroup>
)}
{offered.length > 0 && (
<optgroup label="inside the video — written out when picked">
{offered.map((track) => (
<option key={track.index} value={`track:${track.index}`}>
{embeddedTrackLabel(track)}
</option>
))}
</optgroup>
)}
{empty && <option value="">nothing to translate from</option>}
</select>
</SubtitleField>
<LanguagePicker
label="language to translate into"
languages={languages}
choice={targetChoice}
barred={barred}
onPick={setTargetLanguage}
/>
<SubtitleField label="engine" narrow>
<select
className="form-input"
value={engineDisabled ? "" : engine}
disabled={engineDisabled}
onChange={(event) => setEngine(event.target.value)}
>
{engines.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
{engineDisabled && <option value="">none compiled in</option>}
</select>
</SubtitleField>
<button
type="button"
className="control"
disabled={translateDisabled}
onClick={translate}
>
translate
</button>
</div>
<p
className="subs-note readout"
role="status"
data-tone={empty ? undefined : hintFault === null ? undefined : "fault"}
>
{options === null ? "" : hint}
</p>
<NoteLine note={translateNote} className="subs-note readout" />
</section>
</div>
);
return { chip, panel };
}
-434
View File
@@ -1,434 +0,0 @@
// The shared control and row vocabulary (Master Control, revision 2). Every
// list in the app is one row primitive with a fixed action column, and every
// button is one of five controls. A view that cannot fit them grows a variant
// here; it does not keep a private copy.
import { type IconName, icon } from "./icons";
/* ---- controls ------------------------------------------------------------ */
export interface ControlOptions {
/** Secondary actions: ink on a hairline, never a toggle. */
quiet?: boolean;
/** A leading glyph beside the word. */
glyph?: IconName;
/** Fixed width, so a label that changes (GRAB → SENDING → SENT) never moves the row. */
fixed?: boolean;
}
/** A word control: the primary action of a header or panel, or a quiet secondary one. */
export function control(text: string, options: ControlOptions = {}): HTMLButtonElement {
const button = document.createElement("button");
button.type = "button";
button.className = "control";
if (options.quiet) {
button.classList.add("control-quiet");
}
if (options.fixed) {
button.classList.add("control-fixed");
}
setControlText(button, text, options.glyph);
return button;
}
/** Relabels a word control, keeping its glyph. */
export function setControlText(button: HTMLElement, text: string, glyph?: IconName) {
const word = document.createElement("span");
word.className = "control-word";
word.textContent = text;
button.replaceChildren(...(glyph ? [icon(glyph), word] : [word]));
}
/** A 44px square glyph control. The label is the accessible name and nothing else. */
export function iconControl(glyph: IconName, label: string): HTMLButtonElement {
const button = document.createElement("button");
button.type = "button";
button.className = "control control-icon";
button.setAttribute("aria-label", label);
button.append(icon(glyph));
return button;
}
/** An external link wearing the icon control's skin. */
export function iconLink(content: Node, label: string, href: string): HTMLAnchorElement {
const link = document.createElement("a");
link.className = "control control-icon";
link.href = href;
link.target = "_blank";
link.rel = "noreferrer";
link.setAttribute("aria-label", label);
link.append(content);
return link;
}
export interface LampToggle {
button: HTMLButtonElement;
set: (pressed: boolean) => void;
}
/**
* A rule that is on or off: a lamp plus the word, never a border colour
* alone (the Word-Beside-The-Lamp rule). The state word has a fixed width,
* so flipping it never moves anything.
*/
export function lampToggle(label: string, pressed: boolean): LampToggle {
const button = document.createElement("button");
button.type = "button";
button.className = "toggle";
const lamp = document.createElement("span");
lamp.className = "toggle-lamp";
lamp.setAttribute("aria-hidden", "true");
const name = document.createElement("span");
name.className = "toggle-label";
name.textContent = label;
const state = document.createElement("span");
state.className = "toggle-state";
state.setAttribute("aria-hidden", "true");
button.append(lamp, name, state);
const set = (next: boolean) => {
button.setAttribute("aria-pressed", String(next));
state.textContent = next ? "on" : "off";
};
set(pressed);
return { button, set };
}
export interface Disclosure {
button: HTMLButtonElement;
/** Repaints the label from the current count; the width is the longest label's. */
paint: (count: number) => void;
}
/**
* Show / hide at full control height. The verb swaps but the plate keeps
* one width, and the count is tabular, so opening never moves the head.
*/
export function disclosure(noun: string, target: HTMLElement): Disclosure {
const button = document.createElement("button");
button.type = "button";
button.className = "control control-quiet disclose";
button.setAttribute("aria-expanded", "false");
const word = document.createElement("span");
word.className = "control-word";
button.append(word, icon("chevronDown"));
let last = 0;
const paint = (count: number) => {
last = count;
const open = !target.hidden;
word.textContent = `${open ? "hide" : "show"} ${count}${noun === "" ? "" : ` ${noun}`}`;
button.setAttribute("aria-expanded", String(open));
};
button.addEventListener("click", () => {
target.hidden = !target.hidden;
paint(last);
});
return { button, paint };
}
/**
* The arm-then-confirm as a labelled control, for the ⋯ tray where a phone
* spells the action out. Full width there, so the armed label can be longer.
*/
export function armedDeleteWord(label: string, execute: () => void): HTMLButtonElement {
const button = control(label, { quiet: true, glyph: "trash" });
button.dataset.kind = "delete";
let armed = false;
let timer: number | undefined;
const disarm = () => {
armed = false;
window.clearTimeout(timer);
delete button.dataset.armed;
setControlText(button, label, "trash");
};
button.addEventListener("click", () => {
if (armed) {
disarm();
button.disabled = true;
execute();
return;
}
armed = true;
button.dataset.armed = "true";
setControlText(button, `tap again to ${label}`, "check");
timer = window.setTimeout(disarm, 4000);
});
button.addEventListener("blur", () => {
if (armed) {
disarm();
}
});
return button;
}
/* ---- status -------------------------------------------------------------- */
/**
* Writes a status slot. The slot is always laid out — an empty one keeps its
* line — so a message arriving or leaving never pushes the content below it.
*/
export function setSlot(
slot: HTMLElement,
text: string | null,
tone?: "fault" | "warn",
busy = false,
) {
slot.dataset.empty = String(text === null);
if (busy && text !== null) {
const lamp = document.createElement("span");
lamp.className = "lamp";
lamp.dataset.state = "probing";
lamp.setAttribute("aria-hidden", "true");
slot.replaceChildren(lamp, document.createTextNode(text));
} else {
slot.textContent = text ?? "";
}
if (tone) {
slot.dataset.tone = tone;
} else {
delete slot.dataset.tone;
}
}
/* ---- the row --------------------------------------------------------------- */
/** One cell in a row's action column. An empty cell still takes its width. */
export interface ActionSlot {
node: HTMLElement | null;
/** The width class: a glyph square, a lamp toggle, or a fixed word control. */
width: "icon" | "toggle" | "word";
/** Shown from 40rem up; on a phone this action lives in the ⋯ tray instead. */
wide?: boolean;
/** Shown below 40rem only — an empty cell that keeps a phone column aligned. */
narrow?: boolean;
}
export interface RowParts {
/** `data-row`: which kind of row, for the few rules that differ by kind. */
kind: string;
lead?: HTMLElement | null;
title?: HTMLElement | string | null;
meta?: (HTMLElement | null)[];
sub?: HTMLElement | string | null;
actions?: ActionSlot[];
/** The phone tray: labelled, full-width versions of the wide-only actions. */
more?: HTMLElement[];
/** The whole row opens something: a stretched button under the controls. */
open?: { label: string; run: (origin: HTMLElement) => void; chevron?: boolean };
}
export interface RowDom {
item: HTMLLIElement;
body: HTMLElement;
meta: HTMLElement;
sub: HTMLElement | null;
act: HTMLElement;
/** Full-width area under the line: notes, the ⋯ actions, inline panels. */
tray: HTMLElement;
link: HTMLButtonElement | null;
/** The row's status slot, in the tray. Null clears it. */
say: (text: string | null, tone?: "fault" | "warn") => void;
}
/** A chip, the §9.3 column unit. */
export function chip(text: string, extra?: (chip: HTMLSpanElement) => void): HTMLSpanElement {
const span = document.createElement("span");
span.className = "chip readout";
span.textContent = text;
extra?.(span);
return span;
}
/**
* The one row: `lead | body | actions`, plus a full-width tray. The body is
* `minmax(0, 1fr)`, so a long title or a run of chips is clipped inside it
* and can never push the actions onto a second line.
*/
export function row(parts: RowParts): RowDom {
const item = document.createElement("li");
item.className = "r";
item.dataset.row = parts.kind;
if (parts.lead) {
const lead = document.createElement("div");
lead.className = "r-lead";
lead.append(parts.lead);
item.append(lead);
} else {
item.dataset.nolead = "";
}
const body = document.createElement("div");
body.className = "r-body";
if (parts.title !== undefined && parts.title !== null) {
const title = document.createElement("div");
title.className = "r-title";
if (typeof parts.title === "string") {
title.textContent = parts.title;
} else {
title.append(parts.title);
}
body.append(title);
}
const meta = document.createElement("div");
meta.className = "r-meta";
for (const piece of parts.meta ?? []) {
if (piece !== null) {
meta.append(piece);
}
}
body.append(meta);
let sub: HTMLElement | null = null;
if (parts.sub !== undefined && parts.sub !== null) {
sub = document.createElement("div");
sub.className = "r-sub readout";
if (typeof parts.sub === "string") {
sub.textContent = parts.sub;
} else {
sub.append(parts.sub);
}
body.append(sub);
}
item.append(body);
const act = document.createElement("div");
act.className = "r-act";
const tray = document.createElement("div");
tray.className = "r-tray";
const note = document.createElement("p");
note.className = "r-note readout";
note.setAttribute("role", "status");
note.hidden = true;
tray.append(note);
for (const slot of parts.actions ?? []) {
const cell = document.createElement("span");
cell.className = "r-slot";
cell.dataset.width = slot.width;
if (slot.wide) {
cell.dataset.wide = "";
}
if (slot.narrow) {
cell.dataset.narrow = "";
}
if (slot.node) {
cell.append(slot.node);
}
act.append(cell);
}
if (parts.more && parts.more.length > 0) {
const panel = document.createElement("div");
panel.className = "r-morepanel";
panel.hidden = true;
panel.append(...parts.more);
const more = iconControl("more", "more actions");
more.setAttribute("aria-expanded", "false");
more.addEventListener("click", () => {
panel.hidden = !panel.hidden;
more.setAttribute("aria-expanded", String(!panel.hidden));
});
const cell = document.createElement("span");
cell.className = "r-slot";
cell.dataset.width = "icon";
cell.dataset.narrow = "";
cell.append(more);
act.append(cell);
tray.append(panel);
}
let link: HTMLButtonElement | null = null;
if (parts.open) {
const open = parts.open;
link = document.createElement("button");
link.type = "button";
link.className = "r-link";
link.setAttribute("aria-label", open.label);
const target = link;
link.addEventListener("click", () => open.run(target));
item.prepend(link);
if (open.chevron !== false && (parts.actions ?? []).length === 0) {
const cell = document.createElement("span");
cell.className = "r-slot r-chevron";
cell.dataset.width = "icon";
cell.setAttribute("aria-hidden", "true");
cell.append(icon("chevronRight"));
act.append(cell);
}
}
item.append(act, tray);
const say = (text: string | null, tone?: "fault" | "warn") => {
note.hidden = text === null;
note.textContent = text ?? "";
if (tone) {
note.dataset.tone = tone;
} else {
delete note.dataset.tone;
}
};
return { item, body, meta, sub, act, tray, link, say };
}
/** A row-shaped placeholder: same height and columns as the row it stands for. */
export function skeletonRows(count: number, withLead = true): HTMLLIElement[] {
return Array.from({ length: count }, () => {
const item = document.createElement("li");
item.className = "r r-skel";
item.setAttribute("aria-hidden", "true");
if (withLead) {
const lead = document.createElement("div");
lead.className = "r-lead";
lead.append(skeletonBar("skel-lead"));
item.append(lead);
} else {
item.dataset.nolead = "";
}
const body = document.createElement("div");
body.className = "r-body";
body.append(skeletonBar("skel-line"), skeletonBar("skel-line skel-short"));
const act = document.createElement("div");
act.className = "r-act";
item.append(body, act);
return item;
});
}
export function skeletonBar(className: string): HTMLSpanElement {
const bar = document.createElement("span");
bar.className = `skel ${className}`;
return bar;
}
/* ---- tap to explain -------------------------------------------------------- */
/**
* A chip whose meaning would otherwise live in a tooltip. Touch has no hover,
* so the chip becomes a button that writes its sentence into the row's own
* status slot, and a second tap takes it away.
*/
export function explainable(
target: HTMLElement,
text: string,
say: (text: string | null, tone?: "fault" | "warn") => void,
tone?: "fault" | "warn",
) {
target.setAttribute("role", "button");
target.tabIndex = 0;
target.dataset.explain = "";
target.setAttribute("aria-expanded", "false");
const toggle = (event: Event) => {
event.stopPropagation();
event.preventDefault();
const open = target.getAttribute("aria-expanded") !== "true";
target.setAttribute("aria-expanded", String(open));
say(open ? text : null, tone);
};
target.addEventListener("click", toggle);
target.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
toggle(event);
}
});
}
+547
View File
@@ -0,0 +1,547 @@
// The shared control and row vocabulary (Master Control, revision 2). Every
// list in the app is one row primitive with a fixed action column, and every
// button is one of five controls. A view that cannot fit them grows a variant
// here; it does not keep a private copy.
import {
type ComponentProps,
type HTMLAttributes,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
useCallback,
useState,
} from "react";
import { Icon, type IconName, useArmed } from "./icons";
export type Tone = "fault" | "warn";
/** Joins class names, dropping the falsy ones. */
export function cx(...names: (string | false | null | undefined)[]): string {
return names.filter(Boolean).join(" ");
}
/** A boolean data attribute: present (empty) or absent. */
export function flag(on: boolean | undefined): "" | undefined {
return on ? "" : undefined;
}
/* ---- controls ------------------------------------------------------------ */
export interface ControlProps extends ComponentProps<"button"> {
/** The word on the plate. */
text: string;
/** Secondary actions: ink on a hairline, never a toggle. */
quiet?: boolean;
/** A leading glyph beside the word. */
glyph?: IconName;
/** Fixed width, so a label that changes (GRAB → SENDING → SENT) never moves the row. */
fixed?: boolean;
busy?: boolean;
done?: boolean;
failed?: boolean;
}
/** A word control: the primary action of a header or panel, or a quiet secondary one. */
export function Control({
text,
quiet,
glyph,
fixed,
busy,
done,
failed,
className,
...rest
}: ControlProps) {
return (
<button
type="button"
className={cx("control", quiet && "control-quiet", fixed && "control-fixed", className)}
data-busy={flag(busy)}
data-done={flag(done)}
data-failed={flag(failed)}
{...rest}
>
{glyph && <Icon name={glyph} />}
<span className="control-word">{text}</span>
</button>
);
}
/** A 44px square glyph control. The label is the accessible name and nothing else. */
export function IconControl({
glyph,
label,
className,
...rest
}: ComponentProps<"button"> & { glyph: IconName; label: string }) {
return (
<button
type="button"
className={cx("control control-icon", className)}
aria-label={label}
{...rest}
>
<Icon name={glyph} />
</button>
);
}
/** An external link wearing the icon control's skin. */
export function IconLink({
label,
href,
className,
children,
}: {
label: string;
href: string;
className?: string;
children: ReactNode;
}) {
return (
<a
className={cx("control control-icon", className)}
href={href}
target="_blank"
rel="noreferrer"
aria-label={label}
>
{children}
</a>
);
}
/**
* A rule that is on or off: a lamp plus the word, never a border colour
* alone (the Word-Beside-The-Lamp rule). The state word has a fixed width,
* so flipping it never moves anything.
*/
export function LampToggle({
label,
pressed,
...rest
}: ComponentProps<"button"> & {
label: string;
pressed: boolean;
"data-focus-id"?: string;
}) {
return (
<button type="button" className="toggle" aria-pressed={pressed} {...rest}>
<span className="toggle-lamp" aria-hidden="true" />
<span className="toggle-label">{label}</span>
<span className="toggle-state" aria-hidden="true">
{pressed ? "on" : "off"}
</span>
</button>
);
}
/**
* Show / hide at full control height. The verb swaps but the plate keeps
* one width, and the count is tabular, so opening never moves the head.
*/
export function Disclosure({
noun = "",
count,
open,
onToggle,
}: {
noun?: string;
count: number;
open: boolean;
onToggle: () => void;
}) {
return (
<button
type="button"
className="control control-quiet disclose"
aria-expanded={open}
onClick={onToggle}
>
<span className="control-word">
{`${open ? "hide" : "show"} ${count}${noun === "" ? "" : ` ${noun}`}`}
</span>
<Icon name="chevronDown" />
</button>
);
}
/**
* The arm-then-confirm as a labelled control, for the ⋯ tray where a phone
* spells the action out. Full width there, so the armed label can be longer.
*/
export function ArmedDeleteWord({
label,
execute,
}: {
label: string;
execute: () => Promise<boolean | undefined> | undefined;
}) {
const { armed, spent, click, disarm } = useArmed(execute);
return (
<Control
text={armed ? `tap again to ${label}` : label}
glyph={armed ? "check" : "trash"}
quiet
data-kind="delete"
data-armed={armed ? "true" : undefined}
disabled={spent}
onClick={click}
onBlur={() => {
if (armed) {
disarm();
}
}}
/>
);
}
/* ---- status -------------------------------------------------------------- */
export interface Status {
text: string;
tone?: Tone;
busy?: boolean;
/** A way out carried by the sentence itself (a quiet control after it). */
action?: { label: string; run: () => void };
}
/**
* A status slot. The slot is always laid out — an empty one keeps its line —
* so a message arriving or leaving never pushes the content below it.
*/
export function StatusSlot({ status, className }: { status: Status | null; className: string }) {
return (
<p
className={className}
role="status"
data-empty={String(status === null)}
data-tone={status?.tone}
data-action={flag(status?.action !== undefined)}
>
{status?.busy && <span className="lamp" data-state="probing" aria-hidden="true" />}
{status?.text ?? ""}
{status?.action && <Control text={status.action.label} quiet onClick={status.action.run} />}
</p>
);
}
/** A status setter for one slot, with the same signature everywhere. */
export function useStatus(): [
Status | null,
(text: string | null, tone?: Tone, busy?: boolean) => void,
] {
const [status, setStatus] = useState<Status | null>(null);
const set = useCallback((text: string | null, tone?: Tone, busy = false) => {
setStatus(text === null ? null : { text, tone, busy });
}, []);
return [status, set];
}
/* ---- the row's note ---------------------------------------------------------- */
export interface Note {
text: string;
tone?: Tone;
}
export type Say = (text: string | null, tone?: Tone) => void;
/** The row's status slot, in the tray. Null clears it. */
export function useNote(): [Note | null, Say] {
const [note, setNote] = useState<Note | null>(null);
const say = useCallback<Say>((text, tone) => {
setNote(text === null ? null : { text, tone });
}, []);
return [note, say];
}
/** A note line outside a row, written the way a row's own slot is. */
export function NoteLine({ note, className }: { note: Note | null; className: string }) {
return (
<p className={className} role="status" hidden={note === null} data-tone={note?.tone}>
{note?.text ?? ""}
</p>
);
}
/* ---- chips ------------------------------------------------------------------- */
export interface Explain {
text: string;
say: Say;
tone?: Tone;
}
/**
* A chip whose meaning would otherwise live in a tooltip. Touch has no hover,
* so the chip becomes a button that writes its sentence into the row's own
* status slot, and a second tap takes it away.
*/
function useExplain(explain: Explain | undefined) {
const [open, setOpen] = useState(false);
if (!explain) {
return {};
}
const toggle = (event: MouseEvent | KeyboardEvent) => {
event.stopPropagation();
event.preventDefault();
const next = !open;
setOpen(next);
explain.say(next ? explain.text : null, explain.tone);
};
return {
role: "button",
tabIndex: 0,
"data-explain": "",
"aria-expanded": open,
onClick: toggle,
onKeyDown: (event: KeyboardEvent) => {
if (event.key === "Enter" || event.key === " ") {
toggle(event);
}
},
};
}
export interface ChipProps extends HTMLAttributes<HTMLSpanElement> {
/** `chip readout` by default; a glyph chip drops the readout face. */
base?: string;
explain?: Explain;
[data: `data-${string}`]: string | undefined;
}
/** A chip, the §9.3 column unit. */
export function Chip({ base = "chip readout", className, explain, children, ...rest }: ChipProps) {
const explainProps = useExplain(explain);
return (
<span className={cx(base, className)} {...rest} {...explainProps}>
{children}
</span>
);
}
/* ---- the row --------------------------------------------------------------- */
/** One cell in a row's action column. An empty cell still takes its width. */
export interface ActionSlot {
node: ReactNode | null;
/** The width class: a glyph square, a lamp toggle, or a fixed word control. */
width: "icon" | "toggle" | "word";
/** Shown from 40rem up; on a phone this action lives in the ⋯ tray instead. */
wide?: boolean;
/** Shown below 40rem only — an empty cell that keeps a phone column aligned. */
narrow?: boolean;
}
export interface RowProps {
/** `data-row`: which kind of row, for the few rules that differ by kind. */
kind: string;
lead?: ReactNode;
title?: ReactNode;
titleClassName?: string;
/** The chip line. */
meta?: ReactNode;
sub?: ReactNode;
/** The sub line opens to its full string on a tap. */
subExpands?: boolean;
/** Body content between the chip line and the sub line. */
beforeSub?: ReactNode;
/** Body content after the sub line. */
afterSub?: ReactNode;
bodyClassName?: string;
onBodyClick?: (event: MouseEvent<HTMLDivElement>) => void;
actions?: ActionSlot[];
/** The phone tray: labelled, full-width versions of the wide-only actions. */
more?: ReactNode;
/** The whole row opens something: a stretched button under the controls. */
open?: {
label: string;
run: (origin: HTMLElement) => void;
chevron?: boolean;
className?: string;
expanded?: boolean;
disabled?: boolean;
};
note?: Note | null;
/** Full-width area under the line: inline panels after the note. */
tray?: ReactNode;
}
/** A sub line that opens to its full string on a tap. */
export function Expandable({ className, children }: { className: string; children: ReactNode }) {
const [full, setFull] = useState(false);
return (
// biome-ignore lint/a11y/noStaticElementInteractions: a reading aid, the text is already all there for a screen reader
// biome-ignore lint/a11y/useKeyWithClickEvents: same
<div className={className} data-full={flag(full)} onClick={() => setFull(!full)}>
{children}
</div>
);
}
/**
* The one row: `lead | body | actions`, plus a full-width tray. The body is
* `minmax(0, 1fr)`, so a long title or a run of chips is clipped inside it
* and can never push the actions onto a second line.
*/
export function Row(props: RowProps) {
const [moreOpen, setMoreOpen] = useState(false);
const { open, actions = [] } = props;
return (
<li className="r" data-row={props.kind} data-nolead={flag(!props.lead)}>
{open && (
<button
type="button"
className={cx("r-link", open.className)}
aria-label={open.label}
aria-expanded={open.expanded}
aria-disabled={open.disabled ? "true" : undefined}
onClick={(event) => open.run(event.currentTarget)}
/>
)}
{props.lead && <div className="r-lead">{props.lead}</div>}
{/* biome-ignore lint/a11y/noStaticElementInteractions: the season name expands it too — the chevron stays the accessible control */}
{/* biome-ignore lint/a11y/useKeyWithClickEvents: same */}
<div className={cx("r-body", props.bodyClassName)} onClick={props.onBodyClick}>
{props.title !== undefined && props.title !== null && (
<div className={cx("r-title", props.titleClassName)}>{props.title}</div>
)}
<div className="r-meta">{props.meta}</div>
{props.beforeSub}
{props.sub !== undefined &&
props.sub !== null &&
(props.subExpands ? (
<Expandable className="r-sub readout">{props.sub}</Expandable>
) : (
<div className="r-sub readout">{props.sub}</div>
))}
{props.afterSub}
</div>
<div className="r-act">
{actions.map((slot, index) => (
<span
// the column is positional: a slot is its index
// biome-ignore lint/suspicious/noArrayIndexKey: see above
key={index}
className="r-slot"
data-width={slot.width}
data-wide={flag(slot.wide)}
data-narrow={flag(slot.narrow)}
>
{slot.node}
</span>
))}
{props.more && (
<span className="r-slot" data-width="icon" data-narrow="">
<IconControl
glyph="more"
label="more actions"
aria-expanded={moreOpen}
onClick={() => setMoreOpen(!moreOpen)}
/>
</span>
)}
{open && open.chevron !== false && actions.length === 0 && (
<span className="r-slot r-chevron" data-width="icon" aria-hidden="true">
<Icon name="chevronRight" />
</span>
)}
</div>
<div className="r-tray">
<NoteLine note={props.note ?? null} className="r-note readout" />
{props.more && (
<div className="r-morepanel" hidden={!moreOpen}>
{props.more}
</div>
)}
{props.tray}
</div>
</li>
);
}
/** A row-shaped placeholder: same height and columns as the row it stands for. */
export function SkeletonRows({ count, withLead = true }: { count: number; withLead?: boolean }) {
return Array.from({ length: count }, (_, index) => (
// biome-ignore lint/suspicious/noArrayIndexKey: placeholders have no identity
<li key={index} className="r r-skel" aria-hidden="true" data-nolead={flag(!withLead)}>
{withLead && (
<div className="r-lead">
<span className="skel skel-lead" />
</div>
)}
<div className="r-body">
<span className="skel skel-line" />
<span className="skel skel-line skel-short" />
</div>
<div className="r-act" />
</li>
));
}
/** A list's one-line empty or error state, at row height. */
export function EmptyRow({
text,
tone,
children,
}: {
text: string;
tone?: "fault";
children?: ReactNode;
}) {
return (
<li className="r-empty readout" data-tone={tone}>
{text}
{children}
</li>
);
}
/** A section head: the engraved label, a count, then whatever acts on it. */
export function DeckHead({
label,
labelId,
as: Heading = "h3",
labelClass = "deck-label",
count,
children,
}: {
label: string;
labelId?: string;
as?: "h3" | "h4";
labelClass?: string;
count?: string | number | null;
children?: ReactNode;
}) {
return (
<header className="deck-head">
<Heading className={labelClass} id={labelId}>
{label}
</Heading>
{count !== undefined && <span className="deck-count readout">{count ?? ""}</span>}
{children}
</header>
);
}
/** A group's one plain sentence, which opens to the long form on a tap. */
export function GroupNote({ short, more }: { short: string; more: string }) {
const [open, setOpen] = useState(false);
return (
<div className="group-note" data-explain-group="">
<p>{short}</p>
<IconControl
glyph="info"
label="more about this list"
aria-expanded={open}
onClick={() => setOpen(!open)}
/>
<p className="group-note-more" hidden={!open}>
{more}
</p>
</div>
);
}
+246
View File
@@ -0,0 +1,246 @@
// The library (§4.2, issue #32; §9.7 makes it the homepage): series and
// movies as a poster grid by root (§9.6, #151), or as two lists.
import { Fragment, type ReactNode, useEffect, useRef, useState } from "react";
import { useNav } from "../context";
import { Icon } from "../icons";
import {
fetchLibrary,
type LibrarySeries,
movieNeedsAttention,
seriesNeedsAttention,
} from "../library";
import { MovieCard, MovieRow, SeriesCard, SeriesRow } from "../rows";
import { allRoots, type LibraryMovie, type Root } from "../search";
import { DeckHead, SkeletonRows, StatusSlot, useStatus } from "../ui";
type LibraryShape = "grid" | "list";
const LIBRARY_SHAPE_KEY = "arr.libraryView";
/**
* The grid is default and the choice is per-person — no server state. A
* corrupt or foreign value falls back to the grid rather than breaking open.
*/
function loadLibraryShape(): LibraryShape {
try {
return window.localStorage.getItem(LIBRARY_SHAPE_KEY) === "list" ? "list" : "grid";
} catch {
return "grid";
}
}
/**
* Stable partition: the items that still want something keep their order and
* come first, the satisfied ones keep theirs and follow.
*/
function attentionFirst<T>(items: T[], wants: (item: T) => boolean): T[] {
return [...items.filter(wants), ...items.filter((item) => !wants(item))];
}
interface LibraryData {
series: LibrarySeries[];
movies: LibraryMovie[];
roots: Root[];
}
/** The last answer, so a return to the library paints at once and then refreshes. */
let cached: LibraryData | null = null;
function GridSkeleton() {
return (
<ul className="deck-rows grid-rows" aria-hidden="true">
{Array.from({ length: 6 }, (_, index) => (
// biome-ignore lint/suspicious/noArrayIndexKey: placeholders have no identity
<li key={index}>
<span className="card card-skel">
<span className="card-art" />
<span className="card-body">
<span className="skel skel-line" />
<span className="skel skel-line skel-short" />
</span>
</span>
</li>
))}
</ul>
);
}
export function LibraryView({ hidden }: { hidden: boolean }) {
const nav = useNav();
const [shape, setShapeState] = useState(loadLibraryShape);
const [data, setData] = useState<LibraryData | null>(cached);
const [failed, setFailed] = useState(false);
const [status, setStatus] = useStatus();
// guards a stale fetch from painting over a newer view
const sequence = useRef(0);
useEffect(() => {
sequence.current += 1;
const ticket = sequence.current;
setStatus("reading library…");
void Promise.all([fetchLibrary(), allRoots().catch(() => cached?.roots ?? [])]).then(
([outcome, roots]) => {
if (ticket !== sequence.current) {
return;
}
if (outcome.kind === "error") {
setFailed(true);
setStatus(`library unavailable — ${outcome.detail}`, "fault");
return;
}
cached = { series: outcome.series, movies: outcome.movies, roots };
setFailed(false);
setData(cached);
const total = outcome.series.length + outcome.movies.length;
setStatus(total === 0 ? "library is empty — the search box above adds titles" : null);
},
);
return () => {
sequence.current += 1;
};
}, [setStatus]);
const setShape = (next: LibraryShape) => {
setShapeState(next);
try {
window.localStorage.setItem(LIBRARY_SHAPE_KEY, next);
} catch {
// private mode or full storage: the choice just does not persist
}
};
const shown = failed ? null : data;
const total = shown === null ? 0 : shown.series.length + shown.movies.length;
const roots = shown?.roots ?? [];
// §4.2: nothing is hidden. Satisfied titles sort last so what still
// wants something is what the eye lands on first.
const seriesShown = shown === null ? [] : attentionFirst(shown.series, seriesNeedsAttention);
const moviesShown = shown === null ? [] : attentionFirst(shown.movies, movieNeedsAttention);
let grid: { id: number; label: string; items: { key: string; node: ReactNode }[] }[] = [];
if (shown !== null && shape === "grid") {
// series and movies share a root section, so the two lists interleave
// before the cards are built — otherwise a satisfied series would sit
// above a movie that still wants a file.
const entries = attentionFirst(
[
...seriesShown.map((series) => ({
root_id: series.root_id,
wants: seriesNeedsAttention(series),
key: `s${series.id}`,
node: <SeriesCard series={series} open={nav.openSeries} />,
})),
...moviesShown.map((movie) => ({
root_id: movie.root_id,
wants: movieNeedsAttention(movie),
key: `m${movie.id}`,
node: <MovieCard movie={movie} open={nav.openMovie} />,
})),
],
(entry) => entry.wants,
);
const sections = [
...roots.map((root) => ({
id: root.id,
label: `${root.kind === "tv" ? "series" : "movies"} · ${root.audience}`,
})),
...[
...new Set(
entries
.filter((entry) => !roots.some((root) => root.id === entry.root_id))
.map((entry) => entry.root_id),
),
].map((id) => ({ id, label: `root ${id}` })),
];
grid = sections
.map((section) => ({
...section,
items: entries.filter((entry) => entry.root_id === section.id),
}))
.filter((section) => section.items.length > 0);
}
return (
<main className="deck" aria-label="library" hidden={hidden}>
<header className="page-bar">
<h2 className="page-title">library</h2>
<span className="deck-count readout">
{total === 0 ? "" : `${total} ${total === 1 ? "title" : "titles"}`}
</span>
<StatusSlot status={status} className="head-status readout" />
<fieldset className="segmented" aria-label="layout">
<button
type="button"
className="seg seg-icon"
aria-pressed={shape === "grid"}
aria-label="poster grid"
onClick={() => setShape("grid")}
>
<Icon name="grid" />
</button>
<button
type="button"
className="seg seg-icon"
aria-pressed={shape === "list"}
aria-label="list"
onClick={() => setShape("list")}
>
<Icon name="list" />
</button>
</fieldset>
</header>
<div hidden={shown !== null && (shape === "list" || grid.length === 0)}>
{data === null && !failed && (shape === "grid" ? <GridSkeleton /> : <ListSkeleton />)}
{shown !== null &&
grid.map((section) => (
<section key={section.id} className="deck-group library-grid-group">
<DeckHead label={section.label} count={section.items.length} />
<ul className="deck-rows grid-rows">
{section.items.map((item) => (
<Fragment key={item.key}>{item.node}</Fragment>
))}
</ul>
</section>
))}
</div>
<section
className="deck-group"
hidden={shown === null || shape === "grid" || seriesShown.length === 0}
aria-labelledby="label-lib-series"
>
<DeckHead label="series" labelId="label-lib-series" count={seriesShown.length} />
<ul className="deck-rows">
{shape === "list" &&
seriesShown.map((series) => (
<SeriesRow key={series.id} series={series} roots={roots} open={nav.openSeries} />
))}
</ul>
</section>
<section
className="deck-group"
hidden={shown === null || shape === "grid" || moviesShown.length === 0}
aria-labelledby="label-lib-movies"
>
<DeckHead label="movies" labelId="label-lib-movies" count={moviesShown.length} />
<ul className="deck-rows">
{shape === "list" &&
moviesShown.map((movie) => (
<MovieRow key={movie.id} movie={movie} roots={roots} open={nav.openMovie} />
))}
</ul>
</section>
</main>
);
}
function ListSkeleton() {
return (
<ul className="deck-rows">
<SkeletonRows count={6} />
</ul>
);
}
+582
View File
@@ -0,0 +1,582 @@
// The movie page (§9.6, issue #149): what the film is, its library
// controls, what is on disk, then the §9.3 release deck.
import { useCallback, useEffect, useRef, useState } from "react";
import { Buckets, type DeckState, type ReleaseActions } from "../buckets";
import { LAYER, useEscape, useNav } from "../context";
import { Hero, ProviderLink, RemovePanel, type RemoveSubject, TrailerLink } from "../detail";
import {
fileName,
imdbLink,
type MovieMetadata,
movieMetadata,
rottenTomatoesSearch,
tmdbMovieLink,
updateMovie,
youtubeLink,
} from "../movie";
import {
audienceOf,
BLOCKED_EFFECT,
DownloadChip,
MediaStateChip,
NO_TARGETED_SEARCH,
WaiverChip,
} from "../parts";
import {
type FilesOutcome,
formatSize,
formatSweepAge,
grabRelease,
libraryFolder,
type MovieFile,
type MovieRelease,
movieFiles,
movieReleases,
movieSearchState,
probedAttributeTags,
queueSearch,
removeMovie,
sweepExpected,
waiveAndGrab,
} from "../releases";
import { allRoots, fetchMovie, type LibraryMovie, type Root } from "../search";
import { useSubtitleSection } from "../subs-panel";
import { movieSubtitleStatus, type SubtitleStatus } from "../subtitles";
import {
Chip,
DeckHead,
EmptyRow,
Expandable,
IconControl,
LampToggle,
Row,
SkeletonRows,
StatusSlot,
useNote,
useStatus,
} from "../ui";
// §6.2: the sweep runs on the daemon's own cadence. Poll modestly, and
// stop promising once the backoff window is plausibly in charge.
const SWEEP_POLL_MS = 5000;
const SWEEP_WAIT_MS = 150_000;
/** One imported file: ffprobe truth and honest waivers (§5.6, §5.7). */
function FileRow({
file,
status,
refresh,
}: {
file: MovieFile;
status: SubtitleStatus | undefined;
refresh: () => void;
}) {
const [note, say] = useNote();
// the languages a file carries belong together: subtitles sit beside
// the audio tags `probedAttributeTags` just ended on
const subs = useSubtitleSection(status, refresh);
return (
<Row
kind="file"
title={fileName(file.path)}
titleClassName="readout"
meta={
<>
<WaiverChip waiver={file.waiver} say={say} />
{subs.chip}
{probedAttributeTags(file.probed).map((attribute) => (
<Chip key={attribute}>{attribute}</Chip>
))}
<Chip>{formatSize(file.size)}</Chip>
</>
}
// the full path is evidence, a tap away rather than a hover away
afterSub={<Expandable className="r-sub readout">{file.path}</Expandable>}
note={note}
tray={subs.panel}
/>
);
}
export function MovieView({ movieId, toReleases }: { movieId: number; toReleases: boolean }) {
const nav = useNav();
const [movie, setMovie] = useState<LibraryMovie | null>(null);
const [roots, setRoots] = useState<Root[]>([]);
const [files, setFiles] = useState<FilesOutcome | null>(null);
const [subtitles, setSubtitles] = useState(new Map<number, SubtitleStatus>());
const [metadata, setMetadata] = useState<MovieMetadata | null>(null);
const [heroNote, heroSay] = useNote();
const [status, setStatus] = useStatus();
const [releaseStatus, setReleaseStatus] = useStatus();
const [deck, setDeck] = useState<DeckState>({ kind: "skeleton" });
const [sweeping, setSweeping] = useState(false);
const [moreOpen, setMoreOpen] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
const [busy, setBusy] = useState<"wanted" | "blocked" | "root" | null>(null);
const removeButton = useRef<HTMLButtonElement>(null);
const releasesSection = useRef<HTMLElement>(null);
// guards a stale fetch or poll from painting over a newer one
const sequence = useRef(0);
const pollTimer = useRef<number | undefined>(undefined);
const live = useRef(true);
const paints = useRef(0);
useEffect(() => {
live.current = true;
return () => {
live.current = false;
sequence.current += 1;
window.clearTimeout(pollTimer.current);
};
}, []);
const current = (ticket: number) => live.current && ticket === sequence.current;
const paint = (releases: MovieRelease[]) => {
paints.current += 1;
setDeck({ kind: "releases", releases, paint: paints.current });
};
const refreshMovie = async () => {
const fresh = await fetchMovie(movieId);
if (fresh !== null && live.current) {
setMovie(fresh);
}
};
/** Poll the movie until `last_searched_at` moves off `baseline`. */
const watchSweep = (baseline: string | null, ticket: number) => {
setSweeping(true);
setReleaseStatus("sweeping indexers…", undefined, true);
const deadline = Date.now() + SWEEP_WAIT_MS;
const tick = async () => {
if (!current(ticket)) {
return;
}
const outcome = await movieSearchState(movieId);
if (!current(ticket)) {
return;
}
if (outcome.kind === "state" && outcome.movie.last_searched_at !== baseline) {
setSweeping(false);
await loadReleases(ticket);
return;
}
if (Date.now() >= deadline) {
setSweeping(false);
setReleaseStatus(
"sweep has not landed yet — it may be waiting out its backoff; results appear here once it runs",
);
return;
}
pollTimer.current = window.setTimeout(() => void tick(), SWEEP_POLL_MS);
};
pollTimer.current = window.setTimeout(() => void tick(), SWEEP_POLL_MS);
};
/**
* The empty deck is two different truths (§9.3, issue 101): a sweep that
* has not landed yet, or a sweep that landed and found nothing. Only the
* movie's `last_searched_at` can tell them apart.
*/
const emptyVerdict = async (ticket: number) => {
const outcome = await movieSearchState(movieId);
if (!current(ticket)) {
return;
}
if (outcome.kind === "state" && outcome.movie.last_searched_at !== null) {
setReleaseStatus(
`no releases found — sweep finished ${formatSweepAge(outcome.movie.last_searched_at)}; search indexers runs a new one`,
);
return;
}
if (outcome.kind === "state" && sweepExpected(outcome.movie)) {
// first sweep still in flight — visibly different from "nothing found"
watchSweep(null, ticket);
return;
}
setReleaseStatus("no releases indexed for this title — search indexers runs a sweep now");
};
const loadReleases = async (ticket: number) => {
window.clearTimeout(pollTimer.current);
setReleaseStatus("reading releases…", undefined, true);
const outcome = await movieReleases(movieId);
if (!current(ticket)) {
return;
}
if (outcome.kind === "error") {
setDeck({ kind: "none" });
setReleaseStatus(`releases unavailable — ${outcome.detail}`, "fault");
return;
}
if (outcome.releases.length === 0) {
setDeck({ kind: "none" });
await emptyVerdict(ticket);
return;
}
paint(outcome.releases);
setReleaseStatus(null);
};
/** Refetch verdicts only — the reload an override-written grab triggers. */
const reloadReleases = async () => {
sequence.current += 1;
const ticket = sequence.current;
// a sweep being watched ends here; the verdicts below are the newer answer
window.clearTimeout(pollTimer.current);
setSweeping(false);
const outcome = await movieReleases(movieId);
if (!current(ticket)) {
return;
}
if (outcome.kind === "results") {
if (outcome.releases.length === 0) {
setDeck({ kind: "none" });
} else {
paint(outcome.releases);
}
}
};
const actions: ReleaseActions = {
reload: reloadReleases,
notify: (text, tone) => setReleaseStatus(text, tone),
grab: async (release, bucket) => {
if (bucket !== "eligible") {
return waiveAndGrab(movieId, release.id, release.rejected_rule);
}
const outcome = await grabRelease(movieId, release.id);
return outcome.kind === "done"
? { kind: "done", overrideWritten: false }
: { kind: "error", detail: outcome.detail, overrideWritten: false };
},
};
/**
* Re-read this movie's subtitle status after a manual fetch or
* translation. The panels stay mounted, so an operator who grabbed from a
* search still has the search.
*/
const refreshSubtitles = useCallback(() => {
void movieSubtitleStatus(movieId).then((outcome) => {
if (outcome.kind === "error" || !live.current) {
return;
}
setSubtitles(new Map(outcome.statuses.map((one) => [one.media_file_id, one])));
});
}, [movieId]);
// biome-ignore lint/correctness/useExhaustiveDependencies: the page loads once per title; it is keyed by id
useEffect(() => {
sequence.current += 1;
const ticket = sequence.current;
void (async () => {
const [fresh, filesOutcome, subtitleOutcome, fetchedRoots] = await Promise.all([
fetchMovie(movieId),
movieFiles(movieId),
movieSubtitleStatus(movieId),
allRoots().catch(() => [] as Root[]),
]);
if (!current(ticket)) {
return;
}
setRoots(fetchedRoots);
if (fresh === null) {
setStatus("movie unavailable", "fault");
return;
}
setMovie(fresh);
setSubtitles(
new Map(
subtitleOutcome.kind === "status"
? subtitleOutcome.statuses.map((one) => [one.media_file_id, one])
: [],
),
);
setFiles(filesOutcome);
void movieMetadata(movieId).then((outcome) => {
if (!current(ticket)) {
return;
}
if (outcome.kind === "error") {
// the stored identity stands; the hero's note says why the rest is absent
heroSay(`metadata unavailable — ${outcome.detail}`, "fault");
return;
}
setMetadata(outcome.metadata);
});
await loadReleases(ticket);
})();
}, [movieId]);
// `/movies/{id}/releases` keeps resolving (#149): same page, deck section in view
useEffect(() => {
if (toReleases && movie !== null) {
releasesSection.current?.scrollIntoView({ block: "start" });
}
}, [toReleases, movie]);
const closeRemove = () => {
setRemoveOpen(false);
removeButton.current?.focus();
};
// capture: one Escape steps back one layer — the confirmation first, then the page
useEscape(LAYER.detail, true, nav.close);
useEscape(LAYER.confirm, removeOpen, closeRemove);
const toggle = (field: "wanted" | "blocked", label: string) => {
if (movie === null) {
return;
}
setBusy(field);
void updateMovie(movie.id, { [field]: !movie[field] }).then((outcome) => {
if (outcome.kind === "error") {
setBusy(null);
setStatus(`${label} failed — ${outcome.detail}`, "fault");
return;
}
void refreshMovie().then(() => setBusy(null));
});
};
const changeRoot = (next: number) => {
if (movie === null || !Number.isInteger(next) || next === movie.root_id) {
return;
}
setBusy("root");
void updateMovie(movie.id, { root_id: next }).then((outcome) => {
setBusy(null);
if (outcome.kind === "error") {
setStatus(`root change failed — ${outcome.detail}`, "fault");
return;
}
void refreshMovie();
});
};
const sweep = () => {
if (movie === null) {
return;
}
setSweeping(true);
void (async () => {
// snapshot the last sweep first: its change is the completion signal
const before = await movieSearchState(movie.id);
if (!live.current) {
return;
}
const baseline = before.kind === "state" ? before.movie.last_searched_at : null;
const outcome = await queueSearch(movie.id);
if (!live.current) {
return;
}
if (outcome.kind === "error") {
setSweeping(false);
setReleaseStatus(`search failed — ${outcome.detail}`, "fault");
return;
}
sequence.current += 1;
window.clearTimeout(pollTimer.current);
watchSweep(baseline, sequence.current);
})();
};
const removeSubject: RemoveSubject | null =
movie === null
? null
: {
title: movie.title,
files: () => movieFiles(movie.id),
folder: libraryFolder,
remove: () => removeMovie(movie.id),
seedLine: "the torrent keeps seeding until its tracker rule clears.",
};
// one subject per title, so the panel reads the files once
const subject = useRef<RemoveSubject | null>(null);
if (subject.current === null && removeSubject !== null) {
subject.current = removeSubject;
}
const title = movie?.title ?? "this movie";
const movieRoots = roots.filter((root) => root.kind === "movie");
const rootListed = movie !== null && movieRoots.some((root) => root.id === movie.root_id);
return (
<main className="deck detail" aria-label="movie detail">
<Hero
title={movie?.title ?? ""}
year={movie?.year ?? null}
detail={metadata}
note={heroNote}
onBack={nav.close}
chips={
movie !== null && (
<>
<Chip>{audienceOf(roots, movie.root_id)}</Chip>
<MediaStateChip state={movie.state} wanted={movie.wanted} />
<WaiverChip waiver={movie.waiver} say={heroSay} />
{!movie.wanted && <Chip>not wanted</Chip>}
{movie.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
{/* §9.8: the hero is the row that owns the item, same as the library row */}
<DownloadChip targetKind="movie" targetId={movie.id} say={heroSay} />
</>
)
}
/>
<div className="actionbar">
<button type="button" className="control" disabled={sweeping} onClick={sweep}>
search indexers
</button>
<span className="actionbar-links">
{/* the trailer resolves from the metadata's own key — no second call.
Hidden when absent rather than shown dead (§9.6). */}
{metadata?.trailer && (
<TrailerLink href={youtubeLink(metadata.trailer.youtube_key)} title={title} />
)}
</span>
<IconControl
glyph="more"
label="library settings for this title"
aria-expanded={moreOpen}
aria-controls="movie-more-panel"
onClick={() => setMoreOpen(!moreOpen)}
/>
</div>
<div className="more-panel" id="movie-more-panel" hidden={!moreOpen}>
<div className="more-links">
{metadata !== null && (
<>
<ProviderLink
mark="tmdb"
label={`open ${title} on TMDB`}
href={tmdbMovieLink(metadata.tmdb_id)}
/>
{metadata.imdb_id !== null && (
<ProviderLink
mark="imdb"
label={`open ${title} on IMDb`}
href={imdbLink(metadata.imdb_id)}
/>
)}
{movie !== null && (
<ProviderLink
mark="rt"
label={`search Rotten Tomatoes for ${movie.title}`}
href={rottenTomatoesSearch(movie.title, movie.year)}
/>
)}
</>
)}
</div>
<div className="more-toggles">
<LampToggle
label="wanted"
pressed={movie?.wanted ?? false}
disabled={busy === "wanted"}
onClick={() => toggle("wanted", "wanted")}
/>
<LampToggle
label="targeted search"
pressed={!(movie?.blocked ?? false)}
// the accessible name carries what the label cannot, at rest and on
aria-description={BLOCKED_EFFECT}
disabled={busy === "blocked"}
onClick={() => toggle("blocked", "targeted search change")}
/>
</div>
{/* §6.3 is the whole point of the flag and a bare toggle hides it: the
note appears when the flag is on, which is when the RSS half is the
thing that surprises. At rest the label and the title carry it. */}
<p className="control-note readout" hidden={!movie?.blocked}>
Targeted search is off. RSS still matches this title, so a release can still arrive.
</p>
<label className="field more-field">
<span className="field-label" id="movie-root-label">
root
</span>
<select
className="form-input"
aria-labelledby="movie-root-label"
value={movie === null ? "" : String(movie.root_id)}
disabled={busy === "root"}
onChange={(event) => changeRoot(Number(event.target.value))}
>
{movieRoots.map((root) => (
<option key={root.id} value={String(root.id)}>
{`${root.audience} · ${root.policy_name}`}
</option>
))}
{/* a root list that does not carry the title's own root still shows
it — a select lying by omission would make the next change move
it blindly */}
{movie !== null && !rootListed && (
<option value={String(movie.root_id)}>{`root ${movie.root_id}`}</option>
)}
</select>
</label>
<button
type="button"
className="control control-quiet"
data-kind="delete"
ref={removeButton}
aria-expanded={removeOpen}
aria-controls="remove-panel"
aria-label={movie === null ? undefined : `remove ${movie.title} from the library`}
onClick={() => (removeOpen ? closeRemove() : setRemoveOpen(true))}
>
remove from library
</button>
<div className="remove-panel" id="remove-panel" hidden={!removeOpen}>
{removeOpen && subject.current !== null && (
<RemovePanel
subject={subject.current}
onCancel={closeRemove}
onRemoved={() => {
setRemoveOpen(false);
nav.removed();
}}
/>
)}
</div>
</div>
<StatusSlot status={status} className="deck-status readout" />
<section className="deck-group" aria-labelledby="label-disk">
<DeckHead
label="on disk"
labelId="label-disk"
labelClass="section-title"
count={files?.kind === "files" ? files.files.length : ""}
/>
<ul className="deck-rows">
{files === null && <SkeletonRows count={1} withLead={false} />}
{files?.kind === "error" && (
<EmptyRow text={`files unreadable — ${files.detail}`} tone="fault" />
)}
{files?.kind === "files" && files.files.length === 0 && (
<EmptyRow text="nothing on disk yet — imports land here" />
)}
{files?.kind === "files" &&
files.files.map((file) => (
<FileRow
key={file.id}
file={file}
status={subtitles.get(file.id)}
refresh={refreshSubtitles}
/>
))}
</ul>
</section>
<section className="deck-group" aria-labelledby="label-releases" ref={releasesSection}>
<DeckHead label="releases" labelId="label-releases" labelClass="section-title" />
<StatusSlot status={releaseStatus} className="deck-status readout" />
<Buckets state={deck} actions={actions} />
</section>
</main>
);
}
+392
View File
@@ -0,0 +1,392 @@
// The attention queues (§5.2 + §5.7, issue #33): the only places the app
// asks for a human. Every section always renders, even empty — this is the
// one surface whose good news is an absence, and the operator visits to see it.
import { type ReactNode, useEffect, useRef, useState } from "react";
import { LAYER, useEscape, useLive, useNav } from "../context";
import { AttentionLamp, audienceOf, episodeTag, seasonTag, TitleText } from "../parts";
import {
type AttentionMovie,
type AttentionQueues,
allowEnglishAudio,
attemptsLabel,
attentionTotal,
fetchAttention,
fetchSubtitleQueue,
type MovieSubtitleGaps,
type SeriesAttention,
type SeriesSubtitleGaps,
type SubtitleQueue,
subtitleQueueTotal,
} from "../queues";
import { MovieRow, type OpenTitle } from "../rows";
import { allRoots, type Root } from "../search";
import { missingChipLabel } from "../subtitles";
import {
Chip,
Control,
DeckHead,
EmptyRow,
GroupNote,
Row,
SkeletonRows,
StatusSlot,
useNote,
useStatus,
} from "../ui";
/** Refetches both queues for the destination's badge. */
export async function queueBadgeTotal(): Promise<number | null> {
const [outcome, subtitles] = await Promise.all([fetchAttention(), fetchSubtitleQueue()]);
if (outcome.kind === "error") {
return null;
}
const subtitlesTotal = subtitles.kind === "results" ? subtitleQueueTotal(subtitles.queue) : 0;
return attentionTotal(outcome.queues) + subtitlesTotal;
}
/**
* One TV lane entry: the series plus one chip per episode or season that put
* it there, named `SxxEyy` so the operator knows what to act on.
* Inert — the release deck and overrides arrive with the series detail view
* (issues 129 and 39).
*/
function SeriesAttentionRow({ entry }: { entry: SeriesAttention }) {
return (
<Row
kind="queue"
lead={<AttentionLamp />}
title={<TitleText title={entry.title} year={entry.year} />}
meta={
<>
{entry.episodes.map((episode) => {
const tag = episodeTag(episode.season_number, episode.episode_number);
return (
<Chip key={tag} aria-label={`${tag} waiting`}>
{tag}
</Chip>
);
})}
{entry.seasons.map((season) => (
<Chip key={season.number}>{seasonTag(season.number)}</Chip>
))}
</>
}
/>
);
}
/**
* One no-PT-source entry: the row opens the movie as evidence; the §5.2 one
* click sits in the action column and empties the item.
*/
function NoPtRow({
movie,
roots,
open,
settled,
}: {
movie: AttentionMovie;
roots: Root[];
open: OpenTitle;
settled: (text: string) => void;
}) {
const [note, say] = useNote();
const [state, setState] = useState<"idle" | "busy" | "failed">("idle");
const attempts = attemptsLabel(movie.search_attempts);
return (
<Row
kind="queue"
lead={<AttentionLamp />}
title={<TitleText title={movie.title} year={movie.year} />}
meta={
<>
<Chip>{audienceOf(roots, movie.root_id)}</Chip>
{attempts !== null && (
<Chip aria-label={`${movie.search_attempts} searches found no pt source`}>
{attempts}
</Chip>
)}
</>
}
actions={[
{
node: (
<Control
text={state === "busy" ? "writing" : state === "failed" ? "retry" : "allow english"}
fixed
busy={state === "busy"}
failed={state === "failed"}
disabled={state === "busy"}
onClick={() => {
setState("busy");
say(null);
void allowEnglishAudio(movie.id).then((outcome) => {
if (outcome.kind === "error") {
setState("failed");
say(
`${outcome.overrideWritten ? "override written · " : ""}${outcome.detail}`,
"fault",
);
return;
}
settled(`${movie.title} — english allowed, search queued`);
});
}}
/>
),
width: "word",
},
]}
note={note}
open={{ label: `open ${movie.title}`, run: (origin) => open(movie.id, origin) }}
/>
);
}
/**
* One missing-subtitles entry for a movie: its title, plus one chip per gap
* — language and why (#202). The row opens the movie page, where the
* subtitle section already offers manual search, translate and retry
* (#203, §9.3).
*/
function MovieGapsRow({ movie, open }: { movie: MovieSubtitleGaps; open: OpenTitle }) {
return (
<Row
kind="queue"
lead={<AttentionLamp />}
title={<TitleText title={movie.title} year={movie.year} />}
meta={movie.gaps.map((gap) => <Chip key={gap.language}>{missingChipLabel(gap)}</Chip>)}
open={{ label: `open ${movie.title}`, run: (origin) => open(movie.movie_id, origin) }}
/>
);
}
/**
* One missing-subtitles entry for a series: one chip per episode gap,
* tagged `SxxEyy`, plus one per season row a uniform gap collapsed into
* (§9.5's restraint). Opens the series page, same reasoning as the movie row.
*/
function SeriesGapsRow({ series, open }: { series: SeriesSubtitleGaps; open: OpenTitle }) {
const chips: string[] = [];
for (const episode of series.episodes) {
const tag = episodeTag(episode.season_number, episode.episode_number);
for (const gap of episode.gaps) {
chips.push(`${tag} ${missingChipLabel(gap)}`);
}
}
for (const season of series.seasons) {
const tag = seasonTag(season.season_number);
for (const gap of season.gaps) {
chips.push(`${tag} ${missingChipLabel(gap)}`);
}
}
return (
<Row
kind="queue"
lead={<AttentionLamp />}
title={<TitleText title={series.title} year={series.year} />}
meta={chips.map((text) => <Chip key={text}>{text}</Chip>)}
open={{ label: `open ${series.title}`, run: (origin) => open(series.series_id, origin) }}
/>
);
}
function QueueGroup({
id,
label,
note,
count,
rows,
hidden,
}: {
id: string;
label: string;
note: ReactNode;
count: number | null;
rows: ReactNode;
hidden: boolean;
}) {
return (
<section className="deck-group" hidden={hidden} aria-labelledby={`label-${id}`}>
<DeckHead label={label} labelId={`label-${id}`} count={count ?? ""} />
{note}
<ul className="deck-rows">{rows}</ul>
</section>
);
}
interface Loaded {
queues: AttentionQueues;
subtitles: SubtitleQueue | null;
roots: Root[];
}
export function QueuesView({ hidden }: { hidden: boolean }) {
const nav = useNav();
const { setBadge } = useLive();
const [loaded, setLoaded] = useState<Loaded | null>(null);
const [failed, setFailed] = useState(false);
/** Movies the operator already settled here: the override IS written. */
const [settledIds, setSettledIds] = useState(new Set<number>());
const [status, setStatus] = useStatus();
const sequence = useRef(0);
useEscape(LAYER.base, !hidden, nav.goHome);
useEffect(() => {
sequence.current += 1;
const ticket = sequence.current;
setStatus("reading queues…");
void Promise.all([
fetchAttention(),
fetchSubtitleQueue(),
allRoots().catch(() => [] as Root[]),
]).then(([outcome, subtitlesOutcome, roots]) => {
if (ticket !== sequence.current) {
return;
}
if (outcome.kind === "error") {
setFailed(true);
setStatus(`queues unavailable — ${outcome.detail}`, "fault");
return;
}
const subtitles = subtitlesOutcome.kind === "results" ? subtitlesOutcome.queue : null;
setLoaded({ queues: outcome.queues, subtitles, roots });
const nothingWaiting =
attentionTotal(outcome.queues) === 0 &&
(subtitles === null || subtitleQueueTotal(subtitles) === 0);
if (subtitlesOutcome.kind === "error") {
setStatus(`subtitle queue unavailable — ${subtitlesOutcome.detail}`, "fault");
} else {
setStatus(nothingWaiting ? "nothing needs attention" : null);
}
});
return () => {
sequence.current += 1;
};
}, [setStatus]);
const queues = loaded?.queues;
const noPt = queues?.no_pt_source.filter((movie) => !settledIds.has(movie.id)) ?? [];
const noPtTotal = noPt.length + (queues?.tv_no_pt_source.length ?? 0);
const decisionTotal =
(queues?.needs_decision.length ?? 0) + (queues?.tv_needs_decision.length ?? 0);
const subtitles = loaded?.subtitles;
const subtitlesTotal = (subtitles?.movies.length ?? 0) + (subtitles?.series.length ?? 0);
const total = noPtTotal + decisionTotal + subtitlesTotal;
useEffect(() => {
if (loaded !== null) {
setBadge(total);
}
}, [loaded, total, setBadge]);
const roots = loaded?.roots ?? [];
const placeholder = loaded === null && !failed;
const rows = (count: number, nodes: ReactNode) =>
placeholder ? (
<SkeletonRows count={1} withLead={false} />
) : count === 0 ? (
<EmptyRow text="nothing here" />
) : (
nodes
);
return (
<main className="deck" aria-label="attention queues" hidden={hidden}>
<header className="page-bar">
<h2 className="page-title">queues</h2>
<span className="deck-count readout">
{loaded === null || total === 0 ? "" : `${total} waiting`}
</span>
<StatusSlot status={status} className="head-status readout" />
</header>
<QueueGroup
id="no-pt"
label="no pt source"
hidden={failed}
count={loaded === null ? null : noPtTotal}
note={
<GroupNote
short="Kids titles with no Portuguese release yet."
more="They can sit here for months, by design. Allow English writes the movie's override and its search goes ahead. A series waits for its own page."
/>
}
rows={rows(
noPtTotal,
<>
{noPt.map((movie) => (
<NoPtRow
key={movie.id}
movie={movie}
roots={roots}
open={nav.openMovie}
settled={(text) => {
setSettledIds((settled) => new Set(settled).add(movie.id));
setStatus(text);
}}
/>
))}
{/* the TV lanes share the two sections: one queue per reason,
whatever the kind. Series entries are display-only — their
release deck and overrides arrive with the series detail view
(issues 129 and 39). */}
{queues?.tv_no_pt_source.map((series) => (
<SeriesAttentionRow key={`s${series.series_id}`} entry={series} />
))}
</>,
)}
/>
<QueueGroup
id="decision"
label="needs decision"
hidden={failed}
count={loaded === null ? null : decisionTotal}
note={
<GroupNote
short="Titles where two different releases failed."
more="Open the movie and pick a release by hand. Series entries are display-only for now."
/>
}
rows={rows(
decisionTotal,
<>
{queues?.needs_decision.map((movie) => (
<MovieRow key={movie.id} movie={movie} roots={roots} open={nav.openMovie} />
))}
{queues?.tv_needs_decision.map((series) => (
<SeriesAttentionRow key={`s${series.series_id}`} entry={series} />
))}
</>,
)}
/>
<QueueGroup
id="subtitles"
label="missing subtitles"
hidden={failed}
count={loaded === null ? null : subtitlesTotal}
note={
<GroupNote
short="A wanted subtitle language is missing."
more="Each chip says why: no candidate, a translation or provider failure, the daily budget, or a timing sync that looked wrong. Open the title to search, translate or retry."
/>
}
rows={rows(
subtitlesTotal,
<>
{subtitles?.movies.map((movie) => (
<MovieGapsRow key={movie.movie_id} movie={movie} open={nav.openMovie} />
))}
{subtitles?.series.map((series) => (
<SeriesGapsRow key={series.series_id} series={series} open={nav.openSeries} />
))}
</>,
)}
/>
</main>
);
}
+469
View File
@@ -0,0 +1,469 @@
// The unified search deck (§9.2, issue #30): in-library hits first, TMDB
// below, and an inline add flow under a TMDB row. A pasted magnet or
// .torrent routes to the manual-intake panel. There is no separate add page.
import { type KeyboardEvent, useEffect, useRef, useState } from "react";
import { useNav } from "../context";
import { Icon } from "../icons";
import { RatingChip, RowPoster, TitleText } from "../parts";
import { MovieRow, SeriesHitRow } from "../rows";
import {
addMovie,
addSeries,
allRoots,
parseManualInput,
type Root,
type SearchResponse,
searchTitles,
type TmdbMovie,
type TmdbSeries,
} from "../search";
import { Chip, Control, DeckHead, flag, LampToggle, Row, StatusSlot, useStatus } from "../ui";
/** Which kind the deck is showing. `all` is both, and the default. */
type KindFilter = "all" | "movie" | "series";
/** The filter outlives a single search: it is the operator's, not the query's. */
let lastKind: KindFilter = "all";
/**
* The §9.2 add flow: inline, root and policy pre-filled, one confirm. A
* series asks the one series-level question at add time — `auto_track`
* (§4.1) — and states what it does in one plain line. On success the panel
* keeps its height and says what happened in place.
*/
function AddPanel({
title,
available,
added,
}: {
title: TmdbMovie | TmdbSeries;
available: Root[];
added: () => void;
}) {
const isSeries = title.kind === "series";
const roots = available.filter((root) => root.kind === (isSeries ? "tv" : "movie"));
const [selected, setSelected] = useState<Root | null>(
roots.find((root) => root.audience === "main") ?? roots[0] ?? null,
);
// §4.1: auto_track is a rule about seasons metadata reveals, not intent.
// Future seasons are picked up by themselves; past seasons never are.
const [autoTrack, setAutoTrack] = useState(true);
const [state, setState] = useState<"idle" | "busy" | "done">("idle");
const [already, setAlready] = useState(false);
const [note, setNote] = useState<{ text: string; tone?: "fault" | "ok" } | null>(
roots.length === 0
? {
// a failed fetch and an absent kind are different problems
text:
available.length === 0
? "roots unavailable — daemon down or database missing"
: `no ${isSeries ? "tv" : "movie"} roots configured — create one under settings`,
tone: "fault",
}
: null,
);
const panel = useRef<HTMLDivElement>(null);
const noteRef = useRef<HTMLParagraphElement>(null);
useEffect(() => {
panel.current?.querySelector<HTMLElement>("button")?.focus();
}, []);
const confirm = () => {
const root = selected;
if (!root) {
return;
}
setState("busy");
setNote(null);
const adding =
title.kind === "movie" ? addMovie(title, root.id) : addSeries(title, root.id, autoTrack);
void adding.then((outcome) => {
if (outcome.kind === "error") {
setState("idle");
setNote({ text: `add failed — ${outcome.detail}`, tone: "fault" });
return;
}
const conflict = outcome.kind === "conflict";
setAlready(conflict);
setState("done");
setNote({
tone: "ok",
text: conflict
? "already in library"
: title.kind === "movie"
? `added to ${root.audience} — wanted, search follows`
: `added to ${root.audience} — future seasons ${autoTrack ? "" : "not "}tracked automatically`,
});
added();
window.requestAnimationFrame(() => noteRef.current?.focus());
});
};
const done = state === "done";
return (
<div className="add-panel" ref={panel}>
{/* biome-ignore lint/a11y/useSemanticElements: a fieldset brings its own border, padding and min-width, which this group does not want */}
<div className="add-roots" role="group" aria-label="root folder">
{roots.map((root) => (
<button
key={root.id}
type="button"
className="root-option"
aria-pressed={root === selected}
disabled={done}
onClick={() => setSelected(root)}
>
<span className="root-audience">{root.audience}</span>
<span className="root-policy readout dim">{root.policy_name}</span>
<span className="root-path readout dim">{root.path}</span>
</button>
))}
</div>
{isSeries && (
<div className="add-autotrack">
<LampToggle
label="track future seasons"
pressed={autoTrack}
disabled={done}
onClick={() => setAutoTrack(!autoTrack)}
/>
<p className="add-note">
Seasons that air later are wanted automatically. Past seasons are not.
</p>
</div>
)}
<div className="add-actions">
<Control
text={
state === "busy"
? "adding"
: done
? already
? "in library"
: "added"
: "add to library"
}
fixed
busy={state === "busy"}
done={done}
disabled={roots.length === 0 || state !== "idle"}
onClick={confirm}
/>
<p
className="add-note readout"
role="status"
data-tone={note?.tone}
ref={noteRef}
tabIndex={done ? -1 : undefined}
>
{note?.text ?? ""}
</p>
</div>
</div>
);
}
/** A TMDB hit of either kind — the row opens the add flow under itself (§9.2). */
function TmdbRow({
hit,
fetchRoots,
}: {
hit: TmdbMovie | TmdbSeries;
fetchRoots: () => Promise<Root[]>;
}) {
const [roots, setRoots] = useState<Root[] | null>(null);
const [open, setOpen] = useState(false);
const [added, setAdded] = useState(false);
const link = useRef<HTMLElement | null>(null);
const toggle = (origin: HTMLElement) => {
link.current = origin;
if (added) {
return;
}
if (open) {
setOpen(false);
origin.focus();
return;
}
void fetchRoots().then((available) => {
setRoots(available);
setOpen(true);
});
};
return (
<Row
kind="tmdb"
lead={<RowPoster posterPath={hit.poster_path} title={hit.title} />}
title={<TitleText title={hit.title} year={hit.year} />}
meta={
<>
<Chip>{hit.kind === "series" ? "series" : "movie"}</Chip>
<Chip>{hit.original_language}</Chip>
<RatingChip voteAverage={hit.vote_average} voteCount={hit.vote_count} />
</>
}
sub={hit.overview || null}
actions={[
{
node: (
<span className="r-chevron" aria-hidden="true" data-done={flag(added)}>
<Icon name={added ? "check" : "plus"} />
</span>
),
width: "icon",
},
]}
open={{
label: `add ${hit.title}${hit.year === null ? "" : ` (${hit.year})`}`,
run: toggle,
className: "row-tmdb",
expanded: open,
disabled: added,
}}
tray={
open &&
roots !== null && <AddPanel title={hit} available={roots} added={() => setAdded(true)} />
}
/>
);
}
function ManualIntake({ kind, raw }: { kind: "magnet" | "torrent_url"; raw: string }) {
const parsed = parseManualInput(kind, raw);
return (
<article className="module intake">
<header className="module-head">
<h3 className="module-name">{kind === "magnet" ? "magnet" : "torrent"}</h3>
<span className="module-status readout">recognized</span>
</header>
<p className="module-detail readout">{parsed.name ?? parsed.raw}</p>
{parsed.infohash && <p className="module-detail readout dim">{`btih ${parsed.infohash}`}</p>}
<p className="module-detail readout dim">
manual grab lands with the release buckets — nothing sent yet
</p>
</article>
);
}
/**
* The deck for one query. `run` changes on every request to search — a new
* query, or Enter on the same one — and each change aborts the one before.
*/
export function SearchView({
query,
run,
hidden,
onExitUp,
}: {
query: string;
run: number;
hidden: boolean;
/** ArrowUp from the first row goes back to the input. */
onExitUp: () => void;
}) {
const nav = useNav();
const [response, setResponse] = useState<SearchResponse | null>(null);
const [status, setStatus] = useStatus();
const [kind, setKindState] = useState<KindFilter>(lastKind);
const [roots, setRoots] = useState<Root[]>([]);
const rootsRef = useRef<Root[]>([]);
// The audience chip on a library row needs id → root. allRoots() caches
// success, so a failed boot fetch is retried whenever an add panel opens.
const fetchRoots = () =>
allRoots().then(
(fetched) => {
rootsRef.current = fetched;
setRoots(fetched);
return fetched;
},
() => rootsRef.current,
);
// biome-ignore lint/correctness/useExhaustiveDependencies: fetched once per deck
useEffect(() => {
void fetchRoots();
}, []);
// biome-ignore lint/correctness/useExhaustiveDependencies: `run` is the trigger; the query rides along
useEffect(() => {
if (query === "") {
return;
}
const controller = new AbortController();
setStatus("searching…", undefined, true);
void searchTitles(query, controller.signal).then((outcome) => {
if (outcome.kind === "aborted") {
return;
}
if (outcome.kind === "error") {
setResponse(null);
setStatus(`search failed — ${outcome.detail}`, "fault");
return;
}
setResponse(outcome.response);
});
return () => controller.abort();
}, [run]);
const setKind = (next: KindFilter) => {
lastKind = next;
setKindState(next);
};
// The status the answer implies, painted after the answer itself
useEffect(() => {
if (response === null) {
return;
}
if (
response.manual !== null &&
(response.kind === "magnet" || response.kind === "torrent_url")
) {
setStatus(null);
return;
}
const inLibrary = new Set(response.library.map((title) => title.tmdb_id));
const tmdb = response.tmdb.filter((hit) => !inLibrary.has(hit.tmdb_id));
// Issue #168: an unreachable TMDB degrades only its own group — the
// operator sees the library half plus why TMDB is missing, and can tell
// that apart from a clean "nothing found".
const tmdbDown = response.tmdb_status === "unavailable";
if (response.library.length === 0 && response.tmdb.length === 0) {
setStatus(
tmdbDown ? "no matches in library — tmdb unavailable" : "no matches in library or on tmdb",
);
return;
}
const library = response.library.filter((hit) => kind === "all" || hit.kind === kind);
const tmdbHits = tmdb.filter((hit) => kind === "all" || hit.kind === kind);
if (tmdbDown) {
setStatus("tmdb unavailable — showing library matches only", "fault");
} else if (library.length === 0 && tmdbHits.length === 0) {
// Every match is of the other kind. Name the count it is holding back,
// or the filter reads as a search that found nothing.
const held = response.library.length + tmdb.length;
const other =
kind === "movie"
? `${held} series ${held === 1 ? "does" : "do"}`
: `${held} ${held === 1 ? "movie does" : "movies do"}`;
setStatus(`no ${kind === "movie" ? "movies" : "series"} match — ${other}`);
} else {
setStatus(null);
}
}, [response, kind, setStatus]);
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.key !== "ArrowDown" && event.key !== "ArrowUp") {
return;
}
const target = event.target;
if (!(target instanceof HTMLElement) || !target.classList.contains("r-link")) {
return;
}
event.preventDefault();
const rows = [...event.currentTarget.querySelectorAll<HTMLElement>(".r-link")];
const index = rows.indexOf(target);
if (event.key === "ArrowUp" && index === 0) {
onExitUp();
return;
}
rows[index + (event.key === "ArrowDown" ? 1 : -1)]?.focus();
};
const manual =
response !== null &&
response.manual !== null &&
(response.kind === "magnet" || response.kind === "torrent_url")
? { kind: response.kind, raw: response.manual }
: null;
const inLibrary = new Set(response?.library.map((title) => title.tmdb_id) ?? []);
// a TMDB hit already in the library group below never repeats there
const tmdb = response?.tmdb.filter((hit) => !inLibrary.has(hit.tmdb_id)) ?? [];
const anything = response !== null && (response.library.length > 0 || response.tmdb.length > 0);
const listed = manual === null && anything;
const library = listed
? (response?.library ?? []).filter((hit) => kind === "all" || hit.kind === kind)
: [];
const tmdbHits = listed ? tmdb.filter((hit) => kind === "all" || hit.kind === kind) : [];
const all = [...(response?.library ?? []), ...tmdb];
const countOf = (filter: KindFilter) =>
all.filter((hit) => filter === "all" || hit.kind === filter).length;
return (
<main
className="deck"
id="deck"
aria-label="search results"
hidden={hidden}
onKeyDown={onKeyDown}
>
<header className="page-bar">
<h2 className="page-title">search</h2>
<StatusSlot status={status} className="head-status readout" />
</header>
<div
className="segmented deck-filter"
role="toolbar"
aria-label="show only one kind"
hidden={!listed}
>
{(
[
["all", "all"],
["movie", "movies"],
["series", "series"],
] as const
).map(([value, label]) => (
<button
key={value}
type="button"
className="seg"
data-kind={value}
aria-pressed={kind === value}
onClick={() => setKind(value)}
>
{label}
<span className="filter-count" data-role="count">
{listed ? countOf(value) : ""}
</span>
</button>
))}
</div>
<section className="deck-group" hidden={library.length === 0} aria-labelledby="label-library">
<DeckHead label="in library" labelId="label-library" count={library.length || ""} />
<ul className="deck-rows">
{/* §9.2: in-library hits read as whatever they are — a movie or a
series — and hold the order the API ranked them in. */}
{library.map((hit) =>
hit.kind === "movie" ? (
<MovieRow key={`m${hit.id}`} movie={hit} roots={roots} open={nav.openMovie} />
) : (
<SeriesHitRow key={`s${hit.id}`} series={hit} roots={roots} open={nav.openSeries} />
),
)}
</ul>
</section>
<section className="deck-group" hidden={tmdbHits.length === 0} aria-labelledby="label-tmdb">
<DeckHead label="on tmdb" labelId="label-tmdb" count={tmdbHits.length || ""} />
<ul className="deck-rows">
{tmdbHits.map((hit) => (
<TmdbRow key={`${hit.kind}${hit.tmdb_id}`} hit={hit} fetchRoots={fetchRoots} />
))}
</ul>
</section>
<section className="deck-group" hidden={manual === null} aria-labelledby="label-manual">
<DeckHead label="manual grab" labelId="label-manual" />
{manual !== null && <ManualIntake kind={manual.kind} raw={manual.raw} />}
</section>
</main>
);
}
+840
View File
@@ -0,0 +1,840 @@
// The series page (§4.1, §4.2, §9.3, issue 129): what the show is, its
// library controls, then the season tree with each season's episodes.
import { useCallback, useEffect, useRef, useState } from "react";
import { LAYER, type TvDeckRequest, useEscape, useNav } from "../context";
import { Hero, ProviderLink, RemovePanel, type RemoveSubject, TrailerLink } from "../detail";
import { ArmedDeleteIcon } from "../icons";
import { seriesStatusChipRedundant } from "../library";
import { rottenTomatoesSearch, tmdbSeriesLink, tvdbLink, youtubeLink } from "../movie";
import {
audienceOf,
CountsChip,
DownloadChip,
EpisodeCountsChip,
episodeTag,
MediaStateChip,
NO_TARGETED_SEARCH,
two,
WaiverChip,
} from "../parts";
import { blacklistAdvice, blacklistClass, blacklistReasonLabel, formatSweepAge } from "../releases";
import { allRoots, type Root } from "../search";
import {
type ApiEpisode,
type ApiSeason,
type ApiSeries,
type EpisodeFile,
episodeTarget,
fetchSeasons,
fetchSeries,
fetchSeriesFiles,
fileAttributeTags,
formatAirDate,
isUnaired,
refreshSeriesMetadata,
removeEpisodeFiles,
removeSeasonFiles,
removeSeries,
type SeriesMetadata,
seasonCounts,
seasonTarget,
seriesFolder,
seriesMetadata,
setEpisodeWanted,
setSeasonTracked,
updateSeries,
} from "../series";
import { useSubtitleSection } from "../subs-panel";
import { type EpisodeSubtitleStatus, seriesSubtitleStatus } from "../subtitles";
import {
type ActionSlot,
ArmedDeleteWord,
Chip,
Control,
DeckHead,
EmptyRow,
IconControl,
LampToggle,
Row,
SkeletonRows,
StatusSlot,
useNote,
useStatus,
} from "../ui";
/**
* Issue #177: the on-demand refresh a new series' add sends (#176) lands
* within seconds. Poll modestly and give up bounded so a page left open
* does not spin forever.
*/
const SERIES_REFRESH_POLL_MS = 2000;
const SERIES_REFRESH_WAIT_MS = 30_000;
/** What a season or episode row asks of the page that owns it. */
interface TreeActions {
seriesId: number;
seriesTitle: string;
/** Refetch the tree, then give focus to the control with this `data-focus-id`. */
reload: (focusKey?: string) => void;
fail: (text: string) => void;
openDeck: (request: TvDeckRequest, origin: HTMLElement) => void;
files: Map<number, EpisodeFile>;
subtitles: Map<number, EpisodeSubtitleStatus>;
refreshSubtitles: () => void;
}
/** A toggle that writes, then repaints the tree from what the API says. */
function WritingToggle({
label,
pressed,
write,
focusId,
}: {
label: string;
pressed: boolean;
write: () => Promise<boolean>;
focusId?: string;
}) {
const [busy, setBusy] = useState(false);
return (
<LampToggle
label={label}
pressed={pressed}
disabled={busy}
data-focus-id={focusId}
onClick={() => {
setBusy(true);
void write().then(() => setBusy(false));
}}
/>
);
}
function SeasonRow({
season,
open,
onToggleOpen,
tree,
}: {
season: ApiSeason;
open: boolean;
onToggleOpen: () => void;
tree: TreeActions;
}) {
const [note, say] = useNote();
// season 0 never counts toward tracking or totals (§4.1, §4.2); say so
const name = season.number === 0 ? "specials · s00" : `season ${two(season.number)}`;
const short = season.number === 0 ? "specials" : `season ${two(season.number)}`;
const counts = seasonCounts(season);
const track = () =>
setSeasonTracked(tree.seriesId, season.number, !season.tracked).then((outcome) => {
if (outcome.kind === "error") {
tree.fail(`tracking failed — ${outcome.detail}`);
return false;
}
// §4.1: turning tracking on marks revealed episodes wanted; turning
// it off withdraws nothing. The refetch paints both truths.
tree.reload(`track-${season.number}`);
return true;
});
// #174: files go, episodes stop being wanted, the season stays listed.
// Only offered with files on disk — intent alone is the tracked toggle.
const hasFiles = season.episodes.some((episode) => tree.files.has(episode.id));
const removeFiles = () =>
removeSeasonFiles(tree.seriesId, season.number).then((outcome) => {
if (outcome.kind === "error") {
tree.fail(`remove failed — ${outcome.detail}`);
tree.reload();
return false;
}
// the delete disappears with the files; the tracked toggle survives
tree.reload(`track-${season.number}`);
return undefined;
});
const deleteLabel = `delete ${short} files from disk`;
// #227: the season the operator's report is about read `0/10` with
// nothing saying a pack had been grabbed, downloaded in full and thrown
// out at import. The counts chip beside this one is exactly the number
// that looked like nothing was ever tried.
const failure = season.import_failure;
const failureKind = failure ? blacklistClass(failure.reason) : null;
const told = failure
? `a pack for this season downloaded in full and failed at import${
failure.failed_at === null ? "" : ` ${formatSweepAge(failure.failed_at)}`
} — ${failure.release} · ${blacklistAdvice(failure.reason)}`
: "";
return (
<Row
kind="season"
lead={
<IconControl
glyph="chevronRight"
label={`${short} episodes`}
className="disclose-lead"
aria-expanded={open}
aria-controls={`episodes-${season.number}`}
onClick={onToggleOpen}
/>
}
title={name}
// the season's name expands it too — the chevron stays the accessible control
bodyClassName="r-toggle-body"
onBodyClick={(event) => {
if (event.target instanceof Element && event.target.closest("button, [role=button]")) {
return;
}
onToggleOpen();
}}
meta={
<>
{counts.total > 0 && (
<CountsChip
label={`${counts.available}/${counts.total}`}
available={counts.available}
total={counts.total}
ariaLabel={`${counts.available} of ${counts.total} episodes on disk`}
glyph
/>
)}
{failure && failureKind && (
<Chip
data-flag="import-failed"
data-blacklist={failureKind}
aria-label={told}
explain={{ text: told, say, tone: failureKind === "release" ? "fault" : "warn" }}
>
{`import failed · ${blacklistReasonLabel(failure.reason)}`}
</Chip>
)}
{/* the season-level twin of the episode flag: gone upstream while
files under it remained */}
{season.vanished && <Chip data-flag="vanished">vanished</Chip>}
{/* §9.8: a season row aggregates its own pack grab, last on its line */}
<DownloadChip targetKind="season" targetId={season.id} say={say} />
</>
}
actions={[
{
node: (
<WritingToggle
label="tracked"
pressed={season.tracked}
write={track}
focusId={`track-${season.number}`}
/>
),
width: "toggle",
wide: true,
},
{
node: (
<IconControl
glyph="search"
label={`search releases for ${short}`}
onClick={(event) =>
tree.openDeck(
{
title: tree.seriesTitle,
sub: `season ${two(season.number)} · packs`,
seriesId: tree.seriesId,
target: seasonTarget(tree.seriesId, season.number),
route: {
kind: "seasonReleases",
seriesId: tree.seriesId,
seasonNumber: season.number,
},
},
event.currentTarget,
)
}
/>
),
width: "icon",
},
{
node: hasFiles ? (
<ArmedDeleteIcon
label={deleteLabel}
execute={removeFiles}
explain={(text) => say(text, "warn")}
/>
) : null,
width: "icon",
wide: true,
},
]}
more={
<>
<WritingToggle label="tracked" pressed={season.tracked} write={track} />
{hasFiles && <ArmedDeleteWord label={deleteLabel} execute={removeFiles} />}
</>
}
note={note}
tray={
<ul className="episodes" id={`episodes-${season.number}`} hidden={!open}>
{season.episodes.map((episode) => (
<EpisodeRow
key={episode.id}
seasonNumber={season.number}
episode={episode}
tree={tree}
/>
))}
</ul>
}
/>
);
}
function EpisodeRow({
seasonNumber,
episode,
tree,
}: {
seasonNumber: number;
episode: ApiEpisode;
tree: TreeActions;
}) {
const [note, say] = useNote();
const tagText = episodeTag(seasonNumber, episode.number);
const aired = !isUnaired(episode.air_date);
const onDisk = episode.state === "available";
const status = tree.subtitles.get(episode.id);
const subs = useSubtitleSection(status, tree.refreshSubtitles);
const file = tree.files.get(episode.id);
// #174: the file goes and the episode stops being wanted; the row stays
// listed. Same arm-then-confirm as a settings row.
const removeFile = () =>
removeEpisodeFiles(episode.id).then((outcome) => {
if (outcome.kind === "error") {
tree.fail(`remove failed — ${outcome.detail}`);
tree.reload();
return false;
}
// once missing, the row's want control is what remains to focus
tree.reload(`want-${episode.id}`);
return undefined;
});
const want = () =>
setEpisodeWanted(episode.id, !episode.wanted).then((outcome) => {
if (outcome.kind === "error") {
tree.fail(`want failed — ${outcome.detail}`);
return false;
}
tree.reload(`want-${episode.id}`);
return true;
});
const deleteLabel = `delete the ${tagText} file from disk`;
const actions: ActionSlot[] = [
{
node:
aired && !onDisk ? (
<WritingToggle
label="wanted"
pressed={episode.wanted}
write={want}
focusId={`want-${episode.id}`}
/>
) : null,
width: "toggle",
wide: true,
},
{
node:
aired && !onDisk ? (
<IconControl
glyph="search"
label={`search releases for ${tagText}`}
onClick={(event) =>
tree.openDeck(
{
title: tree.seriesTitle,
sub: `${tagText} · ${episode.title}`,
seriesId: tree.seriesId,
target: episodeTarget(episode.id),
route: { kind: "episodeReleases", episodeId: episode.id },
},
event.currentTarget,
)
}
/>
) : null,
width: "icon",
},
{
node:
aired && onDisk ? (
<ArmedDeleteIcon
label={deleteLabel}
execute={removeFile}
explain={(text) => say(text, "warn")}
/>
) : null,
width: "icon",
wide: true,
},
];
const hasMore = aired;
if (!hasMore) {
actions.push({ node: null, width: "icon", narrow: true });
}
// the want toggle only renders for the missing state, so the chip would
// just repeat it; an unaired episode says so instead of offering a search
const stateChip = !aired ? (
<Chip>unaired</Chip>
) : episode.state !== "missing" ? (
<MediaStateChip state={episode.state} wanted={episode.wanted} />
) : null;
return (
<Row
kind="episode"
lead={<span className="lead-tag readout">{`E${two(episode.number)}`}</span>}
title={episode.title === "" ? "—" : episode.title}
meta={
<>
{stateChip}
{/* issue 122: gone upstream while its file remained — a conflict, not a state */}
{episode.vanished && <Chip data-flag="vanished">vanished</Chip>}
{/* subtitles, then the waiver, then the probed attributes — the row
reads language first, then what was relaxed to let the file in */}
{subs.chip}
{file && <WaiverChip waiver={file.waiver} say={say} />}
{/* §7.4: attribute tags come from ffprobe, so they are true */}
{file &&
fileAttributeTags(file).map((attribute) => (
<Chip key={attribute} data-pri="2">
{attribute}
</Chip>
))}
<Chip data-pri="2">{formatAirDate(episode.air_date)}</Chip>
{/* §9.8: nothing here if the episode is part of a season pack grab —
that download is `target_kind: "season"` and shows on the season row */}
<DownloadChip targetKind="episode" targetId={episode.id} say={say} />
</>
}
actions={actions}
more={
hasMore ? (
onDisk ? (
<ArmedDeleteWord label={deleteLabel} execute={removeFile} />
) : (
<WritingToggle label="wanted" pressed={episode.wanted} write={want} />
)
) : undefined
}
note={note}
tray={subs.panel}
/>
);
}
export function SeriesView({ seriesId, covered }: { seriesId: number; covered: boolean }) {
const nav = useNav();
const view = useRef<HTMLElement>(null);
const [series, setSeries] = useState<ApiSeries | null>(null);
const [seasons, setSeasons] = useState<ApiSeason[] | null>(null);
const [roots, setRoots] = useState<Root[]>([]);
const [files, setFiles] = useState(new Map<number, EpisodeFile>());
const [subtitles, setSubtitles] = useState(new Map<number, EpisodeSubtitleStatus>());
const [metadata, setMetadata] = useState<SeriesMetadata | null>(null);
// which seasons stand open survives the refetch every action triggers
const [expanded, setExpanded] = useState(new Set<number>());
const [heroNote, heroSay] = useNote();
const [status, setStatus] = useStatus();
const [moreOpen, setMoreOpen] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
const [rootBusy, setRootBusy] = useState(false);
// set once the bounded poll for a pending metadata refresh times out
const [refreshGaveUp, setRefreshGaveUp] = useState(false);
const [retrying, setRetrying] = useState(false);
const removeButton = useRef<HTMLButtonElement>(null);
// the control to refocus once the refetch a click triggered repainted
const focusKey = useRef<string | null>(null);
// guards a stale fetch from painting over a newer view
const sequence = useRef(0);
const live = useRef(true);
const refreshPollTimer = useRef<number | undefined>(undefined);
useEffect(() => {
live.current = true;
return () => {
live.current = false;
sequence.current += 1;
window.clearTimeout(refreshPollTimer.current);
};
}, []);
const current = (ticket: number) => live.current && ticket === sequence.current;
/**
* Poll while a refresh is pending, painting seasons as soon as they land
* with no manual reload. Stops on arrival, on the refresh being recorded
* done with none, or once `SERIES_REFRESH_WAIT_MS` passes — a page left
* open must not poll forever (#177).
*/
const watchRefresh = (ticket: number) => {
window.clearTimeout(refreshPollTimer.current);
const deadline = Date.now() + SERIES_REFRESH_WAIT_MS;
const tick = async () => {
if (!current(ticket)) {
return;
}
const [detail, seasonsOutcome] = await Promise.all([
fetchSeries(seriesId),
fetchSeasons(seriesId),
]);
if (!current(ticket)) {
return;
}
if (detail && seasonsOutcome.kind === "seasons") {
setSeries(detail);
setSeasons(seasonsOutcome.seasons);
if (detail.metadata_refreshed_at !== null || seasonsOutcome.seasons.length > 0) {
return;
}
}
if (Date.now() >= deadline) {
setRefreshGaveUp(true);
return;
}
refreshPollTimer.current = window.setTimeout(() => void tick(), SERIES_REFRESH_POLL_MS);
};
refreshPollTimer.current = window.setTimeout(() => void tick(), SERIES_REFRESH_POLL_MS);
};
// biome-ignore lint/correctness/useExhaustiveDependencies: the page is keyed by series id; its helpers are per-render
const load = useCallback(
async (focus?: string) => {
focusKey.current = focus ?? null;
sequence.current += 1;
const ticket = sequence.current;
window.clearTimeout(refreshPollTimer.current);
const [detail, seasonsOutcome, filesOutcome, subtitleOutcome, fetchedRoots] =
await Promise.all([
fetchSeries(seriesId),
fetchSeasons(seriesId),
fetchSeriesFiles(seriesId),
seriesSubtitleStatus(seriesId),
allRoots().catch(() => [] as Root[]),
]);
if (!current(ticket)) {
return;
}
setRoots(fetchedRoots);
if (!detail) {
setStatus("series unavailable", "fault");
return;
}
if (seasonsOutcome.kind === "error") {
setStatus(`seasons unavailable — ${seasonsOutcome.detail}`, "fault");
return;
}
setSeries(detail);
setSeasons(seasonsOutcome.seasons);
setFiles(
new Map(
filesOutcome.kind === "files"
? filesOutcome.files.map((file) => [file.episode_id, file])
: [],
),
);
setSubtitles(
new Map(
subtitleOutcome.kind === "status"
? subtitleOutcome.statuses.map((one) => [one.episode_id, one])
: [],
),
);
setStatus(null);
if (detail.metadata_refreshed_at === null && seasonsOutcome.seasons.length === 0) {
watchRefresh(ticket);
}
void seriesMetadata(seriesId).then((outcome) => {
if (!current(ticket)) {
return;
}
if (outcome.kind === "error") {
// the operational header stands; the hero's note says why the rest is absent
heroSay(`metadata unavailable — ${outcome.detail}`, "fault");
return;
}
setMetadata(outcome.metadata);
});
},
[seriesId],
);
useEffect(() => {
void load();
}, [load]);
// A file delete rebuilds the season tree and moves focus to the control
// that replaced the delete action. Keep keyboard context without making
// the browser scroll the freshly repainted page back to that control.
useEffect(() => {
if (focusKey.current === null || seasons === null) {
return;
}
view.current
?.querySelector<HTMLElement>(`[data-focus-id="${focusKey.current}"]`)
?.focus({ preventScroll: true });
focusKey.current = null;
}, [seasons]);
/**
* Re-read the series' subtitle status after a manual fetch or translation
* and repaint the chips in place — one call for the whole series (§9.6),
* and the open panel survives it.
*/
const refreshSubtitles = useCallback(() => {
void seriesSubtitleStatus(seriesId).then((outcome) => {
if (outcome.kind === "error" || !live.current) {
return;
}
setSubtitles(new Map(outcome.statuses.map((one) => [one.episode_id, one])));
});
}, [seriesId]);
/** The empty state's retry control: resend the on-demand command by hand. */
const retryRefresh = async () => {
const ticket = sequence.current;
setRetrying(true);
setRefreshGaveUp(false);
const outcome = await refreshSeriesMetadata(seriesId);
setRetrying(false);
if (!current(ticket)) {
return;
}
if (outcome.kind === "error") {
setRefreshGaveUp(true);
setStatus(`refresh failed — ${outcome.detail}`, "fault");
return;
}
watchRefresh(ticket);
};
const closeRemove = () => {
setRemoveOpen(false);
removeButton.current?.focus();
};
// one Escape steps back one layer: the confirmation first, then the page
useEscape(LAYER.detail, !covered, nav.close);
useEscape(LAYER.confirm, removeOpen && !covered, closeRemove);
const changeRoot = (next: number) => {
if (series === null || !Number.isInteger(next) || next === series.root_id) {
return;
}
setRootBusy(true);
void updateSeries(series.id, { root_id: next }).then((outcome) => {
setRootBusy(false);
if (outcome.kind === "error") {
setStatus(`root change failed — ${outcome.detail}`, "fault");
return;
}
void load("series-root");
});
};
const subject = useRef<RemoveSubject | null>(null);
if (subject.current === null && series !== null) {
subject.current = {
title: series.title,
files: () => fetchSeriesFiles(seriesId),
folder: seriesFolder,
remove: () => removeSeries(seriesId),
seedLine: "torrents keep seeding until their tracker rules clear.",
};
}
const tree: TreeActions = {
seriesId,
seriesTitle: series?.title ?? "",
reload: (focus) => void load(focus),
fail: (text) => setStatus(text, "fault"),
openDeck: nav.openTvDeck,
files,
subtitles,
refreshSubtitles,
};
/**
* A never-refreshed series (`metadata_refreshed_at` null) reads as a
* refresh under way, since #176 queues one on add and it lands within
* seconds. A refreshed series with no seasons is a settled, if rare,
* empty state upstream — the two must not share a message (#177).
*/
const seasonsEmpty =
series !== null && series.metadata_refreshed_at === null ? (
refreshGaveUp ? (
<EmptyRow text="metadata refresh has not landed yet">
<Control text="retry" quiet disabled={retrying} onClick={() => void retryRefresh()} />
</EmptyRow>
) : (
<li className="r-empty readout">
<span className="lamp" data-state="probing" />
{" refreshing metadata — seasons will appear here"}
</li>
)
) : (
<EmptyRow text="no seasons listed upstream" />
);
const title = series?.title ?? "this series";
const tvRoots = roots.filter((root) => root.kind === "tv");
const rootListed = series !== null && tvRoots.some((root) => root.id === series.root_id);
return (
<main className="deck detail" aria-label="series detail" hidden={covered} ref={view}>
<Hero
title={series?.title ?? ""}
year={series?.year ?? null}
detail={metadata}
note={heroNote}
onBack={nav.close}
chips={
// audience, episode counts and §4.2 status: operational state,
// outranking the artwork, folded into this one header (issue 150)
series !== null && (
<>
<Chip>{audienceOf(roots, series.root_id)}</Chip>
<EpisodeCountsChip
available={series.available_episodes}
total={series.total_episodes}
/>
{!seriesStatusChipRedundant(series) && (
<Chip data-status={series.status}>{series.status}</Chip>
)}
{series.blocked && <Chip>{NO_TARGETED_SEARCH}</Chip>}
</>
)
}
/>
<div className="actionbar">
<span className="actionbar-links">
{metadata?.trailer && (
<TrailerLink href={youtubeLink(metadata.trailer.youtube_key)} title={title} />
)}
</span>
<IconControl
glyph="more"
label="library settings for this title"
aria-expanded={moreOpen}
aria-controls="series-more-panel"
onClick={() => setMoreOpen(!moreOpen)}
/>
</div>
<div className="more-panel" id="series-more-panel" hidden={!moreOpen}>
<div className="more-links">
{metadata !== null && (
<>
<ProviderLink
mark="tmdb"
label={`open ${title} on TMDB`}
href={tmdbSeriesLink(metadata.tmdb_id)}
/>
{/* a series has no imdb_id in this app; TVDB is its second id (§9.6) */}
{metadata.tvdb_id !== null && (
<ProviderLink
mark="tvdb"
label={`open ${title} on TVDB`}
href={tvdbLink(metadata.tvdb_id)}
/>
)}
{series !== null && (
<ProviderLink
mark="rt"
label={`search Rotten Tomatoes for ${series.title}`}
href={rottenTomatoesSearch(series.title, series.year)}
/>
)}
</>
)}
</div>
<label className="field more-field">
<span className="field-label" id="series-root-label">
root
</span>
<select
className="form-input"
data-focus-id="series-root"
aria-labelledby="series-root-label"
value={series === null ? "" : String(series.root_id)}
disabled={rootBusy}
onChange={(event) => changeRoot(Number(event.target.value))}
>
{tvRoots.map((root) => (
<option key={root.id} value={String(root.id)}>
{`${root.audience} · ${root.policy_name}`}
</option>
))}
{series !== null && !rootListed && (
<option value={String(series.root_id)}>{`root ${series.root_id}`}</option>
)}
</select>
</label>
<button
type="button"
className="control control-quiet"
data-kind="delete"
ref={removeButton}
aria-expanded={removeOpen}
aria-controls="series-remove-panel"
aria-label={series === null ? undefined : `remove ${series.title} from the library`}
onClick={() => (removeOpen ? closeRemove() : setRemoveOpen(true))}
>
remove from library
</button>
<div className="remove-panel" id="series-remove-panel" hidden={!removeOpen}>
{removeOpen && subject.current !== null && (
<RemovePanel
subject={subject.current}
onCancel={closeRemove}
onRemoved={() => {
setRemoveOpen(false);
nav.removed();
}}
/>
)}
</div>
</div>
<StatusSlot status={status} className="deck-status readout" />
<section className="deck-group" aria-labelledby="label-seasons">
<DeckHead label="seasons" labelId="label-seasons" labelClass="section-title" />
<ul className="deck-rows seasons">
{seasons === null && <SkeletonRows count={4} />}
{seasons?.map((season) => (
<SeasonRow
key={season.id}
season={season}
open={expanded.has(season.number)}
onToggleOpen={() => {
const next = new Set(expanded);
if (next.has(season.number)) {
next.delete(season.number);
} else {
next.add(season.number);
}
setExpanded(next);
}}
tree={tree}
/>
))}
{seasons !== null && seasons.length === 0 && seasonsEmpty}
</ul>
</section>
</main>
);
}
File diff suppressed because it is too large Load Diff
+408
View File
@@ -0,0 +1,408 @@
// The tv release deck: §9.3 for season packs and single episodes, opened
// over the series page.
import { useEffect, useRef, useState } from "react";
import { Buckets, type DeckState, type ReleaseActions } from "../buckets";
import { LAYER, type TvDeckRequest, useEscape, useNav } from "../context";
import {
blacklistAdvice,
blacklistClass,
blacklistReasonLabel,
formatRetryWait,
formatSweepAge,
type ImportFailure,
type MovieRelease,
type PackStateOutcome,
type SeasonPackState,
} from "../releases";
import { waiveAndGrabTv } from "../series";
import { IconControl, type Status, StatusSlot } from "../ui";
/** §6.2: the sweep runs on the daemon's cadence. Poll modestly, give up softly. */
const TV_SWEEP_POLL_MS = 5000;
const TV_SWEEP_WAIT_MS = 150_000;
export function TvDeckView({ request }: { request: TvDeckRequest }) {
const nav = useNav();
const [status, setStatusState] = useState<Status | null>(null);
const [deck, setDeck] = useState<DeckState>({ kind: "skeleton" });
const [failure, setFailure] = useState<ImportFailure | null>(null);
const [sweeping, setSweepingState] = useState(false);
const sweepingRef = useRef(false);
const setSweeping = (on: boolean) => {
sweepingRef.current = on;
setSweepingState(on);
};
const back = useRef<HTMLButtonElement>(null);
// guards a stale fetch from painting over a newer view
const sequence = useRef(0);
const pollTimer = useRef<number | undefined>(undefined);
const live = useRef(true);
const paints = useRef(0);
const { target } = request;
useEffect(() => {
live.current = true;
back.current?.focus({ preventScroll: true });
window.scrollTo({ top: 0 });
return () => {
live.current = false;
sequence.current += 1;
window.clearTimeout(pollTimer.current);
};
}, []);
useEscape(LAYER.tvDeck, true, nav.close);
const current = (ticket: number) => live.current && ticket === sequence.current;
const setStatus = (text: string | null, tone?: "fault", busy = false) => {
setStatusState(text === null ? null : { text, tone, busy });
};
/**
* A status that carries its own way out. A season held off the pack lane
* cannot be helped by the head's re-search alone (#181, #182), so the
* sentence that explains the wait also offers the retry that ends it.
*/
const setStatusAction = (text: string, label: string, run: () => void) => {
setStatusState({ text, action: { label, run } });
};
const paint = (releases: MovieRelease[]) => {
paints.current += 1;
setDeck({ kind: "releases", releases, paint: paints.current });
};
const actions: ReleaseActions = {
reload: () => load(),
notify: (text, tone) => setStatus(text, tone),
grab: (release, bucket) => {
if (bucket !== "eligible") {
return waiveAndGrabTv(request.seriesId, target, release.id, release.rejected_rule);
}
return target
.grab(release.id)
.then((outcome) =>
outcome.kind === "done"
? { kind: "done" as const, overrideWritten: false }
: { kind: "error" as const, detail: outcome.detail, overrideWritten: false },
);
},
};
async function load(sweepIfEmpty = false) {
sequence.current += 1;
const ticket = sequence.current;
window.clearTimeout(pollTimer.current);
setStatus("reading releases…", undefined, true);
const outcome = await target.releases();
if (!current(ticket)) {
return;
}
if (outcome.kind === "error") {
setDeck({ kind: "none" });
setStatus(`releases unavailable — ${outcome.detail}`, "fault");
return;
}
const painted = outcome.releases.length > 0;
if (painted) {
setSweeping(false);
paint(outcome.releases);
}
// One read of the season's state, shared by the notice and the empty
// verdict below — they answer two questions from the same row.
const pack = await target.packState?.();
if (!current(ticket)) {
return;
}
setFailure(pack?.kind === "state" ? pack.state.import_failure : null);
if (!painted) {
setDeck({ kind: "none" });
await emptyVerdict(ticket, sweepIfEmpty, pack);
return;
}
setStatus(null);
}
/**
* An empty season deck is three different truths (#182), and until the
* season could say which, it blamed backoff for all three: a pack sweep
* still running, a pack sweep that ran and found nothing, and a season on
* the per-episode lane, where no pack sweep is coming at all. The lane
* answers the third; `last_pack_search_at` separates the first two, the
* same way a movie's `last_searched_at` does (#177).
*/
async function emptyVerdict(ticket: number, sweepIfEmpty: boolean, known?: PackStateOutcome) {
// An episode deck has no pack lane, so none of what follows applies to
// it: its own row carries the stamp that separates a sweep in flight
// from a sweep that came back empty.
const episode = await target.searchState?.();
if (!current(ticket)) {
return;
}
if (episode?.kind === "state") {
setSweeping(false);
if (episode.episode.last_searched_at !== null) {
setStatus(
`no releases found — indexers last swept ${formatSweepAge(episode.episode.last_searched_at)}; search indexers runs a new one`,
);
return;
}
if (sweepIfEmpty) {
void startSweep();
return;
}
setStatus("no releases indexed yet — search indexers queues a targeted sweep");
return;
}
const outcome = known ?? (await target.packState?.());
if (!current(ticket)) {
return;
}
if (outcome?.kind === "state" && outcome.state.lane === "per_episode") {
setSweeping(false);
describePerEpisode(outcome.state);
return;
}
if (outcome?.kind === "state" && outcome.state.last_pack_search_at !== null) {
setSweeping(false);
setStatus(
`no season pack found — indexers last swept ${formatSweepAge(outcome.state.last_pack_search_at)}; search indexers runs a new one`,
);
return;
}
// issue 167: an empty deck sweeps on open instead of describing a sweep
if (sweepIfEmpty) {
void startSweep(outcome?.kind === "state" ? outcome.state : null);
return;
}
setStatus("no releases indexed yet — search indexers queues a targeted sweep");
}
/**
* Name the lane instead of the backoff. A season grabbing episode by
* episode has no pack to show and never will while the reason holds, so
* the deck says which reason it is and where the releases actually are.
*/
function describePerEpisode(state: SeasonPackState) {
const elsewhere = "open an episode for its releases";
if (state.reason === "no_episodes") {
setStatus(
"no episodes known for this season yet — a metadata refresh has to find them before anything can be searched",
);
return;
}
if (state.reason === "still_airing") {
setStatus(
`season still airing — a pack is only searched once every episode has aired, so this one is grabbed episode by episode; ${elsewhere}`,
);
return;
}
if (state.reason === "episodes_on_disk") {
setStatus(
`episodes already on disk — a pack would re-import them, so the rest is grabbed episode by episode; ${elsewhere}`,
);
return;
}
const failures =
state.pack_failures === 1 ? "1 failed pack grab" : `${state.pack_failures} failed pack grabs`;
const quiet =
state.pack_retry_at === null
? "pack search is quiet until its backoff elapses"
: `pack search is quiet for another ${formatRetryWait(state.pack_retry_at)}, then retries on its own`;
setStatusAction(
`${failures} — ${quiet}. episodes are grabbed one at a time meanwhile.`,
"retry the pack now",
() => {
void startSweep(state);
},
);
}
/**
* A sweep is done when its releases appear, or when the season stamps the
* pack search it just finished. `baseline` is that stamp as it read before
* the sweep was queued: once it moves, an empty deck is a settled answer
* rather than a pending one, and `load` says so.
*/
function watchSweep(baseline: string | null, ticket: number) {
setSweeping(true);
setStatus("sweeping indexers…", undefined, true);
const deadline = Date.now() + TV_SWEEP_WAIT_MS;
const again = () => {
pollTimer.current = window.setTimeout(() => void tick(), TV_SWEEP_POLL_MS);
};
const tick = async () => {
if (!current(ticket)) {
return;
}
const outcome = await target.releases();
if (!current(ticket)) {
return;
}
if (outcome.kind === "results" && outcome.releases.length > 0) {
setSweeping(false);
paint(outcome.releases);
setStatus(null);
return;
}
const episode = await target.searchState?.();
if (!current(ticket)) {
return;
}
if (episode?.kind === "state") {
if (episode.episode.last_searched_at !== baseline) {
setSweeping(false);
await emptyVerdict(ticket, false);
} else {
again();
}
return;
}
const state = await target.packState?.();
if (!current(ticket)) {
return;
}
if (state?.kind === "state") {
setFailure(state.state.import_failure);
}
if (state?.kind === "state" && state.state.last_pack_search_at !== baseline) {
setSweeping(false);
await emptyVerdict(ticket, false);
return;
}
if (Date.now() >= deadline) {
setSweeping(false);
setStatus(
"sweep has not landed yet — nothing has come back from the indexers; results appear here when it does",
);
return;
}
again();
};
again();
}
/**
* Queue a targeted sweep, then watch for it to land (§6.2). `known` is the
* lane as it read a moment ago, so the watch is only entered when a pack
* sweep is actually expected: on the per-episode lane the sweep searches
* episodes, and waiting for a pack that is not coming is the lie #182 is
* about. A failed pack is the exception — a manual search waives its
* window and does try a pack (#181).
*/
async function startSweep(known?: SeasonPackState | null) {
// the status line's retry stays clickable until the watch replaces it
if (sweepingRef.current) {
return;
}
sweepingRef.current = true;
setSweeping(true);
// The stamp the watch below waits to move. An episode stamps its own
// row; reading it before the search is queued is what keeps the finished
// sweep from being mistaken for the new one.
const episodeBefore = await target
.searchState?.()
.then((it) => (it.kind === "state" ? it.episode.last_searched_at : null));
const before =
known === undefined
? await target.packState?.().then((it) => (it.kind === "state" ? it.state : null))
: known;
if (!live.current) {
return;
}
const outcome = await target.search();
if (!live.current) {
return;
}
sequence.current += 1;
window.clearTimeout(pollTimer.current);
if (outcome.kind === "error") {
setSweeping(false);
setStatus(`search failed — ${outcome.detail}`, "fault");
return;
}
if (before && before.lane === "per_episode" && before.reason !== "pack_backoff") {
setSweeping(false);
setStatus("searching the season's episodes — open an episode for its releases");
return;
}
watchSweep(
target.searchState ? (episodeBefore ?? null) : (before?.last_pack_search_at ?? null),
sequence.current,
);
}
// biome-ignore lint/correctness/useExhaustiveDependencies: one read per deck; the deck is keyed by its target
useEffect(() => {
void load(true);
}, []);
// #227: the season's own history, above the candidates. A pack that
// downloaded in full and was condemned at import (§5.7) blacklists the
// release and puts every episode back to `missing`, which leaves the season
// reading `0/10` as though nothing had ever been tried. It sits outside the
// status line because it is a fact about the season, not about the request
// in flight, and it has to survive a sweep that repaints the status.
let failureWhat = "";
if (failure !== null) {
// A rule name reads as a preposition — "condemned on size"; a reason
// written as a sentence has to be quoted, not conjugated.
const on =
blacklistClass(failure.reason) === "policy"
? ` on ${blacklistReasonLabel(failure.reason)}`
: "";
const said = blacklistClass(failure.reason) === "release" ? `${failure.reason}. ` : "";
failureWhat = `downloaded in full, then condemned at import${on} — ${said}every episode went back to missing and the release is blacklisted.`;
}
return (
<main className="deck detail" aria-label="season and episode releases">
<header className="page-head">
<IconControl glyph="back" label="back" ref={back} onClick={nav.close} />
<div className="page-id">
<h2 className="page-title">{request.title}</h2>
<span className="page-sub readout">{request.sub ?? ""}</span>
</div>
</header>
<div className="actionbar">
<button
type="button"
className="control"
disabled={sweeping}
onClick={() => void startSweep()}
>
search indexers
</button>
</div>
<StatusSlot status={status} className="deck-status readout" />
<section
className="deck-notice"
hidden={failure === null}
data-blacklist={failure === null ? undefined : blacklistClass(failure.reason)}
aria-labelledby="tv-failure-label"
>
<h3 className="deck-label" id="tv-failure-label">
pack abandoned at import
</h3>
<p className="notice-release readout">
{failure === null
? ""
: failure.failed_at === null
? failure.release
: `${failure.release} · ${formatSweepAge(failure.failed_at)}`}
</p>
<p className="notice-line">{failureWhat}</p>
<p className="notice-line">
{failure === null ? "" : `${blacklistAdvice(failure.reason)}.`}
</p>
<p className="notice-line dim">
Nothing was imported, and the torrent was left where it is: nothing is deleted early to
satisfy the library (§7.3).
</p>
</section>
<Buckets state={deck} actions={actions} />
</main>
);
}
+1
View File
@@ -2,6 +2,7 @@
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
+3
View File
@@ -1,3 +1,5 @@
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig, loadEnv } from "vite";
// Dev-mode proxy target: the running daemon. `pnpm dev` gives hot reload while
@@ -9,6 +11,7 @@ export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
const target = (env.ARR_DAEMON_URL ?? DEFAULT_DAEMON_URL).replace(/\/+$/, "");
return {
plugins: [react(), tailwindcss()],
build: {
target: "es2022",
outDir: "dist",