import { useEffect, useState } from "react"; import { CREDENTIALS } from "../../apiContract"; type Evidence = { label: string; value: string }; type Draft = { status: "draft" | "fallback"; caseText: string; reason: string; evidence: Evidence[] }; type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: Draft }; const text = (value: unknown) => typeof value === "string" ? value : ""; const record = (value: unknown): Record => value && typeof value === "object" ? value as Record : {}; export default function CaseText({ itemId, url, onDenied }: { itemId: string; url: (path: string) => string; onDenied: () => void; }) { const [state, setState] = useState({ phase: "loading" }); const [attempt, setAttempt] = useState(0); const [copied, setCopied] = useState<"" | "done" | "failed">(""); useEffect(() => { const controller = new AbortController(); setState({ phase: "loading" }); setCopied(""); void fetch(url(`/items/${encodeURIComponent(itemId)}/case-text`), { credentials: CREDENTIALS, signal: controller.signal }) .then(async (response) => { if ((response.status === 403 || response.status === 404) && !controller.signal.aborted) onDenied(); const body = record(await response.json().catch(() => null)); if (!response.ok) { const error = record(body.error ?? record(body.detail).error); throw new Error(text(error.message) || "Case text could not be loaded."); } if ((body.status !== "draft" && body.status !== "fallback") || !text(body.caseText) || !Array.isArray(body.evidence) || !body.evidence.every((row: unknown) => text(record(row).label) && text(record(row).value))) { throw new Error("Case text could not be read."); } const value: Draft = { status: body.status, caseText: text(body.caseText), reason: text(body.reason), evidence: body.evidence.map((row: unknown) => ({ label: text(record(row).label), value: text(record(row).value) })) }; if (!controller.signal.aborted) setState({ phase: "ready", value }); }).catch((reason: unknown) => { if (!controller.signal.aborted) setState({ phase: "error", message: reason instanceof Error ? reason.message : "Case text could not be loaded." }); }); return () => controller.abort(); }, [itemId, url, onDenied, attempt]); const copy = async () => { if (state.phase !== "ready") return; try { await navigator.clipboard.writeText(state.value.caseText); setCopied("done"); } catch { setCopied("failed"); } }; return

Case text

{copied === "done" && Copied}
{state.phase === "loading" &&
} {state.phase === "error" &&

{state.message}{" "}

} {state.phase === "ready" && <> {state.value.status === "fallback" &&

Template

} {state.value.reason &&

{state.value.reason}

}
{state.value.caseText.split(/\n\s*\n/).map((paragraph, index) =>

{paragraph}

)}

Evidence

{state.value.evidence.map((row, index) =>
{row.label}
{row.value}
)}
} {copied === "failed" &&

Copy did not work. Select the text to copy it.

}
; }