394 lines
20 KiB
TypeScript
394 lines
20 KiB
TypeScript
"use client";
|
||
|
||
import { useWords } from "@/components/Words";
|
||
import Link from "next/link";
|
||
import { useRouter } from "next/navigation";
|
||
import { useEffect, useState, useTransition } from "react";
|
||
import { useLiveIsland } from "@/lib/live";
|
||
import { ChevronDown, ChevronRight, ChevronsDown, ChevronsUp, Lock } from "lucide-react";
|
||
import { moveTaskCard, proposalAction } from "@/app/(app)/actions";
|
||
import { reorderTaskInline } from "@/app/(app)/board-actions";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { AgentBadge } from "@/components/AgentBadge";
|
||
import { cn } from "@/lib/utils";
|
||
import { useT } from "@/components/I18n";
|
||
import { m } from "@peppa/shared/i18n";
|
||
|
||
export type Column = "backlog" | "in_progress" | "review" | "done";
|
||
export interface Card {
|
||
key: string;
|
||
/** PEP-197: the task id (the buttons of «Предложено» send ids). */
|
||
id?: number;
|
||
title: string;
|
||
status: string;
|
||
column: Column;
|
||
/** Epic label (PEP-66), if the story has an open epic. */
|
||
epic?: string | null;
|
||
/** tasks.md progress of a story in work (PEP-33). */
|
||
progress?: CardProgress | null;
|
||
/** PEP-42: "ждёт PEP-3" while a predecessor isn't in review/done. */
|
||
blocked?: string | null;
|
||
/** PEP-75: the persona working on the story right now. */
|
||
agent?: string | null;
|
||
/** PEP-84 / PEP-198: the analyst still holds the story ("уточняется" / "ждёт ваших ответов"). */
|
||
refining?: string | null;
|
||
/** PEP-127: accepted over a conflict — the agent updates the changes, the story closes by itself. */
|
||
accepted?: string | null;
|
||
/** PEP-278: accepted, the version with the changes is not running yet. */
|
||
rollout?: string | null;
|
||
/** PEP-150: a delay on the platform's side — nothing is needed from the owner. */
|
||
delayed?: string | null;
|
||
/** PEP-247: in work without an agent for a lawful reason (pause, no subscription, budget). */
|
||
hold?: string | null;
|
||
/** PEP-182: place in the queue for a free agent (in work, no agent yet). */
|
||
queued?: number | null;
|
||
/** PEP-197: a story of an agent the owner has not decided on — shown in «Предложено», not in the backlog. */
|
||
proposed?: boolean;
|
||
/** PEP-197: «Поломка» / «Важно» / «Мелочь» on stories of the acceptance agent. */
|
||
severity?: "breakage" | "important" | "minor" | null;
|
||
/** PEP-197: made by an agent, not by a person. */
|
||
agentMade?: boolean;
|
||
}
|
||
export interface CardProgress {
|
||
done: number;
|
||
total: number;
|
||
current: string | null;
|
||
}
|
||
|
||
/** «7/12» bar and the item the agent is on (PEP-33). */
|
||
export function ProgressLine({ p, className }: { p: CardProgress; className?: string }) {
|
||
const t = useT();
|
||
const w = useWords();
|
||
const pct = p.total ? Math.round((p.done / p.total) * 100) : 0;
|
||
return (
|
||
<div className={cn("flex min-w-0 flex-col gap-1", className)} title={p.current ? t("Сейчас: {item}", { item: p.current }) : w.engineer ? t("Все пункты tasks.md выполнены") : t("Все шаги плана выполнены")}>
|
||
<div className="flex items-center gap-2">
|
||
<div className="h-1 flex-1 overflow-hidden rounded-full bg-muted">
|
||
<div className="h-full rounded-full bg-info" style={{ width: `${pct}%` }} />
|
||
</div>
|
||
<span className="font-mono text-[11px] text-muted-foreground tabular-nums">
|
||
{p.done}/{p.total}
|
||
</span>
|
||
</div>
|
||
{p.current && <span className="truncate text-[11px] text-muted-foreground">{p.current}</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const DONE_COLLAPSED = "peppa.board.doneCollapsed";
|
||
|
||
const COLUMNS: Array<{ id: Column; title: string; hint: string; dot: string }> = [
|
||
{ id: "backlog", title: m("Бэклог"), hint: "", dot: "bg-muted-foreground" },
|
||
{ id: "in_progress", title: m("В работе"), hint: m("сюда — запустить агента"), dot: "bg-info" },
|
||
{ id: "review", title: m("Ревью"), hint: "", dot: "bg-ok" },
|
||
{ id: "done", title: m("Готово"), hint: "", dot: "bg-ok" },
|
||
];
|
||
const STATUS: Record<string, { label: string; tone: "primary" | "danger" | "info" }> = {
|
||
proposing: { label: m("план"), tone: "primary" },
|
||
awaiting_approval: { label: m("ждёт PM"), tone: "primary" },
|
||
blocked: { label: m("блок"), tone: "danger" },
|
||
in_progress: { label: m("агент"), tone: "info" },
|
||
};
|
||
const NEXT: Partial<Record<Column, { to: Column; label: string }>> = {
|
||
backlog: { to: "in_progress", label: m("В работу →") },
|
||
review: { to: "done", label: m("Принять ✓") },
|
||
};
|
||
|
||
/**
|
||
* Story board: drag a card to another column (or use its button) to move it — the server
|
||
* starts/stops agents; drag it onto a card of its own column to change the order (= priority
|
||
* for the dispatcher, PEP-34). «Готово» can be collapsed (remembered in the browser).
|
||
*/
|
||
export function Board({ cards: server, back }: { cards: Card[]; back: string }) {
|
||
// PEP-225: status and title changes from the live channel apply in place — a card moves to the
|
||
// column of its new status at once; fresh server data (a re-render) replaces the patches.
|
||
const [patches, setPatches] = useState<Map<number, Pick<Card, "status" | "title" | "column">>>(() => new Map());
|
||
useEffect(() => setPatches(new Map()), [server]);
|
||
const cards = patches.size ? server.map((c) => (c.id != null && patches.has(c.id) ? { ...c, ...patches.get(c.id)! } : c)) : server;
|
||
useLiveIsland((e) => {
|
||
if (!e.tasks?.length) return [];
|
||
const byId = new Map(server.map((c) => [c.id, c]));
|
||
const next: Array<[number, Pick<Card, "status" | "title" | "column">]> = [];
|
||
let all = true;
|
||
for (const r of e.tasks) {
|
||
// A new story, one outside the epic filter, or a change of its epic/order/«Предложено» — the server re-renders.
|
||
if (!byId.has(r.id) || r.other) all = false;
|
||
else next.push([r.id, { status: r.status, title: r.title, column: r.column }]);
|
||
}
|
||
if (next.length) setPatches((cur) => new Map([...cur, ...next]));
|
||
return all ? ["t"] : [];
|
||
});
|
||
const w = useWords();
|
||
const router = useRouter();
|
||
const t = useT();
|
||
const [pending, start] = useTransition();
|
||
const [over, setOver] = useState<Column | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [doneCollapsed, setDoneCollapsed] = useState(false);
|
||
useEffect(() => {
|
||
try {
|
||
setDoneCollapsed(localStorage.getItem(DONE_COLLAPSED) === "1");
|
||
} catch {}
|
||
}, []);
|
||
const toggleDone = () => {
|
||
setDoneCollapsed((v) => {
|
||
try {
|
||
localStorage.setItem(DONE_COLLAPSED, v ? "0" : "1");
|
||
} catch {}
|
||
return !v;
|
||
});
|
||
};
|
||
const move = (key: string, to: Column) => {
|
||
const f = new FormData();
|
||
f.set("taskKey", key);
|
||
f.set("to", to);
|
||
f.set("back", back);
|
||
start(() => moveTaskCard(f));
|
||
};
|
||
const reorder = (key: string, to: "top" | "bottom" | "before" | "after", other?: string) =>
|
||
start(async () => {
|
||
setError(await reorderTaskInline(key, to, other));
|
||
router.refresh();
|
||
});
|
||
return (
|
||
<div className="flex flex-col gap-2">
|
||
<Proposed cards={cards.filter((x) => x.proposed)} back={back} />
|
||
{error && (
|
||
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-1.5 text-sm text-destructive">
|
||
{t.text(error)}
|
||
</p>
|
||
)}
|
||
<div className={cn("grid gap-3 sm:grid-cols-2 lg:grid-cols-4", pending && "pointer-events-none opacity-60")}>
|
||
{COLUMNS.map((c) => {
|
||
const list = cards.filter((x) => x.column === c.id && !x.proposed);
|
||
const collapsed = c.id === "done" && doneCollapsed;
|
||
return (
|
||
<section
|
||
key={c.id}
|
||
data-column={c.id}
|
||
aria-label={t(c.title)}
|
||
className={cn("flex min-h-32 flex-col gap-2 rounded-lg border bg-muted/40 p-2", over === c.id && "border-dashed border-primary bg-primary/5", collapsed && "min-h-0")}
|
||
onDragOver={(e) => {
|
||
e.preventDefault();
|
||
setOver(c.id);
|
||
}}
|
||
onDragLeave={() => setOver(null)}
|
||
onDrop={(e) => {
|
||
e.preventDefault();
|
||
setOver(null);
|
||
const key = e.dataTransfer.getData("text/plain");
|
||
const card = cards.find((x) => x.key === key);
|
||
if (!card) return;
|
||
if (card.column !== c.id) move(key, c.id);
|
||
else if (list.at(-1)?.key !== key) reorder(key, "bottom"); // empty space of its own column: to the end
|
||
}}
|
||
>
|
||
<h3 className="m-0 flex items-center gap-2 px-1.5 pt-1 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
|
||
<span className={cn("size-1.5 rounded-full", c.dot)} />
|
||
{t(c.title)}
|
||
<span className="ml-auto tabular-nums">{list.length}</span>
|
||
{c.id === "done" && (
|
||
<button type="button" onClick={toggleDone} aria-expanded={!collapsed} aria-label={collapsed ? t("Развернуть «Готово»") : t("Свернуть «Готово»")} className="-mr-1 rounded p-0.5 hover:bg-muted hover:text-foreground">
|
||
{collapsed ? <ChevronRight className="size-3.5" /> : <ChevronDown className="size-3.5" />}
|
||
</button>
|
||
)}
|
||
</h3>
|
||
{!collapsed && c.hint && <p className="m-0 px-1.5 text-[11px] text-muted-foreground">{t(c.hint)}</p>}
|
||
{!collapsed &&
|
||
list.map((card, i) => (
|
||
<article
|
||
key={card.key}
|
||
draggable
|
||
data-task-key={card.key}
|
||
onDragStart={(e) => e.dataTransfer.setData("text/plain", card.key)}
|
||
onDrop={(e) => {
|
||
const key = e.dataTransfer.getData("text/plain");
|
||
const dragged = cards.find((x) => x.key === key);
|
||
if (!dragged || dragged.column !== c.id) return; // another column: the section moves it
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
setOver(null);
|
||
if (key === card.key) return;
|
||
const r = e.currentTarget.getBoundingClientRect();
|
||
reorder(key, e.clientY < r.top + r.height / 2 ? "before" : "after", card.key);
|
||
}}
|
||
className="group flex cursor-grab flex-col gap-2 rounded-md border bg-card p-2.5 text-sm shadow-xs transition-colors hover:border-primary/40 active:cursor-grabbing"
|
||
>
|
||
<div className="flex items-start gap-1">
|
||
<Link href={`/t/${card.key}`} className="min-w-0 flex-1 text-foreground hover:no-underline">
|
||
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
|
||
</Link>
|
||
{list.length > 1 && (
|
||
<span className="flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 max-sm:opacity-100">
|
||
{i > 0 && (
|
||
<button type="button" title={t("Наверх")} aria-label={t("{key} наверх", { key: card.key })} disabled={pending} onClick={() => reorder(card.key, "top")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||
<ChevronsUp className="size-3.5" />
|
||
</button>
|
||
)}
|
||
{i < list.length - 1 && (
|
||
<button type="button" title={t("Вниз")} aria-label={t("{key} вниз", { key: card.key })} disabled={pending} onClick={() => reorder(card.key, "bottom")} className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground">
|
||
<ChevronsDown className="size-3.5" />
|
||
</button>
|
||
)}
|
||
</span>
|
||
)}
|
||
</div>
|
||
{card.refining && (
|
||
<Badge variant="info" className="self-start" title={t("Аналитик уточняет задачу; агент-разработчик возьмёт её после этого")}>
|
||
{t.text(card.refining)}
|
||
</Badge>
|
||
)}
|
||
{card.accepted && (
|
||
<Badge variant="ok" className="self-start whitespace-normal text-left">
|
||
{card.accepted}
|
||
</Badge>
|
||
)}
|
||
{card.rollout && (
|
||
<Badge variant="info" className="self-start whitespace-normal text-left" data-rollout>
|
||
{card.rollout}
|
||
</Badge>
|
||
)}
|
||
{card.delayed && (
|
||
<Badge variant="muted" className="self-start whitespace-normal text-left">
|
||
{card.delayed}
|
||
</Badge>
|
||
)}
|
||
{card.hold && (
|
||
<Badge variant="warn" className="self-start whitespace-normal text-left" data-hold>
|
||
{card.hold}
|
||
</Badge>
|
||
)}
|
||
{card.queued != null && (
|
||
<Badge variant="muted" className="self-start whitespace-normal text-left" data-queued={card.queued}>
|
||
{t("В очереди: {n}-я, начнётся, когда освободится агент", { n: card.queued })}
|
||
</Badge>
|
||
)}
|
||
{card.severity === "breakage" && !card.proposed && (
|
||
<Badge variant="danger" className="self-start" data-severity="breakage">
|
||
{t("Поломка")}
|
||
</Badge>
|
||
)}
|
||
{card.agent && <AgentBadge name={card.agent} className="text-muted-foreground" />}
|
||
{card.progress && <ProgressLine p={card.progress} />}
|
||
{(STATUS[card.status] || NEXT[c.id] || card.epic || card.blocked) && (
|
||
<div className="flex flex-wrap items-center gap-1.5">
|
||
{card.blocked && (
|
||
<Badge variant="warn" title={w.engineer ? t("Диспетчер не возьмёт стори, пока предшественники не в ревью или готово") : t("Агенты возьмут эту задачу, когда будут готовы задачи, от которых она зависит")}>
|
||
<Lock className="size-3" />
|
||
{t.text(card.blocked)}
|
||
</Badge>
|
||
)}
|
||
{card.epic && (
|
||
<Badge variant="outline" className="max-w-full min-w-0" title={t("Эпик: {name}", { name: card.epic })}>
|
||
<span className="shrink-0 text-muted-foreground">{t("эпик")}</span>
|
||
<span className="truncate">{card.epic}</span>
|
||
</Badge>
|
||
)}
|
||
{STATUS[card.status] && <Badge variant={STATUS[card.status]!.tone}>{t(STATUS[card.status]!.label)}</Badge>}
|
||
{NEXT[c.id] && (
|
||
<Button size="xs" className="ml-auto" disabled={pending} onClick={() => move(card.key, NEXT[c.id]!.to)}>
|
||
{t(NEXT[c.id]!.label)}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
)}
|
||
</article>
|
||
))}
|
||
</section>
|
||
);
|
||
})}
|
||
</div>
|
||
<p className="m-0 text-xs text-muted-foreground">{w.engineer ? t("Порядок в колонке — приоритет: перетащите карточку выше или ниже; диспетчер берёт стори из бэклога сверху.") : t("Порядок в колонке — приоритет: перетащите карточку выше или ниже; агенты берут задачи из бэклога сверху.")}</p>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const SEVERITY: Record<string, { label: string; variant: "danger" | "warn" | "muted" }> = {
|
||
breakage: { label: m("Поломка"), variant: "danger" },
|
||
important: { label: m("Важно"), variant: "warn" },
|
||
minor: { label: m("Мелочь"), variant: "muted" },
|
||
};
|
||
|
||
/**
|
||
* PEP-197: «Предложено» — what the factory suggests on its own. Folded, with a counter; the
|
||
* dispatcher takes nothing from here. «Делать» sends a story to the backlog, «Не надо» archives
|
||
* it and the acceptance agent will not suggest it again. Buttons are at least 44 px for a thumb.
|
||
*/
|
||
function Proposed({ cards, back }: { cards: Card[]; back: string }) {
|
||
const t = useT();
|
||
if (!cards.length) return null;
|
||
const ids = cards.map((c) => c.id).join(",");
|
||
const important = cards.filter((c) => c.severity !== "minor");
|
||
return (
|
||
<details id="proposed" data-proposed className="rounded-lg border border-dashed bg-muted/30 p-2">
|
||
<summary className="flex min-h-11 cursor-pointer items-center gap-2 px-1.5 font-mono text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
|
||
{t("Предложено")}
|
||
<span className="ml-auto tabular-nums">{cards.length}</span>
|
||
</summary>
|
||
<p className="m-0 px-1.5 pb-2 text-xs text-muted-foreground">{t("Это придумала сама фабрика. Пока вы не нажмёте «Делать», агенты за эти задачи не возьмутся.")}</p>
|
||
<div className="flex flex-col gap-2">
|
||
{cards.map((card) => (
|
||
<article key={card.key} data-task-key={card.key} className="flex flex-col gap-2 rounded-md border bg-card p-2.5 text-sm">
|
||
<Link href={`/t/${card.key}`} className="text-foreground hover:no-underline">
|
||
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
|
||
</Link>
|
||
{card.severity && SEVERITY[card.severity] && (
|
||
<Badge variant={SEVERITY[card.severity]!.variant} className="self-start">
|
||
{t(SEVERITY[card.severity]!.label)}
|
||
</Badge>
|
||
)}
|
||
<form action={proposalAction} className="flex flex-wrap gap-2">
|
||
<input type="hidden" name="ids" value={String(card.id)} />
|
||
<input type="hidden" name="back" value={back} />
|
||
<ProposalButtons />
|
||
</form>
|
||
</article>
|
||
))}
|
||
</div>
|
||
{cards.length > 1 && (
|
||
// PEP-209: several small fixes of one page become one story — fewer stories to accept.
|
||
<form action={proposalAction} className="mt-2 flex flex-col gap-1.5 rounded-md border bg-card p-2.5 text-sm" data-proposed-merge>
|
||
<span className="text-xs text-muted-foreground">{t("Отметьте мелкие правки одной страницы — фабрика сделает их одной задачей:")}</span>
|
||
{cards.map((card) => (
|
||
<label key={card.key} className="flex min-h-11 items-center gap-2">
|
||
<input type="checkbox" name="pick" value={card.id} className="size-5" />
|
||
<span className="font-mono text-xs text-primary">{card.key}</span> {card.title}
|
||
</label>
|
||
))}
|
||
<input type="hidden" name="back" value={back} />
|
||
<Button size="sm" name="choice" value="merge" className="min-h-11 self-start">
|
||
{t("Объединить в одну")}
|
||
</Button>
|
||
</form>
|
||
)}
|
||
<form action={proposalAction} className="mt-2 flex flex-wrap gap-2">
|
||
<input type="hidden" name="ids" value={ids} />
|
||
<input type="hidden" name="back" value={back} />
|
||
{important.length > 0 && (
|
||
<Button size="sm" name="choice" value="important" className="min-h-11">
|
||
{t("Делать важные")}
|
||
</Button>
|
||
)}
|
||
<Button size="sm" variant="outline" name="choice" value="none" className="min-h-11">
|
||
{t("Отклонить всё")}
|
||
</Button>
|
||
</form>
|
||
</details>
|
||
);
|
||
}
|
||
|
||
function ProposalButtons() {
|
||
const t = useT();
|
||
return (
|
||
<>
|
||
<Button size="sm" name="choice" value="do" className="min-h-11 min-w-11">
|
||
{t("Делать")}
|
||
</Button>
|
||
<Button size="sm" variant="outline" name="choice" value="no" className="min-h-11 min-w-11">
|
||
{t("Не надо")}
|
||
</Button>
|
||
</>
|
||
);
|
||
}
|