Files
arr/web/src/App.tsx
T
Miguel PalhasandClaude Opus 5.5 e07db5a042 refactor(web): controls, toggles and segments as utilities
look.ts builds each control's class list from its whole state, so no
two utilities fight over a property. The contextual overrides from rows,
trays, page heads and the removal panel become props.

Refs #280

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

700 lines
23 KiB
TypeScript

// 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 { control, cx } from "./look";
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();
}
});
}
/** A rail destination: engraved mono words, an accent rule under the current one. */
const NAV_LINK =
"inline-flex items-center gap-2 min-h-control-h py-0 px-3 font-readout text-xs font-semibold uppercase tracking-label text-ink-muted no-underline border-b-2 border-b-transparent hover:text-accent-bright aria-[current=page]:text-accent aria-[current=page]:border-b-accent";
/** A tab bar destination: glyph over word, a short accent rule on top of the current one. */
const TAB =
"relative grid place-items-center content-center gap-1 text-2xs font-semibold uppercase tracking-wide text-ink-faint no-underline aria-[current=page]:text-accent aria-[current=page]:before:absolute aria-[current=page]:before:top-0 aria-[current=page]:before:inset-x-3/10 aria-[current=page]:before:h-rule aria-[current=page]:before:bg-accent";
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="group/rail sticky top-0 z-20 pt-(--safe-top) border-b border-b-line bg-panel [box-shadow:inset_0_1px_var(--highlight)]"
data-searching={flag(railSearching)}
>
<div className="flex items-center gap-3 w-full max-w-deck h-rail-h mx-auto px-gutter">
{/* phone search mode: the field takes the rail, the identity steps aside */}
<div className="flex flex-none items-center gap-3 mr-auto group-data-searching/rail:hidden sm:mr-0 sm:group-data-searching/rail:flex">
<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="font-display text-xl font-bold tracking-wide leading-none text-ink no-underline hover:text-accent-bright focus-visible:text-accent-bright"
href="/"
id="wordmark"
ref={wordmark}
onClick={(event) => {
event.preventDefault();
goHome();
}}
>
arr
</a>
</div>
<nav className="hidden sm:flex sm:items-center sm:gap-1" 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="readout text-xs text-signal-warn"
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="relative hidden flex-1 items-center min-w-0 group-data-searching/rail:flex sm:flex sm:max-w-search sm:ml-auto">
<span
className="absolute left-3 text-ink-faint pointer-events-none"
aria-hidden="true"
>
<Icon name="search" />
</span>
<input
ref={inputRef}
id="search"
className="readout w-full min-h-control-h py-0 px-8 text-base text-ink bg-ground border border-line rounded-panel [box-shadow:inset_0_1px_var(--lowlight)] caret-accent [transition:border-color_150ms_var(--ease-out)] placeholder:text-ink-faint placeholder:opacity-100 hover:border-line-strong focus:border-accent focus:outline-none sm:text-sm"
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="readout absolute right-3 hidden py-0 px-1 text-2xs text-ink-faint border border-line rounded-panel pointer-events-none lg:inline"
aria-hidden="true"
hidden={inputFocused}
>
/
</span>
<button
type="button"
className={cx(control({ shape: "icon" }), "flex-none ml-2 sm:hidden")}
aria-label="close search"
onClick={() => {
setSearching(false);
clearSearch();
}}
>
<Icon name="close" />
</button>
</div>
<button
type="button"
className={cx(
control({ shape: "icon" }),
"group-data-searching/rail:hidden sm:hidden",
)}
aria-label="search"
onClick={openSearch}
>
<Icon name="search" />
</button>
<span className="readout dim hidden text-xs lg:inline" data-testid="version">
{version}
</span>
</div>
</header>
<nav
className="fixed inset-x-0 bottom-0 z-20 grid grid-cols-4 h-(--tabbar-space) pb-(--safe-bottom) bg-panel border-t border-t-line sm:hidden"
aria-label="destinations"
>
<NavLink destination="library" current={destination} className={TAB} href="/" onGo={go}>
<TabGlyph name="library" />
<span>library</span>
</NavLink>
<NavLink
destination="search"
current={destination}
className={TAB}
href="/search"
onGo={go}
>
<TabGlyph name="search" />
<span>search</span>
</NavLink>
<NavLink
destination="queues"
current={destination}
className={TAB}
href="/queues"
onGo={go}
>
<TabGlyph name="warning" />
<span>queues</span>
<span
className="readout absolute top-1 left-11/20 min-w-badge h-badge py-0 px-1 rounded-pill text-2xs font-bold leading-(--spacing-badge) text-center text-ground bg-signal-warn"
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>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>
);
}