"use client"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import HandoffDialog from "@/components/research/HandoffDialog"; import { Button } from "@/components/ui/button"; import { Field, Input, Select } from "@/components/ui/field"; import { chainable, defaultChainIteration } from "@/lib/create/iterations.mjs"; import { articleHref } from "@/lib/hrefs"; import { researchCaseHref, researchCasesApi } from "@/lib/research/hrefs"; import type { CaseSummary } from "@/lib/research/case-types"; import type { SourceOption } from "@/lib/research/types"; // --------------------------------------------------------------------------- // Create's own forms (plans/umtool-redesign.md, P5). Each is a thin shell over // a writer that already exists -- none writes anything itself: // // ResearchForm POST /api/research/cases (R2) → the case's board // BoardForm a board, then R2's hand-off: POST …//handoff, its // plan shown and confirmed in R2's HandoffDialog → the // article's iterations, or the new project // ArticleVideoForm an article and a done iteration, the chain's steps // (GET /api/articles/chain), then POST it → the article's // iterations, where the chain runs // // Keyboard first: the first field takes the focus, Enter submits, Escape is // Cancel (CreateView puts the focus back on the line). // --------------------------------------------------------------------------- async function json(r: Response): Promise { const b = (await r.json().catch(() => null)) as (T & { error?: string }) | null; if (!r.ok) throw new Error(b?.error ?? `HTTP ${r.status}`); return b as T; } const escToCancel = (onCancel: () => void) => (e: React.KeyboardEvent) => { if (e.key === "Escape" && !e.defaultPrevented) { e.preventDefault(); onCancel(); } }; function Actions({ children, error }: { children: React.ReactNode; error?: string | null }) { return ( <>
{children}
{error && (

{error}

)} ); } // ── Research a question ───────────────────────────────────────────────────── export function ResearchForm({ sources, onCancel }: { sources: SourceOption[]; onCancel: () => void }) { const router = useRouter(); const [query, setQuery] = useState(""); const [title, setTitle] = useState(""); const [source, setSource] = useState(sources[0]?.handle ?? ""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const open = async () => { if (!query.trim()) return; setBusy(true); setError(null); try { const r = await json<{ case: { id: string } }>( await fetch(researchCasesApi(), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query: query.trim(), ...(title.trim() ? { title: title.trim() } : {}), ...(source ? { scope: { source } } : {}) }), }), ); router.push(researchCaseHref(r.case.id)); } catch (e) { setError((e as Error).message); setBusy(false); } }; return (
{ e.preventDefault(); void open(); }} > setQuery(e.target.value)} aria-label="question" placeholder="e.g. how many employees" /> setTitle(e.target.value)} aria-label="case title" placeholder="the question, unless named" className="w-56" /> {sources.length > 0 && ( )}
); } // ── An article or a video from a board (R2's hand-off) ────────────────────── export function BoardForm({ to, cases, casesError, initialCase, onCancel, }: { to: "article" | "video"; cases: CaseSummary[]; casesError: string | null; initialCase?: string | null; onCancel: () => void; }) { const router = useRouter(); const withQuotes = cases.filter((c) => c.quotes > 0); const [pick, setPick] = useState( initialCase && cases.some((c) => c.id === initialCase) ? initialCase : (withQuotes[0]?.id ?? cases[0]?.id ?? ""), ); const [planning, setPlanning] = useState(false); const chosen = cases.find((c) => c.id === pick); if (!cases.length) { return (

{casesError ? `The boards do not read: ${casesError}` : "No boards yet. Pin quotes from Research to a board, then hand it off here."}

); } return ( <>
{ e.preventDefault(); if (chosen) setPlanning(true); }} > {chosen && chosen.quotes === 0 &&

That board has no quotes yet.

}
{/* Outside the form: the dialog carries a form of its own (method="dialog"). */} setPlanning(false)} onDone={(href) => { setPlanning(false); router.push(href); }} /> ); } // ── A video from an article: the chain over a done iteration ──────────────── type IterRow = { n: number; label: string; status: string; hasReport: boolean; reportFrom: number | null; currentReport: boolean; kind: string }; type ChainView = { steps: { name: string; label: string; status: string; optional: boolean }[]; resumeAt: string | null; job: { id: string; state: string } | null }; export function ArticleVideoForm({ articles, initialArticle, onCancel, }: { articles: { id: string; title: string; status: string | null }[]; initialArticle?: string | null; onCancel: () => void; }) { const router = useRouter(); const [article, setArticle] = useState(initialArticle && articles.some((a) => a.id === initialArticle) ? initialArticle : (articles[0]?.id ?? "")); const [its, setIts] = useState(null); const [n, setN] = useState(null); const [chain, setChain] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [stopBefore, setStopBefore] = useState(false); // The article's iterations: those with a report (done) are what a chain runs over. useEffect(() => { if (!article) return; let live = true; setIts(null); setN(null); setChain(null); setError(null); fetch(`/api/articles/iterations?article=${encodeURIComponent(article)}`, { cache: "no-store" }) .then((r) => json<{ iterations: IterRow[] }>(r)) .then((b) => { if (!live) return; // Done, with a report, newest first; the default is the newest with a // report of its own (a chain cuts from a report), never a video revision. const done = chainable(b.iterations); setIts(done); setN(defaultChainIteration(b.iterations) ?? done[0]?.n ?? null); }) .catch((e: Error) => live && setError(e.message)); return () => { live = false; }; }, [article]); // The chain's steps for that iteration, and where a start resumes. useEffect(() => { if (!article || n === null) return; let live = true; setChain(null); fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" }) .then((r) => json<{ chain: ChainView }>(r)) .then((b) => live && setChain(b.chain)) .catch((e: Error) => live && setError(e.message)); return () => { live = false; }; }, [article, n]); const start = async () => { if (!article || n === null) return; // stopBefore (demo epic D1): the run ends before the voices. setBusy(true); setError(null); try { await json( await fetch("/api/articles/chain", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ article, n, ...(stopBefore ? { stopBeforeRender: true } : {}) }), }), ); router.push(articleHref({ site: "articles", id: article }, { tab: "iterations" })); } catch (e) { setError((e as Error).message); setBusy(false); } }; if (!articles.length) { return

No article in the store yet. Start one from a question.

; } const chosen = its?.find((it) => it.n === n) ?? null; const todo = chain ? chain.steps.filter((s) => !s.optional) : []; const from = chain?.resumeAt ? todo.findIndex((s) => s.name === chain.resumeAt) : -1; return (
{ e.preventDefault(); void start(); }} > {its && its.length === 0 &&

This article has no done iteration with a report: the chain runs over one.

} {chain && (

{chosen && ( {chosen.label} · {chosen.kind} {chosen.hasReport ? "" : ` (the report of i${chosen.reportFrom})`}: )} {chain.job?.state === "running" ? "Its chain is running now." : chain.resumeAt === null ? "Every step is done; run one again from the article's Iterations tab." : `${todo.length - Math.max(from, 0)} of ${todo.length} steps to run, from “${todo[Math.max(from, 0)]?.label}”: ${todo .slice(Math.max(from, 0)) .map((s) => s.label) .join(" → ")}`}

)}
); }