// 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; 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(null); const [downloads, setDownloads] = useState([]); 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 ( { event.preventDefault(); onGo(destination); }} > {children} ); } /** 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 ( ); } export function App() { const live = usePoll(); const route = useRoute(); const destination = destinationOf(route); const [layers, setLayers] = useState(() => ({ 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(null); const wordmark = useRef(null); const debounce = useRef(undefined); const routeTicket = useRef(0); // where back and Esc land, and which control gets focus back const overlayParent = useRef(LIBRARY); const overlayOrigin = useRef(null); const tvOrigin = useRef(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