Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 47e130690f28bfbe250843e3d18bbed454f4724e
parent 1cf84ae3cc8434ae443b31bf5f53d815f030051b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 16:46:47 -0400

umtool: the drafts review is an audition deck — one card per field, the cited span playing (video first, the lit line following it), keep/cut/edit/skip as a swipe, a key or a button, undo, a summary; the list one toggle away (?view=list) with the player in its reader; the drafts route's edit action (lib/report/draftEdit.mjs); Verify quotes and Check report on the article page (lib/articles/checks.ts, /api/articles/checks)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/articles/checks/route.ts | 31+++++++++++++++++++++++++++++++
Mumtool/app/api/report/drafts/route.ts | 20+++++++++++++++++++-
Aumtool/components/articles/ArticleChecks.tsx | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/ArticlePage.tsx | 2++
Mumtool/components/projects/MediaDrafts.tsx | 26+++++++++++++++++++++++++-
Mumtool/components/projects/ProjectView.tsx | 2+-
Mumtool/components/projects/ReviewPage.tsx | 47++++++++++++++++++++++++++++++++++++++++-------
Aumtool/components/projects/review/AuditionDeck.tsx | 766+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/articles/checks.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 4++--
Aumtool/lib/report/draftEdit.mjs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/draftEdit.test.mjs | 30++++++++++++++++++++++++++++++
12 files changed, 1219 insertions(+), 12 deletions(-)

