Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 34 additions & 7 deletions packages/app/src/features/projects/graph.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo, useState } from "react";
import { useMemo, useRef, useState, type PointerEvent } from "react";
import { useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { api } from "factorize-api-client";
Expand Down Expand Up @@ -35,10 +35,37 @@ export function ProjectGraph({ projectId }: { projectId: string }) {
// for labels and crossing connections to remain readable.
for (const [column, ids] of columns) ids.forEach((id, row) => positions.set(id, { x: 300 + column * 340, y: 110 + row * 200 }));
graph.nodes.filter(node => node.type === "webhook").forEach((node, row) => positions.set(node.id, { x: 35, y: 110 + row * 190 }));
const width = Math.max(900, ...[...positions.values()].map(p => p.x + 190)), height = Math.max(400, ...[...positions.values()].map(p => p.y + 110));
const width = Math.max(900, ...[...positions.values()].map(p => p.x + 240)), height = Math.max(400, ...[...positions.values()].map(p => p.y + 110));
return { positions, width, height };
}, [query.data]);
const [drag, setDrag] = useState<{ x: number; y: number } | null>(null);
const pointers = useRef(new Map<number, { x: number; y: number; type: string }>());
const lastPanCenter = useRef<{ x: number; y: number } | null>(null);
const graphPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if ((event.target as Element).closest("[data-graph-interactive]")) return;
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY, type: event.pointerType });
const active = [...pointers.current.values()], touch = active.some(pointer => pointer.type === "touch");
if (touch ? active.filter(pointer => pointer.type === "touch").length >= 2 : true) {
const center = active.reduce((point, pointer) => ({ x: point.x + pointer.x / active.length, y: point.y + pointer.y / active.length }), { x: 0, y: 0 });
lastPanCenter.current = center;
}
};
const graphPointerMove = (event: PointerEvent<HTMLDivElement>) => {
if (!pointers.current.has(event.pointerId)) return;
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY, type: event.pointerType });
const active = [...pointers.current.values()], touch = active.some(pointer => pointer.type === "touch");
if (touch && active.filter(pointer => pointer.type === "touch").length < 2) return;
if (!lastPanCenter.current) return;
const center = active.reduce((point, pointer) => ({ x: point.x + pointer.x / active.length, y: point.y + pointer.y / active.length }), { x: 0, y: 0 });
const previous = lastPanCenter.current;
setOffset(current => ({ x: current.x + center.x - previous.x, y: current.y + center.y - previous.y }));
lastPanCenter.current = center;
};
const graphPointerUp = (event: PointerEvent<HTMLDivElement>) => {
pointers.current.delete(event.pointerId);
const active = [...pointers.current.values()], touchCount = active.filter(pointer => pointer.type === "touch").length;
if (!active.length || (active.some(pointer => pointer.type === "touch") && touchCount < 2)) lastPanCenter.current = null;
else if (lastPanCenter.current) lastPanCenter.current = active.reduce((point, pointer) => ({ x: point.x + pointer.x / active.length, y: point.y + pointer.y / active.length }), { x: 0, y: 0 });
};
if (query.isPending) return <p role="status" className="py-10 text-center">Loading project graph…</p>;
if (query.error) return <div role="alert" className="py-6">{query.error.message} <Button onClick={() => void query.refetch()}>Retry</Button></div>;
if (!query.data?.nodes.length) return <Card className="py-10 text-center"><p>No jobs in this project yet.</p></Card>;
Expand All @@ -62,25 +89,25 @@ export function ProjectGraph({ projectId }: { projectId: string }) {
<Button aria-label="Zoom out" onClick={() => zoom(.8)}>−</Button><Button aria-label="Zoom in" onClick={() => zoom(1.25)}>+</Button>
<Button aria-label="Fit graph to view" onClick={() => { setScale(1); setOffset({ x: 0, y: 0 }); }}>Fit to view</Button><span className="ml-2 text-sm text-slate-600 dark:text-slate-400">Drag to pan. Select a job to open it.</span>
</div>
<div className="overflow-hidden rounded-xl border border-stone-200 bg-stone-50 dark:border-slate-800 dark:bg-slate-950" onPointerDown={event => { if (event.target === event.currentTarget) { event.currentTarget.setPointerCapture(event.pointerId); setDrag({ x: event.clientX - offset.x, y: event.clientY - offset.y }); } }} onPointerMove={event => { if (drag) setOffset({ x: event.clientX - drag.x, y: event.clientY - drag.y }); }} onPointerUp={() => setDrag(null)}>
<div className="overflow-hidden rounded-xl border border-stone-200 bg-stone-50 touch-none dark:border-slate-800 dark:bg-slate-950" onPointerDown={graphPointerDown} onPointerMove={graphPointerMove} onPointerUp={graphPointerUp} onPointerCancel={graphPointerUp}>
<svg role="img" aria-label={`Workflow graph with ${graph.nodes.filter(node => node.type === "job").length} jobs and ${graph.edges.length} connections`} viewBox={`0 0 ${layout.width} ${layout.height}`} className="h-[min(68vh,700px)] min-h-[360px] w-full touch-none" preserveAspectRatio="xMidYMid meet">
<defs><marker id="graph-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" fill="context-stroke" /></marker><marker id="graph-arrow-start" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="context-stroke" /></marker></defs>
<g transform={`translate(${offset.x} ${offset.y}) scale(${scale})`}>
{[...edgeGroups].map(([pair, edges]) => {
const [leftId, rightId] = JSON.parse(pair) as [string, string], left = layout.positions.get(leftId), right = layout.positions.get(rightId);
if (!left || !right) return null;
const leftNode = graph.nodes.find(node => node.id === leftId), rightNode = graph.nodes.find(node => node.id === rightId);
const leftWidth = leftNode?.type === "webhook" ? 145 : 170, rightWidth = rightNode?.type === "webhook" ? 145 : 170;
const leftWidth = leftNode?.type === "webhook" ? 145 : 220, rightWidth = rightNode?.type === "webhook" ? 145 : 220;
const leftIsLeft = left.x <= right.x, from = leftIsLeft ? left : right, to = leftIsLeft ? right : left;
const fromId = leftIsLeft ? leftId : rightId, toId = leftIsLeft ? rightId : leftId;
const startWidth = leftIsLeft ? leftWidth : rightWidth, endX = to.x;
const forward = edges.some(edge => edge.source === fromId && edge.target === toId), reverse = edges.some(edge => edge.source === toId && edge.target === fromId);
const muted = edges.every(edge => !edge.enabled), label = [...new Set(edges.map(edge => edge.label).filter(Boolean))].join(" · ");
const stroke = muted ? "#a8a29e" : edges.length === 1 && edges[0].kind === "manual" ? "#7c3aed" : edges.length === 1 && edges[0].kind === "webhook" ? "#0284c7" : "#0f766e";
const groupId = edges.map(edge => edge.id).sort().join("|");
return <g key={groupId} onClick={() => setSelectedEdge(edges[0])} className="cursor-pointer" role="button" tabIndex={0} aria-label={`${label || "Workflow"} connection${edges.length > 1 ? `, ${edges.length} triggers` : ""}`} onKeyDown={event => { if (event.key === "Enter" || event.key === " ") setSelectedEdge(edges[0]); }}><path d={`M ${from.x + startWidth} ${from.y + 35} Q ${(from.x + startWidth + endX) / 2} ${(from.y + to.y) / 2 + 35} ${endX} ${to.y + 35}`} fill="none" stroke={stroke} strokeWidth={selectedEdge && edges.some(edge => edge.id === selectedEdge.id) ? 4 : 2} strokeDasharray={muted ? "6 5" : undefined} markerStart={reverse ? "url(#graph-arrow-start)" : undefined} markerEnd={forward ? "url(#graph-arrow)" : undefined}/><text x={(from.x + startWidth + endX) / 2} y={(from.y + to.y) / 2 + 28} textAnchor="middle" className="fill-slate-700 text-[12px] dark:fill-slate-200">{label}</text></g>;
return <g key={groupId} data-graph-interactive onClick={() => setSelectedEdge(edges[0])} className="cursor-pointer" role="button" tabIndex={0} aria-label={`${label || "Workflow"} connection${edges.length > 1 ? `, ${edges.length} triggers` : ""}`} onKeyDown={event => { if (event.key === "Enter" || event.key === " ") setSelectedEdge(edges[0]); }}><path d={`M ${from.x + startWidth} ${from.y + 35} Q ${(from.x + startWidth + endX) / 2} ${(from.y + to.y) / 2 + 35} ${endX} ${to.y + 35}`} fill="none" stroke={stroke} strokeWidth={selectedEdge && edges.some(edge => edge.id === selectedEdge.id) ? 4 : 2} strokeDasharray={muted ? "6 5" : undefined} markerStart={reverse ? "url(#graph-arrow-start)" : undefined} markerEnd={forward ? "url(#graph-arrow)" : undefined}/><text x={(from.x + startWidth + endX) / 2} y={(from.y + to.y) / 2 + 28} textAnchor="middle" className="fill-slate-700 text-[12px] dark:fill-slate-200">{label}</text></g>;
})}
{graph.nodes.map(node => { const p = layout.positions.get(node.id)!; const isJob = node.type === "job", muted = isJob && !node.enabled, active = isJob && (node.runningCount ?? 0) > 0, height = isJob ? 92 : 70; return <g key={node.id} transform={`translate(${p.x} ${p.y})`} className={isJob ? "cursor-pointer" : ""} role={isJob ? "link" : undefined} tabIndex={isJob ? 0 : undefined} aria-label={isJob ? `${node.jobKind}: ${node.label}${muted ? ", disabled" : ""}${active ? `, running${node.concurrencyLimit && node.concurrencyLimit > 1 ? `, ${node.runningCount}/${node.concurrencyLimit} active` : ""}` : ", not running"}` : node.label} onClick={() => isJob && void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } })} onKeyDown={event => { if (isJob && (event.key === "Enter" || event.key === " ")) void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } }); }}><rect width={isJob ? 170 : 145} height={height} rx="12" fill={muted ? "#e7e5e4" : isJob ? "#fff" : "#e0f2fe"} stroke={muted ? "#a8a29e" : isJob ? "#0f766e" : "#0284c7"} strokeWidth="2" strokeDasharray={muted ? "5 4" : undefined}/><text x="14" y="27" className="fill-slate-800 text-[12px] font-semibold dark:fill-slate-900">{isJob ? node.jobKind : node.provider}</text><text x="14" y="49" className="fill-slate-700 text-[12px] dark:fill-slate-800">{node.label.length > 19 ? node.label.slice(0, 18) + "…" : node.label}</text>{isJob && <><circle cx="19" cy="70" r="5" fill={active ? "#059669" : "#a8a29e"} className={active ? "motion-safe:animate-pulse" : undefined}/><text x="30" y="74" className={`text-[11px] font-medium ${active ? "fill-emerald-700" : "fill-slate-500"}`}>{active ? `Running${node.concurrencyLimit && node.concurrencyLimit > 1 ? ` · ${node.runningCount}/${node.concurrencyLimit}` : ""}` : "Not running"}</text></>}</g>; })}
{graph.nodes.map(node => { const p = layout.positions.get(node.id)!; const isJob = node.type === "job", muted = isJob && !node.enabled, active = isJob && (node.runningCount ?? 0) > 0, height = isJob ? 112 : 70, title = node.label.length > 22 ? node.label.slice(0, 21) + "…" : node.label; return <g key={node.id} data-graph-interactive transform={`translate(${p.x} ${p.y})`} className={isJob ? "cursor-pointer" : ""} role={isJob ? "link" : undefined} tabIndex={isJob ? 0 : undefined} aria-label={isJob ? `${node.label}${muted ? ", disabled" : ""}${active ? `, running${node.concurrencyLimit && node.concurrencyLimit > 1 ? `, ${node.runningCount}/${node.concurrencyLimit} active` : ""}` : ", not running"}` : node.label} onClick={() => isJob && void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } })} onKeyDown={event => { if (isJob && (event.key === "Enter" || event.key === " ")) void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } }); }}><rect width={isJob ? 220 : 145} height={height} rx="12" fill={muted ? "#e7e5e4" : isJob ? "#fff" : "#e0f2fe"} stroke={muted ? "#a8a29e" : isJob ? "#0f766e" : "#0284c7"} strokeWidth="2" strokeDasharray={muted ? "5 4" : undefined}/>{isJob ? <><text x="14" y="25" className="fill-slate-800 text-[11px] font-medium dark:fill-slate-900">{node.jobKind}</text><text x="14" y="53" className="fill-slate-800 text-base font-semibold dark:fill-slate-900">{title}</text><circle cx="19" cy="83" r="5" fill={active ? "#059669" : "#a8a29e"} className={active ? "motion-safe:animate-pulse" : undefined}/><text x="30" y="87" className={`text-[11px] font-medium ${active ? "fill-emerald-700" : "fill-slate-500"}`}>{active ? `Running${node.concurrencyLimit && node.concurrencyLimit > 1 ? ` · ${node.runningCount}/${node.concurrencyLimit}` : ""}` : "Not running"}</text></> : <><text x="14" y="27" className="fill-slate-800 text-[12px] font-semibold dark:fill-slate-900">{node.provider}</text><text x="14" y="49" className="fill-slate-700 text-[12px] dark:fill-slate-800">{node.label.length > 19 ? node.label.slice(0, 18) + "…" : node.label}</text></>}</g>; })}
</g>
</svg>
</div>
Expand Down
12 changes: 10 additions & 2 deletions packages/app/test/jobs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ test("project graph preserves disabled and multiple connections and navigates to
], edges: [
{ id: "lifecycle-a", source: jobId, target: secondJob, label: "Failed, Stopped", kind: "lifecycle", enabled: false },
{ id: "idle-a", source: jobId, target: secondJob, label: "Idle", kind: "idle", enabled: false },
{ id: "manual-a", source: jobId, target: secondJob, label: "Manual", kind: "manual", enabled: false },
{ id: "manual-a", source: secondJob, target: jobId, label: "Manual", kind: "manual", enabled: false },
{ id: "lifecycle-reverse", source: secondJob, target: jobId, label: "Succeeded", kind: "lifecycle", enabled: true },
],
} }));
Expand All @@ -104,7 +104,15 @@ test("project graph preserves disabled and multiple connections and navigates to
assert.equal(await page.getByRole("button", { name: /connection, 4 triggers/ }).count(), 1);
assert.equal(await combined.locator("path").getAttribute("marker-start"), "url(#graph-arrow-start)");
assert.equal(await combined.locator("path").getAttribute("marker-end"), "url(#graph-arrow)");
await page.getByRole("link", { name: "Code: Deploy, disabled" }).click();
assert.equal(await page.getByRole("link", { name: "Deploy, disabled, not running" }).count(), 1);
const svg = page.getByRole("img", { name: /2 jobs and 4 connections/ });
const svgBox = await svg.boundingBox();
await page.mouse.move(svgBox.x + svgBox.width / 2, svgBox.y + svgBox.height / 2);
await page.mouse.down();
await page.mouse.move(svgBox.x + svgBox.width / 2 + 25, svgBox.y + svgBox.height / 2 + 20);
await page.mouse.up();
assert.match(await svg.locator(":scope > g").getAttribute("transform"), /^translate\(25 20\) scale\(1\)$/);
await page.getByRole("link", { name: "Deploy, disabled, not running" }).click();
await page.waitForURL(new RegExp(`/jobs/${secondJob}`));
await context.close();
});
Expand Down
Loading