Files
arr/web/src/views/Series.tsx
T
Miguel PalhasandClaude Opus 5.5 4254c1bde1 refactor(web): grid, add flow and detail pages as utilities
The hero's backdrop scrim and the title placeholder stay in CSS: they
are pseudo-element effects, not layout.

Refs #280

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 18:47:50 +00:00

862 lines
28 KiB
TypeScript

// 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 { control, cx, detail } from "../look";
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,
Deck,
DeckHead,
EmptyRow,
IconControl,
LampToggle,
Row,
Rows,
Section,
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,
fill,
}: {
label: string;
pressed: boolean;
write: () => Promise<boolean>;
focusId?: string;
fill?: boolean;
}) {
const [busy, setBusy] = useState(false);
return (
<LampToggle
fill={fill}
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`}
look="lead"
className="disclose-lead"
iconClassName={cx(
"[transition:transform_200ms_var(--ease-out)]",
open && "[transform:rotate(90deg)]",
)}
aria-expanded={open}
aria-controls={`episodes-${season.number}`}
onClick={onToggleOpen}
/>
}
title={name}
titleStyle="season"
// the season's name expands it too — the chevron stays the accessible control
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 fill label="tracked" pressed={season.tracked} write={track} />
{hasFiles && <ArmedDeleteWord label={deleteLabel} execute={removeFiles} />}
</>
}
note={note}
tray={
<ul
className="m-0 p-0 list-none [background:oklch(from_var(--panel)_l_c_h/50%)]"
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="readout w-control-h text-center text-xs font-semibold text-ink-faint">
{`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 fill 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>
) : (
<EmptyRow
lead={<span className="lamp" data-state="probing" />}
text=" refreshing metadata — seasons will appear here"
/>
)
) : (
<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 (
<Deck detail 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={detail.actionbar}>
<span className={detail.actionbarLinks}>
{metadata?.trailer && (
<TrailerLink href={youtubeLink(metadata.trailer.youtube_key)} title={title} />
)}
</span>
<IconControl
glyph="more"
label="library settings for this title"
className="ml-auto"
aria-expanded={moreOpen}
aria-controls="series-more-panel"
onClick={() => setMoreOpen(!moreOpen)}
/>
</div>
<div className={detail.morePanel} id="series-more-panel" hidden={!moreOpen}>
<div className={detail.moreLinks}>
{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 grid">
<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({ look: "quiet", fill: true, danger: true })}
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="@row:col-span-full" 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} variant="deck" />
<Section labelledBy="label-seasons">
<DeckHead label="seasons" labelId="label-seasons" titled="section" />
<Rows className="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}
</Rows>
</Section>
</Deck>
);
}