"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { jobsHref, openInDraftHref } from "@/lib/hrefs";
import { cn } from "@/lib/utils";
import PlayLink from "./PlayLink";
// ---------------------------------------------------------------------------
// A TAKE's TOOLS that were terminal-only (slice C, 4 Nov), on its card and its
// walk (lane/ui-simplify, 5 Nov). Each is one POST /api/report/takes/tools,
// which runs the CLI's own function with --json:
//
// Check before render umtool lint
--take
// New draft from this take umtool take --id -d --draft --from
// Add items from another umtool timeline import-item : [--after|--before ]
// project (the Cut tab) [--dry-run]: INTO THE DRAFT (L3: every edit lands there; E1, 9 Nov) --
// Preview shows the plan, Import does it
// ---------------------------------------------------------------------------
type Tools = { exit: number; report: Record | null; said?: string; id?: string; error?: string };
async function tool(body: Record): Promise {
const r = await fetch("/api/report/takes/tools", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), cache: "no-store" });
const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as Tools;
if (!r.ok && j.exit === undefined) return { exit: 1, report: null, error: j.error ?? `HTTP ${r.status}` };
return j;
}
/** Check before render: the manifest lint (and the files the posts name) on the take, or on the project's cut. */
export function LintButton({ project, take = null, className }: { project: string; take?: string | null; className?: string }) {
const [busy, setBusy] = useState(false);
const [res, setRes] = useState(null);
const rep = res?.report as { ok?: boolean; errors?: string[]; warnings?: string[]; entries?: number } | null | undefined;
return (
(setBusy(true), void tool({ project, take, op: "lint" }).then((r) => (setRes(r), setBusy(false))))} className={buttonVariants({ variant: "outline", size: "sm" })} title={`umtool lint ${project}${take ? ` --take ${take}` : ""}`}>
{busy ? "Checking…" : "Check before render"}
{res && (res.error || !rep) && {res.error ?? res.said ?? "the check said nothing"} }
{rep && (
{rep.ok ? `✓ ready to render · ${rep.entries ?? 0} entries` : `✕ ${rep.errors?.length ?? 0} error${rep.errors?.length === 1 ? "" : "s"}`}
{(rep.warnings?.length ?? 0) > 0 && ` · ${rep.warnings!.length} warning${rep.warnings!.length === 1 ? "" : "s"}`}
)}
{rep && ((rep.errors?.length ?? 0) > 0 || (rep.warnings?.length ?? 0) > 0) && (
{(rep.errors ?? []).map((e, i) => (
{e}
))}
{(rep.warnings ?? []).slice(0, 8).map((w, i) => (
{w}
))}
)}
);
}
/** New draft from this take: its style and patch, a timeline of its own to walk and edit. */
export function DraftFromButton({ project, take }: { project: string; take: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const [res, setRes] = useState(null);
const go = async () => {
setBusy(true);
const r = await tool({ project, take, op: "draft-from" });
setRes(r);
setBusy(false);
if (r.exit === 0) router.refresh();
};
return (
void go()} className={buttonVariants({ variant: "outline", size: "sm" })} title={`umtool take ${project} --id ${take}-d --draft --from ${take}`}>
New draft from this take
{res?.exit === 0 && res.id && (
draft {res.id} :{" "}
{" "}
·{" "}
Open in draft
)}
{res && res.exit !== 0 && {res.error ?? res.said ?? "refused"} }
);
}
type Entry = { id: string; type: string; words?: string };
/** Add items from another project: cloned into the DRAFT, their files hard-linked in; Preview first. */
export function ImportItems({ project }: { project: string }) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [source, setSource] = useState("");
const [items, setItems] = useState("");
const [where, setWhere] = useState<"auto" | "after" | "before">("auto");
const [anchor, setAnchor] = useState("");
const [entries, setEntries] = useState([]);
const [projects, setProjects] = useState([]);
const [busy, setBusy] = useState(false);
const [plan, setPlan] = useState(null);
const [done, setDone] = useState(null);
useEffect(() => {
if (!open) return;
// The draft's entries as Play reads them: where an item lands.
void fetch(`/api/report/play-view?${new URLSearchParams({ project })}`, { cache: "no-store" })
.then((r) => r.json())
.then((j) => setEntries(Array.isArray(j.entries) ? (j.entries as { id: string; type: string; heading?: string }[]).map((e) => ({ id: e.id, type: e.type, words: e.heading })) : []))
.catch(() => {});
void fetch("/api/jump", { cache: "no-store" })
.then((r) => r.json())
.then((j) => setProjects(((j.pieces ?? []) as { id: string; kind: string }[]).filter((p) => p.kind === "project" && p.id.startsWith("p:")).map((p) => p.id.slice(2))))
.catch(() => {});
}, [open, project]);
const refs = items.trim() ? `${source.trim()}:${items.replace(/\s+/g, "")}` : "";
const run = async (dryRun: boolean) => {
setBusy(true);
const r = await tool({ project, op: "import", refs, ...(where === "after" && anchor ? { after: anchor } : where === "before" && anchor ? { before: anchor } : {}), dryRun });
setBusy(false);
if (dryRun) {
setPlan(r);
setDone(null);
} else {
setDone(r);
setPlan(null);
if (r.exit === 0) router.refresh();
}
};
const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal";
const rows = (t: Tools | null) => ((t?.report as { items?: { id: string; action: string; at?: { index?: number; after?: string | null; before?: string | null } }[] } | null)?.items ?? []);
return (
setOpen((o) => !o)} className={cn(buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" }), "self-start")}>
Add items from another project
{open && (
setSource(e.target.value)} placeholder="project (e.g. emberparadox/mr-obvious-unhinged)" className={cn(input, "w-72 font-mono")} />
{projects.filter((p) => p !== project).map((p) => (
))}
setItems(e.target.value)} placeholder="item ids, comma-separated" className={cn(input, "w-64 font-mono")} />
setWhere(e.target.value as typeof where)} className={input}>
by date (else at the end)
after
before
{where !== "auto" && (
setAnchor(e.target.value)} className={cn(input, "max-w-64")}>
(pick an entry)
{entries.map((e, i) => (
{i + 1}. {e.id}
{e.words ? ` · ${e.words.slice(0, 30)}` : ""}
))}
)}
void run(true)} className={buttonVariants({ variant: "outline", size: "sm" })}>
Preview
void run(false)} className={buttonVariants({ variant: "go", size: "sm" })}>
Import into the draft
)}
{[plan, done].map((t, k) =>
t ? (
{t.exit !== 0 ? (
{t.error ?? t.said ?? "refused"}
) : (
<>
{k === 0 ? "would do: " : "done: "}
{rows(t).map((r) => (
{r.id} {r.action}
{r.at?.after ? ` after ${r.at.after}` : r.at?.before ? ` before ${r.at.before}` : typeof r.at?.index === "number" ? ` at ${r.at.index}` : ""}
))}
>
)}
) : null,
)}
);
}
/** Check the joins of a rendered take (umtool check-joins), queued: its table is the step's log on Jobs. */
export function CheckJoinsButton({ project, take }: { project: string; take: string }) {
const [busy, setBusy] = useState(false);
const [res, setRes] = useState<(Tools & { queued?: string }) | null>(null);
return (
(setBusy(true), void tool({ project, take, op: "queue-check-joins" }).then((r) => (setRes(r), setBusy(false))))} className={buttonVariants({ variant: "outline", size: "sm" })} title={`umtool check-joins ${project} --take ${take}, as a queue step`}>
Check the joins
{res?.queued && (
queued {res.queued} —{" "}
its table on Jobs
)}
{res && !res.queued && {res.error ?? res.said ?? "refused"} }
);
}
/**
* The take's tools, as a take card's row. Add items from another project is the draft's now (the Cut tab):
* a take is not edited in place (L3).
*/
export default function TakeTools({ project, take, rendered = false }: { project: string; take: string; rendered?: boolean }) {
return (
{rendered && }
);
}