Spaces:
Running

WorkPilot-AI / web /src /components /workflows /workflow-canvas.tsx
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
12.7 kB
"use client";
import "@xyflow/react/dist/style.css";
import {
Background,
Controls,
Handle,
Position,
ReactFlow,
type Node,
type NodeProps,
} from "@xyflow/react";
import {
ArrowDownIcon,
ArrowUpIcon,
ClockIcon,
PlusIcon,
ShieldCheckIcon,
Trash2Icon,
WrenchIcon,
ZapIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useI18n } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import {
addStep,
blankStep,
deleteStep,
moveStep,
toFlow,
TRIGGER_NODE_ID,
updateStep,
type StepKind,
type StepNodeData,
type TriggerNodeData,
} from "./dsl";
import type { CatalogTool, Condition, Step, WorkflowDefinition } from "./types";
type TriggerFlowNode = Node<TriggerNodeData, "trigger">;
type StepFlowNode = Node<StepNodeData, "step">;
function TriggerNode({ data }: NodeProps<TriggerFlowNode>) {
return (
<div
className="w-72 rounded-lg border-2 border-primary/40 bg-card px-3 py-2 text-xs shadow-sm"
data-testid="canvas-trigger"
>
<div className="flex items-center gap-1.5 font-medium text-primary">
<ZapIcon className="size-3.5" aria-hidden />
{data.trigger.type}
</div>
<p className="mt-1 text-muted-foreground" dir="ltr">
{data.label}
</p>
<Handle type="source" position={Position.Bottom} isConnectable={false} />
</div>
);
}
const KIND_ICON = { tool: WrenchIcon, wait: ClockIcon, approval: ShieldCheckIcon } as const;
function StepNode({ data, selected }: NodeProps<StepFlowNode>) {
const { m } = useI18n();
const Icon = KIND_ICON[data.kind];
const s = data.step;
return (
<div
className={cn(
"w-72 rounded-lg border bg-card px-3 py-2 text-xs shadow-sm transition-colors",
selected ? "border-primary ring-2 ring-primary/30" : "border-border",
)}
data-testid={`canvas-step-${s.id}`}
data-index={data.index}
>
<Handle type="target" position={Position.Top} isConnectable={false} />
<div className="flex items-center gap-1.5">
<Icon className="size-3.5 text-muted-foreground" aria-hidden />
<span className="font-mono font-semibold">{s.id}</span>
<span className="text-muted-foreground">· {m.workflows.kinds[data.kind]}</span>
{s.requires_approval && (
<Badge variant="outline" className="ms-auto border-warning/40 text-warning">
{m.workflows.needsSignoff}
</Badge>
)}
</div>
<div className="mt-1 space-y-0.5 font-mono text-[11px]" dir="ltr">
{data.kind === "tool" && <p className="truncate font-medium">{s.tool || "—"}</p>}
{data.kind === "wait" && <p>{s.wait?.seconds}s</p>}
{data.kind === "approval" && <p className="truncate">{s.approval?.summary}</p>}
{s.for_each && <p className="truncate text-info">for_each {s.for_each}</p>}
{data.conditions.map((c, i) => (
<p key={i} className="truncate text-muted-foreground">
if {c}
</p>
))}
</div>
<Handle type="source" position={Position.Bottom} isConnectable={false} />
</div>
);
}
const NODE_TYPES = { trigger: TriggerNode, step: StepNode };
/** JSON textarea that applies its value only when it parses. */
function JsonField({
id,
label,
value,
onValid,
testId,
}: {
id: string;
label: string;
value: unknown;
onValid: (v: unknown) => void;
testId?: string;
}) {
const { t } = useI18n();
const [text, setText] = useState(() => JSON.stringify(value ?? null, null, 2));
const [err, setErr] = useState<string | null>(null);
return (
<div className="space-y-1">
<Label htmlFor={id}>{label}</Label>
<Textarea
id={id}
data-testid={testId}
dir="ltr"
className="min-h-20 font-mono text-xs"
value={text}
onChange={(e) => {
setText(e.target.value);
try {
const v: unknown = JSON.parse(e.target.value);
setErr(null);
onValid(v);
} catch (ex) {
setErr(ex instanceof Error ? ex.message : String(ex));
}
}}
/>
{err && (
<p className="text-xs text-destructive" role="alert">
{t("workflows.jsonError")}: {err}
</p>
)}
</div>
);
}
function StepPanel({
defn,
index,
tools,
onChange,
onSelect,
}: {
defn: WorkflowDefinition;
index: number;
tools: CatalogTool[];
onChange: (d: WorkflowDefinition) => void;
onSelect: (i: number | null) => void;
}) {
const { t } = useI18n();
const step = defn.steps[index];
const kind = step.wait ? "wait" : step.approval ? "approval" : "tool";
const set = (patch: Partial<Step>) => onChange(updateStep(defn, index, patch));
const tool = tools.find((x) => x.name === step.tool);
return (
<div className="space-y-3" data-testid="step-panel">
<div className="flex items-center gap-1">
<p className="flex-1 text-sm font-medium">
{t("workflows.editStep")} {index + 1}
</p>
<Button
size="icon-sm"
variant="ghost"
aria-label={t("workflows.moveUp")}
disabled={index === 0}
onClick={() => {
onChange(moveStep(defn, index, -1));
onSelect(index - 1);
}}
>
<ArrowUpIcon aria-hidden />
</Button>
<Button
size="icon-sm"
variant="ghost"
aria-label={t("workflows.moveDown")}
disabled={index === defn.steps.length - 1}
onClick={() => {
onChange(moveStep(defn, index, 1));
onSelect(index + 1);
}}
>
<ArrowDownIcon aria-hidden />
</Button>
<Button
size="icon-sm"
variant="ghost"
aria-label={t("workflows.deleteStep")}
disabled={defn.steps.length <= 1}
onClick={() => {
onChange(deleteStep(defn, index));
onSelect(null);
}}
>
<Trash2Icon aria-hidden />
</Button>
</div>
<div className="space-y-1">
<Label htmlFor="wf-step-id">{t("workflows.stepId")}</Label>
<Input
id="wf-step-id"
dir="ltr"
className="font-mono"
value={step.id}
onChange={(e) => set({ id: e.target.value })}
/>
</div>
{kind === "tool" && (
<>
<div className="space-y-1">
<Label htmlFor="wf-step-tool">{t("workflows.tool")}</Label>
<Input
id="wf-step-tool"
dir="ltr"
className="font-mono"
list="wf-tool-list"
value={step.tool ?? ""}
onChange={(e) => set({ tool: e.target.value })}
/>
<datalist id="wf-tool-list">
{tools.map((x) => (
<option key={x.name} value={x.name}>
{x.description}
</option>
))}
</datalist>
{tool && (
<p className="text-xs text-muted-foreground">
T{tool.tier} · {tool.description}
</p>
)}
</div>
<JsonField
id="wf-step-args"
label={t("workflows.args")}
value={step.args ?? {}}
testId="step-args"
onValid={(v) =>
v && typeof v === "object" && !Array.isArray(v)
? set({ args: v as Record<string, unknown> })
: undefined
}
/>
<div className="space-y-1">
<Label htmlFor="wf-step-foreach">{t("workflows.forEach")}</Label>
<Input
id="wf-step-foreach"
dir="ltr"
className="font-mono"
placeholder="$.orders.items"
value={step.for_each ?? ""}
onChange={(e) => set({ for_each: e.target.value || undefined })}
/>
</div>
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={!!step.requires_approval}
onChange={(e) => set({ requires_approval: e.target.checked || undefined })}
/>
{t("workflows.requiresApproval")}
</label>
</>
)}
{kind === "wait" && (
<div className="space-y-1">
<Label htmlFor="wf-step-wait">{t("workflows.waitSeconds")}</Label>
<Input
id="wf-step-wait"
type="number"
min={1}
value={step.wait?.seconds ?? 60}
onChange={(e) => set({ wait: { seconds: Number(e.target.value) || 1 } })}
/>
</div>
)}
{kind === "approval" && (
<div className="space-y-1">
<Label htmlFor="wf-step-summary">{t("workflows.signoffSummary")}</Label>
<Input
id="wf-step-summary"
value={step.approval?.summary ?? ""}
onChange={(e) => set({ approval: { summary: e.target.value } })}
/>
</div>
)}
<JsonField
id="wf-step-when"
label={t("workflows.when")}
value={step.when ?? []}
onValid={(v) =>
Array.isArray(v) ? set({ when: v.length ? (v as Condition[]) : undefined }) : undefined
}
/>
</div>
);
}
/** Canvas view: trigger + one node per step, top to bottom; edits go through ``onChange``. */
export default function WorkflowCanvas({
defn,
tools,
onChange,
panelKey,
}: {
defn: WorkflowDefinition;
tools: CatalogTool[];
onChange: (d: WorkflowDefinition) => void;
/** Changes when the definition was replaced from outside the canvas (resets the panel). */
panelKey: number;
}) {
const { t } = useI18n();
const [selected, setSelected] = useState<number | null>(null);
const sel = selected !== null && selected < defn.steps.length ? selected : null;
const { nodes, edges } = useMemo(() => toFlow(defn, sel), [defn, sel]);
const add = (kind: StepKind) => {
const at = sel ?? defn.steps.length - 1;
onChange(addStep(defn, blankStep(defn, kind), at));
setSelected(at + 1);
};
return (
<div className="grid gap-4 lg:grid-cols-[1fr_20rem]" data-testid="workflow-canvas">
<div className="h-[32rem] overflow-hidden rounded-lg border bg-muted/20" dir="ltr">
<ReactFlow
nodes={nodes as Node[]}
edges={edges}
nodeTypes={NODE_TYPES}
nodesDraggable={false}
nodesConnectable={false}
elementsSelectable
fitView
proOptions={{ hideAttribution: true }}
onNodeClick={(_, node) => {
if (node.id === TRIGGER_NODE_ID) return setSelected(null);
setSelected((node.data as StepNodeData).index);
}}
onPaneClick={() => setSelected(null)}
>
<Background />
<Controls showInteractive={false} />
</ReactFlow>
</div>
<div className="space-y-4 rounded-lg border bg-card p-3">
<div className="flex flex-wrap gap-1.5">
<Button size="sm" variant="outline" onClick={() => add("tool")} data-testid="add-tool-step">
<PlusIcon aria-hidden /> {t("workflows.kinds.tool")}
</Button>
<Button size="sm" variant="outline" onClick={() => add("wait")}>
<PlusIcon aria-hidden /> {t("workflows.kinds.wait")}
</Button>
<Button size="sm" variant="outline" onClick={() => add("approval")}>
<PlusIcon aria-hidden /> {t("workflows.kinds.approval")}
</Button>
</div>
{sel === null ? (
<p className="text-sm text-muted-foreground">{t("workflows.selectStep")}</p>
) : (
<StepPanel
key={`${panelKey}:${sel}`}
defn={defn}
index={sel}
tools={tools}
onChange={onChange}
onSelect={setSelected}
/>
)}
</div>
</div>
);
}