Files
archie/ui/src/workflows/WorkflowCanvas.vue
T

353 lines
15 KiB
Vue

<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { VueFlow, type NodeMouseEvent, type VueFlowStore } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
import { Controls } from "@vue-flow/controls";
import { usePreferredReducedMotion, useTransition } from "@vueuse/core";
import { ArrowDown, ArrowUp, Copy, Pencil, RotateCcw, Trash2 } from "@lucide/vue";
import "@vue-flow/core/dist/style.css";
import "@vue-flow/controls/dist/style.css";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import AddNode from "./AddNode.vue";
import InsertEdge from "./InsertEdge.vue";
import StepNode, { type StepCardData } from "./StepNode.vue";
import StepTypeItems from "./StepTypeItems.vue";
import { inParallel, type StepPath } from "./workflow-edit";
import LaneNode from "./LaneNode.vue";
import { restartAt, stepTitle, withRuns, workflowGraph, type GraphNode, type StageRun, type StepNodeData } from "./workflow-graph";
import type { WorkflowTrigger } from "./workflow-triggers";
const props = defineProps<{
yaml: string;
stages?: StageRun[];
/** The card open in place: "workflow", "start", or a step's path as JSON. */
open?: string | null;
triggers?: WorkflowTrigger[];
/** Step type names; when given, the canvas offers editing. */
types?: string[];
/** The watched run is parked, so its steps offer to restart it. */
restartable?: boolean;
/** Steps that differ from the definition being compared, by node id. */
marks?: Record<string, "added" | "removed" | "changed">;
/** What is wrong with each step, by its path as JSON. */
problems?: Record<string, string>;
/** The workflow card's title and one-line summary. */
title?: string;
summary?: string;
}>();
const emit = defineEmits<{
toggle: [key: string];
insert: [after: StepPath, type: string];
duplicate: [StepPath];
move: [StepPath, -1 | 1];
remove: [StepPath];
rename: [StepPath, string];
restart: [from: string];
}>();
const NODE_WIDTH = 240;
const OPEN_WIDTH = 416;
const TOP = -140;
const editable = computed(() => !!props.types?.length);
const types = computed(() => [...(props.types ?? []), "parallel", "switch"]);
const branchTypes = computed(() => types.value.filter((type) => ["agent.run", "workflow.call"].includes(type)));
const typesAt = (path?: StepPath) => (path && inParallel(path) ? branchTypes.value : types.value);
const keyOf = (data: StepNodeData) => (data.kind === "step" ? JSON.stringify(data.path ?? null) : data.kind);
const container = ref<HTMLElement | null>(null);
const graph = computed(() => {
const laid = withRuns(workflowGraph(props.yaml), props.stages ?? []);
if (!editable.value) return laid;
// Workflow-wide settings sit on a card above the trigger.
const workflow: GraphNode = { id: "workflow", type: "step", position: { x: 0, y: TOP }, data: { kind: "workflow", key: "workflow", title: props.title || "Workflow", type: "", detail: props.summary ?? "" } };
return { nodes: [workflow, ...laid.nodes], edges: [{ id: "flow-workflow-start", source: "workflow", target: "start", kind: "flow" as const }, ...laid.edges] };
});
const stepCount = computed(() => graph.value.nodes.filter((node) => node.data.path?.length === 2).length);
// Rows are laid out for cards BASE tall. A taller card pushes everything below
// it down by the difference, measured rather than guessed, and an open card
// grows where it sits while the cards below slide down with it.
const BASE = 72;
const heights = ref<Record<string, number>>({});
const closedHeights = ref<Record<string, number>>({});
const anchor = computed(() => graph.value.nodes.find((node) => node.type === "step" && keyOf(node.data) === props.open));
function resized(id: string, height: number): void {
heights.value = { ...heights.value, [id]: height };
if (anchor.value?.id !== id) closedHeights.value = { ...closedHeights.value, [id]: height };
}
const growth = computed(() => {
const id = anchor.value?.id;
return id && heights.value[id] ? Math.max(0, heights.value[id] - (closedHeights.value[id] ?? heights.value[id])) : 0;
});
const motion = usePreferredReducedMotion();
const shift = useTransition(growth, { duration: computed(() => (motion.value === "reduce" ? 0 : 200)) });
const rows = computed(() => {
const excess = new Map<number, number>();
for (const node of graph.value.nodes) {
if (node.type !== "step") continue;
const height = (node.id === anchor.value?.id ? closedHeights.value[node.id] : undefined) ?? heights.value[node.id];
if (height !== undefined) excess.set(node.position.y, Math.max(excess.get(node.position.y) ?? -BASE, height - BASE));
}
return [...excess];
});
const pushed = (y: number) => rows.value.reduce((sum, [row, excess]) => (row < y ? sum + excess : sum), 0);
function card(node: GraphNode): GraphNode {
const data = node.data;
const key = keyOf(data);
const path = data.path;
const extra: Partial<StepCardData> = {
triggers: data.kind === "start" ? (props.triggers ?? []) : data.triggers,
expanded: key === props.open,
editable: editable.value,
problem: path ? props.problems?.[key] : undefined,
onResize: (height: number) => resized(node.id, height),
};
if (editable.value) {
extra.onToggle = () => emit("toggle", key);
if (path) {
extra.onRename = (name: string) => emit("rename", path, name);
extra.onDuplicate = () => emit("duplicate", path);
extra.onRemove = () => emit("remove", path);
}
}
return { ...node, data: { ...data, ...extra } };
}
const nodes = computed(() => {
const open = anchor.value;
return graph.value.nodes.map((node) => {
const original = node;
if (node.type === "add")
node = { ...node, data: { ...node.data, types: typesAt(node.data.insertAfter), editable: editable.value, onInsert: (type: string) => emit("insert", node.data.insertAfter!, type) } as StepNodeData };
else if (node.type === "step") node = card(node);
const mark = props.marks?.[node.id];
if (mark) node = { ...node, data: { ...node.data, mark } };
const { x } = node.position;
const opened = (at: number) => (open && at > open.position.y ? shift.value : 0);
const y = node.position.y + pushed(node.position.y) + opened(node.position.y);
if (original === open) return { ...node, position: { x: x - (OPEN_WIDTH - NODE_WIDTH) / 2, y }, zIndex: 10 };
// A lane grows with the cards inside it.
if (node.type === "lane" && node.style) {
const top = node.position.y;
const bottom = top + parseFloat(node.style.height);
const height = bottom + pushed(bottom) + opened(bottom) - y;
return { ...node, position: { x, y }, style: { ...node.style, height: `${height}px` } };
}
return { ...node, position: { x, y } };
});
});
// The run's trace: an edge lights once the run has reached its target, in the
// colour of how that step went, and moves while the step is running.
const runs = computed(() => new Map(graph.value.nodes.map((node) => [node.id, node.data.run?.status])));
// Data edges bundle into noise, so only the hovered or open step's show.
const hovered = ref<string | null>(null);
const focusId = computed(() => hovered.value ?? anchor.value?.id);
const edges = computed(() =>
graph.value.edges
.filter((edge) => edge.kind === "flow" || edge.source === focusId.value || edge.target === focusId.value)
.map(({ label, offset, insertAfter, otherwise, ...edge }) =>
edge.kind === "flow"
? {
...edge,
type: "insert",
...(otherwise ? { sourceHandle: "otherwise" } : {}),
data: { trace: runs.value.get(edge.target), otherwise, insertAfter, types: typesAt(insertAfter), editable: editable.value, onInsert: (after: StepPath, type: string) => emit("insert", after, type) },
}
: {
...edge,
type: "smoothstep",
pathOptions: { offset: offset ?? 20, borderRadius: 8 },
class: "workflow-data-edge",
data: { label },
},
),
);
const ZOOM = 0.9;
let flow: VueFlowStore | undefined;
const top = computed(() => (editable.value ? TOP : 0));
// Start at a readable size rather than shrinking a long workflow until
// nothing on it can be read, scrolled to the furthest step the watched run has
// reached so the step that is moving stays in view.
function place(store?: VueFlowStore): void {
const animate = !store;
flow = store ?? flow;
if (!flow) return;
const width = container.value?.clientWidth ?? 800;
const height = container.value?.clientHeight ?? 560;
// Scroll only when the furthest step reached would be out of view.
const reached = graph.value.nodes.find((node) => props.marks?.[node.id]) ?? graph.value.nodes.filter((node) => node.data.run).at(-1);
const below = reached && 24 + (reached.position.y - top.value + 180) * ZOOM > height;
const y = below ? height / 3 - reached.position.y * ZOOM : 24 - top.value * ZOOM;
void flow.setViewport({ x: width / 2 - NODE_WIDTH * ZOOM / 2, y, zoom: ZOOM }, { duration: animate ? 300 : 0 });
}
watch(() => graph.value.nodes.filter((node) => node.data.run).length, () => place());
watch(() => props.marks, () => place());
// A card opened low on the canvas scrolls up so its form is in view.
watch(anchor, async (node) => {
await nextTick();
if (!node || !flow) return;
const { x, y, zoom } = flow.getViewport();
const screenTop = (node.position.y + pushed(node.position.y)) * zoom + y;
const height = container.value?.clientHeight ?? 560;
if (screenTop < 8 || screenTop > height / 2) void flow.setViewport({ x, y: y - screenTop + 24, zoom }, { duration: 250 });
});
// The right-click menu opens at the pointer, for the step under it or for the
// canvas itself.
const menu = ref<{ open: boolean; x: number; y: number; step?: StepNodeData }>({ open: false, x: 0, y: 0 });
function openMenu(event: MouseEvent, step?: StepNodeData): void {
if (!editable.value) return;
event.preventDefault();
const box = container.value?.getBoundingClientRect();
menu.value = { open: true, x: event.clientX - (box?.left ?? 0), y: event.clientY - (box?.top ?? 0), step };
}
function onNodeMenu({ event, node }: NodeMouseEvent): void {
if (node.type !== "step" || (node.data as StepNodeData).kind === "workflow") return;
openMenu(event as MouseEvent, node.data as StepNodeData);
}
const menuPath = computed(() => menu.value.step?.path);
const restart = computed(() => (props.restartable && menuPath.value ? restartAt(graph.value, menuPath.value) : null));
const menuIndex = computed(() => Number(menuPath.value?.at(-1)));
const beforePath = computed(() => menuPath.value ? [...menuPath.value.slice(0, -1), menuIndex.value - 1] : []);
</script>
<template>
<div ref="container" class="workflow-canvas relative h-full overflow-hidden rounded-lg border border-border bg-background">
<VueFlow
class="h-full"
:nodes="nodes"
:edges="edges"
:nodes-draggable="false"
:nodes-connectable="false"
:elements-selectable="false"
:min-zoom="0.3"
:max-zoom="1.5"
pan-on-scroll
@pane-ready="place"
@node-mouse-enter="hovered = $event.node.id"
@node-mouse-leave="hovered = null"
@node-context-menu="onNodeMenu"
@pane-context-menu="openMenu($event as MouseEvent)"
>
<template #node-step="nodeProps">
<StepNode v-bind="nodeProps"><slot name="body" :data="nodeProps.data" /></StepNode>
</template>
<template #node-lane="nodeProps">
<LaneNode v-bind="nodeProps" />
</template>
<template #node-add="nodeProps">
<AddNode v-bind="nodeProps" />
</template>
<template #edge-insert="edgeProps">
<InsertEdge v-bind="edgeProps" />
</template>
<Background :gap="20" />
<Controls :show-interactive="false" />
</VueFlow>
<DropdownMenu v-model:open="menu.open">
<DropdownMenuTrigger as-child>
<span class="pointer-events-none absolute size-0" :style="{ left: `${menu.x}px`, top: `${menu.y}px` }" />
</DropdownMenuTrigger>
<DropdownMenuContent class="w-56" align="start">
<template v-if="menu.step?.kind === 'step' && menuPath">
<DropdownMenuLabel class="truncate">{{ menu.step.title || stepTitle(menu.step.type) }}</DropdownMenuLabel>
<template v-if="restart">
<DropdownMenuItem :disabled="restart.blocked" @select="emit('restart', restart.from)"><RotateCcw />{{ restart.label }}</DropdownMenuItem>
<DropdownMenuSeparator />
</template>
<DropdownMenuItem @select="emit('toggle', JSON.stringify(menuPath))"><Pencil />Edit</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Insert before</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="typesAt(menuPath)" @pick="emit('insert', beforePath, $event)" /></DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Insert after</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="typesAt(menuPath)" @pick="emit('insert', menuPath, $event)" /></DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuItem v-if="!['parallel', 'switch'].includes(menu.step.type)" @select="emit('duplicate', menuPath)"><Copy />Duplicate</DropdownMenuItem>
<DropdownMenuItem @select="emit('move', menuPath, -1)"><ArrowUp />Move up</DropdownMenuItem>
<DropdownMenuItem @select="emit('move', menuPath, 1)"><ArrowDown />Move down</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" @select="emit('remove', menuPath)"><Trash2 />Delete</DropdownMenuItem>
</template>
<template v-else>
<DropdownMenuLabel>{{ menu.step?.kind === "start" ? "Add the first step" : "Add a step at the end" }}</DropdownMenuLabel>
<StepTypeItems :types="types" @pick="emit('insert', ['steps', menu.step?.kind === 'start' ? -1 : stepCount - 1], $event)" />
</template>
</DropdownMenuContent>
</DropdownMenu>
</div>
</template>
<style>
.workflow-flow-edge path {
stroke: var(--color-muted-foreground);
stroke-width: 1.5;
}
.workflow-flow-edge.trace-ok path {
stroke: var(--color-ok);
}
.workflow-flow-edge.trace-failed path {
stroke: var(--color-danger);
}
.workflow-flow-edge.trace-interrupted path {
stroke: var(--color-warn);
}
.workflow-flow-edge.trace-running path {
stroke: var(--color-info);
stroke-dasharray: 6 4;
animation: edge-trace 0.8s linear infinite;
}
@keyframes edge-trace {
to {
stroke-dashoffset: -10;
}
}
@media (prefers-reduced-motion: reduce) {
.workflow-flow-edge.trace-running path,
.step-running {
animation: none;
}
}
.workflow-data-edge path {
stroke: var(--color-primary);
stroke-dasharray: 5 4;
stroke-width: 1.25;
}
@keyframes step-running {
50% {
box-shadow: 0 0 0 4px color-mix(in oklab, var(--color-info) 30%, transparent);
}
}
.step-running {
animation: step-running 1.6s ease-in-out infinite;
}
.workflow-canvas .vue-flow__controls {
box-shadow: none;
}
.workflow-canvas .vue-flow__controls-button {
background: var(--color-card);
border-color: var(--color-border);
fill: var(--color-foreground);
}
.workflow-canvas .vue-flow__controls-button:hover {
background: var(--color-secondary);
}
</style>