"use client"; import { useEffect, useRef, useState } from "react"; import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability"; import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { Table, TD, TH } from "@/components/ui/table"; import { useHydrated } from "@/components/ui/use-hydrated"; import { researchCoverageApi } from "@/lib/research/hrefs"; import { cn } from "@/lib/utils"; import type { CoverageResponse, CoverageRow } from "@/lib/research/types"; // --------------------------------------------------------------------------- // THE ARCHIVE INVENTORY (canvas `#view-archive`): channels × years, a number in // every cell, the Meter ramp (--m1..--m5, each with its own ink so the number // reads on it), a gap over 60 days marked under the cell in the doubt line, "—" // where nothing is held. Hover or focus a cell for what it holds; the arrow keys // walk the grid; Table shows the same numbers as rows. // // Two measures: HELD (what the editor has on disk, channel_coverage) and // PUBLISHED (what this source's summaries list, by upload year). The ramp is // sequential and fixed (the canvas's bins), so two archives read alike. // --------------------------------------------------------------------------- type Measure = "held" | "published"; const BINS = [50, 200, 600, 1200]; const binOf = (n: number) => (!n ? 0 : 1 + BINS.filter((b) => n >= b).length); const RAMP = [ "bg-transparent text-muted-2 shadow-[inset_0_0_0_1px_var(--seam)]", "bg-m1 text-[var(--m1-ink)]", "bg-m2 text-[var(--m2-ink)]", "bg-m3 text-[var(--m3-ink)]", "bg-m4 text-[var(--m4-ink)]", "bg-m5 text-[var(--m5-ink)]", ]; const nf = new Intl.NumberFormat("en-US"); function countOf(r: CoverageRow, m: Measure, y: string): number { return (m === "held" ? r.held?.byYear[y] : r.published.byYear[y]) ?? 0; } function tipOf(r: CoverageRow, m: Measure, y: string): string { const n = countOf(r, m, y); const parts = [`${r.name} · ${y}`, n ? `${nf.format(n)} ${m === "held" ? "held" : "published"}` : m === "held" ? "nothing held" : "nothing published"]; if (m === "held" && r.published.byYear[y]) parts.push(`${nf.format(r.published.byYear[y])} published`); if (m === "published" && r.held?.byYear[y]) parts.push(`${nf.format(r.held.byYear[y])} held`); const t = r.tracks?.[y]; if (t && t.transcript + t.captions + t.unknown > 0) parts.push(`transcripts ${t.transcript} · captions ${t.captions}${t.unknown ? ` · unknown ${t.unknown}` : ""}`); const missing = r.published.missingByYear[y]; if (missing) parts.push(Object.entries(missing).map(([s, k]) => `${k} ${(VIDEO_STATE_LABELS[s as VideoState] ?? s).toLowerCase()}`).join(", ")); if (r.held?.gapYears.includes(y)) parts.push("gap over 60 days"); return parts.join(" · "); } /** "just now", "3 min ago", "1 h ago". */ export function ago(ms: number): string { const s = Math.max(0, Math.round(ms / 1000)); if (s < 45) return "just now"; const m = Math.round(s / 60); return m < 60 ? `${m} min ago` : `${Math.round(m / 60)} h ago`; } export default function ArchiveInventory({ data: initial, source }: { data: CoverageResponse; source: string }) { const hydrated = useHydrated(); const [data, setData] = useState(initial); const [refreshing, setRefreshing] = useState(false); const [refreshError, setRefreshError] = useState(null); // The age line re-reads the clock; the counts themselves change only on Refresh. const [now, setNow] = useState(() => Date.now()); useEffect(() => { const id = setInterval(() => setNow(Date.now()), 30_000); return () => clearInterval(id); }, []); const refresh = async () => { setRefreshing(true); setRefreshError(null); try { const r = await fetch(researchCoverageApi({ source }, { fresh: true }), { cache: "no-store" }); const body = await r.json().catch(() => null); if (!r.ok) throw new Error(body?.error ?? `HTTP ${r.status}`); setData(body as CoverageResponse); setNow(Date.now()); } catch (e) { setRefreshError((e as Error).message); } finally { setRefreshing(false); } }; const [measure, setMeasure] = useState(data.held.via === "none" ? "published" : "held"); const [table, setTable] = useState(false); const [tip, setTip] = useState<{ text: string; x: number; y: number } | null>(null); const [focus, setFocus] = useState<[number, number]>([0, 0]); const host = useRef(null); const grid = useRef(null); const { years, rows } = data; const showTip = (el: HTMLElement) => { const h = host.current?.getBoundingClientRect(); const r = el.getBoundingClientRect(); if (!h) return; setTip({ text: el.dataset.tip ?? "", x: r.left - h.left + (host.current?.scrollLeft ?? 0), y: r.bottom - h.top + (host.current?.scrollTop ?? 0) + 6 }); }; const move = (e: React.KeyboardEvent, ri: number, ci: number) => { const d: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }; const k = d[e.key] ?? (e.key === "Home" ? [0, -ci] : e.key === "End" ? [0, years.length - 1 - ci] : null); if (!k) return; e.preventDefault(); const nr = Math.max(0, Math.min(rows.length - 1, ri + k[0])); const nc = Math.max(0, Math.min(years.length - 1, ci + k[1])); setFocus([nr, nc]); grid.current?.querySelector(`td[data-cell="${nr}:${nc}"]`)?.focus(); }; const total = (r: CoverageRow) => (measure === "held" ? r.held?.total : r.published.total); return ( <>
{(["held", "published"] as const).map((m) => ( ))} 1 {RAMP.slice(1).map((c, i) => ( ))} 1,200+ {measure === "held" && ( gap over {data.gapDays} days that year )} — nothing {measure === "held" ? "held" : "published"}

