"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { useHydrated } from "@/components/ui/use-hydrated"; import { projectHref } from "@/lib/hrefs"; import type { HandBaseView, RespellView } from "@/lib/articles/hand-types"; // --------------------------------------------------------------------------- // BY HAND (release 32 R2): what a model does to an article, done by a person, // with no model -- on the Iterations tab, above the iterations. // // Fix a mishearing (`?tab=iterations&heard=` opens it, filled) // `archilyzer reports respell`: the heard forms, what was // said, bracketed or not, a note -> Preview (every change // per file, as word hunks) -> Apply (each file backed up // first) -> the backups, and the video's Build tab when its // manifest changed. The respellings the report has are // listed with their heard forms. // Add a claim a claim in a section (or a new one), its citations picked // from the report's or added from a moment -- an archive // link, a citation, /@ -- whose cues are // shown to pick the quote from; every new quote is checked // against the record before it is saved (the server's). // A fact-check's claim may carry your verdict. // // Both work on ONE iteration (the select): the article's by default. A claim is // written as a new `hand` iteration, or into a hand draft nobody uses yet; // nothing here makes an iteration the article's ("Use this iteration" does). // After a write the Iterations list re-reads (ITERATIONS_CHANGED). // --------------------------------------------------------------------------- export const ITERATIONS_CHANGED = "umtool:iterations-changed"; export type HandBase = { n: number; label: string; kind: string; current: boolean }; const VERDICT_WORDS: Record = { CORROBORATED: "corroborated", PARTLY: "partly", CONTRADICTED: "contradicted", NOT_FOUND: "not found", UNTESTABLE: "untestable", }; const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; async function call(url: string, init?: RequestInit): Promise { const r = await fetch(url, { cache: "no-store", ...init, ...(init?.body ? { headers: { "content-type": "application/json" } } : {}) }); const b = (await r.json().catch(() => ({}))) as T & { error?: string; problems?: string[] }; if (!r.ok) { const e = new Error(b.error ?? `HTTP ${r.status}`) as Error & { problems?: string[] }; e.problems = b.problems ?? []; throw e; } return b; } function Problems({ error }: { error: { message: string; problems: string[] } | null }) { if (!error) return null; return (

{error.message}

