"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "@/lib/report/excerptPick.mjs"; import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; // A POST ITEM (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item excerpt=…` and `posts narrate // --recording` by hand), with `block` the item's id: // THE EXCERPT select words of the post and Add them: the selection snapped to whole words, merged with the // spans already picked, settled where the build will find each one (excerptPick.mjs), saved as // `entry.excerpt` -- verbatim spans in the post's order, read joined with " … ", the card still // showing the whole post with the rest dimmed (POST /api/report/post-item {op: "set"}). // ITS MEDIA each attachment shown or not (off keeps it whole in `mediaOff` -- crop, blur, trim, sound -- and // on puts it back as it was; a file of the post the item never carried can be put on) and a video's // sound on or off. // MY RECORDING a sound file of your own read of it, kept as a recorded take and picked (the multipart POST // /api/report/post-narration: trimmed, levelled; `umtool posts narrate

--recording // --no-clean --no-convert` is the twin). type Range = { start: number; end: number }; type View = { id: string; post: string | null; author: string | null; handle: string | null; text: string; excerpt: string[] | null; ranges: Range[] | null; excerptErrors: string[]; media: { i: number; src: string | null; kind: string | null; mute: boolean; seconds: number | null; audio: boolean }[]; off: { j: number; src: string | null; kind: string | null }[]; files: string[]; narration: { takes: { i: number; file: string; engine: string | null; voice: string | null; seconds: number | null }[]; picked: number | null; off: boolean }; token: string | null; }; /** A (node, offset) of the selection as a character offset into `root`'s text. */ function offsetIn(root: HTMLElement, node: Node, off: number): number | null { if (!root.contains(node)) return null; const r = document.createRange(); r.selectNodeContents(root); r.setEnd(node, off); return r.toString().length; } export default function PostItemInspector({ project, block = null }: InspectorProps) { const router = useRouter(); const [view, setView] = useState(null); const [missing, setMissing] = useState(null); const [ranges, setRanges] = useState([]); const [busy, setBusy] = useState(false); const [said, setSaid] = useState(null); const [file, setFile] = useState(null); const textRef = useRef(null); const fileRef = useRef(null); const load = useCallback(async (reset = true) => { if (!block) return null; const { ok, j } = await call(`/api/report/post-item/inspector?${new URLSearchParams({ project, id: block }).toString()}`); if (!ok) { setMissing(j.error ?? "not a post item"); return null; } setMissing(null); setView(j); if (reset) setRanges(j.ranges ?? []); return j; }, [project, block]); useEffect(() => { void load(); }, [load]); useOnManifestChanged(project, () => load(false)); if (!block) return null; if (missing) return

{missing}

; if (!view) return null; const saved = view.ranges ?? []; const dirty = JSON.stringify(ranges) !== JSON.stringify(saved); const write = async (url: string, body: Record, ok: string) => { setBusy(true); setSaid(null); try { const r = await call(url, { method: "POST", body: JSON.stringify({ project, token: view.token, id: view.id, ...body }) }); if (!r.ok) { setSaid({ ok: false, text: refusal(r.j, r.status) }); if (r.j.stale) await load(); return false; } await load(); setSaid({ ok: true, text: ok }); announceManifestChanged(project); router.refresh(); return true; } finally { setBusy(false); } }; const addSelection = () => { const sel = window.getSelection(); const root = textRef.current; if (!sel || sel.rangeCount === 0 || !root) return; const range = sel.getRangeAt(0); const a = offsetIn(root, range.startContainer, range.startOffset); const b = offsetIn(root, range.endContainer, range.endOffset); if (a === null || b === null) { setSaid({ ok: false, text: "select words inside the post's text first" }); return; } const r = snapToWords(view.text, a, b); if (!r) { setSaid({ ok: false, text: "the selection holds no words" }); return; } setSaid(null); setRanges((rs) => settleRanges(view.text, addRange(rs, r))); sel.removeAllRanges(); }; const saveExcerpt = () => { const spans = spansOf(view.text, ranges); // The build's own rule, checked before the write: each span found where it was picked. const back = rangesOf(view.text, spans); if (spans.length && JSON.stringify(back) !== JSON.stringify(ranges)) { setSaid({ ok: false, text: "a span could not be placed where it was picked — clear and pick again" }); return; } void write("/api/report/post-item", { op: "set", patch: { excerpt: spans.length ? spans : null } }, spans.length ? `Excerpt saved to the draft: ${spans.length} span${spans.length === 1 ? "" : "s"}, read joined with " … ".` : "Excerpt cleared: the whole post is read."); }; const keepMyRecording = async () => { if (!file) return; setBusy(true); setSaid(null); try { const form = new FormData(); form.set("project", project); form.set("id", view.id); form.set("label", "operator"); form.append("part", file, file.name); form.append("text", (view.excerpt?.length ? view.excerpt.join(" … ") : view.text).slice(0, 4000)); form.append("para", "0"); form.set("note", `my recording (${file.name})`); const r = await fetch("/api/report/post-narration", { method: "POST", body: form }); const j = (await r.json().catch(() => ({}))) as { take?: { file: string; seconds?: number }; gain?: number; error?: string }; if (!r.ok || !j.take) { setSaid({ ok: false, text: j.error ?? `HTTP ${r.status}` }); return; } setFile(null); if (fileRef.current) fileRef.current.value = ""; await load(); announceManifestChanged(project); setSaid({ ok: true, text: `Kept as ${j.take.file}${typeof j.take.seconds === "number" ? ` (${j.take.seconds.toFixed(1)} s` : " ("}${typeof j.gain === "number" ? `, levelled ${j.gain >= 0 ? "+" : ""}${j.gain} dB)` : ")"} and picked.` }); router.refresh(); } finally { setBusy(false); } }; const pieces = piecesOf(view.text, ranges); const picked = view.narration.picked !== null ? view.narration.takes[view.narration.picked] : null; return (
excerpt — select words, then Add
{pieces.map((p) => p.picked ? ( {p.text} ) : ( {p.text} ), )}
{ranges.length > 0 && (
    {spansOf(view.text, ranges).map((s, i) => (
  1. “{s}”
  2. ))}
)} {view.excerptErrors.length > 0 &&

{view.excerptErrors.join("; ")}

}
media {view.media.length === 0 && view.off.length === 0 && view.files.length === 0 && no attachment} {view.media.map((m) => (
{m.kind === "video" && m.audio && ( )}
))} {view.off.map((m) => ( ))} {view.files.map((f) => ( ))}
my recording {view.narration.takes.length ? `${view.narration.takes.length} take${view.narration.takes.length === 1 ? "" : "s"}; plays ${picked ? `${picked.file.split("/").pop()}${picked.engine ? ` (${picked.engine})` : ""}` : "none"}` : "not narrated yet"} setFile(e.target.files?.[0] ?? null)} />
); }