Held counts from {ago(now - data.held.at)} {data.held.cached ? " (kept 5 min)" : ""} {data.held.note ? ( · {data.held.note} ) : null} {refreshError && ( {refreshError} )}

{rows.length === 0 ? (

This source lists no channels.

) : table ? ( {rows.flatMap((r) => years .filter((y) => r.held?.byYear[y] || r.published.byYear[y]) .map((y) => ( )), )}
Channel Year Held Published Transcripts Captions Gap
{r.name} {y} {r.held ? nf.format(r.held.byYear[y] ?? 0) : "—"} {nf.format(r.published.byYear[y] ?? 0)} {r.tracks?.[y] ? r.tracks[y].transcript : "—"} {r.tracks?.[y] ? r.tracks[y].captions : "—"} {r.held?.gapYears.includes(y) ? "over 60 days" : ""}
) : (
setTip(null)}> ))} {rows.map((r, ri) => ( {years.map((y, ci) => { const n = countOf(r, measure, y); const gap = measure === "held" && r.held?.gapYears.includes(y); const t = tipOf(r, measure, y); return ( ); })} ))}
{years.map((y) => ( {y.slice(2)} {measure}
{r.name} {r.localOnly && local only} showTip(e.currentTarget)} onFocus={(e) => { setFocus([ri, ci]); showTip(e.currentTarget); }} onBlur={() => setTip(null)} onKeyDown={(e) => move(e, ri, ci)} className={cn( "h-[34px] w-[58px] rounded-[2px] text-center font-mono text-[11px] tabular-nums outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-signal", RAMP[binOf(n)], gap && (n ? "shadow-[inset_0_-2px_0_var(--doubt)]" : "shadow-[inset_0_0_0_1px_var(--seam),inset_0_-2px_0_var(--doubt)]"), )} > {n ? nf.format(n) : "—"} {total(r) != null ? nf.format(total(r)!) : "—"}
{tip && (
{tip.text}
)}
)} ); }