"use client"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import CitedClip from "@/components/clips/CitedClip"; import { Button } from "@/components/ui/button"; import { clock } from "@/components/ui/clock"; import { Field, Input, Select } from "@/components/ui/field"; import { JobProgressBar } from "@/components/ui/job-progress"; import { Panel } from "@/components/ui/panel"; import { phraseFinderHref } from "@/lib/hrefs"; import { montageSlug } from "@/lib/phrase-finder/summary.mjs"; import type { PhraseFinderState, PhraseMode, PhraseSample, PhraseScanRowView, PhraseScanView, TranscriptAround } from "@/lib/phrase-finder/types"; import { phraseSourceOf } from "yt-dlp-transcript-common/lib/montage/phraseSource.mjs"; // --------------------------------------------------------------------------- // THE PHRASE FINDER (release 34), the page's one island. // // phrases one row each: the words (plain words, or a regular expression // -- `auto` tells them apart by its characters), what is searched // under it; Add phrase / ×; a suggestion (a catchphrase report's // candidates) adds a row // channels the ones to scan, filtered by typing; prefer (the copy to cut // from where a stream has one) and exclude (a context that // matches is left out) -- the phrase seed's own four settings // Search one job for every row (POST /api/phrase-finder), its progress // polled; Stop ends it // results per phrase: the instances once folded, by year, Rumble or // another, speaker changes; ten contexts, each with Play (the // clip window or saved video on disk, else Fetch clip) and // Transcript (the cues around it, read in place); Create montage // (the slug prefilled) seeds a project from THIS search // // The data attributes are the e2e spec's handles (phrase-finder.spec.ts). // --------------------------------------------------------------------------- type Row = { key: number; text: string; mode: PhraseMode; label?: string }; const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function niceDate(s: string | null): string { const m = /^(\d{4})(\d{2})(\d{2})/.exec(String(s ?? "")); return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1] ?? "?"} ${m[1]}` : (s ?? "no date"); } const n0 = (n: number) => n.toLocaleString("en-GB"); const scanStamp = (id: string) => { const m = /^ps-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(id); return m ? `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[4]}:${m[5]}` : id; }; /** What a row is searched as, or why it cannot be. */ function sourceOf(r: Row): { source: string; mode: string } | { error: string } | null { if (!r.text.trim()) return null; try { return phraseSourceOf(r.text, r.mode); } catch (e) { return { error: e instanceof Error ? e.message : String(e) }; } } export default function PhraseFinder({ state, initialScan, prefill }: { state: PhraseFinderState; initialScan: PhraseScanView | null; prefill: string }) { const seq = useRef(0); const mk = (r: Omit): Row => ({ ...r, key: ++seq.current }); const [rows, setRows] = useState(() => { if (prefill.trim()) return [mk({ text: prefill.trim(), mode: "auto" })]; if (initialScan) return initialScan.spec.rows.map((r) => mk({ text: r.text, mode: r.mode, label: r.label })); if (state.last?.rows.length) return state.last.rows.map((r) => mk({ text: r.text, mode: r.mode, label: r.label })); return [mk({ text: "", mode: "auto" })]; }); const from = initialScan?.spec ?? state.last; const [chosen, setChosen] = useState>(() => new Set(from?.channels ?? [])); const [prefer, setPrefer] = useState(from?.prefer ?? ""); const [exclude, setExclude] = useState(from?.exclude ?? ""); const [filter, setFilter] = useState(""); const [scan, setScan] = useState(initialScan); const [error, setError] = useState(null); const [starting, setStarting] = useState(false); const running = scan?.state === "running"; const names = useMemo(() => new Map(state.channels.map((c) => [c.slug, c.name])), [state.channels]); // Poll the running search. useEffect(() => { if (!scan || scan.state !== "running") return; let gone = false; const t = setTimeout(async () => { try { const r = await fetch(`/api/phrase-finder/${encodeURIComponent(scan.id)}`, { cache: "no-store" }); const j = await r.json(); if (!gone && r.ok) setScan(j as PhraseScanView); } catch { /* the next poll */ } }, 800); return () => { gone = true; clearTimeout(t); }; }, [scan]); const setRow = (key: number, patch: Partial) => setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch, ...(patch.text !== undefined ? { label: undefined } : {}) } : r))); const addRow = (r: Omit = { text: "", mode: "auto" }) => setRows((rs) => (rs.length === 1 && !rs[0].text.trim() ? [mk(r)] : [...rs, mk(r)])); const removeRow = (key: number) => setRows((rs) => (rs.length > 1 ? rs.filter((r) => r.key !== key) : [mk({ text: "", mode: "auto" })])); const toggle = (slug: string) => setChosen((s) => { const n = new Set(s); if (n.has(slug)) n.delete(slug); else n.add(slug); return n; }); const filled = rows.filter((r) => r.text.trim()); const bad = filled.map(sourceOf).find((s) => s && "error" in s) as { error: string } | undefined; const canSearch = !running && !starting && filled.length > 0 && !bad && (chosen.size > 0 || !!prefer); const search = async () => { if (!canSearch) return; setStarting(true); setError(null); try { const body = { rows: filled.map((r, k) => ({ id: `p${k + 1}`, text: r.text.trim(), mode: r.mode, ...(r.label ? { label: r.label } : {}) })), channels: [...chosen], prefer: prefer || null, exclude: exclude.trim() || null, }; const r = await fetch("/api/phrase-finder", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), cache: "no-store" }); const j = await r.json(); if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); const v = await fetch(`/api/phrase-finder/${encodeURIComponent(j.id)}`, { cache: "no-store" }).then((x) => x.json()); setScan(v as PhraseScanView); window.history.replaceState(null, "", phraseFinderHref({ scan: j.id })); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setStarting(false); } }; const stop = async () => { if (!scan) return; await fetch(`/api/phrase-finder/${encodeURIComponent(scan.id)}`, { method: "DELETE", cache: "no-store" }).catch(() => {}); setScan({ ...scan, state: "cancelled" }); }; const shown = state.channels.filter((c) => { const f = filter.trim().toLowerCase(); return !f || c.slug.toLowerCase().includes(f) || c.name.toLowerCase().includes(f); }); return (
{ e.preventDefault(); void search(); }} > {filled.length} to search}>
    {rows.map((r, k) => { const s = sourceOf(r); return (
  • setRow(r.key, { text: e.target.value })} placeholder={k === 0 ? "slow news day" : "another phrase"} aria-label={`phrase ${k + 1}`} className="min-w-0 flex-1 basis-64" data-phrase-text="" />
    {s && ( {"error" in s ? s.error : `${r.label ? `${r.label} · ` : ""}${s.mode === "words" ? "as words" : "as written"}: /${s.source}/`} )}
  • ); })}
{state.suggestions.length > 0 && (
Suggestions ({state.suggestions.length})
{state.suggestions.map((s) => ( ))}
)}
{chosen.size} picked}> {chosen.size > 0 && (
{[...chosen].map((slug) => ( ))}
)} setFilter(e.target.value)} placeholder="filter channels" aria-label="filter channels" className="mb-2 w-64" data-phrase-channel-filter="" />
{shown.map((c) => ( ))} {!shown.length && No channel matches.}
setExclude(e.target.value)} placeholder="optional" aria-label="exclude" className="w-64" data-phrase-exclude="" /> {state.recent.length > 0 && ( Recent:{" "} {state.recent.slice(0, 5).map((id, k) => ( {k ? ", " : ""} {scanStamp(id)} ))} )}
{(error || bad) && (

{error ?? bad?.error}

)}
{scan && }
); } function ScanResults({ scan, names, onStop, montageKind }: { scan: PhraseScanView; names: Map; onStop: () => void; montageKind: string }) { const p = scan.progress; if (scan.state === "running") { const meter = p && p.total ? { fraction: p.done / p.total, text: `${p.done}/${p.total}` } : null; return (
{p ? `${n0(p.done)} of ${n0(p.total)} transcripts · ${names.get(p.channel) ?? p.channel}` : "starting…"}
); } if (scan.state !== "done" || !scan.rows) { return (

{scan.state === "cancelled" ? "Stopped." : (scan.error ?? "The search failed.")}

); } const rows = scan.rows; return (

{n0(scan.scanned ?? 0)} transcripts read in {scan.seconds ?? "?"} s · {scan.spec.channels.map((c) => names.get(c) ?? c).join(", ")} {scan.spec.prefer ? ` · cut from ${names.get(scan.spec.prefer) ?? scan.spec.prefer} where it has the stream` : ""}

{rows.length > 1 && } {rows.map((r) => ( ))}
); } function Compare({ rows }: { rows: PhraseScanRowView[] }) { const sorted = [...rows].sort((a, b) => b.summary.instances - a.summary.instances); return ( {sorted.map((r) => ( ))}
phrase times by year Rumble / other speaker changes
{r.label ?? r.text} {r.summary.instances} `${y}: ${n}`).join(", ")}> {r.summary.spark} {r.summary.rumble} / {r.summary.notRumble} {r.summary.speakerChecks}
); } function YearBars({ years }: { years: Record }) { const entries = Object.entries(years); const max = Math.max(1, ...entries.map(([, n]) => n)); if (!entries.length) return null; return (
{entries.map(([y, n]) => (
{n || ""} '{y.slice(2)}
))}
); } function PhraseResult({ scan, row, names, montageKind }: { scan: PhraseScanView; row: PhraseScanRowView; names: Map; montageKind: string }) { const s = row.summary; const span = s.first ? `${String(s.first).slice(0, 4)}–${String(s.last).slice(0, 4)}` : ""; return ( /{row.source}/} data-phrase-result={row.id} >
{s.instances}
{s.instances === 1 ? "time" : "times"} {span ? `, ${span}` : ""}
Rumble
{s.rumble}
other
{s.notRumble}
speaker changes
{s.speakerChecks}
{s.placed > 0 && ( <>
placed by words
{s.placed}
)} {s.dropped > 0 && ( <>
excluded
{s.dropped}
)}
raw hits
{s.hits}
{Object.keys(s.bySlug).length > 1 && (

{Object.entries(s.bySlug) .sort((a, b) => b[1] - a[1]) .map(([slug, n]) => `${names.get(slug) ?? slug} ${n}`) .join(" · ")}

)} {s.samples.length > 0 && (
    {s.samples.map((x) => ( ))}
)}
); } function Lit({ context, match }: { context: string; match: string }) { const at = context.toLowerCase().indexOf(match.toLowerCase()); if (!match || at < 0) return <>{context}; return ( <> {context.slice(0, at)} {context.slice(at, at + match.length)} {context.slice(at + match.length)} ); } function Sample({ s, names }: { s: PhraseSample; names: Map }) { const [open, setOpen] = useState<"play" | "text" | null>(null); const [ctx, setCtx] = useState(null); const readTranscript = useCallback(async () => { if (open === "text") return setOpen(null); setOpen("text"); if (ctx && !("error" in ctx)) return; try { const q = new URLSearchParams({ channel: s.slug, video: s.videoId, at: String(s.start) }); const r = await fetch(`/api/phrase-finder/context?${q}`, { cache: "no-store" }); const j = await r.json(); setCtx(r.ok ? (j as TranscriptAround) : { error: j.error ?? `HTTP ${r.status}` }); } catch (e) { setCtx({ error: e instanceof Error ? e.message : String(e) }); } }, [open, ctx, s.slug, s.videoId, s.start]); return (
  • {niceDate(s.date)} {names.get(s.slug) ?? s.slug} {s.videoId} @ {clock(s.start)} {s.speakerCheck && speaker change} {s.via && placed from {names.get(s.via.slug) ?? s.via.slug}}
    {s.title &&
    {s.title}
    }

    {open === "play" && (
    )} {open === "text" && (
    {!ctx ? ( reading… ) : "error" in ctx ? ( {ctx.error} ) : (
      {ctx.cues.map((c) => (
    1. {clock(c.start)} {c.text}
    2. ))}
    )}
    )}
  • ); } function CreateMontage({ scan, row, montageKind }: { scan: PhraseScanView; row: PhraseScanRowView; montageKind: string }) { const router = useRouter(); const [slug, setSlug] = useState(() => montageSlug(row.label ?? row.text)); // The cap (release 35): N instances spread across the years; empty = all. const [max, setMax] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const empty = row.summary.instances === 0; const create = async () => { setBusy(true); setError(null); try { const r = await fetch("/api/projects/new", { method: "POST", headers: { "content-type": "application/json" }, cache: "no-store", body: JSON.stringify({ kind: montageKind, slug: slug.trim(), title: row.label ?? row.text, seed: "phrase", phrase: row.source, channels: scan.spec.channels, prefer: scan.spec.prefer, exclude: scan.spec.exclude, scan: { id: scan.id, row: row.id }, ...(max.trim() ? { max: Number(max.trim()) } : {}), }), }); const j = await r.json(); if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); router.push(j.href); } catch (e) { setError(e instanceof Error ? e.message : String(e)); setBusy(false); } }; return (
    { e.preventDefault(); void create(); }} > setSlug(e.target.value)} aria-label="montage project slug" className="w-72" data-phrase-slug="" /> setMax(e.target.value)} inputMode="numeric" placeholder="all" aria-label="max clips — at most this many, spread across the years in proportion" title="at most this many, spread across the years in proportion (empty: all)" className="w-20" data-phrase-max="" /> {error && ( {error} )}
    ); }