diff --git a/umtool/app/api/articles/checks/route.ts b/umtool/app/api/articles/checks/route.ts @@ -0,0 +1,31 @@ +import { articleQuoteChecks, articleReportCheck } from "@/lib/articles/checks"; +import { isReportHost } from "@/lib/articles/sites"; + +export const dynamic = "force-dynamic"; + +// POST { site, report, what: "quotes" | "check", allowMissingMedia? } +// quotes -> every video, audio and post quote against its record (the CLI's +// `reports verify-quotes --article`): status, score, track, the +// en-orig score, and what plays it +// check -> compose's own findings with nothing written (`reports check +// --article`, a site's `--reports <id>`): pass, or every problem +// lib/articles/checks.ts; read-only, no model. +export async function POST(request: Request) { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + const site = String(b?.site ?? ""); + const report = String(b?.report ?? ""); + if (!isReportHost(site)) return Response.json({ error: `no site ${site}` }, { status: 404 }); + if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(report)) return Response.json({ error: "report must be a report id" }, { status: 400 }); + try { + const body = + b?.what === "check" + ? await articleReportCheck(site, report, { allowMissingMedia: b?.allowMissingMedia === true }) + : b?.what === "quotes" + ? await articleQuoteChecks(site, report) + : null; + if (!body) return Response.json({ error: "what must be quotes or check" }, { status: 400 }); + return Response.json(body, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: (e as { status?: number })?.status ?? 500 }); + } +} diff --git a/umtool/app/api/report/drafts/route.ts b/umtool/app/api/report/drafts/route.ts @@ -2,6 +2,8 @@ import { invalidateProjects } from "@/lib/projects"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, writeDraftedField } from "@/lib/report/manifest.mjs"; import { alternativeById, draftsView } from "@/lib/report/drafts.mjs"; +import { currentFieldValue, valueFromEdit } from "@/lib/report/draftEdit.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { draftsReviewRows, readDraftsReview, setDraftReview } from "umtool-report-to-video/drafts-review"; @@ -19,6 +21,11 @@ export const dynamic = "force-dynamic"; // use { alternative, token? } "Use this": the alternative (`<file>#<i>`) written // through the manifest writer as the operator's edit // (snapshot, validators, the edit-notes guard) +// edit { address, text, note?, token? } the audition deck's EDIT (release 32 R1): the +// field rewritten as text (lib/report/draftEdit.mjs), +// written the same way as `use` -- the operator's +// now -- and approved on its new words when the +// field still has a review row // // Verdicts live in <project>/drafts.review.json (report-to-video's // drafts-review.mjs); a final build refuses a drafted field not approved. @@ -58,6 +65,17 @@ export async function POST(request: Request) { const row = draftsReviewRows(r.manifest, await readDraftsReview(dir)).find((x: { address: string }) => x.address === address); if (!row) return Response.json({ error: `${address || "(no address)"} is not a field this cut has to review` }, { status: 404 }); switch (body.action) { + case "edit": { + const value = valueFromEdit(row.field, currentFieldValue(r.manifest, row), String(body.text ?? "")); + const token = typeof body.token === "string" ? body.token : null; + const w = await withEditNotes(r.project, () => writeDraftedField(dir, { entry: row.entry, field: row.field, value }, { token })); + editNotes = w.editNotes; + invalidateProjects(); + // A field the edit leaves under review (a narration) is approved on its new words. + const after = draftsReviewRows((await readManifest(dir)) ?? r.manifest, await readDraftsReview(dir)).find((x: { address: string }) => x.address === address); + if (after) await setDraftReview(dir, address, { verdict: "approved", key: after.key, text: after.text, ...(note !== undefined ? { note } : {}) }); + break; + } case "approve": await setDraftReview(dir, address, { verdict: "approved", key: row.key, text: row.text, ...(note !== undefined ? { note } : {}) }); break; @@ -71,7 +89,7 @@ export async function POST(request: Request) { await setDraftReview(dir, address, { note: note ?? "" }); break; default: - return Response.json({ error: "action must be approve, reject, clear, note or use" }, { status: 400 }); + return Response.json({ error: "action must be approve, reject, clear, note, edit or use" }, { status: 400 }); } } } catch (e) { diff --git a/umtool/components/articles/ArticleChecks.tsx b/umtool/components/articles/ArticleChecks.tsx @@ -0,0 +1,136 @@ +"use client"; + +import { useState } from "react"; +import CitedClip from "@/components/clips/CitedClip"; +import { buttonVariants } from "@/components/ui/button"; +import type { QuoteChecks, ReportCheck } from "@/lib/articles/checks"; +import type { CitedTarget } from "@/lib/clips/types"; +import { cn } from "@/lib/utils"; + +// VERIFY QUOTES and CHECK REPORT (release 32 R1): the CLI's `reports +// verify-quotes --article` and `reports check --article`, as two buttons on +// the article page (lib/articles/checks.ts runs the same functions). Every +// quote's status, score and track, every problem in its own sentence -- and a +// Play beside each, so the person rules by ear. No model. + +const WARN = new Set(["inexact", "fragment"]); +const tone = (status: string) => + status === "ok" || status === "pass" ? "text-meter" : WARN.has(status) ? "text-doubt-text" : "text-reject-text"; + +function Play({ target, why }: { target: CitedTarget; why: string }) { + const [open, setOpen] = useState(false); + return open ? ( + <CitedClip target={target} reason={why} autoPlay className="mt-1 max-w-[520px]" /> + ) : ( + <button type="button" data-check-play="" onClick={() => setOpen(true)} className={buttonVariants({ variant: "outline", size: "sm" })}> + Play + </button> + ); +} + +export default function ArticleChecks({ site, report }: { site: string; report: string }) { + const [busy, setBusy] = useState<null | "quotes" | "check">(null); + const [result, setResult] = useState<QuoteChecks | ReportCheck | null>(null); + const [error, setError] = useState<string | null>(null); + const [allowMissing, setAllowMissing] = useState(false); + + const run = async (what: "quotes" | "check") => { + setBusy(what); + setError(null); + try { + const r = await fetch("/api/articles/checks", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ site, report, what, allowMissingMedia: allowMissing }), + cache: "no-store", + }); + const j = await r.json(); + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + setResult(j); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(null); + } + }; + + return ( + <div data-article-checks="" className="flex w-full flex-wrap items-center gap-2"> + <button type="button" data-check="quotes" disabled={!!busy} onClick={() => void run("quotes")} className={buttonVariants({ variant: "outline", size: "sm" })}> + {busy === "quotes" ? "Verifying…" : "Verify quotes"} + </button> + <button type="button" data-check="check" disabled={!!busy} onClick={() => void run("check")} className={buttonVariants({ variant: "outline", size: "sm" })}> + {busy === "check" ? "Checking…" : "Check report"} + </button> + <label className="flex items-center gap-1 text-[11.5px] text-muted" title="let a citation without prepared media through, as --allow-missing-media does"> + <input type="checkbox" checked={allowMissing} onChange={(e) => setAllowMissing(e.target.checked)} /> + allow missing media + </label> + {result && ( + <button type="button" onClick={() => setResult(null)} className={buttonVariants({ variant: "ghost", size: "sm" })}> + Close + </button> + )} + {error && ( + <span role="alert" className="basis-full text-[12px] text-reject-text"> + {error} + </span> + )} + {result?.what === "quotes" && ( + <section data-quote-checks={result.rows.length} className="basis-full space-y-1.5 rounded-[3px] border border-seam bg-panel px-3 py-2.5"> + <div className="micro" data-quote-counts=""> + {result.rows.length} quote(s): {Object.entries(result.counts).map(([s, n]) => `${n} ${s}`).join(", ") || "none"} + </div> + <ul className="m-0 list-none space-y-2 p-0"> + {result.rows.map((r) => ( + <li key={r.citation} data-quote-check={r.citation} data-status={r.status} className="space-y-0.5 border-t border-seam pt-1.5 first:border-t-0 first:pt-0"> + <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-0.5 text-[12.5px]"> + <span className={cn("font-mono text-[11.5px] font-semibold uppercase", tone(r.status))}>{r.status}</span> + <span className="font-mono text-[11.5px] text-text">{r.citation}</span> + {!r.cited && <span className="text-[11.5px] text-muted">not cited</span>} + {r.score !== undefined && <span className="num font-mono text-[11.5px] text-text-2">{r.score.toFixed(2)}</span>} + {r.track && <span className="font-mono text-[11px] text-muted">{r.track}</span>} + {r.enOrig !== undefined && r.track !== "transcript.en-orig.vtt" && ( + <span className="font-mono text-[11px] text-muted">en-orig {r.enOrig.toFixed(2)}</span> + )} + <span className="font-mono text-[11px] text-muted"> + {r.channel}/{r.id} + {r.start !== undefined ? ` @ ${r.start}–${r.end} s` : ""} + </span> + </div> + <p className="m-0 font-serif text-[14px] leading-snug text-text-2">“{r.quote}”</p> + {r.message && <p className="m-0 text-[12px] text-text-2">{r.message}</p>} + {r.target && <Play target={r.target} why={`umtool verify quotes ${report} ${r.citation}`} />} + </li> + ))} + </ul> + </section> + )} + {result?.what === "check" && ( + <section data-report-check={result.status} className="basis-full space-y-1.5 rounded-[3px] border border-seam bg-panel px-3 py-2.5"> + <div className={cn("text-[12.5px] font-medium", tone(result.status))} data-check-summary=""> + {result.summary} + </div> + {[...result.allowed.map((a) => `allowed (missing media): ${a}`), ...result.warnings.map((w) => `warning: ${w}`)].map((l) => ( + <div key={l} className="text-[12px] text-doubt-text"> + {l} + </div> + ))} + <ul className="m-0 list-none space-y-2 p-0"> + {result.problems.map((p, i) => ( + <li key={`${p.line}-${i}`} data-check-problem={p.kind} className="space-y-0.5 border-t border-seam pt-1.5 first:border-t-0 first:pt-0"> + <div className="flex flex-wrap items-baseline gap-x-2.5 text-[12.5px]"> + <span className="font-mono text-[11.5px] font-semibold text-reject-text">{p.kind}</span> + <span className="font-mono text-[11.5px] text-text">{p.where}</span> + </div> + <p className="m-0 text-[12.5px] text-text-2">{p.message}</p> + {p.quote && <p className="m-0 font-serif text-[14px] leading-snug text-text-2">“{p.quote}”</p>} + {p.target && <Play target={p.target} why={`umtool check report ${report} ${p.where}`} />} + </li> + ))} + </ul> + </section> + )} + </div> + ); +} diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -8,6 +8,7 @@ import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides import type { Crumb } from "@/components/shell/AppHeader"; import DeleteArticle from "@/components/articles/DeleteArticle"; import { RefreshHost, RefreshMenuItem } from "@/components/articles/RefreshDialog"; +import ArticleChecks from "@/components/articles/ArticleChecks"; import ArticleOverview from "@/components/articles/ArticleOverview"; import ArticleReader from "@/components/articles/ArticleReader"; import WorkspacePanel from "@/components/articles/WorkspacePanel"; @@ -351,6 +352,7 @@ async function ArticleTab({ {p.id} (possible) </Link> ))} + {read.report && <ArticleChecks site={site} report={reportId} />} {source && ( <div className="w-full font-mono text-[11px]" title={source.how}> {source.draft && <span>draft {source.draft}</span>} diff --git a/umtool/components/projects/MediaDrafts.tsx b/umtool/components/projects/MediaDrafts.tsx @@ -4,6 +4,8 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import ChainPanel from "@/components/articles/ChainPanel"; +import CitedClip from "@/components/clips/CitedClip"; +import type { CitedTarget } from "@/lib/clips/types"; import { buttonVariants } from "@/components/ui/button"; import { LitActions, LitGroup, LitLine } from "@/components/ui/lit-line"; import { LitList, type LitDetail } from "@/components/ui/lit-list"; @@ -593,7 +595,11 @@ export type FieldEvidence = { cite: { at: number; duration: number } | null; quote: string | null; url: string | null; - cues: { start: number; text: string }[]; + cues: { start: number; end?: number; text: string }[]; + /** What plays the span (components/clips/CitedClip.tsx); null when the entry names no source. */ + target?: CitedTarget | null; + /** Who is speaking, as the burned-in header names them. */ + speaker?: string | null; }; /** @@ -606,11 +612,14 @@ export function MediaReview({ initial, provenance, evidence, + deckHref, }: { project: string; initial: DraftsView; provenance: Record<string, FieldProvenance>; evidence: Record<string, FieldEvidence>; + /** The audition deck's address (release 32 R1): the toggle back. */ + deckHref?: string; }) { const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; @@ -686,6 +695,11 @@ export function MediaReview({ byline={ev.byline} cite={ev.cite ?? undefined} label="Source" + note={ + ev.target ? ( + <CitedClip key={`${row?.address}|${ev.target.from}`} target={ev.target} keys reason={`umtool drafts review ${project} ${row?.entry ?? ""}`.trim()} report={project} className="pb-1" /> + ) : undefined + } cues={ev.cues.map((c, i) => ({ t: c.start, text: c.text, @@ -703,6 +717,16 @@ export function MediaReview({ ); return ( <BenchBody verdict={verdict} reader={reader} workClassName="space-y-3"> + {deckHref && ( + <div className="flex items-center gap-2 text-[12px]"> + <Link href={deckHref} prefetch={false} data-review-view="deck" className={buttonVariants({ variant: "outline", size: "sm" })}> + Deck + </Link> + <span data-review-view-current="list" className={buttonVariants({ variant: "pressed", size: "sm" })} aria-current="page"> + List + </span> + </div> + )} <GateLine view={view} /> <MediaFields project={project} view={view} act={drafts.act} provenance={provenance} onLit={setLit} lineGo={false} /> </BenchBody> diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -61,7 +61,7 @@ export default async function ProjectView({ if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />; // `/browse/<project>/review` -- every drafted field, approved / rejected // before a final build, and the alternatives a draft task kept. - if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} />; + if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx @@ -1,5 +1,5 @@ import { clock } from "@/components/ui/clock"; -import { projectsHref } from "@/lib/hrefs"; +import { projectsHref, reviewHref } from "@/lib/hrefs"; import { cuesInWindow, readClipDetail, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { draftsView } from "@/lib/report/drafts.mjs"; @@ -10,8 +10,14 @@ import type { ProjectRef } from "@/lib/project-types"; import { BenchFrame, BenchTop } from "./bench/BenchShell"; import { MediaReview, type FieldEvidence, type FieldProvenance } from "./MediaDrafts"; import type { DraftsView } from "./drafts"; +import AuditionDeck from "./review/AuditionDeck"; -// `/projects/<project>/review` -- the drafts review as a BENCH (P4b): every +// `/projects/<project>/review` -- the drafts review. By default the AUDITION +// DECK (release 32 R1, components/projects/review/AuditionDeck.tsx): one card +// per field awaiting review, its cited span playing, keep / cut / edit / skip +// as one gesture. `?view=list` is the list below, for bulk work. +// +// The list is a BENCH (P4b): every // drafted field of the cut, walked one at a time -- `j`/`k` light a field, // `a` approves it, `r` rejects it with its note -- the verdict bar asking // about the lit field, the reader showing the clip it is drawn over. The @@ -20,9 +26,18 @@ import type { DraftsView } from "./drafts"; // <project>/drafts.review.json; a final build refuses a drafted field not // approved on its current value (release 28, M0). +const spanOf = (e: { start: number; end: number; cutStart?: number; cutEnd?: number }) => { + const cut = Number.isFinite(Number(e.cutStart)) && Number.isFinite(Number(e.cutEnd)) && Number(e.cutStart) < Number(e.cutEnd); + const from = cut ? Number(e.cutStart) : Number(e.start); + const to = cut ? Number(e.cutEnd) : Number(e.end); + return Number.isFinite(from) && Number.isFinite(to) && from < to ? { from, to } : null; +}; + const ymd = (d: string | null | undefined) => (d && /^\d{8}$/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : (d ?? null)); -export default async function ReviewPage({ project }: { project: ProjectRef }) { +export default async function ReviewPage({ project, view: mode }: { project: ProjectRef; view?: string }) { + // The audition deck (release 32 R1) unless `?view=list`: the same fields, one card at a time. + const list = mode === "list"; const manifest = await readManifest(project.dir); const [view, provenance, token, detail] = await Promise.all([ draftsView(project.dir, manifest ?? {}) as Promise<DraftsView>, @@ -37,7 +52,7 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { // The source of every clip a drafted field is drawn over: the reader's. const evidence: Record<string, FieldEvidence> = {}; const wanted = new Set(view.rows.map((r) => r.entry).filter((e): e is string => !!e)); - type Entry = { id: string; kind: string; start: number; end: number; cite?: number | null; quote?: string | null; video?: string; channel?: string | null; sourceTitleClean?: string | null; title?: string | null; uploadDate?: string | null; date?: string | null; duration?: number | null; citeUrl?: string | null }; + type Entry = { id: string; kind: string; start: number; end: number; cutStart?: number; cutEnd?: number; cite?: number | null; quote?: string | null; video?: string; channel?: string | null; sourceChannel?: string | null; sourceTitleClean?: string | null; title?: string | null; uploadDate?: string | null; date?: string | null; duration?: number | null; citeUrl?: string | null }; for (const e of ((detail?.entries ?? []) as Entry[]).filter((x) => x.kind === "clip" && wanted.has(x.id))) { const win = await cuesInWindow(project.dir, e.id, e.start - 20, e.end + 20).catch(() => null); const at = e.cite ?? e.start; @@ -48,12 +63,20 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { cite: duration ? { at, duration } : null, quote: e.quote ?? null, url: e.citeUrl ?? null, - cues: (win?.cues ?? []).map((c: { start: number; text: string }) => ({ start: c.start, text: c.text })), + cues: (win?.cues ?? []).map((c: { start: number; end: number; text: string }) => ({ start: c.start, end: c.end, text: c.text })), + // What plays (components/clips/CitedClip.tsx): the cut's own extent when + // it has one, else the clip's; the corpus's directories -- a Rumble + // entry's local dir is `video`, never its siteVideo. + target: spanOf(e) && e.channel && e.video ? { channel: e.channel, video: e.video, ...spanOf(e)!, project: project.id, clip: e.id } : null, + speaker: e.sourceChannel ?? null, }; } // The piece this view belongs to: the article's when an article claims the project (P4a-2). const back = await pieceHrefOfProject(project.id, { tab: "media" }); + // Where a misheard word is fixed: the article's page (its respell form), when an article claims the project. + const articlePage = await pieceHrefOfProject(project.id, { tab: "article" }); + const respell = articlePage.startsWith("/projects/") ? null : articlePage; // To review: the drafted fields awaiting a verdict (the Media tab's count, the Inbox's). const toReview = awaitingReview(view.rows, provenance).length; return ( @@ -65,7 +88,13 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { back={{ href: back, label: project.id }} kind="Drafts review" here="review" - keys={view.rows.length ? [{ keys: ["j", "k"], label: "field" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] : []} + keys={ + !view.rows.length + ? [] + : list + ? [{ keys: ["j", "k"], label: "field" }, { keys: ["a"], label: "approve" }, { keys: ["r"], label: "reject" }] + : [{ keys: ["→"], label: "keep" }, { keys: ["←"], label: "cut" }, { keys: ["↑"], label: "edit" }, { keys: ["↓"], label: "skip" }, { keys: ["␣"], label: "replay" }, { keys: ["z"], label: "undo" }] + } note={ view.rows.length ? `${view.rows.length} fields · ${counts.approved} approved` + (counts.rejected ? ` · ${counts.rejected} rejected` : "") + (toReview ? ` · ${toReview} to review` : "") @@ -74,7 +103,11 @@ export default async function ReviewPage({ project }: { project: ProjectRef }) { /> } > - <MediaReview project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} /> + {list ? ( + <MediaReview project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} deckHref={reviewHref(project.id)} /> + ) : ( + <AuditionDeck project={project.id} initial={{ ...view, token }} provenance={provenance} evidence={evidence} back={back} listHref={reviewHref(project.id, { view: "list" })} respell={respell} /> + )} </BenchFrame> ); } diff --git a/umtool/components/projects/review/AuditionDeck.tsx b/umtool/components/projects/review/AuditionDeck.tsx @@ -0,0 +1,766 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import CitedClip, { warmCited, type CitedClipHandle } from "@/components/clips/CitedClip"; +import { buttonVariants } from "@/components/ui/button"; +import { awaitingReview } from "@/lib/inbox/drafts.mjs"; +import { editTextOf, isEditableField } from "@/lib/report/draftEdit.mjs"; +import { litCount, spokenWords } from "@/lib/clips/words"; +import { cn } from "@/lib/utils"; +import { useDrafts, type DraftRow, type DraftsView } from "../drafts"; +import type { FieldEvidence, FieldProvenance } from "../MediaDrafts"; + +// --------------------------------------------------------------------------- +// THE AUDITION (release 32 R1; the operator's "like a swipe app"): the drafts +// review as a deck of cards, one field per card. The model did the heavy +// lifting -- it drafted the field and picked the moment; the person's one job +// is to LISTEN and rule. So the cited span is already playing, the decision is +// one gesture, and the next card is already loaded underneath. +// +// swipe → / → k KEEP approve the draft as it is +// swipe ← / ← x CUT reject it; a reason chip or a few words, never required +// swipe ↑ / ↑ e EDIT the value as text on the card; Enter keeps it as edited +// swipe ↓ / ↓ s SKIP to the back of the stack +// tap the video / space replay the span +// z / Backspace UNDO the last keep, cut or skip (20 deep) +// tap a word / m mark it MISHEARD (the note says so; the article's page fixes it) +// +// Decisions write through the drafts route (drafts.review.json), the same as +// the list view (`?view=list`). An EDIT writes the field through the +// manifest's writer and is undone from the History tab, not with z. +// --------------------------------------------------------------------------- + +type Decision = "kept" | "cut" | "edited"; +type Undo = { address: string; kind: "kept" | "cut" | "skip"; prev: { verdict: DraftRow["verdict"]; note: string } }; + +const CUT_REASONS = ["misheard", "wrong moment", "says something else", "too long", "wrong speaker"]; +const THRESHOLD = 0.3; +const FLICK = 0.6; +const UNDO_DEPTH = 20; +// The next card rises into place (120 ms); with reduced motion it does not move. +const DECK_CSS = `@keyframes deck-rise { from { transform: scale(0.97) translateY(4px); } to { transform: none; } } +.deck-rise { animation: deck-rise 120ms ease-out; } +@media (prefers-reduced-motion: reduce) { .deck-rise { animation: none; } }`; +const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; + +export default function AuditionDeck({ + project, + initial, + provenance, + evidence, + back, + listHref, + respell, +}: { + project: string; + initial: DraftsView; + provenance: Record<string, FieldProvenance>; + evidence: Record<string, FieldEvidence>; + /** The Media tab. */ + back: string; + listHref: string; + /** The article's page, where a mishearing is fixed (null: no article claims the cut). */ + respell: string | null; +}) { + const drafts = useDrafts(project, initial); + const view = drafts.view ?? initial; + const rowOf = useCallback((a: string) => view.rows.find((r) => r.address === a) ?? null, [view.rows]); + + const [queue, setQueue] = useState<string[]>(() => awaitingReview(initial.rows, provenance).map((r: DraftRow) => r.address)); + const [total, setTotal] = useState(queue.length); + const [decided, setDecided] = useState<Map<string, Decision>>(new Map()); + const [skipped, setSkipped] = useState<Set<string>>(new Set()); + const [undos, setUndos] = useState<Undo[]>([]); + const [started, setStarted] = useState(false); + const [editing, setEditing] = useState<string | null>(null); + const [editText, setEditText] = useState(""); + const [reason, setReason] = useState<string>(""); + const [misheard, setMisheard] = useState<Map<string, Set<number>>>(new Map()); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [drag, setDrag] = useState<{ dx: number; dy: number } | null>(null); + const [leaving, setLeaving] = useState<null | "right" | "left" | "up" | "down">(null); + const [reduced, setReduced] = useState(false); + const clip = useRef<CitedClipHandle | null>(null); + const card = useRef<HTMLDivElement | null>(null); + const start = useRef<{ x: number; y: number; t: number; id: number } | null>(null); + + useEffect(() => { + const m = window.matchMedia("(prefers-reduced-motion: reduce)"); + setReduced(m.matches); + const on = () => setReduced(m.matches); + m.addEventListener("change", on); + return () => m.removeEventListener("change", on); + }, []); + + const live = queue.filter((a) => !skipped.has(a)); + const top = live[0] ?? null; + const under = live[1] ?? null; + const row = top ? rowOf(top) : null; + const ev = row?.entry ? (evidence[row.entry] ?? null) : null; + const counts = useMemo(() => { + const c = { kept: 0, cut: 0, edited: 0 }; + for (const d of decided.values()) c[d] += 1; + return c; + }, [decided]); + const done = decided.size; + + // The card after the next: ask what plays it before it is shown. + useEffect(() => { + const after = live[2]; + const e = after ? evidence[rowOf(after)?.entry ?? ""] : null; + if (e?.target) warmCited(e.target); + }, [live, evidence, rowOf]); + + const noteFor = (address: string, extra: string) => { + const words = misheard.get(address); + const quote = evidence[rowOf(address)?.entry ?? ""]?.quote ?? ""; + const marked = words?.size ? `misheard: ${[...words].map((i) => quote.split(/\s+/).filter(Boolean)[i]).filter(Boolean).join(", ")}` : ""; + return [extra, marked].filter(Boolean).join(" · "); + }; + + const remember = (u: Undo) => setUndos((s) => [...s.slice(-(UNDO_DEPTH - 1)), u]); + + const commit = useCallback( + async (kind: "kept" | "cut" | "skip", address: string) => { + const r = rowOf(address); + if (!r) return; + const prev = { verdict: r.verdict, note: r.note ?? "" }; + setError(null); + if (kind === "skip") { + setSkipped((s) => new Set(s).add(address)); + setQueue((q) => [...q.filter((a) => a !== address), address]); + remember({ address, kind, prev }); + return; + } + setQueue((q) => q.filter((a) => a !== address)); + setDecided((d) => new Map(d).set(address, kind)); + remember({ address, kind, prev }); + try { + if (kind === "kept") await drafts.act("approve", { address, note: noteFor(address, r.note ?? "") }); + else await drafts.act("reject", { address, note: noteFor(address, reason || r.note || "cut on the deck") }); + setReason(""); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setQueue((q) => [address, ...q.filter((a) => a !== address)]); + setDecided((d) => { + const n = new Map(d); + n.delete(address); + return n; + }); + setUndos((s) => s.slice(0, -1)); + } + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [rowOf, drafts, reason, misheard, evidence], + ); + + const decide = useCallback( + (dir: "right" | "left" | "up" | "down") => { + if (!top || busy || leaving) return; + setStarted(true); + if (dir === "up") { + setDrag(null); + const r = rowOf(top); + if (!r) return; + setEditing(top); + setEditText(editTextOf(r.field, r.text)); + return; + } + const address = top; + setLeaving(dir); + setDrag(null); + window.setTimeout( + () => { + setLeaving(null); + void commit(dir === "right" ? "kept" : dir === "left" ? "cut" : "skip", address); + }, + reduced ? 80 : 160, + ); + }, + [top, busy, leaving, rowOf, commit, reduced], + ); + + const undo = useCallback(async () => { + const u = undos[undos.length - 1]; + if (!u || busy) return; + setUndos((s) => s.slice(0, -1)); + setError(null); + if (u.kind === "skip") { + setSkipped((s) => { + const n = new Set(s); + n.delete(u.address); + return n; + }); + setQueue((q) => [u.address, ...q.filter((a) => a !== u.address)]); + return; + } + setBusy(true); + try { + if (!u.prev.verdict) await drafts.act("clear", { address: u.address }); + else if (u.prev.verdict === "approved") await drafts.act("approve", { address: u.address, note: u.prev.note }); + else await drafts.act("reject", { address: u.address, note: u.prev.note || "cut on the deck" }); + setDecided((d) => { + const n = new Map(d); + n.delete(u.address); + return n; + }); + setQueue((q) => [u.address, ...q.filter((a) => a !== u.address)]); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }, [undos, busy, drafts]); + + const saveEdit = async () => { + if (!editing) return; + const address = editing; + setBusy(true); + setError(null); + try { + await drafts.act("edit", { address, text: editText, token: view.token ?? null, note: noteFor(address, "edited on the deck") }); + setEditing(null); + setQueue((q) => q.filter((a) => a !== address)); + setDecided((d) => new Map(d).set(address, "edited")); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const toggleWord = (address: string, i: number) => + setMisheard((m) => { + const n = new Map(m); + const s = new Set(n.get(address) ?? []); + if (s.has(i)) s.delete(i); + else s.add(i); + n.set(address, s); + return n; + }); + + // The keys. Typing (the edit, the cut's few words) and a focused word keep theirs. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + const t = e.target as HTMLElement | null; + if (editing) { + if (e.key === "Escape") { + e.preventDefault(); + setEditing(null); + } + return; + } + if (t?.closest?.(TYPING)) return; + if (t?.closest?.("[data-word]") && (e.key === " " || e.key === "Enter")) return; + const k = e.key; + const act = (fn: () => void) => { + e.preventDefault(); + fn(); + }; + if (k === "ArrowRight" || k === "k") act(() => decide("right")); + else if (k === "ArrowLeft" || k === "x") act(() => decide("left")); + else if (k === "ArrowUp" || k === "e") act(() => decide("up")); + else if (k === "ArrowDown" || k === "s") act(() => decide("down")); + else if (k === "z" || k === "Backspace") act(() => void undo()); + else if (k === " ") + act(() => { + setStarted(true); + clip.current?.playSpan(); + }); + else if (k === "m") act(() => card.current?.querySelector<HTMLButtonElement>("[data-word]")?.focus()); + else if (k === "Escape") (document.activeElement as HTMLElement | null)?.blur?.(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [decide, undo, editing]); + + // The drag: past 30 % of the card's width, or a flick, decides; below it springs back. + const onPointerDown = (e: React.PointerEvent) => { + if (editing || leaving || e.button !== 0) return; + if ((e.target as HTMLElement).closest("button, a, input, textarea, select, [data-word]")) return; + start.current = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId }; + }; + const onPointerMove = (e: React.PointerEvent) => { + const s = start.current; + if (!s || s.id !== e.pointerId) return; + const dx = e.clientX - s.x; + const dy = e.clientY - s.y; + if (!drag && Math.hypot(dx, dy) < 6) return; + if (!drag) (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + setDrag({ dx, dy }); + }; + const onPointerUp = (e: React.PointerEvent) => { + const s = start.current; + start.current = null; + if (!s || !drag) return; + const w = card.current?.offsetWidth ?? 400; + const dt = Math.max(1, performance.now() - s.t); + const { dx, dy } = drag; + const horizontal = Math.abs(dx) >= Math.abs(dy); + const d = horizontal ? dx : dy; + if (Math.abs(d) > THRESHOLD * w || Math.abs(d) / dt > FLICK) { + decide(horizontal ? (dx > 0 ? "right" : "left") : dy < 0 ? "up" : "down"); + } else setDrag(null); + void e; + }; + + // The stamp the drag is heading for. + const stamp = drag + ? Math.abs(drag.dx) >= Math.abs(drag.dy) + ? { kind: drag.dx > 0 ? "KEEP" : "CUT", o: Math.min(1, Math.abs(drag.dx) / ((card.current?.offsetWidth ?? 400) * THRESHOLD)) } + : { kind: drag.dy < 0 ? "EDIT" : "SKIP", o: Math.min(1, Math.abs(drag.dy) / ((card.current?.offsetWidth ?? 400) * THRESHOLD)) } + : leaving + ? { kind: leaving === "right" ? "KEEP" : leaving === "left" ? "CUT" : leaving === "down" ? "SKIP" : "EDIT", o: 1 } + : null; + + const transform = leaving + ? reduced + ? undefined + : leaving === "right" + ? "translate(120%, 0) rotate(8deg)" + : leaving === "left" + ? "translate(-120%, 0) rotate(-8deg)" + : "translate(0, 110%)" + : drag + ? `translate(${drag.dx}px, ${drag.dy}px) rotate(${drag.dx * 0.04}deg)` + : undefined; + + const toggle = ( + <div className="flex items-center gap-2 text-[12px]"> + <span data-review-view-current="deck" className={buttonVariants({ variant: "pressed", size: "sm" })} aria-current="page"> + Deck + </span> + <Link href={listHref} prefetch={false} data-review-view="list" className={buttonVariants({ variant: "outline", size: "sm" })}> + List + </Link> + <span data-deck-count="" className="ml-auto font-mono text-[11.5px] text-muted"> + {total ? `${Math.min(done + 1, total)} / ${total}` : "0 / 0"} · {counts.kept} kept · {counts.cut} cut{counts.edited ? ` · ${counts.edited} edited` : ""} · {skipped.size} skipped + </span> + </div> + ); + + if (!total) { + return ( + <main data-deck="" data-deck-empty="" className="deck-main flex-1 p-4"> + <div className="mx-auto max-w-[520px] space-y-4"> + {toggle} + <p className="m-0 text-[13px] text-text-2">Nothing is waiting for a verdict.</p> + <Link href={back} prefetch={false} className={buttonVariants({ variant: "outline", size: "md" })}> + Back to the Media tab + </Link> + </div> + </main> + ); + } + + if (!top) { + const cut = [...decided].filter(([, d]) => d === "cut").map(([a]) => a); + const skip = [...skipped]; + return ( + <main data-deck="" className="deck-main flex-1 p-4"> + <div className="mx-auto max-w-[520px] space-y-4"> + {toggle} + <section data-deck-summary="" className="space-y-3 rounded-[6px] border border-seam bg-panel p-5"> + <h2 className="m-0 font-display text-[22px] font-semibold leading-tight text-text"> + {counts.kept} kept · {counts.cut} cut{counts.edited ? ` · ${counts.edited} edited` : ""} + {skip.length ? ` · ${skip.length} skipped` : ""} + </h2> + {[ + { label: "Cut", list: cut }, + { label: "Skipped", list: skip }, + ] + .filter((g) => g.list.length) + .map((g) => ( + <div key={g.label}> + <div className="micro">{g.label}</div> + <ul className="m-0 mt-1 list-none space-y-1 p-0"> + {g.list.map((a) => ( + <li key={a} data-summary-row={a} className="text-[13px] text-text-2"> + <span className="font-mono text-[11.5px] text-muted">{rowOf(a)?.entry ?? rowOf(a)?.label}</span> {rowOf(a)?.text} + {g.label === "Cut" && rowOf(a)?.note ? <span className="text-muted"> — {rowOf(a)?.note}</span> : null} + </li> + ))} + </ul> + </div> + ))} + <div className="flex flex-wrap gap-2 pt-1"> + {skip.length > 0 && ( + <button type="button" className={buttonVariants({ variant: "go", size: "md" })} onClick={() => setSkipped(new Set())}> + Review the skipped ones + </button> + )} + {cut.length > 0 && ( + <button + type="button" + className={buttonVariants({ variant: skip.length ? "outline" : "go", size: "md" })} + onClick={() => { + setQueue(cut); + setDecided((d) => { + const n = new Map(d); + for (const a of cut) n.delete(a); + return n; + }); + }} + > + Review the cut ones again + </button> + )} + <Link href={back} prefetch={false} data-deck-back="" className={buttonVariants({ variant: "outline", size: "md" })}> + Back to the Media tab + </Link> + </div> + </section> + {error && <p role="alert" className="m-0 text-[12px] text-reject-text">{error}</p>} + </div> + </main> + ); + } + + const peeks = Math.min(3, live.length - 1); + return ( + <main data-deck="" className="deck-main flex min-h-0 flex-1 flex-col p-3 pb-24 sm:p-4 md:pb-4"> + <div className="mx-auto flex w-full max-w-[520px] flex-col gap-3"> + {toggle} + <style>{DECK_CSS}</style> + <div className="relative"> + {/* The next card, underneath: its media loading already. */} + {under && ( + <div aria-hidden data-card-under={under} className="pointer-events-none absolute inset-0 z-[1] origin-top scale-[0.97] overflow-hidden rounded-[8px] border border-seam bg-panel"> + <Card address={under} row={rowOf(under)} ev={evidence[rowOf(under)?.entry ?? ""] ?? null} preload /> + </div> + )} + <div + ref={card} + key={top} + role="region" + aria-label={`${row?.label ?? "field"}${row?.entry ? ` of ${row.entry}` : ""}`} + tabIndex={-1} + data-card={top} + data-card-top="" + onPointerDown={onPointerDown} + onPointerMove={onPointerMove} + onPointerUp={onPointerUp} + onPointerCancel={() => { + start.current = null; + setDrag(null); + }} + className="deck-card deck-rise relative z-[2] touch-pan-y select-none rounded-[8px] border border-seam-2 bg-panel shadow-sm outline-none focus-visible:ring-2 focus-visible:ring-signal" + style={{ + transform, + opacity: leaving && reduced ? 0 : 1, + transition: drag ? "none" : leaving ? `transform 160ms ease-in, opacity ${reduced ? 80 : 160}ms` : "transform 120ms ease-out", + }} + > + {stamp && stamp.o > 0.05 && ( + <span + data-stamp={stamp.kind} + aria-hidden + className={cn( + "pointer-events-none absolute right-4 top-12 z-10 rounded-[4px] border-[3px] px-2.5 py-0.5 font-display text-[28px] font-bold uppercase tracking-wide", + stamp.kind === "KEEP" ? "border-signal text-signal" : stamp.kind === "CUT" ? "border-muted text-muted line-through" : "border-seam-2 text-text-2", + )} + style={{ opacity: stamp.o, transform: "rotate(-8deg)" }} + > + {stamp.kind} + </span> + )} + <Card + address={top} + row={row} + ev={ev} + index={Math.min(done + 1, total)} + total={total} + playing={started} + clipRef={clip} + marked={misheard.get(top) ?? null} + onWord={(i) => toggleWord(top, i)} + project={project} + editing={editing === top} + editText={editText} + onEditText={setEditText} + onSaveEdit={() => void saveEdit()} + onCancelEdit={() => setEditing(null)} + back={back} + respell={respell} + busy={busy} + /> + {!started && ( + <div className="absolute inset-0 z-20 flex items-center justify-center rounded-[8px] bg-[color-mix(in_srgb,var(--ground)_55%,transparent)]"> + <button + type="button" + data-deck-start="" + className={buttonVariants({ variant: "go", size: "lg" })} + onClick={() => { + setStarted(true); + clip.current?.playSpan(); + }} + > + Start review + </button> + </div> + )} + </div> + </div> + {/* The stack's edges: as many as fields remain, up to three (depth is the truth). */} + {peeks > 0 && ( + <div aria-hidden data-deck-peeks={peeks} className="-mt-3 flex flex-col items-center"> + {Array.from({ length: peeks }, (_, i) => ( + <div key={i} className="h-[5px] rounded-b-[6px] border border-t-0 border-seam bg-panel-2" style={{ width: `${96 - i * 4}%` }} /> + ))} + </div> + )} + {/* A cut's reason: optional, one tap. */} + <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label="Why cut"> + {CUT_REASONS.map((r) => ( + <button + key={r} + type="button" + data-cut-reason={r} + aria-pressed={reason === r} + onMouseDown={(e) => e.preventDefault()} + onClick={() => setReason(reason === r ? "" : r)} + className={cn( + "rounded-full border px-2 py-[2px] text-[11.5px]", + reason === r ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text", + )} + > + {r} + </button> + ))} + <input + value={CUT_REASONS.includes(reason) ? "" : reason} + onChange={(e) => setReason(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + (e.target as HTMLInputElement).blur(); + decide("left"); + } + }} + placeholder="or why, in a few words" + aria-label="Why cut, in a few words" + data-cut-note="" + maxLength={300} + className="min-w-0 flex-1 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[2px] text-[11.5px] text-text outline-none focus:border-signal" + /> + </div> + {error && ( + <p role="alert" data-deck-error="" className="m-0 text-[12px] text-reject-text"> + {error} + </p> + )} + {/* Every gesture is a button too: a bar under the thumb on a phone. */} + <nav + aria-label="Decide" + className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 gap-1.5 border-t border-seam bg-ground p-2 md:static md:z-auto md:border-0 md:bg-transparent md:p-0" + > + <DeckButton action="undo" label="Undo" k="z" disabled={!undos.length || busy} onClick={() => void undo()} /> + <DeckButton action="cut" label="Cut" k="←" disabled={busy} onClick={() => decide("left")} /> + <DeckButton action="edit" label="Edit" k="↑" disabled={busy} onClick={() => decide("up")} /> + <DeckButton action="skip" label="Skip" k="↓" disabled={busy} onClick={() => decide("down")} /> + <DeckButton action="keep" label="Keep" k="→" go disabled={busy} onClick={() => decide("right")} /> + </nav> + {done < 3 && ( + <p data-deck-hint="" className="m-0 hidden text-center font-mono text-[11px] text-muted md:block"> + ← cut · ↑ edit · ↓ skip · keep → · space replays · z undoes + </p> + )} + </div> + </main> + ); +} + +function DeckButton({ action, label, k, go = false, disabled, onClick }: { action: string; label: string; k: string; go?: boolean; disabled?: boolean; onClick: () => void }) { + return ( + <button + type="button" + data-deck-action={action} + disabled={disabled} + aria-label={`${label} (${k})`} + onMouseDown={(e) => e.preventDefault()} + onClick={onClick} + className={cn(buttonVariants({ variant: go ? "go" : "outline", size: "lg" }), "flex-col gap-0 px-1 py-2 md:flex-row md:gap-1.5")} + > + <span>{label}</span> + <kbd className="hidden md:inline">{k}</kbd> + </button> + ); +} + +/** One field's card: what is judged, the span playing, the lit line, where it came from. */ +function Card({ + address, + row, + ev, + index, + total, + preload = false, + playing = false, + clipRef, + marked = null, + onWord, + project, + editing = false, + editText = "", + onEditText, + onSaveEdit, + onCancelEdit, + back, + respell = null, + busy = false, +}: { + address: string; + row: DraftRow | null; + ev: FieldEvidence | null; + index?: number; + total?: number; + preload?: boolean; + playing?: boolean; + clipRef?: React.Ref<CitedClipHandle>; + marked?: Set<number> | null; + onWord?: (i: number) => void; + project?: string; + editing?: boolean; + editText?: string; + onEditText?: (s: string) => void; + onSaveEdit?: () => void; + onCancelEdit?: () => void; + back?: string; + respell?: string | null; + busy?: boolean; +}) { + const [now, setNow] = useState<number | null>(null); + const t = ev?.target ?? null; + const words = useMemo(() => (ev?.quote && t ? spokenWords(ev.quote, ev.cues, t.from, t.to) : []), [ev, t]); + const lit = now === null ? 0 : litCount(words, now); + const value = row?.text ?? ""; + const editable = row ? isEditableField(row.field) : false; + const misheardWords = marked?.size ? [...marked].map((i) => words[i]?.text).filter(Boolean) : []; + + return ( + <div className="space-y-3 p-4 sm:p-5" data-card-body={address}> + <div className="flex items-baseline gap-2"> + <span className="micro">{row?.label ?? address}</span> + {row?.entry && <span className="font-mono text-[11px] text-muted">{row.entry}</span>} + {index !== undefined && total !== undefined && ( + <span className="ml-auto font-mono text-[11px] text-muted"> + {index}/{total} + </span> + )} + </div> + {editing && !editable ? ( + <div className="space-y-1.5" data-card-edit-elsewhere=""> + <p data-card-value="" className="m-0 whitespace-pre-line font-display text-[22px] font-semibold leading-[1.2] text-text"> + {value} + </p> + <p className="m-0 text-[12px] text-text-2"> + This field is edited in its own section:{" "} + <Link href={back ?? "#"} prefetch={false} className="ink-link"> + the Media tab + </Link> + .{" "} + <button type="button" onClick={onCancelEdit} className="ink-link"> + Back to the card + </button> + </p> + </div> + ) : editing ? ( + <div className="space-y-1.5"> + <textarea + autoFocus + data-card-edit="" + aria-label={`Edit the ${row?.label ?? "field"}`} + value={editText} + onChange={(e) => onEditText?.(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + onSaveEdit?.(); + } + }} + rows={Math.max(2, editText.split("\n").length)} + className="w-full resize-y rounded-[3px] border border-signal bg-ground px-2 py-1.5 font-display text-[20px] leading-snug text-text outline-none" + /> + <div className="flex flex-wrap items-center gap-2 text-[11.5px] text-muted"> + <button type="button" data-card-save="" disabled={busy} onClick={onSaveEdit} className={buttonVariants({ variant: "go", size: "sm" })}> + Keep as edited <kbd>Enter</kbd> + </button> + <button type="button" onClick={onCancelEdit} className={buttonVariants({ variant: "ghost", size: "sm" })}> + Cancel <kbd>Esc</kbd> + </button> + <span>Shift+Enter for a new line{row?.field === "onscreen" ? " (line 2 is the subtitle)" : row?.field === "lines" ? " (one teaser line each)" : ""}</span> + {misheardWords.length > 0 && respell && ( + <a + data-fix-mishearing="" + href={`${respell}${respell.includes("?") ? "&" : "?"}heard=${encodeURIComponent(misheardWords.join(","))}`} + className="ink-link" + > + fix this mishearing + </a> + )} + </div> + </div> + ) : ( + <p data-card-value="" className="m-0 whitespace-pre-line font-display text-[22px] font-semibold leading-[1.2] text-text sm:text-[26px]"> + {value || <span className="text-muted">(empty)</span>} + </p> + )} + {t ? ( + <CitedClip + key={`${address}|${t.from}|${t.to}`} + ref={clipRef} + target={t} + face="card" + preload={preload} + autoPlay={playing && !preload} + reason={`umtool drafts review ${project ?? ""} ${row?.entry ?? ""}`.trim()} + report={project} + onTime={setNow} + /> + ) : ( + <p className="m-0 text-[12px] text-muted">{row?.entry ? "No source for this field." : "Not drawn over a clip: read it against the report."}</p> + )} + {words.length > 0 && ( + <p data-lit-quote="" className="m-0 font-serif text-[17px] leading-[1.45] text-text-2"> + “ + {words.map((w, i) => ( + <span key={i}> + <button + type="button" + data-word={i} + data-lit={i < lit ? "" : undefined} + data-misheard={marked?.has(i) ? "" : undefined} + aria-pressed={!!marked?.has(i)} + title={marked?.has(i) ? "marked misheard: tap to unmark" : "tap to mark misheard"} + onClick={() => onWord?.(i)} + className={cn( + "rounded-[2px] px-0 text-left decoration-2 underline-offset-[5px] outline-none focus-visible:ring-2 focus-visible:ring-signal", + i < lit ? "text-text underline decoration-signal" : "", + marked?.has(i) ? "bg-panel-2 line-through decoration-muted" : "", + )} + > + {w.text} + </button> + {i < words.length - 1 ? " " : ""} + </span> + ))} + ” + </p> + )} + {ev && ( + <div className="space-y-0.5 text-[12px] text-muted"> + <div className="truncate text-text-2">{ev.source}</div> + <div className="font-mono text-[11px]">{[ev.speaker, ...ev.byline].filter(Boolean).join(" · ")}</div> + </div> + )} + {row?.drafted && ( + <div className="font-mono text-[11px] text-muted" data-card-drafted=""> + drafted by {row.drafted.model} · {row.drafted.task} + </div> + )} + </div> + ); +} diff --git a/umtool/lib/articles/checks.ts b/umtool/lib/articles/checks.ts @@ -0,0 +1,98 @@ +import { checkReports, verifyReportQuotes, type QuoteResult, type ReportsCheckProblem } from "yt-dlp-transcript-common/bin/reports-check"; +import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; +import type { CitedTarget } from "@/lib/clips/types"; +import { ARTICLES_KEY } from "@/lib/paths"; +import { readReportFile, sitesPaths } from "./sites"; + +// --------------------------------------------------------------------------- +// VERIFY QUOTES and CHECK REPORT on the article page (release 32 R1): the CLI's +// `archilyzer reports verify-quotes --article <id>` and `reports check +// --article <id>` (a site's report: `reports check <site> --reports <id>`), run +// in-process through the same functions (common/bin/reports-check.ts) over +// umtool's roots. No model, no subprocess. Respellings apply (the report's +// own, as the check applies them). Each quote and each problem that names a +// span carries what plays it, so a person can hear it. +// --------------------------------------------------------------------------- + +export type QuoteRow = QuoteResult & { quote: string; target: CitedTarget | null }; +export type QuoteChecks = { what: "quotes"; report: string; rows: QuoteRow[]; counts: Record<string, number>; invalid: string[] }; +export type CheckProblemRow = ReportsCheckProblem & { quote?: string; target?: CitedTarget | null }; +export type ReportCheck = { + what: "check"; + report: string; + status: "pass" | "fail" | "usage" | "empty" | "error"; + summary: string; + problems: CheckProblemRow[]; + allowed: string[]; + warnings: string[]; +}; + +type Cite = NonNullable<Report["citations"]>[string]; +const targetOfCite = (c: Cite | undefined): CitedTarget | null => + c && (c.kind === "video" || c.kind === "audio") && Number.isFinite(c.start) && Number.isFinite(c.end) && c.start < c.end + ? { channel: c.channel, video: c.id, from: c.start, to: c.end, ...(c.kind === "audio" ? { audio: true } : {}) } + : null; + +async function reportOf(site: string, reportId: string): Promise<Report> { + const read = await readReportFile(site, reportId); + if (!read.report) throw Object.assign(new Error(read.problems[0]?.message ?? "no report"), { status: 404 }); + return read.report; +} + +export async function articleQuoteChecks(site: string, reportId: string, opts: { now?: string } = {}): Promise<QuoteChecks> { + const report = await reportOf(site, reportId); + const results = await verifyReportQuotes(report, { paths: sitesPaths(), ...(opts.now ? { now: opts.now } : {}) }); + const counts: Record<string, number> = {}; + for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1; + return { + what: "quotes", + report: reportId, + rows: results.map((r) => { + const c = report.citations?.[r.citation]; + return { ...r, quote: c?.quote ?? "", target: targetOfCite(c) }; + }), + counts, + invalid: [], + }; +} + +export async function articleReportCheck(site: string, reportId: string, opts: { allowMissingMedia?: boolean } = {}): Promise<ReportCheck> { + const report = await reportOf(site, reportId); + const paths = sitesPaths(); + const allowMissingMedia = opts.allowMissingMedia === true; + const r = + site === ARTICLES_KEY + ? await checkReports({ article: reportId, paths, allowMissingMedia }) + : await checkReports({ siteId: site, reports: [reportId], paths, allowMissingMedia }); + const base = { what: "check" as const, report: reportId, problems: [] as CheckProblemRow[], allowed: [] as string[], warnings: [] as string[] }; + switch (r.status) { + case "usage": + case "error": + return { ...base, status: r.status, summary: r.error }; + case "empty": + return { ...base, status: "empty", summary: "nothing published to check" }; + case "pass": { + const me = r.reports.find((x) => x.id === reportId); + return { + ...base, + status: "pass", + summary: + `compose would pass: ${me ? `${me.quotes} quote(s) checked${me.lowest === null ? "" : `, lowest ${me.lowest.toFixed(2)}`}` : `${r.reports.length} report(s)`}, ` + + `${r.moments} moment(s)`, + allowed: r.allowed, + warnings: r.warnings, + }; + } + case "fail": + return { + ...base, + status: "fail", + summary: `compose would fail: ${r.problems.length} problem(s)`, + problems: r.problems.map((p) => { + const cid = p.citation?.startsWith(`${reportId}#`) ? p.citation.slice(reportId.length + 1) : null; + const c = cid ? report.citations?.[cid] : undefined; + return { ...p, ...(c ? { quote: c.quote, target: targetOfCite(c) } : {}) }; + }), + }; + } +} diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -284,8 +284,8 @@ export function narrationHref(project: string, q: NoteOpt = {}): string { } /** The drafts review (release 28). */ -export function reviewHref(project: string, q: NoteOpt = {}): string { - return withQuery(`/projects/${encodePath(project)}/review`, {}, q.note); +export function reviewHref(project: string, q: NoteOpt & { view?: "list" } = {}): string { + return withQuery(`/projects/${encodePath(project)}/review`, q.view ? { view: q.view } : {}, q.note); } /** One cut of a song; `plan` opens a plan of it, `v` a variant row. */ diff --git a/umtool/lib/report/draftEdit.mjs b/umtool/lib/report/draftEdit.mjs @@ -0,0 +1,69 @@ +// EDIT on the audition deck (release 32 R1): a drafted field rewritten by the +// person as plain text, and turned back into the field's value. One line per +// part, so the same textarea serves every field the card can edit: +// +// onscreen line 1 the title, the rest the subtitle +// narration the text +// lines one teaser line per line +// publish.youtube line 1 the title (the description stays) +// +// Any other field (flips, threads, the cut's order, a social post) is edited +// where it always was: the deck links its section. The value goes through the +// manifest's own writer (writeDraftedField), so it is the operator's after. + +export const EDITABLE_FIELDS = Object.freeze(["onscreen", "narration", "lines", "publish.youtube"]); + +/** Whether the card can edit this field in place. */ +export const isEditableField = (field) => EDITABLE_FIELDS.includes(field); + +/** The textarea's text for a field, from the words the review shows (judgedText). */ +export function editTextOf(field, judged) { + const s = typeof judged === "string" ? judged : ""; + if (field === "onscreen") return s.replace(" — ", "\n"); + if (field === "lines") return s.split(" / ").join("\n"); + return s; +} + +const linesOf = (text) => + String(text ?? "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + +/** + * The field's new value from the edited text, keeping what the text does not + * say (a narration's voice, a teaser line's own keys, the description). + * Throws in words when the text cannot be the field. + */ +export function valueFromEdit(field, current, text) { + const lines = linesOf(text); + const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}); + if (field === "onscreen") { + if (!lines.length) throw new Error("an on-screen text needs a title"); + const { title: _t, subtitle: _s, ...rest } = obj(current); + const subtitle = lines.slice(1).join(" "); + return { ...rest, title: lines[0], ...(subtitle ? { subtitle } : {}) }; + } + if (field === "narration") { + const t = String(text ?? "").trim(); + if (!t) throw new Error("a narration needs its words"); + return { ...obj(current), text: t }; + } + if (field === "lines") { + if (!lines.length) throw new Error("a teaser needs at least one line"); + const was = Array.isArray(current) ? current : []; + return lines.map((l, i) => (was[i] && typeof was[i] === "object" ? { ...was[i], text: l } : l)); + } + if (field === "publish.youtube") { + if (!lines.length) throw new Error("a YouTube title cannot be empty"); + return { ...obj(current), title: lines[0] }; + } + throw new Error(`${field} is edited in its own section, not on the card`); +} + +/** The current value of a review row's field in a manifest. */ +export function currentFieldValue(manifest, { entry, field }) { + if (entry) return (manifest?.timeline ?? []).find((e) => e?.id === entry)?.[field]; + if (field === "publish.youtube") return manifest?.publish?.youtube; + return undefined; +} diff --git a/umtool/lib/report/draftEdit.test.mjs b/umtool/lib/report/draftEdit.test.mjs @@ -0,0 +1,30 @@ +// The deck's EDIT (release 32 R1): the edited text back into each field's value. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { currentFieldValue, editTextOf, isEditableField, valueFromEdit } from "./draftEdit.mjs"; + +test("the textarea's text from the review's words, and back", () => { + assert.equal(editTextOf("onscreen", "Title — Sub"), "Title\nSub"); + assert.equal(editTextOf("lines", "a / b / c"), "a\nb\nc"); + assert.deepEqual(valueFromEdit("onscreen", { title: "Old", subtitle: "s", align: "left" }, "New title\nnew sub"), { align: "left", title: "New title", subtitle: "new sub" }); + assert.deepEqual(valueFromEdit("onscreen", { title: "Old", subtitle: "s" }, "Only a title"), { title: "Only a title" }); +}); + +test("narration keeps its voice; a teaser line keeps its own keys", () => { + assert.deepEqual(valueFromEdit("narration", { text: "old", voice: "v1" }, " new words "), { text: "new words", voice: "v1" }); + assert.deepEqual(valueFromEdit("lines", [{ text: "a", hold: 2 }, "b"], "A\nB\nC"), [{ text: "A", hold: 2 }, "B", "C"]); + assert.deepEqual(valueFromEdit("publish.youtube", { title: "t", description: "d" }, "New\nignored"), { title: "New", description: "d" }); +}); + +test("what the card cannot edit, and empty text, are refused in words", () => { + assert.equal(isEditableField("render.chrome.flips"), false); + assert.throws(() => valueFromEdit("render.chrome.flips", [], "x"), /edited in its own section/); + assert.throws(() => valueFromEdit("onscreen", {}, " \n "), /needs a title/); + assert.throws(() => valueFromEdit("lines", [], ""), /at least one line/); +}); + +test("the current value of a row's field", () => { + const m = { timeline: [{ id: "c1", onscreen: { title: "T" } }], publish: { youtube: { title: "Y" } } }; + assert.deepEqual(currentFieldValue(m, { entry: "c1", field: "onscreen" }), { title: "T" }); + assert.deepEqual(currentFieldValue(m, { entry: null, field: "publish.youtube" }), { title: "Y" }); +});