{error.problems.length > 0 && (
    {error.problems.map((p, i) => (
  • {p}
  • ))}
)}
); } const errorOf = (e: unknown) => ({ message: (e as Error).message, problems: (e as { problems?: string[] }).problems ?? [] }); /** «before» → «after» with the changed words marked. */ function Hunk({ text }: { text: string }) { const parts = text.split(/(«[^»]*»)/g); return ( {parts.map((p, i) => p.startsWith("«") ? ( {p.slice(1, -1) || "∅"} ) : ( {p} ), )} ); } // ─── Fix a mishearing ─── function RespellForm({ article, n, view, onDone, initialHeard = "" }: { article: string; n: number | null; view: HandBaseView | null; onDone: () => void; initialHeard?: string }) { const hydrated = useHydrated(); const [heard, setHeard] = useState(initialHeard); const [reads, setReads] = useState(""); const [bracket, setBracket] = useState(false); const [note, setNote] = useState(""); const [plan, setPlan] = useState(null); const [applied, setApplied] = useState(null); const [busy, setBusy] = useState<"preview" | "apply" | null>(null); const [error, setError] = useState<{ message: string; problems: string[] } | null>(null); const asked = JSON.stringify({ heard, reads, bracket, note, n }); const [planned, setPlanned] = useState(""); const run = async (apply: boolean) => { setBusy(apply ? "apply" : "preview"); setError(null); try { const out = await call("/api/articles/respell", { method: "POST", body: JSON.stringify({ article, heard, reads, bracket, note, ...(n !== null ? { iteration: n } : {}), apply }), }); if (apply) { setApplied(out); setPlan(null); onDone(); } else { setPlan(out); setApplied(null); setPlanned(asked); } } catch (e) { setError(errorOf(e)); } finally { setBusy(null); } }; const videoChanged = (v: RespellView) => v.targets.some((t) => t.kind === "video-manifest" && t.changes.length > 0); const shownPlan = plan ?? applied; return (
{view && view.respellings.length > 0 && (
    {view.respellings.map((r, i) => (
  • {r.heard.map((h) => `“${h}”`).join(", ")} → {r.reads} {r.bracket ? (bracketed) : null} {r.note ? · {r.note} : null}
  • ))}
)}
{ e.preventDefault(); void run(false); }} > setHeard(e.target.value)} placeholder="cake cup, cakeup" className="w-56" /> setReads(e.target.value)} placeholder="K-Cup" className="w-40" /> setNote(e.target.value)} placeholder="optional" className="w-48" />
{shownPlan && (

{applied ? "Applied: " : ""} {shownPlan.total} change{shownPlan.total === 1 ? "" : "s"} in {shownPlan.targets.filter((t) => t.changes.length).length} file {shownPlan.targets.filter((t) => t.changes.length).length === 1 ? "" : "s"} {shownPlan.iteration !== null ? ` (i${shownPlan.iteration})` : ""}

{shownPlan.targets.map((t) => (
{t.kind} · {t.file} · {t.changes.length ? `${t.changes.length} change${t.changes.length === 1 ? "" : "s"}` : "gains the respellings only"}
{t.changes.map((c, i) => (
{c.at}
{c.hunks.map((h, j) => (
))}
))}
))} {shownPlan.notes.map((x, i) => (

note: {x}

))} {plan && (
{planned !== asked && the fields changed since the preview: preview again}
)} {applied && ( <> {applied.backups && applied.backups.length > 0 && (
backups (copy one back to undo):
    {applied.backups.map((b) => (
  • {b}
  • ))}
)} {videoChanged(applied) && applied.projectId && ( Rebuild the video → )} )}
)}
); } // ─── Add a claim ─── type Cue = { start: number; end: number; text: string }; type MomentView = { channel: string; id: string; kind: "span" | "post"; at: number; quote: string | null; title: string | null; cues: Cue[]; found: boolean }; type Pending = { kind: "video" | "audio" | "post"; channel: string; id: string; start: number; end: number; quote: string }; function CitationAdder({ onAdd }: { onAdd: (c: Pending) => void }) { const hydrated = useHydrated(); const [moment, setMoment] = useState(""); const [found, setFound] = useState(null); const [pick, setPick] = useState<[number, number] | null>(null); const [kind, setKind] = useState("video"); const [channel, setChannel] = useState(""); const [id, setId] = useState(""); const [start, setStart] = useState(""); const [end, setEnd] = useState(""); const [quote, setQuote] = useState(""); const [error, setError] = useState<{ message: string; problems: string[] } | null>(null); const find = async () => { setError(null); try { const m = await call(`/api/articles/by-hand?moment=${encodeURIComponent(moment)}`); setFound(m); setPick(null); setChannel(m.channel); setId(m.id); setKind(m.kind === "post" ? "post" : "video"); if (m.quote) setQuote(m.quote); if (m.kind === "span") { setStart(String(m.at)); setEnd(""); } } catch (e) { setError(errorOf(e)); } }; // A click picks a cue; a second click on another extends the pick to it. const choose = (i: number) => { if (!found) return; const next: [number, number] = pick && pick[0] === pick[1] && i !== pick[0] ? [Math.min(pick[0], i), Math.max(pick[0], i)] : [i, i]; setPick(next); const cs = found.cues.slice(next[0], next[1] + 1); setQuote(cs.map((c) => c.text.trim()).join(" ")); setStart(String(cs[0]!.start)); setEnd(String(cs[cs.length - 1]!.end)); }; const add = () => { setError(null); const s = Number(start); const e = Number(end); if (!channel.trim() || !id.trim() || !quote.trim()) return setError({ message: "a citation needs its channel, its id and the quote", problems: [] }); if (kind !== "post" && !(Number.isFinite(s) && Number.isFinite(e) && e > s)) return setError({ message: "a span needs a start and a later end, in seconds", problems: [] }); onAdd({ kind, channel: channel.trim(), id: id.trim(), start: s, end: e, quote: quote.trim() }); setFound(null); setPick(null); setMoment(""); setQuote(""); setStart(""); setEnd(""); }; return (
setMoment(e.target.value)} placeholder="https://…/?v=channel/id&t=123" className="font-mono" />
{found && (
{found.found ? (found.title ?? `${found.channel}/${found.id}`) : `${found.channel}/${found.id}: no record in this archive`} {found.cues.length ? " · click a line, then another to take the lines between" : ""}
{found.cues.length > 0 && (
    {found.cues.map((c, i) => { const on = !!pick && i >= pick[0] && i <= pick[1]; return (
  1. ); })}
)}
)}
setChannel(e.target.value)} className="w-36 font-mono" /> setId(e.target.value)} className="w-32 font-mono" /> {kind !== "post" && ( <> setStart(e.target.value)} className="num w-20" /> setEnd(e.target.value)} className="num w-20" /> )}