"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import IntroCardPlayer, { type IntroPage } from "../review/IntroCardPlayer"; import { announceManifestChanged } from "../timelineApi"; // THE INTRO ROW of the Cut tab, and its editor (lane intro-play; operator, 8 Nov 2026: "more first-class intro support // (view in play the cut)"): the intro the cut opens on (`render.intro`) as the first row of the cut, and -- Edit -- its // knobs beside a LIVE PREVIEW of the page the build renders (POST /api/report/chrome/intro with the unsaved value: the // editor's draft page), playable with its sound. Save writes the project's render.intro through the look writer (PUT // /api/report/render, the build's own checks, the manifest's token). Each VERSION (a made take) has its own on/off: off // is its patch's `render.intro: null` (PUT /api/report/chrome/intro). The CLI twin is `umtool intro`. No AI anywhere. type Choices = { styles: string[]; styleDefault: string; marks: string[]; grounds: string[]; seconds: { min: number; max: number; default: number }; titleMax: number; linesMax: number; lineMax: number; }; type Version = { id: string; label: string; draft: boolean; intro: "cut" | "off" | "own" }; type Entry = { style: string; ground: string; mark: string; seconds: number; title?: string; lines?: string[]; site?: { name: string }; sound?: unknown }; type State = { token: string | null; title: string | null; generatedOn: string | null; intro: unknown; errors: string[]; entry: Entry | null; entryError: string | null; versions: Version[]; choices: Choices; }; /** The editor's fields, as typed. */ type Draft = { on: boolean; style: string; seconds: string; mark: string; ground: string; sound: "standin" | "silent" | "file"; soundFile: string; site: string; title: string; lines: string; }; const isObj = (v: unknown): v is Record => !!v && typeof v === "object" && !Array.isArray(v); const objectOf = (v: unknown): Record | null => (typeof v === "string" ? { style: v } : isObj(v) ? { ...v } : null); function draftOf(written: unknown, styleDefault: string): Draft { const o = objectOf(written); return { on: !!o, style: typeof o?.style === "string" ? o.style : styleDefault, seconds: typeof o?.seconds === "number" ? String(o.seconds) : "", mark: typeof o?.mark === "string" ? o.mark : "", ground: typeof o?.ground === "string" ? o.ground : "", sound: o?.sound === false ? "silent" : typeof o?.sound === "string" ? "file" : "standin", soundFile: typeof o?.sound === "string" ? o.sound : "", site: typeof o?.site === "string" ? o.site : isObj(o?.site) ? JSON.stringify(o.site) : "", title: typeof o?.title === "string" ? o.title : "", lines: Array.isArray(o?.lines) ? (o.lines as unknown[]).filter((l) => typeof l === "string").join("\n") : "", }; } /** The value to write: the intro as written with the editor's keys over it (a key it does not show is kept). */ function valueOf(d: Draft, written: unknown): unknown { if (!d.on) return null; const o: Record = objectOf(written) ?? {}; o.style = d.style; const set = (k: string, v: unknown) => { if (v === undefined) delete o[k]; else o[k] = v; }; const n = d.seconds.trim() ? Number(d.seconds) : undefined; set("seconds", n === undefined ? undefined : Number.isFinite(n) ? n : d.seconds.trim()); set("mark", d.mark || undefined); set("ground", d.ground || undefined); set("sound", d.sound === "silent" ? false : d.sound === "file" ? d.soundFile.trim() || undefined : undefined); const site = d.site.trim(); let siteValue: unknown = site || undefined; if (site.startsWith("{")) { try { siteValue = JSON.parse(site); } catch { siteValue = site; } } set("site", siteValue); set("title", d.title.trim() || undefined); const lines = d.lines.split("\n").map((l) => l.trim()).filter(Boolean); set("lines", lines.length ? lines : undefined); const keys = Object.keys(o); return keys.length === 1 && keys[0] === "style" ? o.style : o; } /** One line for the row: what the cut opens on. */ function summaryOf(state: State | null, written: unknown): string { const e = state?.entry; if (e) { const words = [e.title, ...(e.lines ?? [])].filter(Boolean).join(" · "); return `${e.style} · ${e.seconds} s · mark ${e.mark}${e.site ? ` · ${e.site.name}` : ""}${words ? ` · ${words}` : ""}`; } const o = objectOf(written); return o ? `${String(o.style ?? "")}` : "none: the cut opens on its first entry"; } export default function IntroRow({ project, written: initial, open: openInitially = false }: { project: string; written: unknown; open?: boolean }) { const [state, setState] = useState(null); const [open, setOpen] = useState(openInitially); const load = useCallback(async () => { const r = await fetch(`/api/report/chrome/intro?${new URLSearchParams({ project }).toString()}`, { cache: "no-store" }); const j = (await r.json().catch(() => ({}))) as State & { error?: string }; if (r.ok && !j.error) setState(j); return r.ok && !j.error ? j : null; }, [project]); useEffect(() => { void load(); }, [load]); const written = state ? state.intro : initial; const has = written !== null && written !== undefined; return (
intro {summaryOf(state, written)} {state?.versions.some((v) => v.intro === "off") && ( off in {state.versions.filter((v) => v.intro === "off").map((v) => v.id).join(", ")} )}
{open && state && } {open && !state &&

reading the intro…

}
); } function IntroEditor({ project, state, reload }: { project: string; state: State; reload: () => Promise }) { const c = state.choices; const [draft, setDraft] = useState(() => draftOf(state.intro, c.styleDefault)); const [token, setToken] = useState(state.token); const [busy, setBusy] = useState(false); const [said, setSaid] = useState<{ ok: boolean; text: string } | null>(null); useEffect(() => setToken(state.token), [state.token]); const value = useMemo(() => valueOf(draft, state.intro), [draft, state.intro]); const key = JSON.stringify(value); const dirty = key !== JSON.stringify(valueOf(draftOf(state.intro, c.styleDefault), state.intro)) || draft.on !== (state.intro !== null && state.intro !== undefined); const set = (patch: Partial) => { setSaid(null); setDraft((d) => ({ ...d, ...patch })); }; // ---- the live preview: the draft composed as the build draws it, a beat after the last keystroke ---- const [page, setPage] = useState(null); const [problems, setProblems] = useState([]); const [composing, setComposing] = useState(false); const seq = useRef(0); useEffect(() => { const mine = ++seq.current; const t = setTimeout(async () => { if (value === null) { setPage(null); setProblems([]); return; } setComposing(true); try { const r = await fetch("/api/report/chrome/intro", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, intro: value }), }); const j = (await r.json().catch(() => ({}))) as { intro?: IntroPage | null; error?: string; errors?: string[] }; if (mine !== seq.current) return; if (r.ok) { setPage(j.intro ?? null); setProblems([]); } else setProblems(j.errors ?? [String(j.error ?? `HTTP ${r.status}`)]); } catch (e) { if (mine === seq.current) setProblems([e instanceof Error ? e.message : String(e)]); } finally { if (mine === seq.current) setComposing(false); } }, 350); return () => clearTimeout(t); // `key` is the value, serialised: a new object with the same knobs composes nothing. // eslint-disable-next-line react-hooks/exhaustive-deps }, [project, key]); const save = async () => { setBusy(true); setSaid(null); try { const r = await fetch("/api/report/render", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token, patch: { intro: value } }), }); const j = (await r.json().catch(() => ({}))) as { token?: string; error?: string; errors?: string[]; stale?: boolean }; if (!r.ok) { setSaid({ ok: false, text: j.stale ? "The manifest changed since this page read it — Revert reads it again." : (j.errors ?? [j.error ?? `HTTP ${r.status}`]).join("; ") }); return; } const next = await reload(); if (next) setDraft(draftOf(next.intro, c.styleDefault)); setSaid({ ok: true, text: value === null ? "Saved: the cut opens on no intro." : "Saved to the manifest." }); // The draft moved: the workspace's viewer and strip read it again (umtool redesign L7a). announceManifestChanged(project); } finally { setBusy(false); } }; const revert = async () => { const next = await reload(); setDraft(draftOf((next ?? state).intro, c.styleDefault)); setSaid(null); }; // A version's box shows the press at once; the reload after the write says what it is. const [pressed, setPressed] = useState>({}); const setVersion = async (take: string, on: boolean) => { setBusy(true); setSaid(null); setPressed((p) => ({ ...p, [take]: on })); try { const r = await fetch("/api/report/chrome/intro", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, take, on }), }); const j = (await r.json().catch(() => ({}))) as { error?: string }; if (!r.ok) setSaid({ ok: false, text: String(j.error ?? `HTTP ${r.status}`) }); await reload(); } finally { setPressed((p) => { const { [take]: _done, ...rest } = p; return rest; }); setBusy(false); } }; const card = draft.style === "title-card"; const savedHas = state.intro !== null && state.intro !== undefined; return (
set({ seconds: e.target.value })} /> set({ site: e.target.value })} />
{draft.sound === "file" && ( set({ soundFile: e.target.value })} /> )} set({ title: e.target.value })} />